From 237de987f0f3073b35327a4df475314fa6c9e2dd Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 17 Nov 2026 13:03:21 +1100 Subject: [PATCH 01/29] feat(v2): typed client generated from the rest-api OpenAPI document The hand-written v1 client drifts from the API: types are guesses and nothing checks the data the server sends. v2 generates its types and request functions from the OpenAPI document of PlaceOS/rest-api, and parses each response at the boundary, so a mismatch is a typed error with a path instead of a bad value deep in an app. v2 is a separate package in v2/ (Bun, no runtime dependencies) that follows TigerStyle: errors are Result values, every request has a timeout and a body size limit, and the types come from the schemas. The generator patches the document where it is wrong, with a comment for each patch: time fields that the server sends as Unix seconds, request bodies whose fields the document marks as required, and the PATCH/PUT duplicate of each update. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2.yml | 32 + v2/.gitignore | 2 + v2/.prettierrc | 6 + v2/README.md | 185 + v2/bun.lock | 69 + v2/package.json | 39 + v2/scripts/generate.ts | 923 +++++ v2/src/core/assert.ts | 13 + v2/src/core/client.ts | 438 +++ v2/src/core/pagination.ts | 53 + v2/src/core/result.ts | 7 + v2/src/core/schema.ts | 408 +++ .../generated/operations/alert-dashboards.ts | 177 + v2/src/generated/operations/alerts.ts | 159 + v2/src/generated/operations/api-keys.ts | 172 + .../generated/operations/asset-categories.ts | 154 + .../operations/asset-purchase-orders.ts | 151 + v2/src/generated/operations/asset-types.ts | 161 + v2/src/generated/operations/assets.ts | 232 ++ v2/src/generated/operations/brokers.ts | 135 + v2/src/generated/operations/build-monitor.ts | 61 + .../generated/operations/chat-gpt-plugin.ts | 123 + v2/src/generated/operations/chat-gpt.ts | 113 + v2/src/generated/operations/cluster.ts | 121 + v2/src/generated/operations/domains.ts | 176 + v2/src/generated/operations/drivers.ts | 259 ++ v2/src/generated/operations/edges.ts | 464 +++ v2/src/generated/operations/flux.ts | 35 + v2/src/generated/operations/groups-history.ts | 77 + .../operations/groups-invitations.ts | 154 + v2/src/generated/operations/groups-users.ts | 139 + v2/src/generated/operations/groups-zones.ts | 136 + v2/src/generated/operations/groups.ts | 245 ++ v2/src/generated/operations/history.ts | 120 + v2/src/generated/operations/index.ts | 60 + .../operations/ldap-authentications.ts | 152 + v2/src/generated/operations/map-ai.ts | 203 ++ v2/src/generated/operations/metadata.ts | 276 ++ v2/src/generated/operations/modules.ts | 488 +++ v2/src/generated/operations/mqtt.ts | 72 + .../operations/oauth-applications.ts | 155 + .../operations/oauth-authentications.ts | 152 + v2/src/generated/operations/pending-mails.ts | 210 ++ v2/src/generated/operations/playlist-media.ts | 390 +++ v2/src/generated/operations/playlist.ts | 502 +++ v2/src/generated/operations/public-events.ts | 132 + .../operations/push-notifications.ts | 49 + v2/src/generated/operations/repositories.ts | 601 ++++ v2/src/generated/operations/root.ts | 200 ++ .../operations/saml-authentications.ts | 152 + v2/src/generated/operations/schema.ts | 151 + v2/src/generated/operations/settings.ts | 180 + v2/src/generated/operations/short-url.ts | 261 ++ .../operations/signage-ai-providers.ts | 295 ++ v2/src/generated/operations/signage-ai.ts | 220 ++ .../generated/operations/signage-plugins.ts | 153 + .../operations/signage-template-mappings.ts | 173 + .../generated/operations/signage-templates.ts | 362 ++ v2/src/generated/operations/signage.ts | 171 + v2/src/generated/operations/storages.ts | 151 + .../generated/operations/system-triggers.ts | 179 + v2/src/generated/operations/systems.ts | 564 +++ v2/src/generated/operations/tenant-consent.ts | 123 + v2/src/generated/operations/triggers.ts | 177 + v2/src/generated/operations/uploads.ts | 477 +++ v2/src/generated/operations/url-proxy.ts | 44 + v2/src/generated/operations/users.ts | 430 +++ v2/src/generated/operations/web-rtc.ts | 250 ++ v2/src/generated/operations/webhook.ts | 42 + v2/src/generated/operations/zones.ts | 283 ++ v2/src/generated/schemas.ts | 3062 +++++++++++++++++ v2/src/index.ts | 48 + v2/test/client.test.ts | 303 ++ v2/test/pagination.test.ts | 22 + v2/test/schema.test.ts | 146 + v2/test/style.test.ts | 33 + v2/tsconfig.build.json | 18 + v2/tsconfig.json | 28 + vite.config.ts | 3 + 79 files changed, 17882 insertions(+) create mode 100644 .github/workflows/v2.yml create mode 100644 v2/.gitignore create mode 100644 v2/.prettierrc create mode 100644 v2/README.md create mode 100644 v2/bun.lock create mode 100644 v2/package.json create mode 100644 v2/scripts/generate.ts create mode 100644 v2/src/core/assert.ts create mode 100644 v2/src/core/client.ts create mode 100644 v2/src/core/pagination.ts create mode 100644 v2/src/core/result.ts create mode 100644 v2/src/core/schema.ts create mode 100644 v2/src/generated/operations/alert-dashboards.ts create mode 100644 v2/src/generated/operations/alerts.ts create mode 100644 v2/src/generated/operations/api-keys.ts create mode 100644 v2/src/generated/operations/asset-categories.ts create mode 100644 v2/src/generated/operations/asset-purchase-orders.ts create mode 100644 v2/src/generated/operations/asset-types.ts create mode 100644 v2/src/generated/operations/assets.ts create mode 100644 v2/src/generated/operations/brokers.ts create mode 100644 v2/src/generated/operations/build-monitor.ts create mode 100644 v2/src/generated/operations/chat-gpt-plugin.ts create mode 100644 v2/src/generated/operations/chat-gpt.ts create mode 100644 v2/src/generated/operations/cluster.ts create mode 100644 v2/src/generated/operations/domains.ts create mode 100644 v2/src/generated/operations/drivers.ts create mode 100644 v2/src/generated/operations/edges.ts create mode 100644 v2/src/generated/operations/flux.ts create mode 100644 v2/src/generated/operations/groups-history.ts create mode 100644 v2/src/generated/operations/groups-invitations.ts create mode 100644 v2/src/generated/operations/groups-users.ts create mode 100644 v2/src/generated/operations/groups-zones.ts create mode 100644 v2/src/generated/operations/groups.ts create mode 100644 v2/src/generated/operations/history.ts create mode 100644 v2/src/generated/operations/index.ts create mode 100644 v2/src/generated/operations/ldap-authentications.ts create mode 100644 v2/src/generated/operations/map-ai.ts create mode 100644 v2/src/generated/operations/metadata.ts create mode 100644 v2/src/generated/operations/modules.ts create mode 100644 v2/src/generated/operations/mqtt.ts create mode 100644 v2/src/generated/operations/oauth-applications.ts create mode 100644 v2/src/generated/operations/oauth-authentications.ts create mode 100644 v2/src/generated/operations/pending-mails.ts create mode 100644 v2/src/generated/operations/playlist-media.ts create mode 100644 v2/src/generated/operations/playlist.ts create mode 100644 v2/src/generated/operations/public-events.ts create mode 100644 v2/src/generated/operations/push-notifications.ts create mode 100644 v2/src/generated/operations/repositories.ts create mode 100644 v2/src/generated/operations/root.ts create mode 100644 v2/src/generated/operations/saml-authentications.ts create mode 100644 v2/src/generated/operations/schema.ts create mode 100644 v2/src/generated/operations/settings.ts create mode 100644 v2/src/generated/operations/short-url.ts create mode 100644 v2/src/generated/operations/signage-ai-providers.ts create mode 100644 v2/src/generated/operations/signage-ai.ts create mode 100644 v2/src/generated/operations/signage-plugins.ts create mode 100644 v2/src/generated/operations/signage-template-mappings.ts create mode 100644 v2/src/generated/operations/signage-templates.ts create mode 100644 v2/src/generated/operations/signage.ts create mode 100644 v2/src/generated/operations/storages.ts create mode 100644 v2/src/generated/operations/system-triggers.ts create mode 100644 v2/src/generated/operations/systems.ts create mode 100644 v2/src/generated/operations/tenant-consent.ts create mode 100644 v2/src/generated/operations/triggers.ts create mode 100644 v2/src/generated/operations/uploads.ts create mode 100644 v2/src/generated/operations/url-proxy.ts create mode 100644 v2/src/generated/operations/users.ts create mode 100644 v2/src/generated/operations/web-rtc.ts create mode 100644 v2/src/generated/operations/webhook.ts create mode 100644 v2/src/generated/operations/zones.ts create mode 100644 v2/src/generated/schemas.ts create mode 100644 v2/src/index.ts create mode 100644 v2/test/client.test.ts create mode 100644 v2/test/pagination.test.ts create mode 100644 v2/test/schema.test.ts create mode 100644 v2/test/style.test.ts create mode 100644 v2/tsconfig.build.json create mode 100644 v2/tsconfig.json diff --git a/.github/workflows/v2.yml b/.github/workflows/v2.yml new file mode 100644 index 000000000..644cfbea6 --- /dev/null +++ b/.github/workflows/v2.yml @@ -0,0 +1,32 @@ +# Checks the v2 package: types, tests and build. +name: v2 + +on: + pull_request: + paths: + - 'v2/**' + - '.github/workflows/v2.yml' + push: + branches: + - master + paths: + - 'v2/**' + - '.github/workflows/v2.yml' + +jobs: + check: + runs-on: ubuntu-latest + defaults: + run: + working-directory: v2 + steps: + - uses: actions/checkout@v4 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.3 + + - run: bun install --frozen-lockfile + - run: bun run check + - run: bun test + - run: bun run build diff --git a/v2/.gitignore b/v2/.gitignore new file mode 100644 index 000000000..c925c21d5 --- /dev/null +++ b/v2/.gitignore @@ -0,0 +1,2 @@ +/dist +/node_modules diff --git a/v2/.prettierrc b/v2/.prettierrc new file mode 100644 index 000000000..969d4b941 --- /dev/null +++ b/v2/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": true, + "tabWidth": 4, + "semi": true, + "printWidth": 100 +} diff --git a/v2/README.md b/v2/README.md new file mode 100644 index 000000000..88414abd6 --- /dev/null +++ b/v2/README.md @@ -0,0 +1,185 @@ +# @placeos/ts-client v2 + +A typed client for the PlaceOS REST API. A script generates the types and the request functions +from the [OpenAPI document](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) of +the API. The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) +where possible. + +The library has no runtime dependencies. It runs in browsers, in Node 20.3 and later, and in Bun. + +## Use the client + +```ts +import { configure, zones } from '@placeos/ts-client'; + +// Do this one time, when the application starts. +configure({ + baseUrl: 'https://placeos.example.com', // Use '' for the origin of the page. + auth: { kind: 'bearer', token: () => localStorage.getItem('token') }, +}); + +const result = await zones.show({ id: 'zone-1234', complete: true }); +if (result.ok) { + console.log(result.value.data.name); +} else { + console.error(result.error.kind); +} +``` + +There is one namespace for each controller of the API, for example `zones`, `systems` and +`users`. Each function has the name of the server action: `index`, `show`, `create`, `update`, +`destroy`, or a custom action such as `systems.execute`. The comment of each function gives the +HTTP method and the path. + +The first argument has the path parameters, the query parameters and, for an operation with a +body, `body`. The second argument has the options of the request: + +```ts +await zones.update({ id: 'zone-1234', body: { name: 'Level 2' } }); +await systems.execute({ + sys_id: 'sys-1234', + module_slug: 'Display_1', + method: 'power', + body: [true], +}); +``` + +### Results and errors + +A function does not throw for an expected failure. It returns a `Result`. Examine `ok` first: + +| `error.kind` | Meaning | +| -------------------- | -------------------------------------------------------------------------- | +| `http` | The server sent a status that is not 2xx. See `status`, `message`, `body`. | +| `network` | The request got no response. For example, the network is down. | +| `timeout` | The request took more than `timeoutMs`. | +| `aborted` | The `signal` of the caller cancelled the request. | +| `auth_missing` | The `token` function of the `bearer` auth gave `null`. | +| `response_too_large` | The body was more than `responseBytesMax`. | +| `response_invalid` | The body does not match the API document. See `path` and `expected`. | + +A function throws only for a programmer error. For example, a parameter that the operation does +not have, an empty path parameter, or a call before `configure`. + +### More than one client + +`configure` makes the client that each call uses. To use a different client for one call, make it +with `createClient` and give it in the options. The configured client does not change: + +```ts +const other = createClient({ baseUrl: 'https://other.example.com', auth: { kind: 'none' } }); +await zones.index({}, { client: other }); +``` + +### Timeouts and cancel + +Each request has a time limit. The default is 30 seconds. Set a different limit for the client or +for one request: + +```ts +configure({ baseUrl: '', auth: { kind: 'none' }, timeoutMs: 10_000 }); +const controller = new AbortController(); +await zones.index({}, { signal: controller.signal, timeoutMs: 60_000 }); +``` + +### Pages + +An `index` operation returns one page. Use `pageInfo` to get the total and the next offset: + +```ts +import { pageInfo, zones } from '@placeos/ts-client'; + +const result = await zones.index({ limit: 100 }); +if (result.ok) { + const { total, nextOffset } = pageInfo(result.value.headers); +} +``` + +### Tests and mocks + +Give the client a `fetch` function. The client sends each request through it. A test can give +its own client in the options, so it does not change the configured client: + +```ts +const client = createClient({ + baseUrl: '', + auth: { kind: 'none' }, + fetch: async (url, init) => new Response(JSON.stringify({ id: 'zone-1' })), +}); +const result = await zones.show({ id: 'zone-1' }, { client }); +``` + +## Types + +Each schema of the API document has a value and two types with the same base name: + +- `Zone` is the type of a zone from the server. Each field is present. A field that the server can + leave out is `null`. +- `ZoneInput` is the type of a zone that you send. Each field is optional. +- The `Zone` value is the schema. `parseResponse(Zone, value)` parses data from other sources. + +The parser removes the fields that the schema does not have. A request that has a field that the +schema does not have stops with an error, because a typing error in a field name is a bug. + +## Differences from the API document + +The generator changes some parts of the document. Each change has a comment in +`scripts/generate.ts`. + +- **Time fields.** The document says `date-time` for some fields that the server sends as Unix time + in seconds, for example `created_at` on most models. The generator changes these fields to + integers. The list comes from the source of PlaceOS/models. The generator stops if it finds a + `date-time` field that is not in a list, so each new field gets a decision. +- **Required fields in a request.** The document marks a field as required when the server always + sends it. The server can have a default for the same field in a request. Thus each field of a + request body is optional, and the server checks the body. Path and query parameters keep the + `required` of the document. +- **Arrays in a query.** The server reads an array parameter as one value with commas, for example + `zone_id=a,b`. The items of an array parameter must not contain commas. +- **PATCH and PUT.** The server sends PATCH and PUT of `update` to the same method. The client has + only `update`, which sends PATCH. +- **Responses without a schema.** The data is a `Uint8Array` with the raw body. `systems.execute`, + `modules.execute` and `modules.stateValue` are exceptions: they return a `JsonValue`. +- **WebSocket endpoints** (`systems/control`, `webrtc/signaller` and others) are not in the + client. + +## Change the generated code + +Do not edit `src/generated`. The generator downloads the API document from the master branch of +[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api) on each run. It does not keep a copy in +this repository. + +```sh +bun run generate # Downloads the document and writes src/generated. +bun run generate:check # Fails if src/generated does not match the current document. +``` + +The generated files are in the repository, so a change to the API shows as a diff. Examine the +diff before you commit it. `generate:check` can fail because the API changed, not because of your +change, so it is not part of `bun test`. + +The generator stops with an assertion on a part of the document that it does not support. Add the +support to `scripts/generate.ts` and `src/core/schema.ts`. + +## Development + +```sh +bun install +bun run check # Type checks the library, the tests and the scripts. +bun test +bun run build # Writes dist/. +``` + +## What v1 has that v2 does not have + +- The OAuth login flow and the token storage. Give the `bearer` auth a `token` function. +- The realtime WebSocket bindings. +- The mock systems. Give `createClient` a `fetch` function. +- Classes with methods for each model. v2 has plain data and functions. + +## Where v2 does not follow TigerStyle + +- `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove + that the parser output has the type of the schema. The tests check the parser. +- Records from the server are plain objects, not `Map`s. A `Map` does not go through + `JSON.stringify`, and the API sends these objects back and forth. diff --git a/v2/bun.lock b/v2/bun.lock new file mode 100644 index 000000000..8b84db341 --- /dev/null +++ b/v2/bun.lock @@ -0,0 +1,69 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "@placeos/ts-client", + "devDependencies": { + "@types/bun": "1.4.3", + "prettier": "3.9.10", + "typescript": "7.0.2", + }, + }, + }, + "packages": { + "@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="], + + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], + + "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], + + "@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="], + + "@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="], + + "@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="], + + "@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="], + + "@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="], + + "@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="], + + "@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="], + + "@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="], + + "@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="], + + "@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="], + + "@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="], + + "@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="], + + "@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="], + + "@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="], + + "@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="], + + "@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="], + + "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="], + + "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], + + "bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="], + + "prettier": ["prettier@3.9.10", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA=="], + + "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], + + "undici-types": ["undici-types@8.12.4", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="], + + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + } +} diff --git a/v2/package.json b/v2/package.json new file mode 100644 index 000000000..6e7118093 --- /dev/null +++ b/v2/package.json @@ -0,0 +1,39 @@ +{ + "name": "@placeos/ts-client", + "version": "2.0.0-alpha.0", + "description": "Typed PlaceOS REST API client, generated from the PlaceOS OpenAPI document", + "license": "MIT", + "type": "module", + "repository": { + "type": "git", + "url": "https://github.com/PlaceOS/ts-client.git", + "directory": "v2" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "files": [ + "dist", + "src" + ], + "sideEffects": false, + "engines": { + "node": ">=20.3" + }, + "scripts": { + "generate": "bun scripts/generate.ts", + "generate:check": "bun scripts/generate.ts --check", + "check": "tsc --noEmit && tsc --noEmit -p tsconfig.build.json", + "test": "bun test", + "build": "rm -rf dist && tsc -p tsconfig.build.json", + "format": "prettier --write ." + }, + "devDependencies": { + "@types/bun": "1.4.3", + "prettier": "3.9.10", + "typescript": "7.0.2" + } +} diff --git a/v2/scripts/generate.ts b/v2/scripts/generate.ts new file mode 100644 index 000000000..48ee62e6b --- /dev/null +++ b/v2/scripts/generate.ts @@ -0,0 +1,923 @@ +/** + * Generates `src/generated` from the OpenAPI document of the PlaceOS REST API. It downloads the + * document from the master branch of PlaceOS/rest-api on each run, so the output follows the API. + * + * bun run generate Writes the generated files. + * bun scripts/generate.ts --check Fails if a generated file is not up to date. + * + * The output is one schema file and one operation file for each API controller. The schema file + * has a schema value and a type of the same name for each named schema of the document. Each + * operation file has one function for each endpoint of the controller. + * + * The generator stops with an assertion on a part of the document that it does not support. Then + * a change to the document cannot make the output wrong without a message. + */ +import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { format, resolveConfig } from 'prettier'; +import { assert } from '../src/core/assert.ts'; +import { isRecord } from '../src/core/schema.ts'; + +const ROOT = join(import.meta.dir, '..'); +const SPEC_URL = + 'https://raw.githubusercontent.com/PlaceOS/rest-api/refs/heads/master/OPENAPI_DOC.yml'; +const SPEC_TIMEOUT_MS = 30_000; +const GENERATED_DIR = join(ROOT, 'src', 'generated'); +const OPERATIONS_DIR = join(GENERATED_DIR, 'operations'); +const SPEC_BYTES_MAX = 16 * 1024 * 1024; +const EMIT_DEPTH_MAX = 32; +const LINE_WIDTH_MAX = 100; +const HEADER = + '// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit.\n'; + +/** + * The spec generator of the server loses the `type: "integer"` hint of a `Time` field that has an + * epoch converter, if the field is a PgORM `attribute` or can be nil. The document then says + * `date-time`, but the server sends and accepts Unix time in seconds. Each entry comes from the + * source of PlaceOS/models and PlaceOS/rest-api. + */ +const TIMESTAMPS = ['created_at', 'updated_at']; +const EPOCH_FIELDS: ReadonlyMap = new Map([ + ['PlaceOS.Api.ApiKeys.Response', ['expires_at']], + ['PlaceOS.Model.Alert', TIMESTAMPS], + ['PlaceOS.Model.AlertDashboard', TIMESTAMPS], + ['PlaceOS.Model.ApiKey', [...TIMESTAMPS, 'expires_at']], + ['PlaceOS.Model.Asset', TIMESTAMPS], + ['PlaceOS.Model.AssetCategory', TIMESTAMPS], + ['PlaceOS.Model.AssetPurchaseOrder', TIMESTAMPS], + ['PlaceOS.Model.AssetType', TIMESTAMPS], + ['PlaceOS.Model.Authority', TIMESTAMPS], + ['PlaceOS.Model.Broker', TIMESTAMPS], + ['PlaceOS.Model.Chat', TIMESTAMPS], + ['PlaceOS.Model.ControlSystem', [...TIMESTAMPS, 'signage_last_seen']], + ['PlaceOS.Model.DoorkeeperApplication', TIMESTAMPS], + ['PlaceOS.Model.Driver', TIMESTAMPS], + ['PlaceOS.Model.Edge', [...TIMESTAMPS, 'last_seen']], + ['PlaceOS.Model.Edge.KeyResponse', [...TIMESTAMPS, 'last_seen']], + ['PlaceOS.Model.History', ['created_at']], + ['PlaceOS.Model.JsonSchema', TIMESTAMPS], + ['PlaceOS.Model.LdapAuthentication', TIMESTAMPS], + ['PlaceOS.Model.Module', [...TIMESTAMPS, 'error_timestamp']], + ['PlaceOS.Model.OAuthAuthentication', TIMESTAMPS], + ['PlaceOS.Model.Playlist', TIMESTAMPS], + ['PlaceOS.Model.Playlist.Item', TIMESTAMPS], + ['PlaceOS.Model.Playlist.ItemSchedule', TIMESTAMPS], + ['PlaceOS.Model.Playlist.Revision', TIMESTAMPS], + ['PlaceOS.Model.Repository', TIMESTAMPS], + ['PlaceOS.Model.SamlAuthentication', TIMESTAMPS], + ['PlaceOS.Model.Settings', TIMESTAMPS], + ['PlaceOS.Model.Shortener', [...TIMESTAMPS, 'valid_from', 'valid_until']], + ['PlaceOS.Model.SignagePlugin', TIMESTAMPS], + ['PlaceOS.Model.Storage', TIMESTAMPS], + ['PlaceOS.Model.Trigger', TIMESTAMPS], + ['PlaceOS.Model.Trigger.Conditions.TimeDependent', ['time']], + ['PlaceOS.Model.TriggerInstance', TIMESTAMPS], + ['PlaceOS.Model.Upload', TIMESTAMPS], + ['PlaceOS.Model.User.AdminMetadataResponse', ['created_at', 'last_login']], + ['PlaceOS.Model.User.AdminResponse', ['created_at', 'last_login']], + ['PlaceOS.Model.User.PublicMetadataResponse', ['created_at', 'last_login']], + ['PlaceOS.Model.User.PublicResponse', ['created_at', 'last_login']], + ['PlaceOS.Model.Zone', TIMESTAMPS], +]); + +/** + * The `date-time` fields that really are RFC 3339 strings: models with `PgORM::Timestamps`, and + * `Time` fields without a converter. With `EPOCH_FIELDS`, each `date-time` field of a named schema + * must be in one list, so that a new field gets a decision. + */ +const STRING_TIME_FIELDS: ReadonlyMap = new Map([ + ['PlaceOS.Api.BuildMonitor.TaskStatus', ['timestamp']], + ['PlaceOS.Api.ChatGPT.Plugin.Details', ['current_time']], + ['PlaceOS.Api.Groups.Invitations.InvitationCreatePayload', ['expires_at']], + ['PlaceOS.Api.MicrosoftNotification.ChangeNotification', ['subscriptionExpirationDateTime']], + ['PlaceOS.Api.Root.SourceResyncStatus', ['started_at', 'finished_at']], + ['PlaceOS.Api.Uploads.UploadInfo', ['cache_modified']], + ['PlaceOS.Model.Group', TIMESTAMPS], + ['PlaceOS.Model.GroupInvitation', [...TIMESTAMPS, 'expires_at']], + ['PlaceOS.Model.GroupUser', TIMESTAMPS], + ['PlaceOS.Model.GroupZone', TIMESTAMPS], + ['PlaceOS.Model.PendingMail', [...TIMESTAMPS, 'send_at', 'expiry', 'sent_at', 'rejected_at']], + ['PlaceOS.Model.SignageTemplate', TIMESTAMPS], + ['PlaceOS.Model.SignageTemplate.SystemTemplate', TIMESTAMPS], + ['PlaceOS.Model.Upload', ['cache_modified']], +]); + +/** Operations that send JSON, but have no response schema in the document. */ +const JSON_RESPONSE_OPERATIONS: ReadonlySet = new Set([ + 'PlaceOS::Api::Modules_execute', + 'PlaceOS::Api::Modules_state_value', + 'PlaceOS::Api::Systems_execute', +]); + +/** Names that the core modules export. A generated name must not hide one. */ +const CORE_NAMES: ReadonlySet = new Set([ + 'AnyOperation', + 'AnySchema', + 'Auth', + 'CallError', + 'CallOptions', + 'CallResult', + 'Client', + 'ClientConfig', + 'FetchFunction', + 'HttpMethod', + 'Input', + 'IntegerFormat', + 'JsonValue', + 'ObjectField', + 'Operation', + 'OperationData', + 'OperationInput', + 'Output', + 'PageInfo', + 'Reply', + 'Result', + 'Schema', + 'SchemaError', + 'SchemaNode', + 'Simplify', +]); + +const RESERVED_WORDS: ReadonlySet = new Set( + ( + 'break case catch class const continue debugger default delete do else enum export ' + + 'extends false finally for function if import in instanceof new null return super ' + + 'switch this throw true try typeof var void while with yield let static implements ' + + 'interface package private protected public await' + ).split(' '), +); + +/** Schema keys that change nothing in the output. Other keys stop the generator. */ +const IGNORED_SCHEMA_KEYS: ReadonlySet = new Set(['description', 'example', 'title']); +/** Schema keys that the generator supports. */ +const SCHEMA_KEYS: ReadonlySet = new Set([ + '$ref', + 'additionalProperties', + 'anyOf', + 'enum', + 'format', + 'items', + 'maxItems', + 'minItems', + 'prefixItems', + 'properties', + 'required', + 'type', +]); +const METHODS = ['get', 'post', 'put', 'patch', 'delete'] as const; +const INTEGER_FORMATS: ReadonlySet = new Set(['Int32', 'UInt32', 'Int64']); +const NUMBER_FORMATS: ReadonlySet = new Set(['Float32', 'Float64']); +const STRING_FORMATS: ReadonlySet = new Set(['date-time', 'email', 'uuid']); +/** Named schemas that are only an alias of a JSON type. The output puts them inline. */ +const INLINE_SCHEMA_NAMES: ReadonlySet = new Set(['Bool', 'JSON.Any', 'String']); + +type SpecNode = Readonly>; + +/** One endpoint, ready to write. */ +interface OperationPlan { + readonly operationId: string; + readonly controller: string; + readonly action: string; + readonly method: (typeof METHODS)[number]; + readonly path: string; + readonly pathKeys: readonly string[]; + readonly summary: string; + readonly description: string; + /** Code of the expressions. */ + readonly params: string; + readonly paramsRequired: boolean; + readonly body: string | null; + readonly response: string | null; + readonly imports: Imports; +} + +/** What an expression uses: combinators of the core, and named schemas. */ +interface Imports { + readonly combinators: Set; + readonly schemas: Set; +} + +await main(); + +async function main(): Promise { + const check = process.argv.includes('--check'); + const specText = await downloadSpec(); + const spec = asNode(Bun.YAML.parse(specText), 'the document'); + assert(asString(field(spec, 'openapi'), 'openapi').startsWith('3.'), 'the document is 3.x'); + const components = asNode(field(spec, 'components'), 'components'); + const schemas = asNode(field(components, 'schemas'), 'components.schemas'); + const paths = asNode(field(spec, 'paths'), 'paths'); + + // Read each operation. The emit of its schemas collects the named schemas that it uses. + const operations: OperationPlan[] = []; + const skipped: string[] = []; + for (const [path, itemValue] of Object.entries(paths)) { + const item = asNode(itemValue, `paths.${path}`); + for (const method of METHODS) { + const operationValue = field(item, method); + if (operationValue === undefined) continue; + const plan = planOperation(schemas, path, method, asNode(operationValue, path)); + if (plan === null) { + skipped.push(`${method.toUpperCase()} ${path}`); + } else { + operations.push(plan); + } + } + } + + // A controller sends PATCH and PUT of an update to one action. Keep the PATCH only. + const kept = removeDuplicateUpdates(operations); + + // Emit each named schema that an operation uses, and the schemas that those use. + const named = new Map(); + const pending: string[] = []; + for (const plan of kept) pending.push(...plan.imports.schemas); + const schemaNames = new Map(); + const generatedNames = new Set(); + for (const specName of Object.keys(schemas)) { + if (!isNamedSchema(specName)) continue; + const name = schemaTypeName(specName); + for (const generated of [name, `${name}Input`, `${name}Schema`]) { + assert(!generatedNames.has(generated), `the schema name ${generated} is unique`); + assert(!CORE_NAMES.has(generated), `the schema name ${generated} is not a core name`); + generatedNames.add(generated); + } + schemaNames.set(name, specName); + } + for (let index = 0; index < pending.length; index += 1) { + assert(index <= schemaNames.size * schemaNames.size, 'the schema queue is bounded'); + const name = pending[index] ?? ''; + if (named.has(name)) continue; + const specName = schemaNames.get(name); + assert(specName !== undefined, `the schema ${name} exists`); + const imports: Imports = { combinators: new Set(), schemas: new Set() }; + const node = asNode(field(schemas, specName), specName); + const code = emitNamedSchema(schemas, specName, node, imports); + named.set(name, { code, imports }); + pending.push(...imports.schemas); + } + + const files = new Map(); + files.set(join(GENERATED_DIR, 'schemas.ts'), writeSchemasFile(named)); + const controllers = new Map(); + for (const plan of kept) { + const list = controllers.get(plan.controller) ?? []; + list.push(plan); + controllers.set(plan.controller, list); + } + const namespaces: string[] = []; + for (const controller of [...controllers.keys()].sort()) { + const plans = controllers.get(controller) ?? []; + const fileName = kebabCase(controllerWords(controller)); + files.set(join(OPERATIONS_DIR, `${fileName}.ts`), writeOperationsFile(controller, plans)); + namespaces.push( + `export * as ${camelCase(controllerWords(controller))} from './${fileName}.ts';`, + ); + } + const indexIntro = '/** One namespace for each controller of the API. */'; + files.set( + join(OPERATIONS_DIR, 'index.ts'), + `${HEADER}\n${indexIntro}\n${namespaces.join('\n')}\n`, + ); + + // Format, then write or compare. + const config = (await resolveConfig(join(ROOT, 'package.json'))) ?? {}; + const stale: string[] = []; + for (const [filePath, code] of files) { + const formatted = wrapLongComments(await format(code, { ...config, filepath: filePath })); + const current = await readFile(filePath, 'utf8').catch(() => null); + if (current === formatted) continue; + stale.push(filePath); + if (!check) { + await mkdir(join(filePath, '..'), { recursive: true }); + await writeFile(filePath, formatted); + } + } + // Remove generated files of controllers that the document does not have now. + for (const entry of await readdir(OPERATIONS_DIR)) { + const filePath = join(OPERATIONS_DIR, entry); + if (files.has(filePath)) continue; + const text = await readFile(filePath, 'utf8'); + assert(text.startsWith(HEADER), `${filePath} is a generated file`); + stale.push(filePath); + if (!check) await rm(filePath); + } + + console.log( + `${kept.length} operations in ${controllers.size} controllers, ${named.size} schemas.`, + ); + console.log(`Skipped ${skipped.length} WebSocket endpoints: ${skipped.join(', ')}.`); + if (check && stale.length > 0) { + console.error(`Not up to date. Run \`bun run generate\`:\n ${stale.join('\n ')}`); + process.exit(1); + } + console.log(check ? 'Up to date.' : `Wrote ${stale.length} files.`); +} + +/** Downloads the document. The generator stops if the download fails. */ +async function downloadSpec(): Promise { + const response = await fetch(SPEC_URL, { signal: AbortSignal.timeout(SPEC_TIMEOUT_MS) }); + assert(response.ok, `the download of ${SPEC_URL} succeeds (status ${response.status})`); + const lengthText = response.headers.get('content-length'); + if (lengthText !== null) { + assert(Number(lengthText) <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); + } + const text = await response.text(); + assert(text.length <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); + return text; +} + +/** Reads one operation of the document. Returns `null` for a WebSocket endpoint. */ +function planOperation( + schemas: SpecNode, + path: string, + method: (typeof METHODS)[number], + operation: SpecNode, +): OperationPlan | null { + const operationId = asString(field(operation, 'operationId'), `${path} operationId`); + const idMatch = /^PlaceOS::Api::([A-Za-z:]+)_([a-z0-9_]+)$/.exec(operationId); + assert(idMatch !== null, `${operationId} has the form PlaceOS::Api::Controller_action`); + const controller = idMatch[1] ?? ''; + const action = idMatch[2] ?? ''; + + // The success response. The API has one for each operation. + const responses = asNode(field(operation, 'responses'), `${operationId} responses`); + const successes = Object.keys(responses).filter((status) => /^[123]\d\d$/.test(status)); + assert(successes.length === 1, `${operationId} has one success response`); + const status = successes[0] ?? ''; + if (status === '101') return null; + + const imports: Imports = { combinators: new Set(), schemas: new Set() }; + let response: string | null = null; + const success = asNode(field(responses, status), `${operationId} ${status}`); + const content = field(success, 'content'); + if (JSON_RESPONSE_OPERATIONS.has(operationId)) { + assert(content === undefined, `${operationId} has no response schema to replace`); + imports.combinators.add('json'); + response = 'json()'; + } else if (content !== undefined) { + const schema = asNode(jsonContentSchema(content, operationId), `${operationId} schema`); + response = emitSchema(schemas, schema, imports, 0); + } + + // The parameters: one object schema with the path parameters and the query parameters. + const pathKeys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1] ?? ''); + const fields: string[] = []; + const required: string[] = []; + const parameterNames = new Set(); + for (const parameterValue of asArray(field(operation, 'parameters') ?? [], operationId)) { + const parameter = asNode(parameterValue, `${operationId} parameter`); + const name = asString(field(parameter, 'name'), `${operationId} parameter name`); + const location = asString(field(parameter, 'in'), `${operationId} ${name} in`); + assert(location === 'path' || location === 'query', `${operationId} ${name} is supported`); + assert(!parameterNames.has(name), `${operationId} ${name} is unique`); + assert(name !== 'body', `${operationId} has no parameter named body`); + parameterNames.add(name); + if (location === 'path') { + assert(pathKeys.includes(name), `${operationId} ${name} is in the path`); + required.push(name); + } else if (field(parameter, 'required') === true) { + required.push(name); + } + const schema = asNode(field(parameter, 'schema'), `${operationId} ${name} schema`); + const expression = emitSchema(schemas, schema, imports, 0); + const description = optionalString(field(parameter, 'description'), name) ?? ''; + fields.push(`${docComment(description, 4)}${propertyKey(name)}: ${expression},`); + } + for (const key of pathKeys) { + assert(parameterNames.has(key), `${operationId} has a path parameter ${key}`); + } + imports.combinators.add('parameters'); + const requiredList = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; + const params = `parameters({\n${fields.join('\n')}\n}${requiredList})`; + + let body: string | null = null; + const requestBody = field(operation, 'requestBody'); + if (requestBody !== undefined) { + const bodyNode = asNode(requestBody, `${operationId} requestBody`); + assert(field(bodyNode, 'required') === true, `${operationId} requires its body`); + const schema = asNode( + jsonContentSchema(field(bodyNode, 'content'), operationId), + `${operationId} body schema`, + ); + body = emitSchema(schemas, schema, imports, 0); + } + + return { + operationId, + controller, + action, + method, + path, + pathKeys, + summary: optionalString(field(operation, 'summary'), `${operationId} summary`) ?? '', + description: optionalString(field(operation, 'description'), operationId) ?? '', + params, + paramsRequired: required.length > 0 || body !== null, + body, + response, + imports, + }; +} + +/** + * The server routes PATCH and PUT of `update` to one method. The document has both, as `update` + * and `update_2`. This keeps the PATCH, with the name of the action without `_2`. + */ +function removeDuplicateUpdates(operations: readonly OperationPlan[]): OperationPlan[] { + const byKey = new Map(); + for (const plan of operations) byKey.set(`${plan.controller}#${plan.action}`, plan); + const kept: OperationPlan[] = []; + for (const plan of operations) { + const pairAction = plan.action.endsWith('_2') + ? plan.action.slice(0, -2) + : `${plan.action}_2`; + const pair = byKey.get(`${plan.controller}#${pairAction}`); + if (pair === undefined) { + kept.push(plan); + continue; + } + const same = + pair.path === plan.path && + pair.params === plan.params && + pair.body === plan.body && + pair.response === plan.response; + assert(same, `${plan.operationId} has the same signature as ${pair.operationId}`); + const methods = [plan.method, pair.method].sort().join(); + assert(methods === 'patch,put', `${plan.operationId} is a PATCH and PUT pair`); + if (plan.method === 'put') continue; + kept.push({ ...plan, action: plan.action.replace(/_2$/, '') }); + } + return kept; +} + +/** The emit of a named schema. It applies the time field patches to its properties. */ +function emitNamedSchema( + schemas: SpecNode, + specName: string, + node: SpecNode, + imports: Imports, +): string { + const epochFields = new Set(EPOCH_FIELDS.get(specName) ?? []); + const stringFields = new Set(STRING_TIME_FIELDS.get(specName) ?? []); + const name = schemaTypeName(specName); + const description = optionalString(field(node, 'description'), specName) ?? ''; + // The named interfaces make the declaration files and the editor hovers show `Zone`, not the + // full shape at each use. The shape is in the schema only. + const schemaName = `${name}Schema`; + const doc = docComment(description, 0); + if (field(node, 'properties') === undefined) { + assert(epochFields.size === 0, `${specName} has the time fields of the patch`); + imports.combinators.add('Output'); + imports.combinators.add('Input'); + imports.combinators.add('Schema'); + return ( + `const ${schemaName} = ${emitSchema(schemas, node, imports, 0)};\n` + + `${doc}export type ${name} = Output;\n` + + `export type ${name}Input = Input;\n` + + `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schemaName};\n` + ); + } + const timeFields = { specName, epochFields, stringFields }; + const expression = emitObject(schemas, node, imports, 0, timeFields); + imports.combinators.add('Output'); + imports.combinators.add('Input'); + imports.combinators.add('Schema'); + return ( + `const ${schemaName} = ${expression};\n` + + `${doc}export interface ${name} extends Output {}\n` + + `export interface ${name}Input extends Input {}\n` + + `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schemaName};\n` + ); +} + +/** The time field decisions of one named schema. */ +interface TimeFields { + readonly specName: string; + readonly epochFields: ReadonlySet; + readonly stringFields: ReadonlySet; +} + +/** Returns the code of a schema expression, such as `nullable(string())`. */ +function emitSchema(schemas: SpecNode, node: SpecNode, imports: Imports, depth: number): string { + assert(depth < EMIT_DEPTH_MAX, 'the schema depth is less than EMIT_DEPTH_MAX'); + for (const key of Object.keys(node)) { + const supported = IGNORED_SCHEMA_KEYS.has(key) || SCHEMA_KEYS.has(key); + assert(supported, `the schema key "${key}" is supported`); + } + + const ref = field(node, '$ref'); + if (ref !== undefined) { + const specName = asString(ref, '$ref').replace('#/components/schemas/', ''); + assert(Object.hasOwn(schemas, specName), `the schema ${specName} exists`); + if (specName === 'JSON.Any') { + imports.combinators.add('json'); + return 'json()'; + } + if (!isNamedSchema(specName)) { + return emitSchema( + schemas, + asNode(field(schemas, specName), specName), + imports, + depth + 1, + ); + } + const name = schemaTypeName(specName); + imports.schemas.add(name); + return name; + } + + const anyOf = field(node, 'anyOf'); + if (anyOf !== undefined) { + const variants = asArray(anyOf, 'anyOf').map((variant) => asNode(variant, 'anyOf item')); + const others = variants.filter((variant) => field(variant, 'type') !== 'null'); + assert(others.length > 0, 'an anyOf has a variant that is not null'); + const codes = others.map((variant) => emitSchema(schemas, variant, imports, depth + 1)); + let inner = codes[0] ?? ''; + if (codes.length > 1) { + imports.combinators.add('union'); + inner = `union([${codes.join(', ')}])`; + } + if (others.length === variants.length) return inner; + imports.combinators.add('nullable'); + return `nullable(${inner})`; + } + + const enumValue = field(node, 'enum'); + if (enumValue !== undefined) { + const values = asArray(enumValue, 'enum'); + const strings = values.every((value) => typeof value === 'string'); + const integers = values.every((value) => Number.isSafeInteger(value)); + assert(strings || integers, 'an enum has strings only or integers only'); + imports.combinators.add('literal'); + return `literal(${JSON.stringify(values)})`; + } + + const type = field(node, 'type'); + const formatValue = optionalString(field(node, 'format'), 'format'); + switch (type) { + case 'string': + assert( + formatValue === null || STRING_FORMATS.has(formatValue), + `format ${formatValue}`, + ); + imports.combinators.add('string'); + return 'string()'; + case 'integer': + assert( + formatValue === null || INTEGER_FORMATS.has(formatValue), + `format ${formatValue}`, + ); + imports.combinators.add('integer'); + return formatValue === null || formatValue === 'Int64' + ? 'integer()' + : `integer('${formatValue}')`; + case 'number': + assert( + formatValue === null || NUMBER_FORMATS.has(formatValue), + `format ${formatValue}`, + ); + imports.combinators.add('number'); + return 'number()'; + case 'boolean': + imports.combinators.add('boolean'); + return 'boolean()'; + case 'array': { + const prefixItems = field(node, 'prefixItems'); + if (prefixItems !== undefined) { + // A Crystal `Tuple`: a fixed length and no other items. + const list = asArray(prefixItems, 'prefixItems'); + assert(field(node, 'items') === false, 'a tuple has no other items'); + assert(field(node, 'minItems') === list.length, 'a tuple has a fixed length'); + assert(field(node, 'maxItems') === list.length, 'a tuple has a fixed length'); + const codes = list.map((item) => + emitSchema(schemas, asNode(item, 'prefixItems item'), imports, depth + 1), + ); + imports.combinators.add('tuple'); + return `tuple([${codes.join(', ')}])`; + } + assert(field(node, 'minItems') === undefined, 'an array has no minItems'); + assert(field(node, 'maxItems') === undefined, 'an array has no maxItems'); + imports.combinators.add('array'); + const items = field(node, 'items'); + if (items === undefined) { + imports.combinators.add('json'); + return 'array(json())'; + } + return `array(${emitSchema(schemas, asNode(items, 'items'), imports, depth + 1)})`; + } + case 'object': { + if (field(node, 'properties') !== undefined) { + return emitObject(schemas, node, imports, depth, null); + } + const values = field(node, 'additionalProperties'); + if (isRecord(values)) { + imports.combinators.add('record'); + return `record(${emitSchema(schemas, values, imports, depth + 1)})`; + } + // The server writes `JSON::Any` as `{ type: object }`, but it can be any JSON value. + imports.combinators.add('json'); + return 'json()'; + } + case undefined: + imports.combinators.add('json'); + return 'json()'; + default: + assert(false, `the schema type ${JSON.stringify(type)} is supported`); + return ''; + } +} + +function emitObject( + schemas: SpecNode, + node: SpecNode, + imports: Imports, + depth: number, + timeFields: TimeFields | null, +): string { + const properties = asNode(field(node, 'properties'), 'properties'); + const required = asArray(field(node, 'required') ?? [], 'required').map((key) => + asString(key, 'required key'), + ); + for (const key of required) assert(Object.hasOwn(properties, key), `required ${key} exists`); + const fields: string[] = []; + for (const [key, value] of Object.entries(properties)) { + assert(key !== '__proto__', 'a property is not named __proto__'); + const property = asNode(value, `property ${key}`); + let description = optionalString(field(property, 'description'), key) ?? ''; + let expression: string; + const isTime = isDateTime(property); + if (timeFields === null) { + expression = emitSchema(schemas, property, imports, depth + 1); + } else if (timeFields.epochFields.has(key)) { + assert(isTime, `${timeFields.specName}.${key} is a date-time to patch`); + imports.combinators.add('integer'); + expression = 'integer()'; + if (isNullable(property)) { + imports.combinators.add('nullable'); + expression = 'nullable(integer())'; + } + const separator = description.length > 0 ? '\n\n' : ''; + description = `${description}${separator}Unix time in seconds.`; + } else { + const known = timeFields.stringFields.has(key); + assert(isTime === known, `${timeFields.specName}.${key} has a time decision`); + expression = emitSchema(schemas, property, imports, depth + 1); + } + fields.push(`${docComment(description, 4)}${propertyKey(key)}: ${expression},`); + } + if (timeFields !== null) { + const keys = [...timeFields.epochFields, ...timeFields.stringFields]; + for (const key of keys) assert(Object.hasOwn(properties, key), `${key} is a property`); + } + imports.combinators.add('object'); + const requiredList = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; + return `object({\n${fields.join('\n')}\n}${requiredList})`; +} + +function isDateTime(node: SpecNode): boolean { + if (field(node, 'format') === 'date-time') return true; + const anyOf = field(node, 'anyOf'); + if (anyOf === undefined) return false; + return asArray(anyOf, 'anyOf').some( + (variant) => field(asNode(variant, 'anyOf'), 'format') === 'date-time', + ); +} + +function isNullable(node: SpecNode): boolean { + const anyOf = field(node, 'anyOf'); + if (anyOf === undefined) return false; + return asArray(anyOf, 'anyOf').some( + (variant) => field(asNode(variant, 'anyOf'), 'type') === 'null', + ); +} + +function jsonContentSchema(content: unknown, operationId: string): unknown { + const contentNode = asNode(content, `${operationId} content`); + const types = Object.keys(contentNode); + assert(types.join() === 'application/json', `${operationId} has JSON content only`); + return field(asNode(field(contentNode, 'application/json'), operationId), 'schema'); +} + +function writeSchemasFile(named: ReadonlyMap): string { + // A `const` must come after the schemas that it uses. The document has no cycles. + const order: string[] = []; + const state = new Map(); + const visit = (name: string, depth: number): void => { + assert(depth <= named.size, 'the schema graph has no cycles'); + const current = state.get(name); + if (current === 'done') return; + assert(current !== 'visiting', `the schema ${name} is not in a cycle`); + state.set(name, 'visiting'); + const entry = named.get(name); + assert(entry !== undefined, `the schema ${name} was emitted`); + for (const dependency of [...entry.imports.schemas].sort()) visit(dependency, depth + 1); + state.set(name, 'done'); + order.push(name); + }; + for (const name of [...named.keys()].sort()) visit(name, 0); + + const combinators = new Set(); + for (const entry of named.values()) { + for (const combinator of entry.imports.combinators) combinators.add(combinator); + } + const body = order.map((name) => named.get(name)?.code ?? '').join('\n'); + return `${HEADER}${importLine([...combinators], '../core/schema.ts')}\n${body}`; +} + +function writeOperationsFile(controller: string, plans: readonly OperationPlan[]): string { + const combinators = new Set(); + const schemaImports = new Set(); + const functionNames = new Set(); + const blocks: string[] = []; + for (const plan of [...plans].sort((a, b) => a.action.localeCompare(b.action, 'en'))) { + for (const name of plan.imports.combinators) combinators.add(name); + for (const name of plan.imports.schemas) schemaImports.add(name); + const functionName = camelCase(plan.action.split('_')); + assert(!RESERVED_WORDS.has(functionName), `${functionName} is not a reserved word`); + assert(!functionNames.has(functionName), `${controller}.${functionName} is unique`); + functionNames.add(functionName); + const constant = plan.action.toUpperCase(); + const method = plan.method.toUpperCase(); + const text = [sentence(plan.summary), plan.description, `\`${method} ${plan.path}\``] + .filter((part) => part.length > 0) + .join('\n\n'); + const inputDefault = plan.paramsRequired ? '' : ' = {}'; + blocks.push( + `${docComment(text, 0)}export function ${functionName}(\n` + + `input: OperationInput${inputDefault},\n` + + `options?: CallOptions,\n` + + `): Promise> {\n` + + `return call(${constant}, input, options);\n}\n\n` + + `const ${constant} = operation({\n` + + `method: '${method}',\n` + + `path: '${plan.path}',\n` + + `pathKeys: ${JSON.stringify(plan.pathKeys)},\n` + + `params: ${plan.params},\n` + + `body: ${plan.body ?? 'null'},\n` + + `response: ${plan.response ?? 'null'},\n` + + `});\n`, + ); + } + const namespace = camelCase(controllerWords(controller)); + const intro = + `/**\n * The \`${controller}\` controller of the API. Import it as the \`${namespace}\` ` + + `namespace.\n *\n * @module\n */\n`; + const schemaLine = + schemaImports.size > 0 + ? `import { ${[...schemaImports].sort().join(', ')} } from '../schemas.ts';\n` + : ''; + return ( + `${HEADER}${intro}` + + `import { call, operation, type CallOptions, type CallResult, ` + + `type OperationInput } from '../../core/client.ts';\n` + + importLine([...combinators], '../../core/schema.ts') + + `${schemaLine}\n${blocks.join('\n')}` + ); +} + +function importLine(names: readonly string[], from: string): string { + const sorted = [...names].sort(); + const types = new Set(['Input', 'Output', 'Schema']); + const parts = sorted.map((name) => (types.has(name) ? `type ${name}` : name)); + return `import { ${parts.join(', ')} } from '${from}';\n`; +} + +/** True for a schema of the document that gets a name in the output. */ +function isNamedSchema(specName: string): boolean { + if (INLINE_SCHEMA_NAMES.has(specName)) return false; + return /^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)*$/.test(specName); +} + +/** `PlaceOS.Model.Playlist.Item` becomes `PlaylistItem`. Acronyms become words: `UserJwt`. */ +function schemaTypeName(specName: string): string { + let name = specName; + for (const prefix of ['PlaceOS.Model.', 'PlaceOS.Api.', 'PlaceOS.Core.Client.', 'PlaceOS.']) { + if (name.startsWith(prefix)) { + name = name.slice(prefix.length); + break; + } + } + return name + .split('.') + .map((segment) => pascalCase(splitWords(segment))) + .join(''); +} + +/** `Groups::Users` becomes the words `groups`, `users`. */ +function controllerWords(controller: string): string[] { + return controller.split('::').flatMap(splitWords); +} + +/** Splits a Crystal name into lower case words. `OAuthApplications` is `oauth`, `applications`. */ +function splitWords(name: string): string[] { + const words = name.replace(/OAuth/g, 'Oauth').match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+/g); + assert(words !== null, `${name} has words`); + assert(words.join('') === name.replace(/OAuth/g, 'Oauth'), `${name} splits into words`); + return words.map((word) => word.toLowerCase()); +} + +function pascalCase(words: readonly string[]): string { + return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(''); +} + +function camelCase(words: readonly string[]): string { + const name = pascalCase(words); + return name.charAt(0).toLowerCase() + name.slice(1); +} + +function kebabCase(words: readonly string[]): string { + return words.join('-'); +} + +function propertyKey(key: string): string { + return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key); +} + +/** `list the zones` becomes `List the zones.` */ +function sentence(text: string): string { + const trimmed = text.trim(); + if (trimmed.length === 0) return ''; + const capital = trimmed.charAt(0).toUpperCase() + trimmed.slice(1); + return /[.!?]$/.test(capital) ? capital : `${capital}.`; +} + +/** + * Wraps the comment lines that are longer than the line width. The formatter can indent a comment + * more than `docComment` knew, and it does not wrap comments. + */ +function wrapLongComments(code: string): string { + const output: string[] = []; + for (const line of code.split('\n')) { + if (line.length <= LINE_WIDTH_MAX) { + output.push(line); + continue; + } + const single = /^(\s*)\/\*\* (.*) \*\/$/.exec(line); + const inner = /^(\s*) \* (.*)$/.exec(line); + const match = single ?? inner; + assert(match !== null, `a long generated line is a comment: ${line}`); + const indent = match[1] ?? ''; + const lines = wrapWords(match[2] ?? '', LINE_WIDTH_MAX - indent.length - 3); + if (single !== null) output.push(`${indent}/**`); + for (const text of lines) output.push(`${indent} * ${text}`); + if (single !== null) output.push(`${indent} */`); + } + return output.join('\n'); +} + +/** Splits text into lines of `width` characters or less. A longer word gets its own line. */ +function wrapWords(text: string, width: number): string[] { + assert(width > 0, 'the wrap width is more than zero'); + const lines: string[] = []; + let line = ''; + for (const word of text.split(/\s+/)) { + if (line.length > 0 && line.length + 1 + word.length > width) { + lines.push(line); + line = word; + } else { + line = line.length > 0 ? `${line} ${word}` : word; + } + } + lines.push(line); + return lines; +} + +/** A JSDoc comment, wrapped to the line width. Empty text gives no comment. */ +function docComment(text: string, indent: number): string { + const trimmed = text.trim(); + if (trimmed.length === 0) return ''; + const width = LINE_WIDTH_MAX - indent - 3; + const lines: string[] = []; + for (const paragraph of trimmed.replaceAll('*/', '*\\/').split(/\n\s*\n/)) { + if (lines.length > 0) lines.push(''); + lines.push(...wrapWords(paragraph, width)); + } + if (lines.length === 1 && (lines[0] ?? '').length + 7 <= width) return `/** ${lines[0]} */\n`; + return `/**\n${lines.map((line) => (line.length > 0 ? ` * ${line}` : ' *')).join('\n')}\n */\n`; +} + +function field(node: SpecNode, key: string): unknown { + return Object.hasOwn(node, key) ? node[key] : undefined; +} + +function asNode(value: unknown, subject: string): SpecNode { + assert(isRecord(value), `${subject} is an object`); + return value; +} + +function asArray(value: unknown, subject: string): readonly unknown[] { + assert(Array.isArray(value), `${subject} is an array`); + const items: readonly unknown[] = value; + return items; +} + +function asString(value: unknown, subject: string): string { + assert(typeof value === 'string', `${subject} is a string`); + return value; +} + +function optionalString(value: unknown, subject: string): string | null { + if (value === undefined) return null; + return asString(value, subject); +} diff --git a/v2/src/core/assert.ts b/v2/src/core/assert.ts new file mode 100644 index 000000000..7d5b36971 --- /dev/null +++ b/v2/src/core/assert.ts @@ -0,0 +1,13 @@ +/** + * Stops the operation on a programmer error. Also narrows the type for the compiler. + * + * Use it for facts that the types cannot say. Do not catch the error and continue. + */ +export function assert(condition: boolean, message: string): asserts condition { + if (!condition) throw new Error(`Assertion failed: ${message}`); +} + +/** Marks the end of an exhaustive `switch`. A new case is then a compile error. */ +export function unreachable(value: never): never { + throw new Error(`Unreachable: ${JSON.stringify(value)}`); +} diff --git a/v2/src/core/client.ts b/v2/src/core/client.ts new file mode 100644 index 000000000..20f434ddc --- /dev/null +++ b/v2/src/core/client.ts @@ -0,0 +1,438 @@ +import { assert, unreachable } from './assert.ts'; +import type { Result } from './result.ts'; +import { + checkRequest, + isRecord, + json, + parseResponse, + type AnySchema, + type Input, + type JsonValue, + type Output, + type SchemaError, + type Simplify, +} from './schema.ts'; + +export const TIMEOUT_MS_DEFAULT = 30_000; +export const RESPONSE_BYTES_MAX_DEFAULT = 64 * 1024 * 1024; +/** A stream can send empty chunks. This stops a read loop that does not get closer to the end. */ +export const RESPONSE_READS_MAX = 1 << 20; + +/** Sends the requests. It has the signature of the global `fetch`, so a test can replace it. */ +export type FetchFunction = (url: string, init: RequestInit) => Promise; + +/** How the client tells the server who it is. */ +export type Auth = + | { readonly kind: 'none' } + /** + * Sends `Authorization: Bearer `. The client calls `token` before each request, so the + * application can refresh the token. `null` means that no token is available. + */ + | { readonly kind: 'bearer'; readonly token: () => string | null | Promise } + /** Sends `X-API-Key: `. */ + | { readonly kind: 'api_key'; readonly key: string }; + +export interface ClientConfig { + /** The origin of the server, for example `https://placeos.example.com`. `''` is this origin. */ + readonly baseUrl: string; + readonly auth: Auth; + /** Headers to add to each request. */ + readonly headers?: Readonly>; + /** The default time limit of a request, from the start to the end of the response body. */ + readonly timeoutMs?: number; + /** The maximum size of a response body. A larger body gives a `response_too_large` error. */ + readonly responseBytesMax?: number; + readonly fetch?: FetchFunction; +} + +/** The settings that each request uses. Make one with `createClient`. */ +export interface Client { + readonly baseUrl: string; + readonly auth: Auth; + readonly headers: Readonly>; + readonly timeoutMs: number; + readonly responseBytesMax: number; + readonly fetch: FetchFunction; +} + +export interface CallOptions { + /** The client for this request. Without it, the call uses the client of `configure`. */ + readonly client?: Client; + /** Cancels the request. */ + readonly signal?: AbortSignal; + /** Replaces the `timeoutMs` of the client for this request. */ + readonly timeoutMs?: number; +} + +/** A request that failed for an expected reason. Each kind is a different action for the caller. */ +export type CallError = + /** The `bearer` auth had no token. */ + | { readonly kind: 'auth_missing' } + /** The `signal` of the caller cancelled the request. */ + | { readonly kind: 'aborted' } + | { readonly kind: 'timeout'; readonly timeoutMs: number } + /** The request did not get a response, for example because the network is down. */ + | { readonly kind: 'network'; readonly message: string } + | { readonly kind: 'response_too_large'; readonly bytesMax: number } + /** The server sent a status that is not 2xx. `message` is the `error` field of the body. */ + | { + readonly kind: 'http'; + readonly status: number; + readonly message: string | null; + readonly body: JsonValue | null; + } + /** The server sent a 2xx body that does not match the schema of the operation. */ + | { + readonly kind: 'response_invalid'; + readonly status: number; + readonly path: string; + readonly expected: string; + }; + +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + +/** + * One endpoint of the API, as data. The generated functions call `call` with an operation. + * + * `params` is an object schema with the path parameters and the query parameters. `response` is + * `null` when the API document gives no schema for the body. The data is then the raw bytes. + */ +export interface Operation< + P extends AnySchema, + B extends AnySchema | null, + R extends AnySchema | null, +> { + readonly method: HttpMethod; + /** The path template, for example `/api/engine/v2/zones/{id}`. */ + readonly path: string; + readonly pathKeys: readonly string[]; + readonly params: P; + readonly body: B; + readonly response: R; +} + +export type AnyOperation = Operation; + +/** The input of an operation: the path and query parameters, and `body` if it has one. */ +export type OperationInput = + O extends Operation + ? B extends AnySchema + ? Simplify & { readonly body: Input }> + : Input

+ : never; + +/** The data of a successful response of an operation. */ +export type OperationData = + O extends Operation + ? R extends AnySchema + ? Output + : Uint8Array + : never; + +export interface Reply { + readonly status: number; + readonly headers: Headers; + readonly data: T; +} + +export type CallResult = Result>, CallError>; + +/** Checks the client settings once, so that each request can trust them. */ +export function createClient(config: ClientConfig): Client { + assert(!config.baseUrl.endsWith('/'), 'the baseUrl has no trailing slash'); + const timeoutMs = config.timeoutMs ?? TIMEOUT_MS_DEFAULT; + assertPositiveInteger(timeoutMs, 'timeoutMs'); + const responseBytesMax = config.responseBytesMax ?? RESPONSE_BYTES_MAX_DEFAULT; + assertPositiveInteger(responseBytesMax, 'responseBytesMax'); + if (config.auth.kind === 'api_key') { + assert(config.auth.key.length > 0, 'the API key is not empty'); + } + // A browser stops `fetch` with "Illegal invocation" when `this` is not the global object. + const fetchFunction: FetchFunction = + config.fetch ?? ((url, init) => globalThis.fetch(url, init)); + return Object.freeze({ + baseUrl: config.baseUrl, + auth: config.auth, + headers: Object.freeze({ ...config.headers }), + timeoutMs, + responseBytesMax, + fetch: fetchFunction, + }); +} + +/** + * The client of `configure`. It is the one module state of the library, so that an application + * does not give its client to each call. + */ +let configuredClient: Client | null = null; + +/** + * Makes the client that each call uses when its options have no `client`. Call it once, when the + * application starts. A second call replaces the client. + * + * ```ts + * configure({ baseUrl: '', auth: { kind: 'bearer', token: () => getToken() } }); + * const result = await zones.show({ id: 'zone-1234' }); + * ``` + */ +export function configure(config: ClientConfig): Client { + configuredClient = createClient(config); + return configuredClient; +} + +/** Defines an operation. It checks the definition when the module loads. */ +export function operation< + P extends AnySchema, + B extends AnySchema | null, + R extends AnySchema | null, +>(definition: Operation): Operation { + assert(definition.path.startsWith('/'), 'the path starts with a slash'); + assert(definition.params.node.kind === 'object', 'the params schema is an object'); + const templateKeys = [...definition.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]); + assert( + templateKeys.join() === definition.pathKeys.join(), + `the path keys of ${definition.path} are in pathKeys`, + ); + return definition; +} + +/** + * Sends a request for `operation` and parses the response. + * + * An expected failure, such as a network error, is in the result. An input that does not match the + * schema is a programmer error, and the call throws. A call without a client, from `options` or + * from `configure`, is also a programmer error. + */ +export async function call( + operation: O, + input: OperationInput, + options: CallOptions = {}, +): Promise> { + // Read the client before the first `await`, so the whole request uses one client. + const client = options.client ?? configuredClient; + assert(client !== null, 'configure() ran before this call, or the options have a client'); + const result = await send(client, operation, input, options); + // `send` parsed the data with `operation.response`, which gives `OperationData` its type. + return result as CallResult; +} + +async function send( + client: Client, + operation: AnyOperation, + input: unknown, + options: CallOptions, +): Promise, CallError>> { + assert(isRecord(input), 'the input is an object'); + const { body, ...params } = input; + + // Check the data immediately before it leaves the program, as a pair to the response parse. + const paramsChecked = checkRequest(operation.params, params); + assertValid(paramsChecked, `the parameters of ${operation.method} ${operation.path}`); + assert(isRecord(paramsChecked.value), 'the checked parameters are an object'); + const url = buildUrl(client.baseUrl, operation, paramsChecked.value); + let bodyText: string | null = null; + if (operation.body === null) { + assert(body === undefined, `${operation.method} ${operation.path} has no body`); + } else { + const bodyChecked = checkRequest(operation.body, body); + assertValid(bodyChecked, `the body of ${operation.method} ${operation.path}`); + bodyText = JSON.stringify(bodyChecked.value); + } + + const headers = new Headers(client.headers); + headers.set('Accept', 'application/json'); + if (bodyText !== null) headers.set('Content-Type', 'application/json'); + switch (client.auth.kind) { + case 'none': + break; + case 'bearer': { + const token = await client.auth.token(); + if (token === null) return { ok: false, error: { kind: 'auth_missing' } }; + headers.set('Authorization', `Bearer ${token}`); + break; + } + case 'api_key': + headers.set('X-API-Key', client.auth.key); + break; + default: + return unreachable(client.auth); + } + + const timeoutMs = options.timeoutMs ?? client.timeoutMs; + assertPositiveInteger(timeoutMs, 'timeoutMs'); + const timeoutSignal = AbortSignal.timeout(timeoutMs); + const signal = + options.signal === undefined + ? timeoutSignal + : AbortSignal.any([options.signal, timeoutSignal]); + + // `fetch` and the body stream throw for operating errors. Convert them to values here. + let response: Response; + let bytes: Result; + try { + const fetchFunction = client.fetch; + response = await fetchFunction(url, { + method: operation.method, + headers, + body: bodyText, + signal, + }); + bytes = await readBody(response, client.responseBytesMax); + } catch (error) { + if (options.signal?.aborted === true) return { ok: false, error: { kind: 'aborted' } }; + if (timeoutSignal.aborted) return { ok: false, error: { kind: 'timeout', timeoutMs } }; + const message = error instanceof Error ? error.message : String(error); + return { ok: false, error: { kind: 'network', message } }; + } + if (!bytes.ok) { + return { + ok: false, + error: { kind: 'response_too_large', bytesMax: client.responseBytesMax }, + }; + } + + if (!response.ok) { + const parsed = parseJson(bytes.value); + let errorBody: JsonValue | null = null; + if (parsed.ok) { + const body = parseResponse(json(), parsed.value); + if (body.ok) errorBody = body.value; + } + let message: string | null = null; + if (isRecord(errorBody) && typeof errorBody['error'] === 'string') { + message = errorBody['error']; + } + return { + ok: false, + error: { kind: 'http', status: response.status, message, body: errorBody }, + }; + } + + const reply = { status: response.status, headers: response.headers }; + if (operation.response === null) return { ok: true, value: { ...reply, data: bytes.value } }; + const parsed = parseJson(bytes.value); + if (!parsed.ok) { + return { + ok: false, + error: { kind: 'response_invalid', status: reply.status, path: '$', expected: 'JSON' }, + }; + } + const data = parseResponse(operation.response, parsed.value); + if (!data.ok) { + return { + ok: false, + error: { kind: 'response_invalid', status: reply.status, ...data.error }, + }; + } + return { ok: true, value: { ...reply, data: data.value } }; +} + +/** + * Puts the path parameters in the path template and the other parameters in the query string. + * + * The server reads an array parameter as one comma-separated value, so items must not contain + * commas. + */ +function buildUrl( + baseUrl: string, + operation: AnyOperation, + params: Readonly>, +): string { + let path = operation.path; + for (const key of operation.pathKeys) { + const text = queryScalar(params[key]); + // An empty segment sends the request to a different endpoint, such as the collection. + assert(text.length > 0, `the path parameter "${key}" is not empty`); + path = path.replace(`{${key}}`, () => encodeURIComponent(text)); + } + + const node = operation.params.node; + assert(node.kind === 'object', 'the params schema is an object'); + const query = new URLSearchParams(); + for (const field of node.fields) { + if (operation.pathKeys.includes(field.key)) continue; + const value = params[field.key]; + if (value === undefined || value === null) continue; + if (Array.isArray(value)) { + const items: readonly unknown[] = value; + query.append(field.key, items.map(queryScalar).join(',')); + } else { + query.append(field.key, queryScalar(value)); + } + } + const queryText = query.toString(); + if (queryText.length === 0) return `${baseUrl}${path}`; + return `${baseUrl}${path}?${queryText}`; +} + +function queryScalar(value: unknown): string { + if (typeof value === 'string') return value; + assert( + typeof value === 'number' || typeof value === 'boolean', + 'a parameter is a string, a number or a boolean', + ); + return String(value); +} + +/** Reads the body, but stops at `bytesMax` bytes. The caller converts a throw to a value. */ +async function readBody( + response: Response, + bytesMax: number, +): Promise> { + const lengthText = response.headers.get('content-length'); + if (lengthText !== null) { + const length = Number(lengthText); + if (Number.isSafeInteger(length) && length > bytesMax) { + await response.body?.cancel(); + return { ok: false, error: 'too_large' }; + } + } + if (response.body === null) return { ok: true, value: new Uint8Array(0) }; + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + for (let read = 0; read < RESPONSE_READS_MAX; read += 1) { + const chunk = await reader.read(); + if (chunk.done) { + const bytes = new Uint8Array(size); + let offset = 0; + for (const part of chunks) { + bytes.set(part, offset); + offset += part.byteLength; + } + assert(offset === size, 'the chunks fill the body'); + return { ok: true, value: bytes }; + } + size += chunk.value.byteLength; + if (size > bytesMax) { + await reader.cancel(); + return { ok: false, error: 'too_large' }; + } + chunks.push(chunk.value); + } + await reader.cancel(); + return { ok: false, error: 'too_large' }; +} + +/** `JSON.parse` throws on bad input. This converts the exception to a value. */ +function parseJson(bytes: Uint8Array): Result { + try { + return { ok: true, value: JSON.parse(new TextDecoder().decode(bytes)) }; + } catch { + return { ok: false, error: 'json_invalid' }; + } +} + +function assertValid( + result: Result, + subject: string, +): asserts result is { readonly ok: true; readonly value: T } { + if (result.ok) return; + assert(false, `${subject} match the schema. At ${result.error.path}: ${result.error.expected}`); +} + +function assertPositiveInteger(value: number, name: string): void { + assert(Number.isSafeInteger(value), `${name} is an integer`); + assert(value > 0, `${name} is more than zero`); +} diff --git a/v2/src/core/pagination.ts b/v2/src/core/pagination.ts new file mode 100644 index 000000000..b070a0628 --- /dev/null +++ b/v2/src/core/pagination.ts @@ -0,0 +1,53 @@ +/** A longer `Link` header is not from this API. The parser ignores it. */ +export const LINK_HEADER_LENGTH_MAX = 8_192; + +/** The pagination data of an index response. */ +export interface PageInfo { + /** The `X-Total-Count` header: the number of results for all pages. */ + readonly total: number | null; + /** The `offset` of the next page, from the `Link` header. `null` on the last page. */ + readonly nextOffset: number | null; +} + +/** + * Reads the pagination headers of an index response. + * + * ```ts + * const first = await zones.index({ limit: 100 }); + * if (first.ok) { + * const page = pageInfo(first.value.headers); + * if (page.nextOffset !== null) { + * const second = await zones.index({ limit: 100, offset: page.nextOffset }); + * } + * } + * ``` + */ +export function pageInfo(headers: Headers): PageInfo { + return { + total: parseCount(headers.get('x-total-count')), + nextOffset: parseNextOffset(headers.get('link')), + }; +} + +function parseCount(text: string | null): number | null { + if (text === null) return null; + const count = Number(text); + if (Number.isSafeInteger(count) && count >= 0) return count; + return null; +} + +/** The server sends `; rel="next"`. Other links are ignored. */ +function parseNextOffset(header: string | null): number | null { + if (header === null) return null; + if (header.length > LINK_HEADER_LENGTH_MAX) return null; + for (const link of header.split(',')) { + const match = /^\s*<([^>]*)>\s*;\s*rel="?next"?\s*$/.exec(link); + if (match === null) continue; + const target = match[1] ?? ''; + // The target is often a path only. The base makes it a URL that `URL` can parse. + if (!URL.canParse(target, 'http://base.invalid')) return null; + const offset = new URL(target, 'http://base.invalid').searchParams.get('offset'); + return parseCount(offset); + } + return null; +} diff --git a/v2/src/core/result.ts b/v2/src/core/result.ts new file mode 100644 index 000000000..f267c7db6 --- /dev/null +++ b/v2/src/core/result.ts @@ -0,0 +1,7 @@ +/** + * The value of an operation that can fail for an expected reason, such as a network error. + * + * Check `ok` before you use `value`. A `throw` is only for programmer errors. + */ +export type Result = + { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }; diff --git a/v2/src/core/schema.ts b/v2/src/core/schema.ts new file mode 100644 index 000000000..f10696fbf --- /dev/null +++ b/v2/src/core/schema.ts @@ -0,0 +1,408 @@ +import { assert, unreachable } from './assert.ts'; +import type { Result } from './result.ts'; + +/** + * Schemas describe the data of the API. Each schema is plain data that `parseResponse` and + * `checkRequest` interpret. The TypeScript types come from the schema with `Output` and `Input`, + * so the shape is written one time only. + * + * ```ts + * const Zone = object({ id: string(), name: nullable(string()) }, ['id']); + * type Zone = Output; // { readonly id: string; readonly name: string | null } + * ``` + */ + +/** The schema tree is generated, so its depth is small. This catches a cycle by mistake. */ +export const SCHEMA_DEPTH_MAX = 64; + +/** Any value that `JSON.parse` can return. */ +export type JsonValue = + null | boolean | number | string | readonly JsonValue[] | { readonly [key: string]: JsonValue }; + +/** The integer formats of the API, and the range of each one. */ +export const INTEGER_RANGES = { + Int32: { min: -(2 ** 31), max: 2 ** 31 - 1 }, + UInt32: { min: 0, max: 2 ** 32 - 1 }, + Int64: { min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER }, +} as const; + +export type IntegerFormat = keyof typeof INTEGER_RANGES; + +/** A node of the schema tree. The parser interprets it. */ +export type SchemaNode = + | { readonly kind: 'string' } + | { readonly kind: 'literal'; readonly values: ReadonlySet } + | { readonly kind: 'integer'; readonly min: number; readonly max: number } + | { readonly kind: 'number' } + | { readonly kind: 'boolean' } + | { readonly kind: 'json' } + | { readonly kind: 'nullable'; readonly inner: SchemaNode } + | { readonly kind: 'array'; readonly items: SchemaNode } + | { readonly kind: 'tuple'; readonly items: readonly SchemaNode[] } + | { readonly kind: 'record'; readonly values: SchemaNode } + | { + readonly kind: 'object'; + readonly fields: readonly ObjectField[]; + readonly keys: ReadonlySet; + } + | { readonly kind: 'union'; readonly variants: readonly SchemaNode[] }; + +export interface ObjectField { + readonly key: string; + readonly node: SchemaNode; + /** The parser fails on a response without this field. */ + readonly requiredInResponse: boolean; + /** The check fails on a request without this field. */ + readonly requiredInRequest: boolean; +} + +/** + * A schema: a node for the parser, and the types for the compiler. + * + * `O` is the type of data that comes from the server. `I` is the type of data that you send. + */ +export interface Schema { + readonly node: SchemaNode; + /** Only for the compiler. It has no value at run time. */ + readonly '~types'?: { readonly output: O; readonly input: I }; +} + +export type AnySchema = Schema; + +/** The type of the data that `parseResponse` returns for a schema. */ +export type Output = S extends Schema ? O : never; + +/** The type of the data that you give to a request for a schema. */ +export type Input = S extends Schema ? I : never; + +/** Shows an intersection as one object type in editor hovers. */ +export type Simplify = { [K in keyof T]: T[K] } & {}; + +/** Where a parse failed, as a path such as `$.items[3].name`, and what the parser expected. */ +export interface SchemaError { + readonly path: string; + readonly expected: string; +} + +export function string(): Schema { + return { node: { kind: 'string' } }; +} + +/** A string or number that must be one of `values`. */ +export function literal( + values: V, +): Schema { + assert(values.length > 0, 'a literal schema has at least one value'); + return { node: { kind: 'literal', values: new Set(values) } }; +} + +/** An integer in the range of `format`. All formats stay in the safe range of `number`. */ +export function integer(format: IntegerFormat = 'Int64'): Schema { + const range = INTEGER_RANGES[format]; + return { node: { kind: 'integer', min: range.min, max: range.max } }; +} + +/** A finite number. */ +export function number(): Schema { + return { node: { kind: 'number' } }; +} + +export function boolean(): Schema { + return { node: { kind: 'boolean' } }; +} + +/** Any JSON value. The parser does not look inside it. */ +export function json(): Schema { + return { node: { kind: 'json' } }; +} + +export function nullable(inner: Schema): Schema { + return { node: { kind: 'nullable', inner: inner.node } }; +} + +export function array(items: Schema): Schema { + return { node: { kind: 'array', items: items.node } }; +} + +/** An array with a fixed length, and a schema for each position. */ +export function tuple( + items: V, +): Schema<{ readonly [K in keyof V]: Output }, { readonly [K in keyof V]: Input }> { + assert(items.length > 0, 'a tuple has at least one item'); + return { node: { kind: 'tuple', items: items.map((item) => item.node) } }; +} + +/** An object with keys that are not known before run time. Each value has the same schema. */ +export function record( + values: Schema, +): Schema>, Readonly>> { + return { node: { kind: 'record', values: values.node } }; +} + +type Fields = { readonly [key: string]: AnySchema }; + +/** + * In a response, a field that is not in `required` can be missing. The parser sets it to `null`, + * so each field of the output is always present. + */ +type ObjectOutput = { + readonly [K in keyof F]: K extends R ? Output : Output | null; +}; + +/** In a request, a field that is not in `R` is optional. */ +type ObjectInput = Simplify< + { readonly [K in keyof F as K extends R ? K : never]: Input } & { + readonly [K in keyof F as K extends R ? never : K]?: Input; + } +>; + +/** + * An object with known fields. The parser drops the fields of a response that it does not know. + * + * `required` lists the fields that the server always sends. In a request each field is optional, + * because the API document does not say which fields the server needs: a field that the server + * always sends can have a default when it reads a request. The server checks the request. + */ +export function object( + fields: F, + required: readonly R[] = [], +): Schema, ObjectInput> { + return { node: objectNode(fields, new Set(required), new Set()) }; +} + +/** + * The path and query parameters of an operation. Unlike `object`, the `required` fields are also + * required in a request, because the document says which parameters the server needs. + */ +export function parameters( + fields: F, + required: readonly R[] = [], +): Schema, ObjectInput> { + const requiredKeys = new Set(required); + return { node: objectNode(fields, requiredKeys, requiredKeys) }; +} + +function objectNode( + fields: Fields, + requiredInResponse: ReadonlySet, + requiredInRequest: ReadonlySet, +): SchemaNode { + const list: ObjectField[] = []; + for (const [key, schema] of Object.entries(fields)) { + // An assignment to `__proto__` changes the prototype instead of a field. + assert(key !== '__proto__', 'a field is not named __proto__'); + list.push({ + key, + node: schema.node, + requiredInResponse: requiredInResponse.has(key), + requiredInRequest: requiredInRequest.has(key), + }); + } + for (const key of [...requiredInResponse, ...requiredInRequest]) { + assert(Object.hasOwn(fields, key), `the required key "${key}" is a field`); + } + return { kind: 'object', fields: list, keys: new Set(Object.keys(fields)) }; +} + +/** + * A value that matches one of `variants`. The parser tries each variant in sequence and returns + * the first match, so put the most specific variant first. + */ +export function union( + variants: V, +): Schema, Input> { + assert(variants.length > 1, 'a union has two variants or more'); + return { node: { kind: 'union', variants: variants.map((variant) => variant.node) } }; +} + +/** + * Parses data that comes from the server. Use it on each value from outside the program. + * + * The output is a new value. It has each field of the schema, in the order of the schema, and no + * other fields. + */ +export function parseResponse(schema: Schema, value: unknown): Result { + const failure: Failure = { expected: '', segments: [] }; + const parsed = walk(schema.node, value, 'response', failure, 0); + if (parsed === FAIL) return { ok: false, error: describeFailure(failure) }; + // The walk built `parsed` from the same nodes that give `O` its shape. This is one of the two + // places where the compiler must trust the parser. The tests check the parser. + return { ok: true, value: parsed as O }; +} + +/** + * Checks data immediately before it goes to the server. The types check it at compile time, and + * this checks it at run time, for callers that pass data the types do not describe. + * + * It does not accept fields that the schema does not know. Optional fields stay missing. + */ +export function checkRequest(schema: Schema, value: I): Result { + const failure: Failure = { expected: '', segments: [] }; + const checked = walk(schema.node, value, 'request', failure, 0); + if (checked === FAIL) return { ok: false, error: describeFailure(failure) }; + // See `parseResponse`. + return { ok: true, value: checked as I }; +} + +/** True for a value that has string keys: an object that is not `null` and not an array. */ +export function isRecord(value: unknown): value is Readonly> { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +type Direction = 'response' | 'request'; + +/** The parser records a failure here. Each level adds its path segment as the failure returns. */ +interface Failure { + expected: string; + segments: string[]; +} + +const FAIL: unique symbol = Symbol('schema-fail'); + +/** + * Interprets `node` on `value`. It returns the clean value, or `FAIL` and records the reason. + * + * The recursion follows the schema, not the data, so the schema sets its depth. + */ +function walk( + node: SchemaNode, + value: unknown, + direction: Direction, + failure: Failure, + depth: number, +): unknown { + assert(depth < SCHEMA_DEPTH_MAX, 'the schema depth is less than SCHEMA_DEPTH_MAX'); + switch (node.kind) { + case 'string': + if (typeof value === 'string') return value; + return fail(failure, 'string'); + case 'literal': + if (typeof value === 'string' || typeof value === 'number') { + if (node.values.has(value)) return value; + } + return fail(failure, `one of ${[...node.values].map(String).join(', ')}`); + case 'integer': + if (typeof value === 'number' && Number.isSafeInteger(value)) { + if (value >= node.min && value <= node.max) return value; + } + return fail(failure, `integer from ${node.min} to ${node.max}`); + case 'number': + if (typeof value === 'number' && Number.isFinite(value)) return value; + return fail(failure, 'finite number'); + case 'boolean': + if (typeof value === 'boolean') return value; + return fail(failure, 'boolean'); + case 'json': + if (value === undefined) return fail(failure, 'JSON value'); + return value; + case 'nullable': + if (value === null) return null; + return walk(node.inner, value, direction, failure, depth + 1); + case 'array': { + if (!Array.isArray(value)) return fail(failure, 'array'); + const items: readonly unknown[] = value; + const output: unknown[] = []; + for (let index = 0; index < items.length; index += 1) { + const item = walk(node.items, items[index], direction, failure, depth + 1); + if (item === FAIL) { + failure.segments.push(`[${index}]`); + return FAIL; + } + output.push(item); + } + return output; + } + case 'tuple': { + if (!Array.isArray(value)) return fail(failure, 'array'); + const items: readonly unknown[] = value; + if (items.length !== node.items.length) { + return fail(failure, `array of length ${node.items.length}`); + } + const output: unknown[] = []; + for (let index = 0; index < node.items.length; index += 1) { + const itemNode = node.items[index]; + assert(itemNode !== undefined, 'the index is in the tuple'); + const item = walk(itemNode, items[index], direction, failure, depth + 1); + if (item === FAIL) { + failure.segments.push(`[${index}]`); + return FAIL; + } + output.push(item); + } + return output; + } + case 'record': { + if (!isRecord(value)) return fail(failure, 'object'); + const entries: [string, unknown][] = []; + for (const key of Object.keys(value)) { + const entryValue = value[key]; + if (entryValue === undefined) { + assert(direction === 'request', 'JSON has no undefined values'); + continue; + } + const entry = walk(node.values, entryValue, direction, failure, depth + 1); + if (entry === FAIL) { + failure.segments.push(`.${key}`); + return FAIL; + } + entries.push([key, entry]); + } + // `fromEntries` defines each key as a field, also a key such as `__proto__`. + return Object.fromEntries(entries); + } + case 'object': { + if (!isRecord(value)) return fail(failure, 'object'); + const output: Record = {}; + for (const field of node.fields) { + const fieldValue = Object.hasOwn(value, field.key) ? value[field.key] : undefined; + if (fieldValue === undefined) { + const required = + direction === 'response' + ? field.requiredInResponse + : field.requiredInRequest; + if (required) { + failure.segments.push(`.${field.key}`); + return fail(failure, 'a value for the required field'); + } + // A response has each field. A request leaves an optional field missing, + // because the server reads a missing field and `null` differently. + if (direction === 'response') output[field.key] = null; + continue; + } + const parsed = walk(field.node, fieldValue, direction, failure, depth + 1); + if (parsed === FAIL) { + failure.segments.push(`.${field.key}`); + return FAIL; + } + output[field.key] = parsed; + } + if (direction === 'request') { + for (const key of Object.keys(value)) { + if (node.keys.has(key)) continue; + if (value[key] === undefined) continue; + failure.segments.push(`.${key}`); + return fail(failure, 'no field with this name'); + } + } + return output; + } + case 'union': + for (const variant of node.variants) { + const parsed = walk(variant, value, direction, failure, depth + 1); + if (parsed !== FAIL) return parsed; + failure.segments.length = 0; + } + return fail(failure, 'a match for one variant of the union'); + default: + return unreachable(node); + } +} + +function fail(failure: Failure, expected: string): typeof FAIL { + failure.expected = expected; + return FAIL; +} + +function describeFailure(failure: Failure): SchemaError { + return { path: `$${failure.segments.reverse().join('')}`, expected: failure.expected }; +} diff --git a/v2/src/generated/operations/alert-dashboards.ts b/v2/src/generated/operations/alert-dashboards.ts new file mode 100644 index 000000000..47280e744 --- /dev/null +++ b/v2/src/generated/operations/alert-dashboards.ts @@ -0,0 +1,177 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `AlertDashboards` controller of the API. Import it as the `alertDashboards` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { Alert, AlertDashboard } from '../schemas.ts'; + +/** + * Get all alerts for a dashboard. + * + * `GET /api/engine/v2/alert_dashboards/{id}/alerts` + */ +export function alerts( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(ALERTS, input, options); +} + +const ALERTS = operation({ + method: 'GET', + path: '/api/engine/v2/alert_dashboards/{id}/alerts', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: array(Alert), +}); + +/** + * Adds a new alert dashboard. + * + * `POST /api/engine/v2/alert_dashboards` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/alert_dashboards', + pathKeys: [], + params: parameters({}), + body: AlertDashboard, + response: AlertDashboard, +}); + +/** + * Removes an alert dashboard. + * + * `DELETE /api/engine/v2/alert_dashboards/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/alert_dashboards/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List the alert dashboards. + * + * `GET /api/engine/v2/alert_dashboards` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/alert_dashboards', + pathKeys: [], + params: parameters({ + /** return dashboards for a specific authority */ + authority_id: nullable(string()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(AlertDashboard), +}); + +/** + * Returns the details of an alert dashboard. + * + * `GET /api/engine/v2/alert_dashboards/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/alert_dashboards/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: AlertDashboard, +}); + +/** + * Updates an alert dashboard. + * + * `PATCH /api/engine/v2/alert_dashboards/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/alert_dashboards/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: AlertDashboard, + response: AlertDashboard, +}); diff --git a/v2/src/generated/operations/alerts.ts b/v2/src/generated/operations/alerts.ts new file mode 100644 index 000000000..288d90f39 --- /dev/null +++ b/v2/src/generated/operations/alerts.ts @@ -0,0 +1,159 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Alerts` controller of the API. Import it as the `alerts` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { Alert } from '../schemas.ts'; + +/** + * Adds a new alert. + * + * `POST /api/engine/v2/alerts` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/alerts', + pathKeys: [], + params: parameters({}), + body: Alert, + response: Alert, +}); + +/** + * Removes an alert. + * + * `DELETE /api/engine/v2/alerts/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/alerts/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List the alerts. + * + * `GET /api/engine/v2/alerts` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/alerts', + pathKeys: [], + params: parameters({ + /** return alerts for a specific dashboard */ + alert_dashboard_id: nullable(string()), + /** filter by alert severity */ + severity: nullable(string()), + /** filter by alert type */ + alert_type: nullable(string()), + /** filter by enabled status */ + enabled: nullable(boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Alert), +}); + +/** + * Returns the details of an alert. + * + * `GET /api/engine/v2/alerts/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/alerts/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + /** return the dashboard associated with this alert */ + dashboard: nullable(boolean()), + }, + ['id'], + ), + body: null, + response: Alert, +}); + +/** + * Updates an alert. + * + * `PATCH /api/engine/v2/alerts/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/alerts/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Alert, + response: Alert, +}); diff --git a/v2/src/generated/operations/api-keys.ts b/v2/src/generated/operations/api-keys.ts new file mode 100644 index 000000000..c70a547e1 --- /dev/null +++ b/v2/src/generated/operations/api-keys.ts @@ -0,0 +1,172 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `ApiKeys` controller of the API. Import it as the `apiKeys` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { ApiKey, ApiKeysResponse, UserJwt } from '../schemas.ts'; + +/** + * Create a new API key. + * + * `POST /api/engine/v2/api_keys` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/api_keys', + pathKeys: [], + params: parameters({}), + body: ApiKey, + response: ApiKeysResponse, +}); + +/** + * Remove an API key. + * + * `DELETE /api/engine/v2/api_keys/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/api_keys/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Returns a list of the API keys associated with the provided domain, otherwise all domains. + * + * `GET /api/engine/v2/api_keys` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/api_keys', + pathKeys: [], + params: parameters({ + /** the ID of the domain to be listed */ + authority_id: nullable(string()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(ApiKeysResponse), +}); + +/** + * Obtain the a JSON JWT representation of the API key permissions. + * + * `GET /api/engine/v2/api_keys/inspect` + */ +export function inspectKey( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INSPECT_KEY, input, options); +} + +const INSPECT_KEY = operation({ + method: 'GET', + path: '/api/engine/v2/api_keys/inspect', + pathKeys: [], + params: parameters({}), + body: null, + response: UserJwt, +}); + +/** + * Returns the requested API key details. + * + * `GET /api/engine/v2/api_keys/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/api_keys/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: ApiKeysResponse, +}); + +/** + * Updates an API key name, description user or scopes. + * + * `PATCH /api/engine/v2/api_keys/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/api_keys/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: ApiKey, + response: ApiKeysResponse, +}); diff --git a/v2/src/generated/operations/asset-categories.ts b/v2/src/generated/operations/asset-categories.ts new file mode 100644 index 000000000..d0f982f00 --- /dev/null +++ b/v2/src/generated/operations/asset-categories.ts @@ -0,0 +1,154 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `AssetCategories` controller of the API. Import it as the `assetCategories` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { AssetCategory } from '../schemas.ts'; + +/** + * Create an asset category. + * + * `POST /api/engine/v2/asset_categories` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/asset_categories', + pathKeys: [], + params: parameters({}), + body: AssetCategory, + response: AssetCategory, +}); + +/** + * Delete an asset category. + * + * `DELETE /api/engine/v2/asset_categories/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/asset_categories/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List asset categories. + * + * `GET /api/engine/v2/asset_categories` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/asset_categories', + pathKeys: [], + params: parameters({ + /** + * true returns only hidden categories, false only non-hidden categories; omit to return all + * categories + */ + hidden: nullable(boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(AssetCategory), +}); + +/** + * Get a single asset category. + * + * `GET /api/engine/v2/asset_categories/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/asset_categories/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: AssetCategory, +}); + +/** + * Update an asset category with the fields in the request body and return the saved category. + * + * `PATCH /api/engine/v2/asset_categories/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/asset_categories/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: AssetCategory, + response: AssetCategory, +}); diff --git a/v2/src/generated/operations/asset-purchase-orders.ts b/v2/src/generated/operations/asset-purchase-orders.ts new file mode 100644 index 000000000..8c234fae4 --- /dev/null +++ b/v2/src/generated/operations/asset-purchase-orders.ts @@ -0,0 +1,151 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `AssetPurchaseOrders` controller of the API. Import it as the `assetPurchaseOrders` + * namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { AssetPurchaseOrder } from '../schemas.ts'; + +/** + * Create an asset purchase order. + * + * `POST /api/engine/v2/asset_purchase_orders` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/asset_purchase_orders', + pathKeys: [], + params: parameters({}), + body: AssetPurchaseOrder, + response: AssetPurchaseOrder, +}); + +/** + * Delete an asset purchase order. + * + * `DELETE /api/engine/v2/asset_purchase_orders/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List asset purchase orders. + * + * `GET /api/engine/v2/asset_purchase_orders` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/asset_purchase_orders', + pathKeys: [], + params: parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(AssetPurchaseOrder), +}); + +/** + * Get a single asset purchase order. + * + * `GET /api/engine/v2/asset_purchase_orders/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: AssetPurchaseOrder, +}); + +/** + * Update an asset purchase order with the fields in the request body and return the saved purchase + * order. + * + * `PATCH /api/engine/v2/asset_purchase_orders/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: AssetPurchaseOrder, + response: AssetPurchaseOrder, +}); diff --git a/v2/src/generated/operations/asset-types.ts b/v2/src/generated/operations/asset-types.ts new file mode 100644 index 000000000..5ee04c175 --- /dev/null +++ b/v2/src/generated/operations/asset-types.ts @@ -0,0 +1,161 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `AssetTypes` controller of the API. Import it as the `assetTypes` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { AssetType } from '../schemas.ts'; + +/** + * Create an asset type. + * + * `POST /api/engine/v2/asset_types` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/asset_types', + pathKeys: [], + params: parameters({}), + body: AssetType, + response: AssetType, +}); + +/** + * Delete an asset type. + * + * `DELETE /api/engine/v2/asset_types/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/asset_types/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List asset types, each with a count of its assets. + * + * `GET /api/engine/v2/asset_types` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/asset_types', + pathKeys: [], + params: parameters({ + /** only return asset types with exactly this brand */ + brand: nullable(string()), + /** only return asset types with exactly this model number */ + model_number: nullable(string()), + /** only return asset types in this asset category id */ + category_id: nullable(string()), + /** + * limits asset_count to assets whose zone_id is this zone id; does not filter the asset + * types + * returned + */ + zone_id: nullable(string()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(AssetType), +}); + +/** + * Get a single asset type. + * + * `GET /api/engine/v2/asset_types/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/asset_types/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: AssetType, +}); + +/** + * Update an asset type with the fields in the request body and return the saved asset type. + * + * `PATCH /api/engine/v2/asset_types/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/asset_types/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: AssetType, + response: AssetType, +}); diff --git a/v2/src/generated/operations/assets.ts b/v2/src/generated/operations/assets.ts new file mode 100644 index 000000000..e8e28e764 --- /dev/null +++ b/v2/src/generated/operations/assets.ts @@ -0,0 +1,232 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Assets` controller of the API. Import it as the `assets` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { Asset } from '../schemas.ts'; + +/** + * Create several assets; the body is a JSON array of assets. + * + * `POST /api/engine/v2/assets/bulk` + */ +export function bulkCreate( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_CREATE, input, options); +} + +const BULK_CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/assets/bulk', + pathKeys: [], + params: parameters({}), + body: array(Asset), + response: array(Asset), +}); + +/** + * Delete several assets; the body is a JSON array of asset ids. + * + * `DELETE /api/engine/v2/assets/bulk` + */ +export function bulkDestroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_DESTROY, input, options); +} + +const BULK_DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/assets/bulk', + pathKeys: [], + params: parameters({}), + body: array(string()), + response: null, +}); + +/** + * Update several assets; the body is a JSON array of assets, each with its `id`. + * + * `PATCH /api/engine/v2/assets/bulk` + */ +export function bulkUpdate( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_UPDATE, input, options); +} + +const BULK_UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/assets/bulk', + pathKeys: [], + params: parameters({}), + body: array(Asset), + response: array(Asset), +}); + +/** + * Create an asset. + * + * `POST /api/engine/v2/assets` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/assets', + pathKeys: [], + params: parameters({}), + body: Asset, + response: Asset, +}); + +/** + * Delete an asset. + * + * `DELETE /api/engine/v2/assets/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/assets/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List assets, filtered by the params provided. + * + * `GET /api/engine/v2/assets` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/assets', + pathKeys: [], + params: parameters({ + /** only return assets whose zone_id field is this zone id */ + zone_id: nullable(string()), + /** + * comma separated zone ids; only return assets whose zones list contains every one of them + */ + zones: nullable(array(string())), + /** only return assets of this asset type id */ + type_id: nullable(string()), + /** only return assets acquired on this asset purchase order id */ + order_id: nullable(string()), + /** only return assets with exactly this barcode */ + barcode: nullable(string()), + /** only return assets with exactly this serial number */ + serial_number: nullable(string()), + /** true returns only bookable assets, false only non-bookable assets; omit for both */ + bookable: nullable(boolean()), + /** true returns only accessible assets, false only non-accessible assets; omit for both */ + accessible: nullable(boolean()), + /** comma separated features; returns assets that have any of these features */ + features: nullable(array(string())), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Asset), +}); + +/** + * Get a single asset. + * + * `GET /api/engine/v2/assets/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/assets/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: Asset, +}); + +/** + * Update an asset with the fields in the request body and return the saved asset. + * + * `PATCH /api/engine/v2/assets/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/assets/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Asset, + response: Asset, +}); diff --git a/v2/src/generated/operations/brokers.ts b/v2/src/generated/operations/brokers.ts new file mode 100644 index 000000000..4dd8b1c84 --- /dev/null +++ b/v2/src/generated/operations/brokers.ts @@ -0,0 +1,135 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Brokers` controller of the API. Import it as the `brokers` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, parameters, string } from '../../core/schema.ts'; +import { Broker } from '../schemas.ts'; + +/** + * Returns the list of MQTT brokers receiving state information. + * + * `GET /api/engine/v2/brokers` + */ +export function collection( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(COLLECTION, input, options); +} + +const COLLECTION = operation({ + method: 'GET', + path: '/api/engine/v2/brokers', + pathKeys: [], + params: parameters({}), + body: null, + response: array(Broker), +}); + +/** + * Adds a new broker. + * + * `POST /api/engine/v2/brokers` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/brokers', + pathKeys: [], + params: parameters({}), + body: Broker, + response: Broker, +}); + +/** + * Removes a broker. + * + * `DELETE /api/engine/v2/brokers/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/brokers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Returns the details of the selected broker. + * + * `GET /api/engine/v2/brokers/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/brokers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: Broker, +}); + +/** + * Updates the details of a broker. + * + * `PATCH /api/engine/v2/brokers/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/brokers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Broker, + response: Broker, +}); diff --git a/v2/src/generated/operations/build-monitor.ts b/v2/src/generated/operations/build-monitor.ts new file mode 100644 index 000000000..f2056f364 --- /dev/null +++ b/v2/src/generated/operations/build-monitor.ts @@ -0,0 +1,61 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `BuildMonitor` controller of the API. Import it as the `buildMonitor` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, parameters, string, union } from '../../core/schema.ts'; +import { BuildMonitorCancelStatus, BuildMonitorTaskStatus, State } from '../schemas.ts'; + +/** `DELETE /api/engine/v2/build/cancel/{job}` */ +export function cancel( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CANCEL, input, options); +} + +const CANCEL = operation({ + method: 'DELETE', + path: '/api/engine/v2/build/cancel/{job}', + pathKeys: ['job'], + params: parameters( + { + /** ID of previously submitted compilation job */ + job: string(), + }, + ['job'], + ), + body: null, + response: BuildMonitorCancelStatus, +}); + +/** `GET /api/engine/v2/build/monitor` */ +export function monitor( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(MONITOR, input, options); +} + +const MONITOR = operation({ + method: 'GET', + path: '/api/engine/v2/build/monitor', + pathKeys: [], + params: parameters({ + /** + * state of job to return. One of [pending,running,cancelled error,done]. Defaults to + * 'pending' + */ + state: State, + }), + body: null, + response: union([array(BuildMonitorTaskStatus), string()]), +}); diff --git a/v2/src/generated/operations/chat-gpt-plugin.ts b/v2/src/generated/operations/chat-gpt-plugin.ts new file mode 100644 index 000000000..4ba7ed634 --- /dev/null +++ b/v2/src/generated/operations/chat-gpt-plugin.ts @@ -0,0 +1,123 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `ChatGPT::Plugin` controller of the API. Import it as the `chatGptPlugin` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, json, object, parameters, record, string, union } from '../../core/schema.ts'; +import { ChatGptPluginDetails } from '../schemas.ts'; + +/** + * Executes functionality offered by a capability, you'll need to obtain the function schema to + * perform requests. Then to use this operation you'll need to provide the capability id and the + * function name params. + * + * `POST /api/engine/v2/chatgpt/plugin/{system_id}/call_function/{capability_id}/{function_name}` + */ +export function callFunction( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CALL_FUNCTION, input, options); +} + +const CALL_FUNCTION = operation({ + method: 'POST', + path: '/api/engine/v2/chatgpt/plugin/{system_id}/call_function/{capability_id}/{function_name}', + pathKeys: ['system_id', 'capability_id', 'function_name'], + params: parameters( + { + system_id: string(), + /** The ID of the capability, exactly as provided in the capability list */ + capability_id: string(), + /** The name of the function to call */ + function_name: string(), + }, + ['system_id', 'capability_id', 'function_name'], + ), + body: object( + { + function_params: union([record(json()), string()]), + }, + ['function_params'], + ), + response: object( + { + response: string(), + }, + ['response'], + ), +}); + +/** + * Obtain the list of capabilities that this API can provide, must be called if the user requests + * some related functionality, to obtain details of the current user such as their name and email + * address and the current local time of the user. + * + * `GET /api/engine/v2/chatgpt/plugin/{system_id}/capabilities` + */ +export function capabilities( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CAPABILITIES, input, options); +} + +const CAPABILITIES = operation({ + method: 'GET', + path: '/api/engine/v2/chatgpt/plugin/{system_id}/capabilities', + pathKeys: ['system_id'], + params: parameters( + { + system_id: string(), + }, + ['system_id'], + ), + body: null, + response: ChatGptPluginDetails, +}); + +/** + * If a request could benefit from a capability, obtain the list of function schemas by providing + * the id string. + * + * `GET /api/engine/v2/chatgpt/plugin/{system_id}/function_schema/{capability_id}` + */ +export function functionSchema( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(FUNCTION_SCHEMA, input, options); +} + +const FUNCTION_SCHEMA = operation({ + method: 'GET', + path: '/api/engine/v2/chatgpt/plugin/{system_id}/function_schema/{capability_id}', + pathKeys: ['system_id', 'capability_id'], + params: parameters( + { + system_id: string(), + /** The ID of the capability, exactly as provided in the capability list */ + capability_id: string(), + }, + ['system_id', 'capability_id'], + ), + body: null, + response: array( + object( + { + function: string(), + description: string(), + parameters: record(json()), + }, + ['function', 'description', 'parameters'], + ), + ), +}); diff --git a/v2/src/generated/operations/chat-gpt.ts b/v2/src/generated/operations/chat-gpt.ts new file mode 100644 index 000000000..b86e39f11 --- /dev/null +++ b/v2/src/generated/operations/chat-gpt.ts @@ -0,0 +1,113 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `ChatGPT` controller of the API. Import it as the `chatGpt` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, object, parameters, string } from '../../core/schema.ts'; +import { Chat } from '../schemas.ts'; + +/** + * Remove chat and associated history. + * + * `DELETE /api/engine/v2/chatgpt/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/chatgpt/{id}', + pathKeys: ['id'], + params: parameters( + { + /** the id of the chat to delete */ + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List user chats. + * + * `GET /api/engine/v2/chatgpt` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/chatgpt', + pathKeys: [], + params: parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Chat), +}); + +/** + * Show user chat history. + * + * `GET /api/engine/v2/chatgpt/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/chatgpt/{id}', + pathKeys: ['id'], + params: parameters( + { + /** return the chat messages associated with this chat id */ + id: string(), + }, + ['id'], + ), + body: null, + response: array( + object( + { + role: string(), + content: nullable(string()), + timestamp: string(), + }, + ['role', 'timestamp'], + ), + ), +}); diff --git a/v2/src/generated/operations/cluster.ts b/v2/src/generated/operations/cluster.ts new file mode 100644 index 000000000..b3919d4ab --- /dev/null +++ b/v2/src/generated/operations/cluster.ts @@ -0,0 +1,121 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Cluster` controller of the API. Import it as the `cluster` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, parameters, string } from '../../core/schema.ts'; +import { ClusterDriverStatus, ClusterNodeStatus, ClusterVersions } from '../schemas.ts'; + +/** + * Terminates a driver on the node selected. + * + * `DELETE /api/engine/v2/cluster/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/cluster/{id}', + pathKeys: ['id'], + params: parameters( + { + /** specifies the core node we want to send the request to */ + id: string(), + /** the name of the driver to terminate */ + driver: string(), + }, + ['id', 'driver'], + ), + body: null, + response: null, +}); + +/** + * Returns the list of core nodes running in the cluster. + * + * `GET /api/engine/v2/cluster` + */ +export function nodes( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(NODES, input, options); +} + +const NODES = operation({ + method: 'GET', + path: '/api/engine/v2/cluster', + pathKeys: [], + params: parameters({ + /** return the detailed status of the node including memory and CPU usage? */ + include_status: boolean(), + }), + body: null, + response: array(ClusterNodeStatus), +}); + +/** + * Forces the core nodes to perform a cluster rebalance. + * + * forces the core nodes to perform a cluster rebalance can be useful for debugging when monitoring + * the logs + * + * `POST /api/engine/v2/cluster/rebalance` + */ +export function rebalance( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(REBALANCE, input, options); +} + +const REBALANCE = operation({ + method: 'POST', + path: '/api/engine/v2/cluster/rebalance', + pathKeys: [], + params: parameters({}), + body: null, + response: ClusterVersions, +}); + +/** + * Return the details of a particular core node. + * + * `GET /api/engine/v2/cluster/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/cluster/{id}', + pathKeys: ['id'], + params: parameters( + { + /** specifies the core node we want to send the request to */ + id: string(), + /** return the detailed status of the drivers running on the node? */ + include_status: boolean(), + }, + ['id'], + ), + body: null, + response: array(ClusterDriverStatus), +}); diff --git a/v2/src/generated/operations/domains.ts b/v2/src/generated/operations/domains.ts new file mode 100644 index 000000000..d617a38a2 --- /dev/null +++ b/v2/src/generated/operations/domains.ts @@ -0,0 +1,176 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Domains` controller of the API. Import it as the `domains` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { Authority } from '../schemas.ts'; + +/** + * Add a new domain. + * + * `POST /api/engine/v2/domains` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/domains', + pathKeys: [], + params: parameters({}), + body: Authority, + response: Authority, +}); + +/** + * Remove a domain. + * + * `DELETE /api/engine/v2/domains/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/domains/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List the domains. + * + * `GET /api/engine/v2/domains` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/domains', + pathKeys: [], + params: parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Authority), +}); + +/** + * Find the domain name by looking into domain registerd email domains. + * + * `GET /api/engine/v2/domains/lookup/{email}` + */ +export function lookup( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(LOOKUP, input, options); +} + +const LOOKUP = operation({ + method: 'GET', + path: '/api/engine/v2/domains/lookup/{email}', + pathKeys: ['email'], + params: parameters( + { + /** User email to lookup domain for */ + email: string(), + }, + ['email'], + ), + body: null, + response: string(), +}); + +/** + * Show the selected domain. + * + * `GET /api/engine/v2/domains/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/domains/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: Authority, +}); + +/** + * Udpate a domains details. + * + * `PATCH /api/engine/v2/domains/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/domains/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Authority, + response: Authority, +}); diff --git a/v2/src/generated/operations/drivers.ts b/v2/src/generated/operations/drivers.ts new file mode 100644 index 000000000..b23d119f3 --- /dev/null +++ b/v2/src/generated/operations/drivers.ts @@ -0,0 +1,259 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Drivers` controller of the API. Import it as the `drivers` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { Driver, DriverRole } from '../schemas.ts'; + +/** + * Check if the driver is available on the cluster. + * + * `GET /api/engine/v2/drivers/{id}/compiled` + */ +export function compiled( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(COMPILED, input, options); +} + +const COMPILED = operation({ + method: 'GET', + path: '/api/engine/v2/drivers/{id}/compiled', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Add a new driver to the cluster. + * + * `POST /api/engine/v2/drivers` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/drivers', + pathKeys: [], + params: parameters({}), + body: Driver, + response: Driver, +}); + +/** + * Remove a driver and its modules from a cluster. + * + * `DELETE /api/engine/v2/drivers/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/drivers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List the drivers available on a cluster. + * + * `GET /api/engine/v2/drivers` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/drivers', + pathKeys: [], + params: parameters({ + /** filter by the type of driver */ + role: nullable(DriverRole), + /** list only drivers for which update is available */ + update_available: nullable(boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Driver), +}); + +/** + * Get the readme for a driver. + * + * `GET /api/engine/v2/drivers/{id}/readme` + */ +export function readme( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(README, input, options); +} + +const README = operation({ + method: 'GET', + path: '/api/engine/v2/drivers/{id}/readme', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: string(), +}); + +/** + * Force recompile a driver, useful if libraries and supporting files have been updated. + * + * `POST /api/engine/v2/drivers/{id}/recompile` + */ +export function recompile( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(RECOMPILE, input, options); +} + +const RECOMPILE = operation({ + method: 'POST', + path: '/api/engine/v2/drivers/{id}/recompile', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: string(), +}); + +/** + * Download and reload driver on core cluster, useful when reloading a re-compiled driver. + * + * `POST /api/engine/v2/drivers/{id}/reload` + */ +export function reload( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(RELOAD, input, options); +} + +const RELOAD = operation({ + method: 'POST', + path: '/api/engine/v2/drivers/{id}/reload', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: string(), +}); + +/** + * View the details of a driver. + * + * `GET /api/engine/v2/drivers/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/drivers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + /** check if the driver is compiled? */ + compilation_status: boolean(), + }, + ['id'], + ), + body: null, + response: Driver, +}); + +/** + * Udpate a drivers details. + * + * `PATCH /api/engine/v2/drivers/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/drivers/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Driver, + response: Driver, +}); diff --git a/v2/src/generated/operations/edges.ts b/v2/src/generated/operations/edges.ts new file mode 100644 index 000000000..ec5f1cc2b --- /dev/null +++ b/v2/src/generated/operations/edges.ts @@ -0,0 +1,464 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Edges` controller of the API. Import it as the `edges` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { + array, + integer, + json, + nullable, + object, + parameters, + record, + string, +} from '../../core/schema.ts'; +import { + ConnectionMetrics, + Edge, + EdgeCreateBody, + EdgeError, + EdgeHealth, + EdgeKeyResponse, + EdgeModuleStatus, + EdgeStatistics, +} from '../schemas.ts'; + +/** + * Manual error cleanup trigger. + * + * `POST /api/engine/v2/edges/monitoring/cleanup` + */ +export function cleanupErrors( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CLEANUP_ERRORS, input, options); +} + +const CLEANUP_ERRORS = operation({ + method: 'POST', + path: '/api/engine/v2/edges/monitoring/cleanup', + pathKeys: [], + params: parameters({ + /** Hours of error history to retain */ + hours: integer('Int32'), + }), + body: null, + response: record(record(json())), +}); + +/** + * Add a new edge location. + * + * `POST /api/engine/v2/edges` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/edges', + pathKeys: [], + params: parameters({}), + body: EdgeCreateBody, + response: EdgeKeyResponse, +}); + +/** + * Remove an edge location. + * + * `DELETE /api/engine/v2/edges/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/edges/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Get connection metrics for a specific edge. + * + * `GET /api/engine/v2/edges/{id}/connections` + */ +export function edgeConnections( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDGE_CONNECTIONS, input, options); +} + +const EDGE_CONNECTIONS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}/connections', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: nullable(ConnectionMetrics), +}); + +/** + * Get errors for a specific edge. + * + * `GET /api/engine/v2/edges/{id}/errors` + */ +export function edgeErrors( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDGE_ERRORS, input, options); +} + +const EDGE_ERRORS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}/errors', + pathKeys: ['id'], + params: parameters( + { + id: string(), + /** Number of recent errors to return */ + limit: integer('Int32'), + /** Error type filter */ + type: nullable(string()), + }, + ['id'], + ), + body: null, + response: array(EdgeError), +}); + +/** + * Get health status for a specific edge. + * + * `GET /api/engine/v2/edges/{id}/health` + */ +export function edgeHealth( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDGE_HEALTH, input, options); +} + +const EDGE_HEALTH = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}/health', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: nullable(EdgeHealth), +}); + +/** + * Get module status for a specific edge. + * + * `GET /api/engine/v2/edges/{id}/modules/status` + */ +export function edgeModuleStatus( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDGE_MODULE_STATUS, input, options); +} + +const EDGE_MODULE_STATUS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}/modules/status', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: EdgeModuleStatus, +}); + +/** + * Get connection metrics for all edges. + * + * `GET /api/engine/v2/edges/connections` + */ +export function edgesConnections( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EDGES_CONNECTIONS, input, options); +} + +const EDGES_CONNECTIONS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/connections', + pathKeys: [], + params: parameters({}), + body: null, + response: record(ConnectionMetrics), +}); + +/** + * Get errors from all edges. + * + * `GET /api/engine/v2/edges/errors` + */ +export function edgesErrors( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EDGES_ERRORS, input, options); +} + +const EDGES_ERRORS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/errors', + pathKeys: [], + params: parameters({ + /** Number of recent errors to return */ + limit: integer('Int32'), + /** Error type filter */ + type: nullable(string()), + }), + body: null, + response: record(array(EdgeError)), +}); + +/** + * Get health status for all edges. + * + * `GET /api/engine/v2/edges/health` + */ +export function edgesHealth( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EDGES_HEALTH, input, options); +} + +const EDGES_HEALTH = operation({ + method: 'GET', + path: '/api/engine/v2/edges/health', + pathKeys: [], + params: parameters({}), + body: null, + response: record(EdgeHealth), +}); + +/** + * Get module failures from all edges. + * + * `GET /api/engine/v2/edges/modules/failures` + */ +export function edgesModuleFailures( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EDGES_MODULE_FAILURES, input, options); +} + +const EDGES_MODULE_FAILURES = operation({ + method: 'GET', + path: '/api/engine/v2/edges/modules/failures', + pathKeys: [], + params: parameters({}), + body: null, + response: record(array(record(json()))), +}); + +/** + * Get overall edge statistics. + * + * `GET /api/engine/v2/edges/statistics` + */ +export function edgesStatistics( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EDGES_STATISTICS, input, options); +} + +const EDGES_STATISTICS = operation({ + method: 'GET', + path: '/api/engine/v2/edges/statistics', + pathKeys: [], + params: parameters({}), + body: null, + response: EdgeStatistics, +}); + +/** + * List the edges in the system. + * + * list the edges in the system. an edge can be thought of as a location and each edge location can + * have multiple nodes servicing it + * + * `GET /api/engine/v2/edges` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/edges', + pathKeys: [], + params: parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Edge), +}); + +/** + * Real-time error summary. + * + * `GET /api/engine/v2/edges/monitoring/summary` + */ +export function monitoringSummary( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(MONITORING_SUMMARY, input, options); +} + +const MONITORING_SUMMARY = operation({ + method: 'GET', + path: '/api/engine/v2/edges/monitoring/summary', + pathKeys: [], + params: parameters({}), + body: null, + response: record(record(json())), +}); + +/** + * Return the details of an edge location. + * + * `GET /api/engine/v2/edges/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: Edge, +}); + +/** + * Admins can obtain the token edge nodes will use to connect to the cluster. + * + * `GET /api/engine/v2/edges/{id}/token` + */ +export function token( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(TOKEN, input, options); +} + +const TOKEN = operation({ + method: 'GET', + path: '/api/engine/v2/edges/{id}/token', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: object( + { + token: string(), + }, + ['token'], + ), +}); + +/** + * Update the details of an edge location. + * + * `PATCH /api/engine/v2/edges/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/edges/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Edge, + response: Edge, +}); diff --git a/v2/src/generated/operations/flux.ts b/v2/src/generated/operations/flux.ts new file mode 100644 index 000000000..ae2241680 --- /dev/null +++ b/v2/src/generated/operations/flux.ts @@ -0,0 +1,35 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Flux` controller of the API. Import it as the `flux` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { parameters, string } from '../../core/schema.ts'; + +/** + * An influxDB proxy endpoint, route compatible with existing influxDB clients. + * + * `POST /api/v2/query` + */ +export function query( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = operation({ + method: 'POST', + path: '/api/v2/query', + pathKeys: [], + params: parameters({}), + body: string(), + response: null, +}); diff --git a/v2/src/generated/operations/groups-history.ts b/v2/src/generated/operations/groups-history.ts new file mode 100644 index 000000000..1dae88ffb --- /dev/null +++ b/v2/src/generated/operations/groups-history.ts @@ -0,0 +1,77 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Groups::History` controller of the API. Import it as the `groupsHistory` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { History } from '../schemas.ts'; + +/** + * List audit entries, newest first. sys_admin sees everything; other. + * + * List audit entries, newest first. sys_admin sees everything; other callers must pass `group_id=` + * and have Manage on it. + * + * `GET /api/engine/v2/group_history` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/group_history', + pathKeys: [], + params: parameters({ + /** only return changes to this group and its memberships */ + group_id: nullable(string()), + /** the maximum number of results to return */ + limit: integer('Int32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('Int32'), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(History), +}); + +/** `GET /api/engine/v2/group_history/{id}` */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/group_history/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: History, +}); diff --git a/v2/src/generated/operations/groups-invitations.ts b/v2/src/generated/operations/groups-invitations.ts new file mode 100644 index 000000000..5095f575c --- /dev/null +++ b/v2/src/generated/operations/groups-invitations.ts @@ -0,0 +1,154 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Groups::Invitations` controller of the API. Import it as the `groupsInvitations` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { + GroupInvitation, + GroupUser, + GroupsInvitationsInvitationCreatePayload, + GroupsInvitationsInvitationCreatedResponse, +} from '../schemas.ts'; + +/** + * Accept the invitation, materialising it into a GroupUser for the. + * + * Accept the invitation, materialising it into a GroupUser for the current user. The invitation row + * is destroyed on success. + * + * `POST /api/engine/v2/group_invitations/{id}/accept` + */ +export function accept( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(ACCEPT, input, options); +} + +const ACCEPT = operation({ + method: 'POST', + path: '/api/engine/v2/group_invitations/{id}/accept', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: GroupUser, +}); + +/** + * Custom body-driven create so we can return the plaintext secret. + * + * Custom body-driven create so we can return the plaintext secret alongside the invitation. + * Authorisation check is inline here (not a before_action) so the body is consumed exactly once. + * + * `POST /api/engine/v2/group_invitations` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/group_invitations', + pathKeys: [], + params: parameters({}), + body: GroupsInvitationsInvitationCreatePayload, + response: GroupsInvitationsInvitationCreatedResponse, +}); + +/** `DELETE /api/engine/v2/group_invitations/{id}` */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/group_invitations/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * List invitations. Optionally filter by `group_id`. Non-admin. + * + * List invitations. Optionally filter by `group_id`. Non-admin callers must have Manage on the + * target group. + * + * `GET /api/engine/v2/group_invitations` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/group_invitations', + pathKeys: [], + params: parameters({ + group_id: nullable(string()), + limit: integer('Int32'), + offset: integer('Int32'), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(GroupInvitation), +}); + +/** `GET /api/engine/v2/group_invitations/{id}` */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/group_invitations/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: GroupInvitation, +}); diff --git a/v2/src/generated/operations/groups-users.ts b/v2/src/generated/operations/groups-users.ts new file mode 100644 index 000000000..5e5efe843 --- /dev/null +++ b/v2/src/generated/operations/groups-users.ts @@ -0,0 +1,139 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Groups::Users` controller of the API. Import it as the `groupsUsers` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { GroupUser } from '../schemas.ts'; + +/** `POST /api/engine/v2/group_users` */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/group_users', + pathKeys: [], + params: parameters({}), + body: GroupUser, + response: GroupUser, +}); + +/** `DELETE /api/engine/v2/group_users/{user_id}/{group_id}` */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/group_users/{user_id}/{group_id}', + pathKeys: ['user_id', 'group_id'], + params: parameters( + { + user_id: string(), + group_id: string(), + }, + ['user_id', 'group_id'], + ), + body: null, + response: null, +}); + +/** + * GroupUser rows. Optional `group_id` scopes to one group;. + * + * GroupUser rows. Optional `group_id` scopes to one group; `user_id=me` returns the current user's + * own rows. Non-admin callers without Manage on the specified group see only their own. + * + * `GET /api/engine/v2/group_users` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/group_users', + pathKeys: [], + params: parameters({ + group_id: nullable(string()), + user_id: nullable(string()), + limit: integer('Int32'), + offset: integer('Int32'), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(GroupUser), +}); + +/** `GET /api/engine/v2/group_users/{user_id}/{group_id}` */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/group_users/{user_id}/{group_id}', + pathKeys: ['user_id', 'group_id'], + params: parameters( + { + user_id: string(), + group_id: string(), + }, + ['user_id', 'group_id'], + ), + body: null, + response: GroupUser, +}); + +/** `PATCH /api/engine/v2/group_users/{user_id}/{group_id}` */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/group_users/{user_id}/{group_id}', + pathKeys: ['user_id', 'group_id'], + params: parameters( + { + user_id: string(), + group_id: string(), + }, + ['user_id', 'group_id'], + ), + body: GroupUser, + response: GroupUser, +}); diff --git a/v2/src/generated/operations/groups-zones.ts b/v2/src/generated/operations/groups-zones.ts new file mode 100644 index 000000000..78d5a3414 --- /dev/null +++ b/v2/src/generated/operations/groups-zones.ts @@ -0,0 +1,136 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Groups::Zones` controller of the API. Import it as the `groupsZones` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { GroupZone } from '../schemas.ts'; + +/** `POST /api/engine/v2/group_zones` */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/group_zones', + pathKeys: [], + params: parameters({}), + body: GroupZone, + response: GroupZone, +}); + +/** `DELETE /api/engine/v2/group_zones/{group_id}/{zone_id}` */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', + pathKeys: ['group_id', 'zone_id'], + params: parameters( + { + group_id: string(), + zone_id: string(), + }, + ['group_id', 'zone_id'], + ), + body: null, + response: null, +}); + +/** + * List GroupZone rows. Filterable by group_id / zone_id. + * + * `GET /api/engine/v2/group_zones` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/group_zones', + pathKeys: [], + params: parameters({ + group_id: nullable(string()), + zone_id: nullable(string()), + limit: integer('Int32'), + offset: integer('Int32'), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(GroupZone), +}); + +/** `GET /api/engine/v2/group_zones/{group_id}/{zone_id}` */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', + pathKeys: ['group_id', 'zone_id'], + params: parameters( + { + group_id: string(), + zone_id: string(), + }, + ['group_id', 'zone_id'], + ), + body: null, + response: GroupZone, +}); + +/** `PATCH /api/engine/v2/group_zones/{group_id}/{zone_id}` */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', + pathKeys: ['group_id', 'zone_id'], + params: parameters( + { + group_id: string(), + zone_id: string(), + }, + ['group_id', 'zone_id'], + ), + body: GroupZone, + response: GroupZone, +}); diff --git a/v2/src/generated/operations/groups.ts b/v2/src/generated/operations/groups.ts new file mode 100644 index 000000000..9754ae206 --- /dev/null +++ b/v2/src/generated/operations/groups.ts @@ -0,0 +1,245 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Groups` controller of the API. Import it as the `groups` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { + array, + boolean, + integer, + json, + nullable, + parameters, + record, + string, +} from '../../core/schema.ts'; +import { Group, GroupUser, GroupsAdGroupSync, GroupsCurrentGroup } from '../schemas.ts'; + +/** + * Create a new group. A root group (parent_id nil) requires. + * + * Create a new group. A root group (parent_id nil) requires sys_admin; a child group requires + * Manage on the parent. + * + * `POST /api/engine/v2/groups` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/groups', + pathKeys: [], + params: parameters({}), + body: Group, + response: Group, +}); + +/** `GET /api/engine/v2/groups/current` */ +export function current( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CURRENT, input, options); +} + +const CURRENT = operation({ + method: 'GET', + path: '/api/engine/v2/groups/current', + pathKeys: [], + params: parameters({ + /** filter to groups participating in this subsystem (e.g. 'signage') */ + subsystem: nullable(string()), + }), + body: null, + response: array(GroupsCurrentGroup), +}); + +/** + * Destroy a group (cascades children and junctions via FK). + * + * `DELETE /api/engine/v2/groups/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/groups/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Effective feature flags for this group. + * + * Effective feature flags for this group. The group's own `features` merged over every ancestor's, + * per subsystem, with the deepest group winning each key. Shape: `{subsystem => {key => value}}`. + * + * `GET /api/engine/v2/groups/{id}/features` + */ +export function features( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(FEATURES, input, options); +} + +const FEATURES = operation({ + method: 'GET', + path: '/api/engine/v2/groups/{id}/features', + pathKeys: ['id'], + params: parameters( + { + id: string(), + /** only return this subsystem's features */ + subsystem: nullable(string()), + }, + ['id'], + ), + body: null, + response: record(record(json())), +}); + +/** + * List groups. sys_admin sees all within the current authority; other. + * + * List groups. sys_admin sees all within the current authority; other users see only groups they're + * a member of (direct or transitive). Optionally filter by `parent_id` for tree queries (pass the + * literal string `root` for root-level groups). Pass `q` for a case-insensitive substring search on + * `name`. + * + * `GET /api/engine/v2/groups` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/groups', + pathKeys: [], + params: parameters({ + /** filter by parent group id; pass 'root' for root-level groups */ + parent_id: nullable(string()), + /** case-insensitive substring search on name (SQL ILIKE) */ + q: nullable(string()), + /** include children_count for each group (useful for tree views) */ + include_children_count: boolean(), + limit: integer('Int32'), + offset: integer('Int32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Group), +}); + +/** + * Show group details. Visible if sys_admin or a member. + * + * `GET /api/engine/v2/groups/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/groups/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: Group, +}); + +/** + * Sync a user's group memberships with their AD groups. + * + * Sync a user's group memberships with their AD groups. Uses each group's `ad_group_mappings` to + * add the user to mapped groups and remove memberships that were auto-assigned from AD groups the + * user has left; manually added memberships are untouched. Returns the user's group memberships in + * the current authority. Requires support or sys_admin. + * + * `POST /api/engine/v2/groups/ad_groups/sync` + */ +export function syncAdGroups( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SYNC_AD_GROUPS, input, options); +} + +const SYNC_AD_GROUPS = operation({ + method: 'POST', + path: '/api/engine/v2/groups/ad_groups/sync', + pathKeys: [], + params: parameters({}), + body: GroupsAdGroupSync, + response: array(GroupUser), +}); + +/** + * Update the group (name / description / parent / features). + * + * Update the group (name / description / parent / features). Changing `features` requires Manage on + * the parent group. + * + * `PATCH /api/engine/v2/groups/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/groups/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: Group, + response: Group, +}); diff --git a/v2/src/generated/operations/history.ts b/v2/src/generated/operations/history.ts new file mode 100644 index 000000000..5c5d98ecd --- /dev/null +++ b/v2/src/generated/operations/history.ts @@ -0,0 +1,120 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `History` controller of the API. Import it as the `history` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { History, PgOrmBase } from '../schemas.ts'; + +/** + * List changes, newest first. + * + * `GET /api/engine/v2/history` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/history', + pathKeys: [], + params: parameters({ + /** only return changes to these resource types (table names) */ + resource_types: nullable(array(string())), + /** exclude changes to these resource types (table names) */ + exclude_resource_types: nullable(array(string())), + /** only return changes to this resource, usually combined with `resource_types` */ + resource_id: nullable(string()), + /** only return changes related to this parent, such as a group, playlist or booking */ + correlation_id: nullable(string()), + /** only return changes made by this user */ + user_id: nullable(string()), + /** only return these kinds of change: create, update, delete, approve or restore */ + actions: nullable(array(string())), + /** only return changes made at or after this time, as a unix epoch */ + period_start: nullable(integer()), + /** only return changes made before this time, as a unix epoch */ + period_end: nullable(integer()), + /** the maximum number of results to return */ + limit: integer('Int32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('Int32'), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(History), +}); + +/** `GET /api/engine/v2/history/{id}` */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/history/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: History, +}); + +/** + * Restores a deleted record from its change history, keeping its id. + * + * Restores a deleted record from its change history, keeping its id. Records deleted alongside it + * are not restored and redacted fields, such as passwords and secrets, are left empty. + * + * `POST /api/engine/v2/history/undelete` + */ +export function undelete( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UNDELETE, input, options); +} + +const UNDELETE = operation({ + method: 'POST', + path: '/api/engine/v2/history/undelete', + pathKeys: [], + params: parameters( + { + /** the type (table name) of the deleted resource */ + resource_type: string(), + /** the id of the deleted resource */ + resource_id: string(), + }, + ['resource_type', 'resource_id'], + ), + body: null, + response: PgOrmBase, +}); diff --git a/v2/src/generated/operations/index.ts b/v2/src/generated/operations/index.ts new file mode 100644 index 000000000..2a8dd1ae4 --- /dev/null +++ b/v2/src/generated/operations/index.ts @@ -0,0 +1,60 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. + +/** One namespace for each controller of the API. */ +export * as alertDashboards from './alert-dashboards.ts'; +export * as alerts from './alerts.ts'; +export * as apiKeys from './api-keys.ts'; +export * as assetCategories from './asset-categories.ts'; +export * as assetPurchaseOrders from './asset-purchase-orders.ts'; +export * as assetTypes from './asset-types.ts'; +export * as assets from './assets.ts'; +export * as brokers from './brokers.ts'; +export * as buildMonitor from './build-monitor.ts'; +export * as chatGpt from './chat-gpt.ts'; +export * as chatGptPlugin from './chat-gpt-plugin.ts'; +export * as cluster from './cluster.ts'; +export * as domains from './domains.ts'; +export * as drivers from './drivers.ts'; +export * as edges from './edges.ts'; +export * as flux from './flux.ts'; +export * as groups from './groups.ts'; +export * as groupsHistory from './groups-history.ts'; +export * as groupsInvitations from './groups-invitations.ts'; +export * as groupsUsers from './groups-users.ts'; +export * as groupsZones from './groups-zones.ts'; +export * as history from './history.ts'; +export * as ldapAuthentications from './ldap-authentications.ts'; +export * as mqtt from './mqtt.ts'; +export * as mapAi from './map-ai.ts'; +export * as metadata from './metadata.ts'; +export * as modules from './modules.ts'; +export * as oauthApplications from './oauth-applications.ts'; +export * as oauthAuthentications from './oauth-authentications.ts'; +export * as pendingMails from './pending-mails.ts'; +export * as playlist from './playlist.ts'; +export * as playlistMedia from './playlist-media.ts'; +export * as publicEvents from './public-events.ts'; +export * as pushNotifications from './push-notifications.ts'; +export * as repositories from './repositories.ts'; +export * as root from './root.ts'; +export * as samlAuthentications from './saml-authentications.ts'; +export * as schema from './schema.ts'; +export * as settings from './settings.ts'; +export * as shortUrl from './short-url.ts'; +export * as signage from './signage.ts'; +export * as signageAi from './signage-ai.ts'; +export * as signageAiProviders from './signage-ai-providers.ts'; +export * as signagePlugins from './signage-plugins.ts'; +export * as signageTemplateMappings from './signage-template-mappings.ts'; +export * as signageTemplates from './signage-templates.ts'; +export * as storages from './storages.ts'; +export * as systemTriggers from './system-triggers.ts'; +export * as systems from './systems.ts'; +export * as tenantConsent from './tenant-consent.ts'; +export * as triggers from './triggers.ts'; +export * as uploads from './uploads.ts'; +export * as urlProxy from './url-proxy.ts'; +export * as users from './users.ts'; +export * as webRtc from './web-rtc.ts'; +export * as webhook from './webhook.ts'; +export * as zones from './zones.ts'; diff --git a/v2/src/generated/operations/ldap-authentications.ts b/v2/src/generated/operations/ldap-authentications.ts new file mode 100644 index 000000000..9c9ed5d92 --- /dev/null +++ b/v2/src/generated/operations/ldap-authentications.ts @@ -0,0 +1,152 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `LdapAuthentications` controller of the API. Import it as the `ldapAuthentications` + * namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { LdapAuthentication } from '../schemas.ts'; + +/** + * Creates a new authentication method. + * + * `POST /api/engine/v2/ldap_auths` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/ldap_auths', + pathKeys: [], + params: parameters({}), + body: LdapAuthentication, + response: LdapAuthentication, +}); + +/** + * Removes an authentication method. + * + * `DELETE /api/engine/v2/ldap_auths/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/ldap_auths/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Returns a list of authentications. + * + * `GET /api/engine/v2/ldap_auths` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/ldap_auths', + pathKeys: [], + params: parameters({ + /** return authentications that belong to the provided domain */ + authority_id: nullable(string()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(LdapAuthentication), +}); + +/** + * Returns the details of a particular authentication. + * + * `GET /api/engine/v2/ldap_auths/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/ldap_auths/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: LdapAuthentication, +}); + +/** + * Updates the details of an authentication. + * + * `PATCH /api/engine/v2/ldap_auths/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PATCH', + path: '/api/engine/v2/ldap_auths/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: LdapAuthentication, + response: LdapAuthentication, +}); diff --git a/v2/src/generated/operations/map-ai.ts b/v2/src/generated/operations/map-ai.ts new file mode 100644 index 000000000..97e69dad1 --- /dev/null +++ b/v2/src/generated/operations/map-ai.ts @@ -0,0 +1,203 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `MapAI` controller of the API. Import it as the `mapAi` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../core/schema.ts'; +import { + MapAiCapabilities, + MapAiEditParams, + MapAiJobResponse, + MapAiResolveParams, + SignageAiJobUsageRow, +} from '../schemas.ts'; + +/** + * Ask a running job to stop. A call already with the vendor runs to completion. + * + * `POST /api/engine/v2/maps/ai/jobs/{id}/cancel` + */ +export function cancel( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CANCEL, input, options); +} + +const CANCEL = operation({ + method: 'POST', + path: '/api/engine/v2/maps/ai/jobs/{id}/cancel', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: MapAiJobResponse, +}); + +/** + * What this domain can do, and what the caller has left of their quota. + * + * `GET /api/engine/v2/maps/ai/capabilities` + */ +export function capabilities( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CAPABILITIES, input, options); +} + +const CAPABILITIES = operation({ + method: 'GET', + path: '/api/engine/v2/maps/ai/capabilities', + pathKeys: [], + params: parameters({}), + body: null, + response: MapAiCapabilities, +}); + +/** + * Ask for operations that carry out an instruction on a level's map. + * + * `POST /api/engine/v2/maps/ai/edit` + */ +export function edit( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDIT, input, options); +} + +const EDIT = operation({ + method: 'POST', + path: '/api/engine/v2/maps/ai/edit', + pathKeys: [], + params: parameters({}), + body: MapAiEditParams, + response: MapAiJobResponse, +}); + +/** + * Recent map edit jobs. + * + * `GET /api/engine/v2/maps/ai/jobs` + */ +export function indexJobs( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX_JOBS, input, options); +} + +const INDEX_JOBS = operation({ + method: 'GET', + path: '/api/engine/v2/maps/ai/jobs', + pathKeys: [], + params: parameters({ + /** only the caller's own jobs */ + mine: boolean(), + /** only jobs against this zone */ + zone_id: nullable(string()), + /** map_edit; another kind lists that kind instead */ + kind: string(), + limit: integer('Int32'), + }), + body: null, + response: array(MapAiJobResponse), +}); + +/** + * Record what the person did with the answer: which ops were applied or. + * + * record what the person did with the answer: which ops were applied or rejected and why, and the + * upload the saved map became + * + * `POST /api/engine/v2/maps/ai/jobs/{id}/resolve` + */ +export function resolve( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(RESOLVE, input, options); +} + +const RESOLVE = operation({ + method: 'POST', + path: '/api/engine/v2/maps/ai/jobs/{id}/resolve', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: MapAiResolveParams, + response: MapAiJobResponse, +}); + +/** + * Long poll: holds until the job changes past `since`, or `wait` runs out. + * + * `GET /api/engine/v2/maps/ai/jobs/{id}` + */ +export function showJob( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW_JOB, input, options); +} + +const SHOW_JOB = operation({ + method: 'GET', + path: '/api/engine/v2/maps/ai/jobs/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + /** seconds to hold the request open, 0 to answer immediately */ + wait: integer('Int32'), + /** the version the caller already has */ + since: nullable(integer('Int32')), + }, + ['id'], + ), + body: null, + response: MapAiJobResponse, +}); + +/** + * Map edit spend per provider and model. + * + * `GET /api/engine/v2/maps/ai/usage` + */ +export function usage( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(USAGE, input, options); +} + +const USAGE = operation({ + method: 'GET', + path: '/api/engine/v2/maps/ai/usage', + pathKeys: [], + params: parameters({ + /** unix seconds, defaults to 30 days ago */ + from: nullable(integer()), + /** unix seconds, defaults to now */ + to: nullable(integer()), + }), + body: null, + response: array(SignageAiJobUsageRow), +}); diff --git a/v2/src/generated/operations/metadata.ts b/v2/src/generated/operations/metadata.ts new file mode 100644 index 000000000..ff16e0605 --- /dev/null +++ b/v2/src/generated/operations/metadata.ts @@ -0,0 +1,276 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Metadata` controller of the API. Import it as the `metadata` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { + array, + boolean, + integer, + nullable, + parameters, + record, + string, +} from '../../core/schema.ts'; +import { MetadataChildren, MetadataInterface, MetadataRename } from '../schemas.ts'; + +/** + * Fetch metadata with a specific name for multiple resources. + * + * Fetch metadata with a specific name for multiple resources + * + * Allows bulk retrieval of metadata across multiple parent entities + * + * `GET /api/engine/v2/metadata/{name}/bulk` + */ +export function bulkFetch( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_FETCH, input, options); +} + +const BULK_FETCH = operation({ + method: 'GET', + path: '/api/engine/v2/metadata/{name}/bulk', + pathKeys: ['name'], + params: parameters( + { + /** the name of the metadata key to fetch */ + name: string(), + /** comma-separated list of parent IDs (zones, systems, users, etc.) */ + parent_ids: array(string()), + }, + ['name', 'parent_ids'], + ), + body: null, + response: record(nullable(MetadataInterface)), +}); + +/** + * Fetch metadata for Zone children. + * + * Fetch metadata for Zone children + * + * Filter for a specific metadata by name via `name` param. Includes the parent metadata by default + * via `include_parent` param. + * + * `GET /api/engine/v2/metadata/{id}/children` + */ +export function childrenMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CHILDREN_METADATA, input, options); +} + +const CHILDREN_METADATA = operation({ + method: 'GET', + path: '/api/engine/v2/metadata/{id}/children', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be returned */ + id: string(), + /** the parent metadata is included in the results by default */ + include_parent: boolean(), + /** filter for a particular metadata key */ + name: nullable(string()), + }, + ['id'], + ), + body: null, + response: array(MetadataChildren), +}); + +/** + * Remove a metadata entry from the database. + * + * `DELETE /api/engine/v2/metadata/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/metadata/{id}', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be returned */ + id: string(), + /** the name of the metadata key */ + name: string(), + }, + ['id', 'name'], + ), + body: null, + response: null, +}); + +/** + * Returns the version history for a Settings model. + * + * `GET /api/engine/v2/metadata/{id}/history` + */ +export function history( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(HISTORY, input, options); +} + +const HISTORY = operation({ + method: 'GET', + path: '/api/engine/v2/metadata/{id}/history', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be returned */ + id: string(), + /** the name of the metadata key */ + name: nullable(string()), + /** the maximum number of results to return */ + limit: integer('Int32'), + /** the starting offset of the result set. Used to implement pagination */ + offset: integer('Int32'), + }, + ['id'], + ), + body: null, + response: record(array(MetadataInterface)), +}); + +/** + * Update only the keys provided on the selected metadata. + * + * update only the keys provided on the selected metadata udpates are signalled on the + * `placeos/metadata/changed` channel + * + * `PATCH /api/engine/v2/metadata/{id}` + */ +export function merge( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MERGE, input, options); +} + +const MERGE = operation({ + method: 'PATCH', + path: '/api/engine/v2/metadata/{id}', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be updated */ + id: string(), + }, + ['id'], + ), + body: MetadataInterface, + response: MetadataInterface, +}); + +/** + * Rename a metadata field. + * + * rename a metadata field udpates are signalled on the `placeos/metadata/changed` channel + * + * `PATCH /api/engine/v2/metadata/{id}/name` + */ +export function rename( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(RENAME, input, options); +} + +const RENAME = operation({ + method: 'PATCH', + path: '/api/engine/v2/metadata/{id}/name', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be renamed */ + id: string(), + }, + ['id'], + ), + body: MetadataRename, + response: MetadataInterface, +}); + +/** + * Fetch metadata for a model. + * + * Fetch metadata for a model + * + * Filter for a specific metadata by name via `name` param + * + * `GET /api/engine/v2/metadata/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = operation({ + method: 'GET', + path: '/api/engine/v2/metadata/{id}', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be returned */ + id: string(), + /** the name of the metadata key */ + name: nullable(string()), + }, + ['id'], + ), + body: null, + response: record(MetadataInterface), +}); + +/** + * Replace the metadata with this new metadata. + * + * replace the metadata with this new metadata udpates are signalled on the + * `placeos/metadata/changed` channel + * + * `PUT /api/engine/v2/metadata/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = operation({ + method: 'PUT', + path: '/api/engine/v2/metadata/{id}', + pathKeys: ['id'], + params: parameters( + { + /** the parent id of the metadata to be replaced */ + id: string(), + }, + ['id'], + ), + body: MetadataInterface, + response: MetadataInterface, +}); diff --git a/v2/src/generated/operations/modules.ts b/v2/src/generated/operations/modules.ts new file mode 100644 index 000000000..ca10ce469 --- /dev/null +++ b/v2/src/generated/operations/modules.ts @@ -0,0 +1,488 @@ +// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. +/** + * The `Modules` controller of the API. Import it as the `modules` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../core/client.ts'; +import { + array, + boolean, + integer, + json, + nullable, + parameters, + record, + string, +} from '../../core/schema.ts'; +import { Module, ModulesPingResult, Settings } from '../schemas.ts'; + +/** + * Add a new module / instance of a driver. + * + * `POST /api/engine/v2/modules` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = operation({ + method: 'POST', + path: '/api/engine/v2/modules', + pathKeys: [], + params: parameters({ + /** add the new module to this control system */ + system_id: nullable(string()), + }), + body: Module, + response: Module, +}); + +/** + * Remove a module. + * + * `DELETE /api/engine/v2/modules/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = operation({ + method: 'DELETE', + path: '/api/engine/v2/modules/{id}', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: null, +}); + +/** + * Executes a command on a module. + * + * Executes a command on a module The `/systems/` route can be used to introspect modules for the + * list of methods and argument requirements + * + * `POST /api/engine/v2/modules/{id}/exec/{method}` + */ +export function execute( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EXECUTE, input, options); +} + +const EXECUTE = operation({ + method: 'POST', + path: '/api/engine/v2/modules/{id}/exec/{method}', + pathKeys: ['id', 'method'], + params: parameters( + { + id: string(), + /** the name of the methodm we want to execute */ + method: string(), + }, + ['id', 'method'], + ), + body: array(json()), + response: json(), +}); + +/** + * Return a list of modules configured on the cluster. + * + * `GET /api/engine/v2/modules` + */ +export function index( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INDEX, input, options); +} + +const INDEX = operation({ + method: 'GET', + path: '/api/engine/v2/modules', + pathKeys: [], + params: parameters({ + /** only return modules updated before this time (unix epoch) */ + as_of: nullable(integer()), + /** + * only return modules running in this system (query params are ignored if this is provided) + */ + control_system_id: nullable(string()), + /** only return instances of this driver */ + driver_id: nullable(string()), + /** do not return logic modules (return only modules that can exist in multiple systems) */ + no_logic: boolean(), + /** return only running modules */ + running: nullable(boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: string(), + /** the maximum number of results to return */ + limit: integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: nullable(string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: array(string()), + }), + body: null, + response: array(Module), +}); + +/** + * Loads the module if not already loaded. + * + * Loads the module if not already loaded If the module is already running, it will be updated to + * latest settings. + * + * `POST /api/engine/v2/modules/{id}/load` + */ +export function load( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(LOAD, input, options); +} + +const LOAD = operation({ + method: 'POST', + path: '/api/engine/v2/modules/{id}/load', + pathKeys: ['id'], + params: parameters( + { + id: string(), + }, + ['id'], + ), + body: null, + response: boolean(), +}); + +/** + * Captures the module's debug output for a period of time, as lines of. + * + * Captures the module's debug output for a period of time, as lines of `

+ ? [B] extends [null] + ? Input

+ : B extends AnySchema + ? Simplify & { readonly body: Input }> + : never : never; -/** The data of a successful response of an operation. */ +/** The data of a successful response of an operation. The `null` check is first, as above. */ export type OperationData = O extends Operation - ? R extends AnySchema - ? Output - : Uint8Array + ? [R] extends [null] + ? Uint8Array + : R extends AnySchema + ? Output + : never : never; export interface Reply { diff --git a/v2/src/migrate/cli.ts b/v2/src/migrate/cli.ts new file mode 100644 index 000000000..1353bb721 --- /dev/null +++ b/v2/src/migrate/cli.ts @@ -0,0 +1,170 @@ +#!/usr/bin/env node +/** + * The migration tool. It rewrites the v1 calls of a project to v2. + * + * npx -p @placeos/ts-client@2 placeos-migrate src Shows the changes. Writes no file. + * npx -p @placeos/ts-client@2 placeos-migrate --write src Writes the changes. + * + * It uses the `typescript` package of the project in the current folder. + * + * @module + */ +import { readdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { join, relative, resolve } from 'node:path'; +import type * as TS from 'typescript-5'; +import { COMPAT_MODULE, migrateSource, type Finding, type MigrateTables } from './migrate.ts'; +import { V1_CALLS, V1_COMPAT, V1_TYPES, V1_UNMAPPED } from './v1-map.ts'; + +/** A project has fewer source files. The tool stops at this count. */ +const FILES_MAX = 50_000; +/** A larger file is not hand-written source. The tool skips it. */ +const FILE_BYTES_MAX = 5_000_000; +const SKIPPED_FOLDERS: ReadonlySet = new Set([ + 'node_modules', + 'dist', + 'coverage', + 'out-tsc', + '.git', + '.angular', + '.nx', +]); +const SOURCE_FILE = /\.(ts|tsx|mts|cts)$/; + +const USAGE = `Usage: placeos-migrate [--write] ... + +Rewrites the calls of @placeos/ts-client v1 to v2. Without --write, it shows the changes and +writes no file. Commit your work first, so that you can see and undo the changes.`; + +await main(process.argv.slice(2)); + +async function main(argv: readonly string[]): Promise { + const write = argv.includes('--write'); + const paths = argv.filter((arg) => !arg.startsWith('--')); + if (paths.length === 0 || argv.includes('--help')) { + console.log(USAGE); + process.exitCode = paths.length === 0 ? 1 : 0; + return; + } + const ts = loadTypeScript(); + if (ts === null) { + console.error( + 'The tool needs the typescript package. Run it in the folder of your project.', + ); + process.exitCode = 1; + return; + } + + const tables: MigrateTables = { + calls: V1_CALLS, + types: V1_TYPES, + compat: V1_COMPAT, + unmapped: V1_UNMAPPED, + }; + for (const path of paths) { + const exists = await stat(path).then( + () => true, + () => false, + ); + if (exists) continue; + console.error(`${path} does not exist.`); + process.exitCode = 1; + return; + } + const files = await sourceFiles(paths.map((path) => resolve(path))); + const findings: { file: string; finding: Finding }[] = []; + const migrated = new Set(); + let changedFiles = 0; + let changes = 0; + for (const file of files) { + const text = await readFile(file, 'utf8'); + const result = migrateSource(ts, file, text, tables); + const name = relative(process.cwd(), file); + for (const finding of result.findings) findings.push({ file: name, finding }); + for (const fn of result.migrated) migrated.add(fn); + if (result.text === text) continue; + changedFiles += 1; + changes += result.changes; + console.log(`${write ? 'changed' : 'would change'} ${name} (${result.changes})`); + if (write) await writeFile(file, result.text); + } + + if (findings.length > 0) { + console.log(`\nNot changed. Change these by hand:`); + for (const { file, finding } of findings) { + console.log( + ` ${file}:${finding.line}:${finding.column} ${finding.name}: ${finding.message}`, + ); + } + } + const notes = [...migrated] + .sort() + .flatMap((fn) => (V1_CALLS[fn]?.notes ?? []).map((note) => ` ${fn}: ${note}`)); + if (notes.length > 0) console.log(`\nDifferences of the changed calls:\n${notes.join('\n')}`); + + console.log( + `\n${files.length} files read. ${changedFiles} files ${write ? 'changed' : 'to change'}, ` + + `${changes} changes, ${findings.length} uses to change by hand.`, + ); + if (!write && changedFiles > 0) console.log('Run again with --write to write the changes.'); + if (write && changedFiles > 0) { + console.log( + `\nNext:\n` + + ` 1. Install v2: npm install @placeos/ts-client@2\n` + + ` 2. Call configure() once, before the first call (README: Log in).\n` + + ` 3. Run the compiler. It shows the changes to the data, such as a field that can be null.\n` + + ` 4. orThrow from ${COMPAT_MODULE} keeps the v1 errors. Check the Result in new code.`, + ); + } +} + +/** The `typescript` package of the project, or `null`. */ +function loadTypeScript(): typeof TS | null { + const require = createRequire(join(process.cwd(), 'package.json')); + try { + const loaded: unknown = require('typescript'); + return isTypeScript(loaded) ? loaded : null; + } catch { + return null; + } +} + +/** The tool uses only the parser, so a check of its entry points is enough. */ +function isTypeScript(value: unknown): value is typeof TS { + return ( + typeof value === 'object' && + value !== null && + 'createSourceFile' in value && + typeof value.createSourceFile === 'function' && + 'forEachChild' in value && + typeof value.forEachChild === 'function' + ); +} + +/** The source files in the paths, without the generated and installed folders. */ +async function sourceFiles(paths: readonly string[]): Promise { + const files: string[] = []; + const queue = [...paths]; + for (let index = 0; index < queue.length; index += 1) { + if (files.length >= FILES_MAX) { + console.error(`Stopped at ${FILES_MAX} files. Give a smaller folder.`); + break; + } + const path = queue[index] ?? ''; + const info = await stat(path); + if (info.isDirectory()) { + for (const entry of await readdir(path, { withFileTypes: true })) { + if (entry.isDirectory() && SKIPPED_FOLDERS.has(entry.name)) continue; + if (entry.isDirectory() || entry.isFile()) queue.push(join(path, entry.name)); + } + continue; + } + if (!SOURCE_FILE.test(path) || path.endsWith('.d.ts')) continue; + if (info.size > FILE_BYTES_MAX) { + console.error(`Skipped ${path}: it is larger than ${FILE_BYTES_MAX} bytes.`); + continue; + } + files.push(path); + } + return files.sort(); +} diff --git a/v2/src/migrate/map.ts b/v2/src/migrate/map.ts new file mode 100644 index 000000000..2e6db15af --- /dev/null +++ b/v2/src/migrate/map.ts @@ -0,0 +1,65 @@ +/** + * The types of the v1 to v2 call map. `scripts/v1-map.ts` writes the map in `v1-map.ts`, and the + * migration tool reads it. + * + * @module + */ + +/** + * The source of a v2 input value, made from the v1 arguments. + * + * - `arg`: the v1 argument at this index. + * - `member`: a property of the v1 argument at this index, such as the `version` of the data. + * - `literal`: a fixed value. + * - `concat`: a string of fixed text and arguments, such as `${module}_${index}`. + * - `object`: an object. A `spread` entry spreads the properties of an argument. + * - `array`: an array. + */ +export type Template = + | { readonly kind: 'arg'; readonly index: number } + | { readonly kind: 'member'; readonly index: number; readonly key: string } + | { readonly kind: 'literal'; readonly value: string | number | boolean | null } + | { readonly kind: 'concat'; readonly parts: readonly (string | number)[] } + | { readonly kind: 'object'; readonly entries: readonly ObjectEntry[] } + | { readonly kind: 'array'; readonly items: readonly Template[] }; + +/** A property of an `object` template. A `number` in `concat` parts is an argument index. */ +export type ObjectEntry = + | { readonly kind: 'property'; readonly key: string; readonly value: Template } + | { readonly kind: 'spread'; readonly index: number }; + +/** A parameter of a v1 function. */ +export interface V1Parameter { + readonly name: string; + /** The source text of the default value, or `null`. */ + readonly initializer: string | null; + /** + * - `mapped`: the v2 input has this argument. + * - `ignored`: v2 has no use for it. An example is the `method` of the v1 updates: v2 sends the + * update method of the API document. The tool removes it. + * - `unsupported`: the v2 call has no place for it. The tool does not change a call that gives + * it. + */ + readonly use: 'mapped' | 'ignored' | 'unsupported'; +} + +/** The v2 call for one v1 function. */ +export interface CallMapping { + /** The namespace export of v2, such as `zones`. */ + readonly namespace: string; + /** The operation of the namespace, such as `show`. */ + readonly operation: string; + readonly parameters: readonly V1Parameter[]; + /** The v2 input. It is always an `object` template. */ + readonly input: Template; + /** + * `data` for a v1 function that gives the data, `page` for one that gives `{ total, data, next }`. + */ + readonly result: 'data' | 'page'; + /** A key that v1 selects in the response data, such as the `name` of `showMetadata`. */ + readonly pick: Template | null; + /** Differences that the tool cannot fix. The report shows them. */ + readonly notes: readonly string[]; +} + +export type CallMap = Readonly>; diff --git a/v2/src/migrate/migrate.ts b/v2/src/migrate/migrate.ts new file mode 100644 index 000000000..0d93cbaea --- /dev/null +++ b/v2/src/migrate/migrate.ts @@ -0,0 +1,668 @@ +/** + * Rewrites the v1 calls of one source file to v2. `cli.ts` reads and writes the files. + * + * ```ts + * import * as ts from 'typescript'; + * const result = migrateSource(ts, 'zone.ts', text, V1_TABLES); + * ``` + * + * - A call of a mapped v1 function becomes the v2 operation with `.then(orThrow)`, so the code + * still gets the data, and an error still rejects the promise. + * - A type reference to a v1 class becomes the v2 type, such as `PlaceZone` to `Zone`. + * - The tool does not change other uses of v1. Each one is a finding, with a hint. + * + * The tool only parses the file. It does not type check it. After the migration, the compiler + * shows the differences of the data, such as a field that can now be `null`. + * + * @module + */ +import type * as TS from 'typescript-5'; +import { assert } from '../core/assert.ts'; +import type { CallMap, CallMapping, Template } from './map.ts'; + +export const V1_MODULE = '@placeos/ts-client'; +export const COMPAT_MODULE = '@placeos/ts-client/compat'; +/** A name that collides gets a suffix. A file has fewer names with the same base. */ +const ALIASES_MAX = 100; + +export interface MigrateTables { + readonly calls: CallMap; + readonly types: Readonly>; + /** The v1 names that `@placeos/ts-client/compat` has. Their imports move there. */ + readonly compat: Readonly>; + readonly unmapped: Readonly>; +} + +/** A use of v1 that the tool did not change. */ +export interface Finding { + /** 1-based. */ + readonly line: number; + /** 1-based. */ + readonly column: number; + /** The v1 name. */ + readonly name: string; + readonly message: string; +} + +export interface MigrateResult { + readonly text: string; + /** The number of calls and type references that the tool changed. */ + readonly changes: number; + readonly findings: readonly Finding[]; + /** The v1 functions of the changed calls. The report shows their notes. */ + readonly migrated: ReadonlySet; +} + +interface Edit { + readonly start: number; + readonly end: number; + readonly text: string; +} + +/** Rewrites the v1 calls of one file. The text is the same when the file does not import v1. */ +export function migrateSource( + ts: typeof TS, + fileName: string, + text: string, + tables: MigrateTables, +): MigrateResult { + const kind = /\.[cm]?tsx$/.test(fileName) ? ts.ScriptKind.TSX : ts.ScriptKind.TS; + const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind); + + const imports = readImports(ts, source); + if (imports.declarations.length === 0) { + return { text, changes: 0, findings: [], migrated: new Set() }; + } + const taken = declaredNames(ts, source); + const edits: Edit[] = []; + const findings: Finding[] = []; + const migrated = new Set(); + /** The uses of each local name of a named import, and how many the tool changed. */ + const uses = new Map(); + /** The local names of the v2 namespaces that the new import gives. */ + const namespaceNames = new Map(); + /** The v2 types that the new import gives, by local name. */ + const typeNames = new Map(); + const compatNames = new Set(); + /** The local names of the v1 imports that move to the compat module. */ + const moved = new Set(); + for (const [local, imported] of imports.named) { + const kind = tables.compat[imported]; + if (kind === undefined) continue; + moved.add(local); + const name = local === imported ? imported : `${imported} as ${local}`; + compatNames.add(kind === 'type' ? `type ${name}` : name); + } + let changes = 0; + + function find(node: TS.Node, name: string, message: string): void { + const at = source.getLineAndCharacterOfPosition(node.getStart(source)); + findings.push({ line: at.line + 1, column: at.character + 1, name, message }); + } + + /** A local name for a new import: the name, or the name with a suffix if the file has it. */ + function localName(name: string): string { + if (!taken.has(name)) { + taken.add(name); + return name; + } + for (let index = 1; index <= ALIASES_MAX; index += 1) { + const alias = `${name}V2${index === 1 ? '' : index}`; + if (taken.has(alias)) continue; + taken.add(alias); + return alias; + } + assert(false, `a free local name for ${name}`); + } + + function namespaceLocal(namespace: string): string { + const known = namespaceNames.get(namespace); + if (known !== undefined) return known; + const name = localName(namespace); + namespaceNames.set(namespace, name); + return name; + } + + function typeLocal(v2Name: string): string { + for (const [local, name] of typeNames) if (name === v2Name) return local; + const local = localName(v2Name); + typeNames.set(local, v2Name); + return local; + } + + /** The text of a node, with the edits inside it. The edits become part of the parent edit. */ + function textOf(node: TS.Node): string { + const start = node.getStart(source); + const inside = edits.filter((edit) => edit.start >= start && edit.end <= node.end); + return applyEdits(text.slice(start, node.end), inside, start); + } + + /** Replaces a node. The edits inside it are removed, because the new text has them. */ + function replace(node: TS.Node, replacement: string): void { + const start = node.getStart(source); + for (let index = edits.length - 1; index >= 0; index -= 1) { + const edit = edits[index]; + if (edit !== undefined && edit.start >= start && edit.end <= node.end) + edits.splice(index, 1); + } + edits.push({ start, end: node.end, text: replacement }); + } + + function countUse(local: string, changed: boolean): void { + const count = uses.get(local) ?? { total: 0, changed: 0 }; + uses.set(local, { total: count.total + 1, changed: count.changed + (changed ? 1 : 0) }); + } + + /** Rewrites a call. Gives `false`, with a finding, when it cannot. */ + function rewriteCall(call: TS.CallExpression, name: string, prefix: string | null): boolean { + const mapping = tables.calls[name]; + assert(mapping !== undefined, `${name} has a mapping`); + const rendered = renderCall(ts, call, mapping, textOf); + if (typeof rendered === 'string') { + find(call, name, rendered); + return false; + } + const namespace = + prefix === null ? namespaceLocal(mapping.namespace) : `${prefix}.${mapping.namespace}`; + const helper = mapping.result === 'page' ? 'orThrowPage' : 'orThrow'; + compatNames.add(helper); + const pick = + rendered.pick === null + ? '' + : `.then((${rendered.pickParameter}) => ${rendered.pickParameter}[${rendered.pick}])`; + replace( + call, + `${namespace}.${mapping.operation}(${rendered.input}).then(${helper})${pick}`, + ); + migrated.add(name); + changes += 1; + return true; + } + + function visit(node: TS.Node): void { + // The children first, so that a call in an argument is changed before the outer call. + ts.forEachChild(node, visit); + + if (ts.isCallExpression(node)) { + const callee = node.expression; + if (ts.isIdentifier(callee)) { + const imported = imports.named.get(callee.text); + if (imported !== undefined && imported in tables.calls) { + countUse(callee.text, rewriteCall(node, imported, null)); + } + } else if ( + ts.isPropertyAccessExpression(callee) && + ts.isIdentifier(callee.expression) && + imports.namespaces.has(callee.expression.text) && + callee.name.text in tables.calls + ) { + rewriteCall(node, callee.name.text, callee.expression.text); + } + return; + } + + if (ts.isTypeReferenceNode(node)) { + const typeName = node.typeName; + if (ts.isIdentifier(typeName)) { + const imported = imports.named.get(typeName.text); + if (imported === undefined || moved.has(typeName.text)) return; + const v2Name = tables.types[imported]; + if (v2Name !== undefined) { + replace(typeName, typeLocal(v2Name)); + countUse(typeName.text, true); + changes += 1; + } + return; + } + const left = typeName.left; + const v2Name = tables.types[typeName.right.text]; + if ( + ts.isIdentifier(left) && + imports.namespaces.has(left.text) && + v2Name !== undefined + ) { + replace(typeName.right, v2Name); + changes += 1; + } + return; + } + + if (ts.isIdentifier(node) && isReference(ts, node)) { + const imported = imports.named.get(node.text); + // A mapped callee or type name is counted at its parent. + if (imported === undefined || moved.has(node.text)) return; + // v1 and v2 have the same module name. A name that v1 does not export is from v2. + if (!isV1Name(tables, imported)) return; + if (isCountedAtParent(ts, node, imported, tables)) return; + countUse(node.text, false); + find(node, imported, hint(tables, imported)); + return; + } + + if ( + ts.isPropertyAccessExpression(node) && + ts.isIdentifier(node.expression) && + imports.namespaces.has(node.expression.text) && + !(ts.isCallExpression(node.parent) && node.parent.expression === node) + ) { + const name = node.name.text; + if (name in tables.compat) find(node, name, `import it from ${COMPAT_MODULE}`); + else if (name in tables.calls || name in tables.unmapped || name in tables.types) { + find(node, name, hint(tables, name)); + } + return; + } + + // A test double names the function in a string: `vi.spyOn(ts_client, 'showZone')`. + if (ts.isStringLiteral(node) && imports.namespaces.size > 0 && node.text in tables.calls) { + const mapping = tables.calls[node.text]; + const target = + mapping === undefined ? '' : ` (${mapping.namespace}.${mapping.operation})`; + find(node, node.text, `a test double of v1: make it for the v2 call${target}`); + } + } + visit(source); + + // The new import of the v2 namespaces and types, and of the helpers. + const added = [ + ...[...namespaceNames].map(([name, local]) => + name === local ? name : `${name} as ${local}`, + ), + ...[...typeNames].map(([local, name]) => + name === local ? `type ${name}` : `type ${name} as ${local}`, + ), + ].sort(compareSpecifiers); + const changed = importEdits(ts, source, imports.declarations, uses, tables, added, moved); + edits.push(...changed.edits); + // The new imports go after the last v1 import, or in its place when the tool removes it. + const lines: string[] = []; + if (changed.pending.length > 0) { + lines.push(`import { ${changed.pending.join(', ')} } from '${V1_MODULE}';`); + } + if (compatNames.size > 0) { + const names = [...compatNames].sort(compareSpecifiers).join(', '); + lines.push(`import { ${names} } from '${COMPAT_MODULE}';`); + } + const last = imports.declarations.at(-1); + assert(last !== undefined, 'a v1 import exists'); + if (lines.length > 0 && changed.removed.has(last)) { + const start = last.getStart(source); + edits.push({ start, end: start, text: lines.map((line) => `${line}\n`).join('') }); + } else if (lines.length > 0) { + edits.push({ + start: last.end, + end: last.end, + text: lines.map((line) => `\n${line}`).join(''), + }); + } + + findings.sort((a, b) => a.line - b.line || a.column - b.column); + return { text: applyEdits(text, edits, 0), changes, findings, migrated }; +} + +interface V1Imports { + readonly declarations: readonly TS.ImportDeclaration[]; + /** Local name to v1 name. */ + readonly named: ReadonlyMap; + readonly namespaces: ReadonlySet; +} + +function readImports(ts: typeof TS, source: TS.SourceFile): V1Imports { + const declarations: TS.ImportDeclaration[] = []; + const named = new Map(); + const namespaces = new Set(); + for (const statement of source.statements) { + if (!ts.isImportDeclaration(statement)) continue; + const specifier = statement.moduleSpecifier; + if (!ts.isStringLiteral(specifier) || specifier.text !== V1_MODULE) continue; + const bindings = statement.importClause?.namedBindings; + if (bindings === undefined) continue; + declarations.push(statement); + if (ts.isNamespaceImport(bindings)) { + namespaces.add(bindings.name.text); + continue; + } + for (const element of bindings.elements) { + named.set(element.name.text, (element.propertyName ?? element.name).text); + } + } + return { declarations, named, namespaces }; +} + +/** The names that the file declares or uses, so that a new import does not hide one. */ +function declaredNames(ts: typeof TS, source: TS.SourceFile): Set { + const names = new Set(); + function visit(node: TS.Node): void { + if (ts.isIdentifier(node) && isReference(ts, node)) names.add(node.text); + ts.forEachChild(node, visit); + } + visit(source); + return names; +} + +/** `false` for the name of a property or a member, such as `name` in `a.name` or `{ name: 1 }`. */ +function isReference(ts: typeof TS, node: TS.Identifier): boolean { + const parent = node.parent; + if (ts.isPropertyAccessExpression(parent)) return parent.expression === node; + if (ts.isQualifiedName(parent)) return parent.left === node; + if ( + ts.isPropertyAssignment(parent) || + ts.isPropertyDeclaration(parent) || + ts.isPropertySignature(parent) || + ts.isMethodDeclaration(parent) || + ts.isMethodSignature(parent) || + ts.isGetAccessorDeclaration(parent) || + ts.isSetAccessorDeclaration(parent) || + ts.isEnumMember(parent) + ) { + return parent.name !== node; + } + if (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent)) return false; + return true; +} + +/** The callee of a mapped call, or a mapped type name. `visit` counts these at the parent. */ +function isCountedAtParent( + ts: typeof TS, + node: TS.Identifier, + imported: string, + tables: MigrateTables, +): boolean { + const parent = node.parent; + if (ts.isCallExpression(parent) && parent.expression === node) return imported in tables.calls; + if (ts.isTypeReferenceNode(parent) && parent.typeName === node) { + return imported in tables.types; + } + return false; +} + +function isV1Name(tables: MigrateTables, name: string): boolean { + return ( + name in tables.calls || + name in tables.types || + name in tables.compat || + name in tables.unmapped + ); +} + +/** The hint for a use that the tool did not change. */ +function hint(tables: MigrateTables, name: string): string { + const type = tables.types[name]; + if (type !== undefined) return `v2 has no classes: use an object of the type ${type}`; + const mapping = tables.calls[name]; + if (mapping !== undefined) { + return `a use that is not a call: use ${mapping.namespace}.${mapping.operation}`; + } + return tables.unmapped[name] ?? 'v2 has no replacement'; +} + +interface RenderedCall { + readonly input: string; + readonly pick: string | null; + readonly pickParameter: string; +} + +/** The v2 input of a v1 call, or the reason that the tool cannot make it. */ +function renderCall( + ts: typeof TS, + call: TS.CallExpression, + mapping: CallMapping, + textOf: (node: TS.Node) => string, +): RenderedCall | string { + const args = call.arguments; + if (args.some((arg) => ts.isSpreadElement(arg))) + return 'a spread argument: change the call by hand'; + if (args.length > mapping.parameters.length) + return 'more arguments than v1 has: change the call by hand'; + + const given: (TS.Expression | null)[] = mapping.parameters.map((_parameter, index) => { + const arg = args[index]; + if (arg === undefined || (ts.isIdentifier(arg) && arg.text === 'undefined')) return null; + return arg; + }); + for (const [index, parameter] of mapping.parameters.entries()) { + if (given[index] !== null && parameter.use === 'unsupported') { + return `v2 has no place for the ${parameter.name} argument: change the call by hand`; + } + } + // An argument that the v2 call uses twice is evaluated twice. Only a simple one can be. + const counts = new Map(); + countArgs(mapping.input, counts); + if (mapping.pick !== null) countArgs(mapping.pick, counts); + for (const [index, count] of counts) { + const arg = given[index]; + if (count > 1 && arg !== null && arg !== undefined && !isSimple(ts, arg)) { + const name = mapping.parameters[index]?.name ?? String(index); + return `the v2 call uses the ${name} argument twice: put it in a variable first`; + } + } + + const value = (index: number): Value | null => { + const arg = given[index]; + if (arg !== null && arg !== undefined) return { text: textOf(arg), node: arg }; + const initializer = mapping.parameters[index]?.initializer ?? null; + return initializer === null ? null : { text: initializer, node: null }; + }; + // An input that is only a spread of one argument is that argument: `zones.index(query)`. + const [only] = mapping.input.kind === 'object' ? mapping.input.entries : []; + const whole = + mapping.input.kind === 'object' && + mapping.input.entries.length === 1 && + only?.kind === 'spread' + ? value(only.index) + : null; + const input = + whole !== null && whole.node !== null && !ts.isObjectLiteralExpression(whole.node) + ? whole.text + : (renderTemplate(ts, mapping.input, value, textOf) ?? '{}'); + const pick = mapping.pick === null ? null : renderTemplate(ts, mapping.pick, value, textOf); + const pickText = pick ?? ''; + const pickParameter = + ['data', 'value', 'response'].find((name) => !new RegExp(`\\b${name}\\b`).test(pickText)) ?? + 'v2Data'; + return { input, pick, pickParameter }; +} + +interface Value { + readonly text: string; + /** The argument, or `null` for a default value. */ + readonly node: TS.Expression | null; +} + +/** The source text of a template, or `null` when it needs an argument that the call does not give. */ +function renderTemplate( + ts: typeof TS, + template: Template, + value: (index: number) => Value | null, + textOf: (node: TS.Node) => string, +): string | null { + switch (template.kind) { + case 'arg': + return value(template.index)?.text ?? null; + case 'member': { + const given = value(template.index); + if (given === null) return null; + const base = + given.node === null || isSimple(ts, given.node) ? given.text : `(${given.text})`; + return `${base}.${template.key}`; + } + case 'literal': + return typeof template.value === 'string' + ? quote(template.value) + : String(template.value); + case 'concat': { + // A literal argument becomes text: `${'Display'}_${1}` is 'Display_1'. + const parts: ({ text: string } | { code: string })[] = []; + for (const part of template.parts) { + const given = typeof part === 'string' ? null : value(part); + if (typeof part === 'string') parts.push({ text: part }); + else if (given === null) return null; + else parts.push(literalText(ts, given) ?? { code: given.text }); + } + if (parts.every((part) => 'text' in part)) { + return quote(parts.map((part) => ('text' in part ? part.text : '')).join('')); + } + const body = parts.map((part) => + 'text' in part + ? part.text.replace(/[`\\]|\$\{/g, (match) => `\\${match}`) + : `\${${part.code}}`, + ); + return `\`${body.join('')}\``; + } + case 'array': { + const items = template.items.map((item) => renderTemplate(ts, item, value, textOf)); + return `[${items.filter((item) => item !== null).join(', ')}]`; + } + case 'object': { + const parts: string[] = []; + for (const entry of template.entries) { + if (entry.kind === 'spread') { + const given = value(entry.index); + if (given === null) continue; + // An object literal gives its properties, not a spread of a new object. + if (given.node !== null && ts.isObjectLiteralExpression(given.node)) { + parts.push(...given.node.properties.map((property) => textOf(property))); + } else if (given.node !== null || given.text !== '{}') { + parts.push(`...${given.text}`); + } + continue; + } + const rendered = renderTemplate(ts, entry.value, value, textOf); + if (rendered === null) continue; + const key = /^[A-Za-z_$][\w$]*$/.test(entry.key) ? entry.key : quote(entry.key); + parts.push(rendered === key ? key : `${key}: ${rendered}`); + } + return parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`; + } + } +} + +function countArgs(template: Template, counts: Map): void { + const add = (index: number) => counts.set(index, (counts.get(index) ?? 0) + 1); + switch (template.kind) { + case 'arg': + case 'member': + add(template.index); + return; + case 'literal': + return; + case 'concat': + for (const part of template.parts) if (typeof part === 'number') add(part); + return; + case 'array': + for (const item of template.items) countArgs(item, counts); + return; + case 'object': + for (const entry of template.entries) { + if (entry.kind === 'spread') add(entry.index); + else countArgs(entry.value, counts); + } + } +} + +/** A name, a property path or a literal. It has no side effects, so it can be evaluated twice. */ +function isSimple(ts: typeof TS, node: TS.Expression): boolean { + if (ts.isIdentifier(node) || node.kind === ts.SyntaxKind.ThisKeyword) return true; + if ( + ts.isStringLiteral(node) || + ts.isNumericLiteral(node) || + ts.isNoSubstitutionTemplateLiteral(node) + ) { + return true; + } + if (ts.isPropertyAccessExpression(node)) return isSimple(ts, node.expression); + if (ts.isParenthesizedExpression(node)) return isSimple(ts, node.expression); + return false; +} + +/** The text of a string or number literal, or `null` for other code. */ +function literalText(ts: typeof TS, given: Value): { text: string } | null { + const node = given.node; + if (node === null) return /^-?\d+$/.test(given.text) ? { text: given.text } : null; + if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) + return { text: node.text }; + if (ts.isNumericLiteral(node)) return { text: node.text }; + return null; +} + +function quote(text: string): string { + return `'${text.replace(/[\\']/g, (match) => `\\${match}`).replace(/\n/g, '\\n')}'`; +} + +/** + * The edits of the v1 imports. A specifier stays when the file still has a use of it that the tool + * did not change. Then the compiler shows that use. The new specifiers go in the first import that + * stays, or in a new import. + */ +function importEdits( + ts: typeof TS, + source: TS.SourceFile, + declarations: readonly TS.ImportDeclaration[], + uses: ReadonlyMap, + tables: MigrateTables, + added: readonly string[], + moved: ReadonlySet, +): { edits: Edit[]; pending: string[]; removed: ReadonlySet } { + const edits: Edit[] = []; + const removed = new Set(); + let pending = [...added]; + for (const declaration of declarations) { + const clause = declaration.importClause; + const bindings = clause?.namedBindings; + if (clause === undefined || bindings === undefined || !ts.isNamedImports(bindings)) + continue; + const kept: string[] = []; + for (const element of bindings.elements) { + const imported = (element.propertyName ?? element.name).text; + const count = uses.get(element.name.text) ?? { total: 0, changed: 0 }; + const known = imported in tables.calls || imported in tables.types; + const done = + moved.has(element.name.text) || + (count.total === count.changed && (count.total > 0 || known)); + if (!done) kept.push(element.getText(source)); + } + const merge = !clause.isTypeOnly && pending.length > 0; + const specifiers = merge ? [...kept, ...pending].sort(compareSpecifiers) : kept; + if (merge) pending = []; + if (specifiers.length === bindings.elements.length && !merge) continue; + const start = declaration.getStart(source); + if (specifiers.length === 0) { + // Remove the line, with its line break. + const end = + source.text[declaration.end] === '\n' ? declaration.end + 1 : declaration.end; + edits.push({ start, end, text: '' }); + removed.add(declaration); + continue; + } + const typeOnly = clause.isTypeOnly ? 'type ' : ''; + const from = declaration.moduleSpecifier.getText(source); + edits.push({ + start, + end: declaration.end, + text: `import ${typeOnly}{ ${specifiers.join(', ')} } from ${from};`, + }); + } + return { edits, pending, removed }; +} + +/** Sorts import specifiers by name, without the `type` keyword. */ +function compareSpecifiers(a: string, b: string): number { + const key = (text: string) => text.replace(/^type /, '').toLowerCase(); + return key(a).localeCompare(key(b)); +} + +/** + * Applies edits that do not overlap to a text that starts at `offset` of the file. An insert at the + * start of a replaced range goes before the new text. + */ +function applyEdits(text: string, edits: readonly Edit[], offset: number): string { + const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end); + let out = text; + let limit = Number.POSITIVE_INFINITY; + for (const edit of sorted) { + assert(edit.end <= limit, 'the edits do not overlap'); + out = out.slice(0, edit.start - offset) + edit.text + out.slice(edit.end - offset); + limit = edit.start; + } + return out; +} diff --git a/v2/src/migrate/v1-enums.ts b/v2/src/migrate/v1-enums.ts new file mode 100644 index 000000000..d19352e34 --- /dev/null +++ b/v2/src/migrate/v1-enums.ts @@ -0,0 +1,63 @@ +// Generated by scripts/v1-map.ts from the v1 source. Do not edit. +/** + * The enums of v1, for `@placeos/ts-client/compat`. + * + * @module + */ + +/** The values of the v1 enum `AuthType`. */ +export const AuthType = { Certificate: 0, NoAuth: 1, UserPassword: 2 } as const; +export type AuthType = (typeof AuthType)[keyof typeof AuthType]; + +/** The values of the v1 enum `EncryptionLevel`. */ +export const EncryptionLevel = { None: 0, Support: 1, Admin: 2, NeverDisplay: 3 } as const; +export type EncryptionLevel = (typeof EncryptionLevel)[keyof typeof EncryptionLevel]; + +/** The values of the v1 enum `MediaAnimation`. */ +export const MediaAnimation = { + Default: 0, + Cut: 1, + CrossFade: 2, + SlideTop: 3, + SlideLeft: 4, + SlideRight: 5, + SlideBottom: 6, +} as const; +export type MediaAnimation = (typeof MediaAnimation)[keyof typeof MediaAnimation]; + +/** The values of the v1 enum `PlaceDriverRole`. */ +export const PlaceDriverRole = { SSH: 0, Device: 1, Service: 2, Websocket: 3, Logic: 99 } as const; +export type PlaceDriverRole = (typeof PlaceDriverRole)[keyof typeof PlaceDriverRole]; + +/** The values of the v1 enum `PlaceRepositoryType`. */ +export const PlaceRepositoryType = { Driver: 'driver', Interface: 'interface' } as const; +export type PlaceRepositoryType = (typeof PlaceRepositoryType)[keyof typeof PlaceRepositoryType]; + +/** The values of the v1 enum `TriggerConditionOperator`. */ +export const TriggerConditionOperator = { + EQ: 'equal', + NEQ: 'not_equal', + GT: 'greater_than', + GTE: 'greater_than_or_equal', + LT: 'less_than', + LTE: 'less_than_or_equal', + AND: 'and', + OR: 'or', + XOR: 'exclusive_or', +} as const; +export type TriggerConditionOperator = + (typeof TriggerConditionOperator)[keyof typeof TriggerConditionOperator]; + +/** The values of the v1 enum `TriggerTimeConditionType`. */ +export const TriggerTimeConditionType = { AT: 'at', CRON: 'cron' } as const; +export type TriggerTimeConditionType = + (typeof TriggerTimeConditionType)[keyof typeof TriggerTimeConditionType]; + +/** The values of the v1 enum `TriggerWebhookType`. */ +export const TriggerWebhookType = { + ExecuteBefore: 0, + ExecuteAfter: 1, + PayloadOnly: 2, + IgnorePayload: 3, +} as const; +export type TriggerWebhookType = (typeof TriggerWebhookType)[keyof typeof TriggerWebhookType]; diff --git a/v2/src/migrate/v1-map.ts b/v2/src/migrate/v1-map.ts new file mode 100644 index 000000000..7dabf1dc3 --- /dev/null +++ b/v2/src/migrate/v1-map.ts @@ -0,0 +1,4712 @@ +// Generated by scripts/v1-map.ts from the v1 source and the v2 operations. Do not edit. +import type { CallMap } from './map.ts'; + +/** The v2 call for each v1 REST function. */ +export const V1_CALLS: CallMap = { + acceptGroupInvitation: { + namespace: 'groupsInvitations', + operation: 'accept', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAlert: { + namespace: 'alerts', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAlertDashboard: { + namespace: 'alertDashboards', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addApiKey: { + namespace: 'apiKeys', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addApplication: { + namespace: 'oauthApplications', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAsset: { + namespace: 'assets', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAssetCategory: { + namespace: 'assetCategories', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAssetPurchaseOrder: { + namespace: 'assetPurchaseOrders', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAssets: { + namespace: 'assets', + operation: 'bulkCreate', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addAssetType: { + namespace: 'assetTypes', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addBroker: { + namespace: 'brokers', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addDomain: { + namespace: 'domains', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addDriver: { + namespace: 'drivers', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addEdge: { + namespace: 'edges', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addGroup: { + namespace: 'groups', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addGroupInvitation: { + namespace: 'groupsInvitations', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addGroupUser: { + namespace: 'groupsUsers', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addGroupZone: { + namespace: 'groupsZones', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addLDAPSource: { + namespace: 'ldapAuthentications', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addModule: { + namespace: 'modules', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addOAuthSource: { + namespace: 'oauthAuthentications', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addRepository: { + namespace: 'repositories', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSAMLSource: { + namespace: 'samlAuthentications', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSettings: { + namespace: 'settings', + operation: 'create', + parameters: [ + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'spread', index: 1 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + addShortUrl: { + namespace: 'shortUrl', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignageAIProvider: { + namespace: 'signageAiProviders', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignageMedia: { + namespace: 'playlistMedia', + operation: 'create', + parameters: [ + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'spread', index: 1 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignagePlaylist: { + namespace: 'playlist', + operation: 'create', + parameters: [ + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'spread', index: 1 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignagePlugin: { + namespace: 'signagePlugins', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignageTemplate: { + namespace: 'signageTemplates', + operation: 'create', + parameters: [ + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'spread', index: 1 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + addSignageTemplateMapping: { + namespace: 'signageTemplateMappings', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addStorage: { + namespace: 'storages', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSystem: { + namespace: 'systems', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addSystemModule: { + namespace: 'systems', + operation: 'addModule', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'module_id', initializer: null, use: 'mapped' }, + { name: 'data', initializer: '{}', use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'module_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: ['v2 has no body for data'], + }, + addSystemTrigger: { + namespace: 'systemTriggers', + operation: 'create', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'data', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + addTrigger: { + namespace: 'triggers', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addUser: { + namespace: 'users', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + addZone: { + namespace: 'zones', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + apiScopes: { + namespace: 'root', + operation: 'scopes', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + approveSignagePlaylist: { + namespace: 'playlist', + operation: 'approveMedia', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + approveSignageTemplate: { + namespace: 'signageTemplates', + operation: 'approve', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + buildMonitor: { + namespace: 'buildMonitor', + operation: 'monitor', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + bulkMetadata: { + namespace: 'metadata', + operation: 'bulkFetch', + parameters: [ + { name: 'name', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'name', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + cancelBuildJob: { + namespace: 'buildMonitor', + operation: 'cancel', + parameters: [{ name: 'job', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'job', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + cancelSignageAIJob: { + namespace: 'signageAi', + operation: 'cancel', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + claimSignageAIImage: { + namespace: 'signageAi', + operation: 'claim', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'request', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + cleanupEdgeMonitoring: { + namespace: 'edges', + operation: 'cleanupErrors', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + clusterRebalance: { + namespace: 'cluster', + operation: 'rebalance', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + clusterVersions: { + namespace: 'root', + operation: 'clusterVersion', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + coreVersions: { + namespace: 'root', + operation: 'clusterVersion', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + currentGroups: { + namespace: 'groups', + operation: 'current', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + currentUser: { + namespace: 'users', + operation: 'current', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + currentUserResourceToken: { + namespace: 'users', + operation: 'resourceToken', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + driverReadme: { + namespace: 'drivers', + operation: 'readme', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + edgeConnections: { + namespace: 'edges', + operation: 'edgesConnections', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + edgeConnectionsFor: { + namespace: 'edges', + operation: 'edgeConnections', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + edgeErrors: { + namespace: 'edges', + operation: 'edgesErrors', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + edgeErrorsFor: { + namespace: 'edges', + operation: 'edgeErrors', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + edgeHealth: { + namespace: 'edges', + operation: 'edgesHealth', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + edgeHealthFor: { + namespace: 'edges', + operation: 'edgeHealth', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + edgeModuleFailures: { + namespace: 'edges', + operation: 'edgesModuleFailures', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + edgeModuleStatus: { + namespace: 'edges', + operation: 'edgeModuleStatus', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + edgeMonitoringSummary: { + namespace: 'edges', + operation: 'monitoringSummary', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + edgeStatistics: { + namespace: 'edges', + operation: 'edgesStatistics', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + editSignageImage: { + namespace: 'signageAi', + operation: 'edit', + parameters: [{ name: 'request', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + executeOnModule: { + namespace: 'modules', + operation: 'execute', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'method', initializer: null, use: 'mapped' }, + { name: 'args', initializer: '[]', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'method', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + executeOnSystem: { + namespace: 'systems', + operation: 'execute', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'method', initializer: null, use: 'mapped' }, + { name: 'module', initializer: null, use: 'mapped' }, + { name: 'index', initializer: '1', use: 'mapped' }, + { name: 'args', initializer: '[]', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'module_slug', + value: { kind: 'concat', parts: [2, '_', 3] }, + }, + { kind: 'property', key: 'method', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 4 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + executeOnZone: { + namespace: 'zones', + operation: 'zoneExecute', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'method', initializer: null, use: 'mapped' }, + { name: 'module', initializer: null, use: 'mapped' }, + { name: 'index', initializer: '1', use: 'mapped' }, + { name: 'args', initializer: '[]', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'module_slug', + value: { kind: 'concat', parts: [2, '_', 3] }, + }, + { kind: 'property', key: 'method', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 4 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + functionList: { + namespace: 'systems', + operation: 'functions', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'module', initializer: null, use: 'mapped' }, + { name: 'index', initializer: '1', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'module_slug', + value: { kind: 'concat', parts: [1, '_', 2] }, + }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + generateQrCode: { + namespace: 'shortUrl', + operation: 'generateQrCode', + parameters: [{ name: 'options', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: ['v1 sent format=svg, and v2 has no format parameter'], + }, + generateSignageImage: { + namespace: 'signageAi', + operation: 'generate', + parameters: [{ name: 'request', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + getShortUrlQrCodeSvg: { + namespace: 'shortUrl', + operation: 'svgQr', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + googleNotification: { + namespace: 'pushNotifications', + operation: 'google', + parameters: [{ name: 'body', initializer: '{}', use: 'unsupported' }], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: ['v2 has no body for body'], + }, + healthCheck: { + namespace: 'root', + operation: 'root', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + inspectApiKey: { + namespace: 'apiKeys', + operation: 'inspectKey', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + isDriverCompiled: { + namespace: 'drivers', + operation: 'compiled', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listChildMetadata: { + namespace: 'metadata', + operation: 'childrenMetadata', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listDashboardAlerts: { + namespace: 'alertDashboards', + operation: 'alerts', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'page', + pick: null, + notes: [], + }, + listInterfaceRepositories: { + namespace: 'repositories', + operation: 'loadedInterfaces', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + listMetadata: { + namespace: 'metadata', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listMetadataHistory: { + namespace: 'metadata', + operation: 'history', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listPublicEvents: { + namespace: 'publicEvents', + operation: 'index', + parameters: [ + { name: 'system_id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listRemoteRepositoryBranches: { + namespace: 'repositories', + operation: 'remoteBranches', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listRemoteRepositoryCommits: { + namespace: 'repositories', + operation: 'remoteCommits', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listRemoteRepositoryDefaultBranch: { + namespace: 'repositories', + operation: 'remoteDefaultBranch', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryBranches: { + namespace: 'repositories', + operation: 'branches', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryCommits: { + namespace: 'repositories', + operation: 'commits', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryDefaultBranch: { + namespace: 'repositories', + operation: 'defaultBranch', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryDriverDetails: { + namespace: 'repositories', + operation: 'details', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryDrivers: { + namespace: 'repositories', + operation: 'drivers', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryFiles: { + namespace: 'repositories', + operation: 'files', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listRepositoryFolders: { + namespace: 'repositories', + operation: 'folders', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listSignageMediaTagCounts: { + namespace: 'playlistMedia', + operation: 'tagCounts', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listSignageMediaTags: { + namespace: 'playlistMedia', + operation: 'tags', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listSignagePlaylistApprovers: { + namespace: 'playlist', + operation: 'approvers', + parameters: [{ name: 'group_id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'group_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listSignagePlaylistMedia: { + namespace: 'playlist', + operation: 'media', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listSignagePlaylistMediaRevisions: { + namespace: 'playlist', + operation: 'mediaRevisions', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + listSignageTemplateApprovers: { + namespace: 'signageTemplates', + operation: 'approvers', + parameters: [{ name: 'group_id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'group_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listSystemTriggers: { + namespace: 'systemTriggers', + operation: 'index', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'page', + pick: null, + notes: [], + }, + listSystemZones: { + namespace: 'systems', + operation: 'sysZones', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'page', + pick: null, + notes: [], + }, + listTriggerInstances: { + namespace: 'triggers', + operation: 'instances', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + listZoneTags: { + namespace: 'zones', + operation: 'tags', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + listZoneTriggers: { + namespace: 'zones', + operation: 'triggerInstances', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'page', + pick: null, + notes: [], + }, + loadModule: { + namespace: 'modules', + operation: 'load', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + lookupDomainByEmail: { + namespace: 'domains', + operation: 'lookup', + parameters: [{ name: 'email', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'email', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + lookupModuleState: { + namespace: 'modules', + operation: 'stateLookup', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'key', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'key', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + lookupSystemModuleState: { + namespace: 'systems', + operation: 'stateLookup', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'module', initializer: null, use: 'mapped' }, + { name: 'index', initializer: '1', use: 'mapped' }, + { name: 'lookup', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'module_slug', + value: { kind: 'concat', parts: [1, '_', 2] }, + }, + { kind: 'property', key: 'key', value: { kind: 'arg', index: 3 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + moduleRuntimeError: { + namespace: 'modules', + operation: 'showError', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + moduleSettings: { + namespace: 'modules', + operation: 'settings', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + moduleState: { + namespace: 'modules', + operation: 'state', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + mqttAccess: { + namespace: 'mqtt', + operation: 'mqttAccess', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + mqttUser: { + namespace: 'mqtt', + operation: 'mqttUser', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + office365Notification: { + namespace: 'pushNotifications', + operation: 'microsoft', + parameters: [{ name: 'body', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + platformInfo: { + namespace: 'root', + operation: 'platformInfo', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + proxyUrl: { + namespace: 'urlProxy', + operation: 'proxy', + parameters: [ + { name: 'url', initializer: null, use: 'mapped' }, + { name: 'options', initializer: '{}', use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'url', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + publicEventGuestToken: { + namespace: 'publicEvents', + operation: 'guestToken', + parameters: [ + { name: 'system_id', initializer: null, use: 'mapped' }, + { name: 'body', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + pullRepositoryChanges: { + namespace: 'repositories', + operation: 'pull', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: ['v2 has no body for query_params'], + }, + queryAlertDashboards: { + namespace: 'alertDashboards', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryAlerts: { + namespace: 'alerts', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryApiKeys: { + namespace: 'apiKeys', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryApplications: { + namespace: 'oauthApplications', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryAssetCategories: { + namespace: 'assetCategories', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryAssetPurchaseOrders: { + namespace: 'assetPurchaseOrders', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryAssets: { + namespace: 'assets', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryAssetTypes: { + namespace: 'assetTypes', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryBrokers: { + namespace: 'brokers', + operation: 'collection', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryClusters: { + namespace: 'cluster', + operation: 'nodes', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryDomains: { + namespace: 'domains', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryDrivers: { + namespace: 'drivers', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryEdges: { + namespace: 'edges', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryGroupHistory: { + namespace: 'groupsHistory', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryGroupInvitations: { + namespace: 'groupsInvitations', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryGroups: { + namespace: 'groups', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryGroupUsers: { + namespace: 'groupsUsers', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryGroupZones: { + namespace: 'groupsZones', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryHistory: { + namespace: 'history', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryLDAPSources: { + namespace: 'ldapAuthentications', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryModules: { + namespace: 'modules', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryOAuthSources: { + namespace: 'oauthAuthentications', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryProcesses: { + namespace: 'cluster', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + queryRepositories: { + namespace: 'repositories', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySAMLSources: { + namespace: 'samlAuthentications', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySettings: { + namespace: 'settings', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryShortUrls: { + namespace: 'shortUrl', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignageAIJobs: { + namespace: 'signageAi', + operation: 'indexJobs', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + querySignageAIProviders: { + namespace: 'signageAiProviders', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignageMedia: { + namespace: 'playlistMedia', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignagePlaylists: { + namespace: 'playlist', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignagePlugins: { + namespace: 'signagePlugins', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignageTemplateMappings: { + namespace: 'signageTemplateMappings', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySignageTemplates: { + namespace: 'signageTemplates', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryStorages: { + namespace: 'storages', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySystems: { + namespace: 'systems', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + querySystemsWithEmails: { + namespace: 'systems', + operation: 'findByEmail', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryTriggers: { + namespace: 'triggers', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryUserGroups: { + namespace: 'users', + operation: 'groups', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + queryUsers: { + namespace: 'users', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + queryWebrtcRooms: { + namespace: 'webRtc', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + queryZones: { + namespace: 'zones', + operation: 'index', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'page', + pick: null, + notes: [], + }, + recompileDriver: { + namespace: 'drivers', + operation: 'recompile', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + registerPublicEvent: { + namespace: 'publicEvents', + operation: 'register', + parameters: [ + { name: 'system_id', initializer: null, use: 'mapped' }, + { name: 'body', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + reloadDriver: { + namespace: 'drivers', + operation: 'reload', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAlert: { + namespace: 'alerts', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAlertDashboard: { + namespace: 'alertDashboards', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeApiKey: { + namespace: 'apiKeys', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeApplication: { + namespace: 'oauthApplications', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAsset: { + namespace: 'assets', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAssetCategory: { + namespace: 'assetCategories', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAssetPurchaseOrder: { + namespace: 'assetPurchaseOrders', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAssets: { + namespace: 'assets', + operation: 'bulkDestroy', + parameters: [ + { name: 'id_list', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'spread', index: 1 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeAssetType: { + namespace: 'assetTypes', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeBroker: { + namespace: 'brokers', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeDomain: { + namespace: 'domains', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeDriver: { + namespace: 'drivers', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeEdge: { + namespace: 'edges', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeGroup: { + namespace: 'groups', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeGroupInvitation: { + namespace: 'groupsInvitations', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeGroupUser: { + namespace: 'groupsUsers', + operation: 'destroy', + parameters: [ + { name: 'user_id', initializer: null, use: 'mapped' }, + { name: 'group_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'user_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeGroupZone: { + namespace: 'groupsZones', + operation: 'destroy', + parameters: [ + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'zone_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'zone_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeLDAPSource: { + namespace: 'ldapAuthentications', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeMetadata: { + namespace: 'metadata', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeModule: { + namespace: 'modules', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeOAuthSource: { + namespace: 'oauthAuthentications', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeRepository: { + namespace: 'repositories', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSAMLSource: { + namespace: 'samlAuthentications', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSettings: { + namespace: 'settings', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeShortUrl: { + namespace: 'shortUrl', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageAIProvider: { + namespace: 'signageAiProviders', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageMedia: { + namespace: 'playlistMedia', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageMediaTag: { + namespace: 'playlistMedia', + operation: 'removeTag', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + removeSignagePlaylist: { + namespace: 'playlist', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignagePlugin: { + namespace: 'signagePlugins', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageTemplate: { + namespace: 'signageTemplates', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageTemplateDraft: { + namespace: 'signageTemplates', + operation: 'destroyDraft', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSignageTemplateMapping: { + namespace: 'signageTemplateMappings', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeStorage: { + namespace: 'storages', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSystem: { + namespace: 'systems', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSystemModule: { + namespace: 'systems', + operation: 'removeModule', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'module_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'module_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeSystemTrigger: { + namespace: 'systemTriggers', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'trigger_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'trig_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeTrigger: { + namespace: 'triggers', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeUser: { + namespace: 'users', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + removeUserResourceToken: { + namespace: 'users', + operation: 'deleteResourceToken', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + removeZone: { + namespace: 'zones', + operation: 'destroy', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + renameMetadata: { + namespace: 'metadata', + operation: 'rename', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + renameSignageMediaTag: { + namespace: 'playlistMedia', + operation: 'renameTag', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + requestApprovalSignagePlaylist: { + namespace: 'playlist', + operation: 'requestApproval', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'message', initializer: "''", use: 'mapped' }, + { name: 'approver_id', initializer: "''", use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'approver_id', value: { kind: 'arg', index: 3 } }, + { + kind: 'property', + key: 'body', + value: { + kind: 'object', + entries: [ + { kind: 'property', key: 'message', value: { kind: 'arg', index: 2 } }, + ], + }, + }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + requestApprovalSignageTemplate: { + namespace: 'signageTemplates', + operation: 'requestApproval', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'message', initializer: "''", use: 'mapped' }, + { name: 'approver_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'approver_id', value: { kind: 'arg', index: 3 } }, + { + kind: 'property', + key: 'body', + value: { + kind: 'object', + entries: [ + { kind: 'property', key: 'message', value: { kind: 'arg', index: 2 } }, + ], + }, + }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + retrieveEdgeToken: { + namespace: 'edges', + operation: 'token', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + reviveUser: { + namespace: 'users', + operation: 'revive', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + scheduleSignagePlaylistMedia: { + namespace: 'playlist', + operation: 'scheduleMedia', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + searchUserMetadata: { + namespace: 'users', + operation: 'search', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + serviceVersion: { + namespace: 'root', + operation: 'version', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + settingsHistory: { + namespace: 'settings', + operation: 'history', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + shareSignageMedia: { + namespace: 'playlistMedia', + operation: 'share', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + shareSignagePlaylists: { + namespace: 'playlist', + operation: 'share', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + shareSignageTemplates: { + namespace: 'signageTemplates', + operation: 'share', + parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + showAlert: { + namespace: 'alerts', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showAlertDashboard: { + namespace: 'alertDashboards', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showApiKey: { + namespace: 'apiKeys', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showApplication: { + namespace: 'oauthApplications', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showAsset: { + namespace: 'assets', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showAssetCategory: { + namespace: 'assetCategories', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showAssetPurchaseOrder: { + namespace: 'assetPurchaseOrders', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showAssetType: { + namespace: 'assetTypes', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showBroker: { + namespace: 'brokers', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showCluster: { + namespace: 'cluster', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showDomain: { + namespace: 'domains', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showDriver: { + namespace: 'drivers', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showEdge: { + namespace: 'edges', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroup: { + namespace: 'groups', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroupFeatures: { + namespace: 'groups', + operation: 'features', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroupHistory: { + namespace: 'groupsHistory', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroupInvitation: { + namespace: 'groupsInvitations', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroupUser: { + namespace: 'groupsUsers', + operation: 'show', + parameters: [ + { name: 'user_id', initializer: null, use: 'mapped' }, + { name: 'group_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'user_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showGroupZone: { + namespace: 'groupsZones', + operation: 'show', + parameters: [ + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'zone_id', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'zone_id', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showHistory: { + namespace: 'history', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showLDAPSource: { + namespace: 'ldapAuthentications', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showMetadata: { + namespace: 'metadata', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'name', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'name', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: { kind: 'arg', index: 1 }, + notes: [], + }, + showModule: { + namespace: 'modules', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showOAuthSource: { + namespace: 'oauthAuthentications', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showRepository: { + namespace: 'repositories', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showSAMLSource: { + namespace: 'samlAuthentications', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showSettings: { + namespace: 'settings', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showShortUrl: { + namespace: 'shortUrl', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignage: { + namespace: 'signage', + operation: 'display', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + { name: 'options', initializer: null, use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignageAIJob: { + namespace: 'signageAi', + operation: 'showJob', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + { name: 'options', initializer: null, use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignageAIProvider: { + namespace: 'signageAiProviders', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignageMedia: { + namespace: 'playlistMedia', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignagePlaylist: { + namespace: 'playlist', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignagePlugin: { + namespace: 'signagePlugins', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignageTemplate: { + namespace: 'signageTemplates', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSignageTemplateMapping: { + namespace: 'signageTemplateMappings', + operation: 'show', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showStorage: { + namespace: 'storages', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSystem: { + namespace: 'systems', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showSystemTrigger: { + namespace: 'systemTriggers', + operation: 'show', + parameters: [ + { name: 'sys_id', initializer: null, use: 'mapped' }, + { name: 'trig_id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'trig_id', value: { kind: 'arg', index: 1 } }, + { kind: 'spread', index: 2 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showTrigger: { + namespace: 'triggers', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showUser: { + namespace: 'users', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showWebhook: { + namespace: 'webhook', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + showWebrtcRoom: { + namespace: 'webRtc', + operation: 'publicRoom', + parameters: [{ name: 'system_id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + showZone: { + namespace: 'zones', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + signageAICapabilities: { + namespace: 'signageAi', + operation: 'capabilities', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + signageAIUsage: { + namespace: 'signageAi', + operation: 'usage', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, + signal: { + namespace: 'root', + operation: 'signal', + parameters: [ + { name: 'channel', initializer: null, use: 'mapped' }, + { name: 'body', initializer: '{}', use: 'unsupported' }, + ], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'channel', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: ['v2 has no body for body'], + }, + sourceResync: { + namespace: 'root', + operation: 'sourceResync', + parameters: [{ name: 'clear', initializer: 'false', use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'clear', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + sourceResyncStatus: { + namespace: 'root', + operation: 'sourceResyncStatus', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + startModule: { + namespace: 'modules', + operation: 'start', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + startSystem: { + namespace: 'systems', + operation: 'start', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: ['v2 sends query_params in the query, v1 sent it in the body'], + }, + stopModule: { + namespace: 'modules', + operation: 'stop', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + stopSystem: { + namespace: 'systems', + operation: 'stop', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: ['v2 sends query_params in the query, v1 sent it in the body'], + }, + systemMetadata: { + namespace: 'systems', + operation: 'metadata', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + systemModuleState: { + namespace: 'systems', + operation: 'state', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'module', initializer: null, use: 'mapped' }, + { name: 'index', initializer: '1', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'module_slug', + value: { kind: 'concat', parts: [1, '_', 2] }, + }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + systemModuleTypes: { + namespace: 'systems', + operation: 'types', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + systemSettings: { + namespace: 'systems', + operation: 'settings', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + terminateProcess: { + namespace: 'cluster', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + testSignageAIProvider: { + namespace: 'signageAiProviders', + operation: 'test', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAlert: { + namespace: 'alerts', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAlertDashboard: { + namespace: 'alertDashboards', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateApiKey: { + namespace: 'apiKeys', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateApplication: { + namespace: 'oauthApplications', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAsset: { + namespace: 'assets', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAssetCategory: { + namespace: 'assetCategories', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAssetPurchaseOrder: { + namespace: 'assetPurchaseOrders', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAssets: { + namespace: 'assets', + operation: 'bulkUpdate', + parameters: [ + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + updateAssetType: { + namespace: 'assetTypes', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateBroker: { + namespace: 'brokers', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateDomain: { + namespace: 'domains', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateDriver: { + namespace: 'drivers', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateEdge: { + namespace: 'edges', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateGroup: { + namespace: 'groups', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateGroupUser: { + namespace: 'groupsUsers', + operation: 'update', + parameters: [ + { name: 'user_id', initializer: null, use: 'mapped' }, + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'user_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateGroupZone: { + namespace: 'groupsZones', + operation: 'update', + parameters: [ + { name: 'group_id', initializer: null, use: 'mapped' }, + { name: 'zone_id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'group_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'zone_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateLDAPSource: { + namespace: 'ldapAuthentications', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateMetadata: { + namespace: 'metadata', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'put'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateModule: { + namespace: 'modules', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateOAuthSource: { + namespace: 'oauthAuthentications', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateRepository: { + namespace: 'repositories', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSAMLSource: { + namespace: 'samlAuthentications', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSettings: { + namespace: 'settings', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 2 }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateShortUrl: { + namespace: 'shortUrl', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignageAIProvider: { + namespace: 'signageAiProviders', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignageMedia: { + namespace: 'playlistMedia', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignageMetrics: { + namespace: 'signage', + operation: 'updateMetrics', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'metrics', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignagePlaylist: { + namespace: 'playlist', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignagePlaylistMedia: { + namespace: 'playlist', + operation: 'updateMedia', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignagePlaylistMediaSchedule: { + namespace: 'playlist', + operation: 'updateSchedule', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'item_id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'item_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignagePlugin: { + namespace: 'signagePlugins', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignageTemplate: { + namespace: 'signageTemplates', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSignageTemplateMapping: { + namespace: 'signageTemplateMappings', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateStorage: { + namespace: 'storages', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSystem: { + namespace: 'systems', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { + kind: 'property', + key: 'version', + value: { kind: 'member', index: 1, key: 'version' }, + }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateSystemTrigger: { + namespace: 'systemTriggers', + operation: 'show', + parameters: [ + { name: 'sys_id', initializer: null, use: 'mapped' }, + { name: 'trig_id', initializer: null, use: 'mapped' }, + { name: 'data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'sys_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'trig_id', value: { kind: 'arg', index: 1 } }, + { kind: 'spread', index: 2 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateTrigger: { + namespace: 'triggers', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateUser: { + namespace: 'users', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + updateZone: { + namespace: 'zones', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + userMetadata: { + namespace: 'users', + operation: 'metadata', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + userResourceToken: { + namespace: 'users', + operation: 'userResourceToken', + parameters: [{ name: 'id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + webrtcGuestEntry: { + namespace: 'webRtc', + operation: 'guestEntry', + parameters: [ + { name: 'system_id', initializer: null, use: 'mapped' }, + { name: 'participant', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'system_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + webrtcGuestExit: { + namespace: 'webRtc', + operation: 'guestExit', + parameters: [], + input: { kind: 'object', entries: [] }, + result: 'data', + pick: null, + notes: [], + }, + webrtcKickUser: { + namespace: 'webRtc', + operation: 'kickUser', + parameters: [ + { name: 'user_id', initializer: null, use: 'mapped' }, + { name: 'session_id', initializer: null, use: 'mapped' }, + { name: 'reason', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'user_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'session_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + webrtcSessionMembers: { + namespace: 'webRtc', + operation: 'members', + parameters: [{ name: 'session_id', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'session_id', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, + webrtcTransferUser: { + namespace: 'webRtc', + operation: 'transferGuest', + parameters: [ + { name: 'user_id', initializer: null, use: 'mapped' }, + { name: 'session_id', initializer: null, use: 'mapped' }, + { name: 'connection_details', initializer: null, use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'user_id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'session_id', value: { kind: 'arg', index: 1 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 2 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, + zoneMetadata: { + namespace: 'zones', + operation: 'metadata', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, +}; + +/** The v2 type for each v1 class, such as `Zone` for `PlaceZone`. */ +export const V1_TYPES: Readonly> = { + PlaceAlert: 'Alert', + PlaceAlertDashboard: 'AlertDashboard', + PlaceApiKey: 'ApiKeysResponse', + PlaceApplication: 'DoorkeeperApplication', + PlaceAsset: 'Asset', + PlaceAssetCategory: 'AssetCategory', + PlaceAssetPurchaseOrder: 'AssetPurchaseOrder', + PlaceAssetType: 'AssetType', + PlaceDomain: 'Authority', + PlaceDriver: 'Driver', + PlaceEdge: 'Edge', + PlaceGroup: 'Group', + PlaceGroupInvitation: 'GroupInvitation', + PlaceGroupUser: 'GroupUser', + PlaceGroupZone: 'GroupZone', + PlaceHistory: 'History', + PlaceLDAPSource: 'LdapAuthentication', + PlaceMetadata: 'MetadataInterface', + PlaceModule: 'Module', + PlaceMQTTBroker: 'Broker', + PlaceOAuthSource: 'OauthAuthentication', + PlaceRepository: 'Repository', + PlaceSAMLSource: 'SamlAuthentication', + PlaceSettings: 'Settings', + PlaceShortUrl: 'Shortener', + PlaceStorage: 'Storage', + PlaceSystem: 'ControlSystem', + PlaceTrigger: 'Trigger', + PlaceUser: 'UserAdminMetadataResponse', + PlaceZone: 'Zone', + SignageMedia: 'PlaylistItem', + SignagePlaylist: 'Playlist', + SignagePlaylistItemSchedule: 'PlaylistItemSchedule', + SignagePlaylistMedia: 'PlaylistRevision', + SignagePlugin: 'SignagePlugin', + SignageTemplate: 'SignageTemplate', + SignageTemplateMapping: 'SignageTemplateSystemTemplate', +}; + +/** The v1 names that `@placeos/ts-client/compat` has. The tool moves their imports. */ +export const V1_COMPAT: Readonly> = { + AuthType: 'value', + EncryptionLevel: 'value', + MediaAnimation: 'value', + PlaceDriverRole: 'value', + PlaceRepositoryType: 'value', + QueryResponse: 'type', + TriggerConditionOperator: 'value', + TriggerTimeConditionType: 'value', + TriggerWebhookType: 'value', +}; + +/** The v1 exports that the tool does not change, with a hint. */ +export const V1_UNMAPPED: Readonly> = { + addAnswer: 'no v2 operation for POST /api/staff/v1/surveys/answers', + addInvitation: 'no v2 operation for POST /api/staff/v1/surveys/invitations', + addMetadata: 'no v2 operation for POST /api/engine/v2/metadata', + addQuestion: 'no v2 operation for POST /api/staff/v1/surveys/questions', + addSurvey: 'no v2 operation for POST /api/staff/v1/surveys', + apiEndpoint: 'use createAuthSession and configure (README: Log in)', + apiKey: 'use createAuthSession and configure (README: Log in)', + appHeaders: 'use createAuthSession and configure (README: Log in)', + authorise: 'use createAuthSession and configure (README: Log in)', + authority: 'use createAuthSession and configure (README: Log in)', + bind: 'use createRealtime (README: Realtime)', + cleanObject: 'v2 has no replacement', + cleanupAuth: 'use createAuthSession and configure (README: Log in)', + clientId: 'use createAuthSession and configure (README: Log in)', + computedSignal: 'v2 has no replacement', + connectionState: 'use createRealtime (README: Realtime)', + consoleHasColours: 'v2 has no replacement', + convertPairStringToMap: 'v2 has no replacement', + create: 'a v1 request helper: use the generated operation', + createSignal: 'v2 has no replacement', + debug: 'use createRealtime (README: Realtime)', + debug_events: 'v2 has no replacement', + del: 'use a generated operation, or fetch', + deregisterMockEndpoint: 'use a generated operation, or fetch', + deregisterSystem: 'use createRealtime (README: Realtime)', + edgeControlUrl: 'it sends 0 requests', + edgeErrorsStreamUrl: 'it sends 0 requests', + edgeErrorsStreamUrlFor: 'it sends 0 requests', + edgeModulesStreamUrl: 'it sends 0 requests', + exchangeEntraToken: 'use createAuthSession and configure (README: Log in)', + execute: 'use createRealtime (README: Realtime)', + generateNonce: 'v2 has no replacement', + get: 'use a generated operation, or fetch', + getFragments: 'v2 has no replacement', + getModule: 'use createRealtime (README: Realtime)', + getSystem: 'use createRealtime (README: Realtime)', + handleAuthRedirect: 'use createAuthSession and configure (README: Log in)', + hasToken: 'use createAuthSession and configure (README: Log in)', + host: 'use createAuthSession and configure (README: Log in)', + httpRoute: 'use createAuthSession and configure (README: Log in)', + humanReadableByteCount: 'v2 has no replacement', + ignore: 'use createRealtime (README: Realtime)', + invalidateToken: 'use createAuthSession and configure (README: Log in)', + is_connected: 'use createRealtime (README: Realtime)', + isFixedDevice: 'use createAuthSession and configure (README: Log in)', + isMobileSafari: 'v2 has no replacement', + isMock: 'use createAuthSession and configure (README: Log in)', + isNestedFrame: 'v2 has no replacement', + isOnline: 'use createAuthSession and configure (README: Log in)', + isSecure: 'use createAuthSession and configure (README: Log in)', + isTrusted: 'use createAuthSession and configure (README: Log in)', + lastRequestTotal: 'a v1 request helper: use the generated operation', + listen: 'use createRealtime (README: Realtime)', + listenForToken: 'use createAuthSession and configure (README: Log in)', + log: 'v2 has no replacement', + logout: 'use createAuthSession and configure (README: Log in)', + mediaThumbnail: 'it sends 0 requests', + MockPlaceWebsocketModule: 'v2 has no replacement', + MockPlaceWebsocketSystem: 'v2 has no replacement', + mockSystem: 'use createRealtime (README: Realtime)', + onlineState: 'use createAuthSession and configure (README: Log in)', + parseLinkHeader: 'v2 has no replacement', + patch: 'use a generated operation, or fetch', + PlaceCluster: 'v2 has no replacement', + PlaceErrorCodes: 'v2 has no replacement', + PlaceGroupHistory: 'v2 has no replacement', + PlaceLogLevel: 'v2 has no replacement', + PlaceModuleBinding: 'v2 has no replacement', + PlaceProcess: 'v2 has no replacement', + PlaceResource: 'v2 has no replacement', + PlaceSystemBinding: 'v2 has no replacement', + PlaceVariableBinding: 'v2 has no replacement', + PlaceZoneMetadata: 'v2 has no replacement', + post: 'use a generated operation, or fetch', + put: 'use a generated operation, or fetch', + qrCodeUrl: 'it sends 0 requests', + query: 'a v1 request helper: use the generated operation', + queryAnswers: 'no v2 operation for GET /api/staff/v1/surveys/answers', + queryInvitations: 'no v2 operation for GET /api/staff/v1/surveys/invitations', + queryQuestions: 'no v2 operation for GET /api/staff/v1/surveys/questions', + querySurveys: 'no v2 operation for GET /api/staff/v1/surveys', + redirectUri: 'use createAuthSession and configure (README: Log in)', + refreshAuthority: 'use createAuthSession and configure (README: Log in)', + refreshToken: 'use createAuthSession and configure (README: Log in)', + registerMockEndpoint: 'use a generated operation, or fetch', + registerSystem: 'use createRealtime (README: Realtime)', + remove: 'a v1 request helper: use the generated operation', + removeFragment: 'v2 has no replacement', + removeInvitation: 'no v2 operation for DELETE /api/staff/v1/surveys/invitations/s0zq', + removeQuestion: 'no v2 operation for DELETE /api/staff/v1/surveys/questions/s0zq', + removeSurvey: 'no v2 operation for DELETE /api/staff/v1/surveys/s0zq', + requestTotal: 'a v1 request helper: use the generated operation', + responseHeaders: 'use a generated operation, or fetch', + scoped_log: 'v2 has no replacement', + setAPI_Key: 'use createAuthSession and configure (README: Log in)', + setAppHeaders: 'use createAuthSession and configure (README: Log in)', + setMockNotFoundHandler: 'use a generated operation, or fetch', + setStorage: 'use createAuthSession and configure (README: Log in)', + setToken: 'use createAuthSession and configure (README: Log in)', + setup: 'use createAuthSession and configure (README: Log in)', + shortUrlQrCodePngUrl: 'it sends 0 requests', + shortUrlRedirectUrl: 'it sends 0 requests', + show: 'a v1 request helper: use the generated operation', + showInvitation: 'no v2 operation for GET /api/staff/v1/surveys/invitations/s0zq', + showQuestion: 'no v2 operation for GET /api/staff/v1/surveys/questions/s0zq', + showSurvey: 'no v2 operation for GET /api/staff/v1/surveys/s0zq', + simplifiedTime: 'v2 has no replacement', + sleep: 'v2 has no replacement', + status: 'use createRealtime (README: Realtime)', + Survey: 'v2 has no replacement', + SurveyAnswer: 'v2 has no replacement', + SurveyInvitation: 'v2 has no replacement', + SurveyQuestion: 'v2 has no replacement', + systemControlUrl: 'it sends 0 requests', + token: 'use createAuthSession and configure (README: Log in)', + unbind: 'use createRealtime (README: Realtime)', + undeleteResource: 'v1 sends a body, and history.undelete has none', + update: 'a v1 request helper: use the generated operation', + updateInvitation: 'no v2 operation for PATCH /api/staff/v1/surveys/invitations/s0zq', + updateQuestion: 'no v2 operation for PATCH /api/staff/v1/surveys/questions/s0zq', + updateSurvey: 'no v2 operation for PATCH /api/staff/v1/surveys/s0zq', + value: 'use createRealtime (README: Realtime)', + waitForSignal: 'v2 has no replacement', + webrtcSignallerUrl: 'it sends 0 requests', + websocketRoute: 'use createRealtime (README: Realtime)', +}; diff --git a/v2/test/loose/consumer.ts b/v2/test/loose/consumer.ts new file mode 100644 index 000000000..b7cf574b0 --- /dev/null +++ b/v2/test/loose/consumer.ts @@ -0,0 +1,25 @@ +/** + * Goal: the published types work in a project without `strictNullChecks`, such as backoffice. + * Method: `bun run build` compiles these calls against `dist`. Each `@ts-expect-error` line must + * be an error. + */ +import { orThrow, orThrowPage, PlaceDriverRole } from '../../dist/compat.js'; +import { metadata, zones, type Driver, type Zone } from '../../dist/index.js'; + +export async function calls(): Promise { + // An operation without a body does not ask for one. + const zone: Zone = await zones.show({ id: 'zone-1' }).then(orThrow); + const page = await zones.index({ limit: 10 }).then(orThrowPage); + await zones.update({ id: zone.id, body: { name: 'name' } }).then(orThrow); + await metadata.show({ id: 'zone-1', name: 'settings' }).then(orThrow); + // A v1 enum value fits the v2 field. + const role: Driver['role'] = PlaceDriverRole.Logic; + // @ts-expect-error the body is missing + await zones.update({ id: 'zone-1' }); + // @ts-expect-error a parameter that the operation does not have + await zones.show({ id: 'zone-1', no_such_parameter: true }); + // Without `strictNullChecks`, `ok === false` narrows the result. `!result.ok` does not. + const result = await zones.show({ id: 'zone-1' }); + if (result.ok === false) return result.error.kind; + return `${page.total} ${role} ${result.value.data.name}`; +} diff --git a/v2/test/loose/tsconfig.json b/v2/test/loose/tsconfig.json new file mode 100644 index 000000000..8593bd559 --- /dev/null +++ b/v2/test/loose/tsconfig.json @@ -0,0 +1,16 @@ +{ + // Type checks a consumer without `strict`, as in projects such as backoffice. Without + // `strictNullChecks`, `null` fits each type, and conditional types can change. + "compilerOptions": { + "target": "ES2022", + "module": "preserve", + "moduleResolution": "bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": [], + "noEmit": true, + "skipLibCheck": true, + "strict": false, + "strictNullChecks": false + }, + "include": ["consumer.ts"] +} diff --git a/v2/test/migrate.test.ts b/v2/test/migrate.test.ts new file mode 100644 index 000000000..26da57e3e --- /dev/null +++ b/v2/test/migrate.test.ts @@ -0,0 +1,142 @@ +/** + * Goal: the migration tool rewrites v1 calls to the correct v2 calls, and it does not change a use + * that it cannot rewrite safely. + * Method: run `migrateSource` with the generated map on small v1 files, and compare the text. + */ +import { expect, test } from 'bun:test'; +import * as ts from 'typescript-5'; +import { migrateSource, type MigrateTables } from '../src/migrate/migrate.ts'; +import { V1_CALLS, V1_COMPAT, V1_TYPES, V1_UNMAPPED } from '../src/migrate/v1-map.ts'; + +const TABLES: MigrateTables = { + calls: V1_CALLS, + types: V1_TYPES, + compat: V1_COMPAT, + unmapped: V1_UNMAPPED, +}; + +function migrate(text: string) { + return migrateSource(ts, 'file.ts', text, TABLES); +} + +test('rewrites calls, types and imports', () => { + const result = migrate( + [ + "import { PlaceZone, queryZones, showZone } from '@placeos/ts-client';", + 'async function load(id: string, query: object): Promise {', + ' const list = await queryZones(query);', + ' return showZone(id, { complete: true });', + '}', + ].join('\n'), + ); + expect(result.text).toBe( + [ + "import { type Zone, zones } from '@placeos/ts-client';", + "import { orThrow, orThrowPage } from '@placeos/ts-client/compat';", + 'async function load(id: string, query: object): Promise {', + ' const list = await zones.index(query).then(orThrowPage);', + ' return zones.show({ id, complete: true }).then(orThrow);', + '}', + ].join('\n'), + ); + expect(result.changes).toBe(3); + expect(result.findings).toEqual([]); +}); + +test('maps path templates, default values, members and picked keys', () => { + const result = migrate( + [ + "import { executeOnZone, showMetadata, updateSystem } from '@placeos/ts-client';", + "executeOnZone(id, 'power', 'Display');", + 'showMetadata(zone.id, name);', + 'updateSystem(system.id, system);', + ].join('\n'), + ); + expect(result.text.split('\n').slice(2)).toEqual([ + "zones.zoneExecute({ id, module_slug: 'Display_1', method: 'power', body: [] }).then(orThrow);", + 'metadata.show({ id: zone.id, name }).then(orThrow).then((data) => data[name]);', + 'systems.update({ sys_id: system.id, version: system.version, body: system }).then(orThrow);', + ]); +}); + +test('keeps the uses that it cannot rewrite, with a finding', () => { + const text = [ + "import { addSystemModule, getModule, showMetadata, showZone } from '@placeos/ts-client';", + "addSystemModule('sys-1', 'mod-1', { a: 1 });", + 'showMetadata(id, names()[0]);', + "getModule('sys-1', 'Bookings');", + 'const load = showZone;', + ].join('\n'); + const result = migrate(text); + expect(result.text).toBe(text); + expect(result.findings.map((finding) => `${finding.line} ${finding.name}`)).toEqual([ + '2 addSystemModule', + '3 showMetadata', + '4 getModule', + '5 showZone', + ]); +}); + +test('gives a new import another name when the file has the name', () => { + const result = migrate( + [ + "import { queryZones } from '@placeos/ts-client';", + 'const zones = await queryZones();', + ].join('\n'), + ); + expect(result.text).toBe( + [ + "import { zones as zonesV2 } from '@placeos/ts-client';", + "import { orThrowPage } from '@placeos/ts-client/compat';", + 'const zones = await zonesV2.index({}).then(orThrowPage);', + ].join('\n'), + ); +}); + +test('rewrites calls on a namespace import, and finds test doubles', () => { + const result = migrate( + [ + "import * as client from '@placeos/ts-client';", + 'client.showZone(id);', + "vi.spyOn(client, 'showZone');", + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import * as client from '@placeos/ts-client';", + "import { orThrow } from '@placeos/ts-client/compat';", + 'client.zones.show({ id }).then(orThrow);', + "vi.spyOn(client, 'showZone');", + ]); + expect(result.findings.map((finding) => finding.message)).toEqual([ + 'a test double of v1: make it for the v2 call (zones.show)', + ]); +}); + +test('moves the v1 enums and the QueryResponse type to the compat module', () => { + const result = migrate( + [ + "import { PlaceDriverRole, QueryResponse } from '@placeos/ts-client';", + 'const role = PlaceDriverRole.Logic;', + 'let page: QueryResponse;', + ].join('\n'), + ); + expect(result.text.split('\n')[0]).toBe( + "import { PlaceDriverRole, type QueryResponse } from '@placeos/ts-client/compat';", + ); + expect(result.findings).toEqual([]); +}); + +test('a second run changes nothing', () => { + const first = migrate( + [ + "import { getModule, PlaceZone, showZone } from '@placeos/ts-client';", + 'const zone: PlaceZone = await showZone(id);', + "getModule('sys-1', 'Bookings');", + ].join('\n'), + ); + const second = migrate(first.text); + expect(second.text).toBe(first.text); + expect(second.changes).toBe(0); + // The v2 names of the first run are not findings. + expect(second.findings.map((finding) => finding.name)).toEqual(['getModule']); +}); diff --git a/v2/tsconfig.build.json b/v2/tsconfig.build.json index 43e4602c8..eeebe7313 100644 --- a/v2/tsconfig.build.json +++ b/v2/tsconfig.build.json @@ -14,5 +14,7 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src"] + "include": ["src"], + // The migration tool uses Node APIs. tsconfig.cli.json builds it. + "exclude": ["src/migrate/cli.ts"] } diff --git a/v2/tsconfig.cli.json b/v2/tsconfig.cli.json new file mode 100644 index 000000000..871121ce3 --- /dev/null +++ b/v2/tsconfig.cli.json @@ -0,0 +1,9 @@ +{ + // Builds the migration tool. It runs on Node, so it has the Node types. The library does not. + "extends": "./tsconfig.build.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src/migrate/cli.ts"], + "exclude": [] +} diff --git a/v2/tsconfig.json b/v2/tsconfig.json index edfc98f1c..1b77bf424 100644 --- a/v2/tsconfig.json +++ b/v2/tsconfig.json @@ -24,5 +24,7 @@ "noUnusedParameters": true, "useUnknownInCatchVariables": true }, - "include": ["src", "test", "scripts"] + "include": ["src", "test", "scripts"], + // `bun run build` checks it against `dist`, without `strict`. + "exclude": ["test/loose"] } From a501df14ec89c7460145cb7c59d00020ca805fb2 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 17 Nov 2026 20:09:25 +1100 Subject: [PATCH 07/29] feat(v2): typed endpoint mocks, v1 mocks in compat, and short type names Apps on v1 mock the client in their tests and in a mock mode. After the migration, those mocks no longer reached the v2 calls, and some v2 schema names did not say what they are. - `@placeos/ts-client/mock`: `mockEndpoint('zones.show', handler)` answers the calls of one endpoint. The compiler checks the name, the input and the data. The client checks the input and parses the data as it does for a response. Operations now have a `name`, and the client has an optional `mock` hook. - `@placeos/ts-client/compat` has the v1 mock endpoints (`registerMockEndpoint`, `mockFetch`) and mock systems (`registerSystem`, `mockRealtimeEnvironment`), and `missingFields: 'zero'` fills the required fields that mock data leaves out, as the v1 classes did. - The migration tool rewrites test doubles: `vi.mocked`, `expect`, `vi.spyOn`, mock values, argument checks and `vi.mock` factories (with `fromV1Mock`). On a copy of backoffice, 329 of 399 tests pass after the tool; the rest use v1 classes or v1 pagination, which it reports. - Short names for odd schema names: `User`, `System`, `Application`, `Domain`, `Metadata`, `ShortUrl`, `SignageTemplateMapping`. Co-Authored-By: Claude Opus 5.5 --- v2/README.md | 129 ++++- v2/package.json | 8 +- v2/scripts/generate.ts | 35 +- v2/scripts/v1-map.ts | 46 +- v2/src/compat.ts | 77 --- .../{migrate/v1-enums.ts => compat/enums.ts} | 2 +- v2/src/compat/http-mock.ts | 261 ++++++++++ v2/src/compat/index.ts | 16 + v2/src/compat/realtime-mock.ts | 249 +++++++++ v2/src/compat/result.ts | 155 ++++++ v2/src/core/client.ts | 87 +++- v2/src/core/schema.ts | 72 ++- .../generated/operations/alert-dashboards.ts | 6 + v2/src/generated/operations/alerts.ts | 5 + v2/src/generated/operations/api-keys.ts | 6 + .../generated/operations/asset-categories.ts | 5 + .../operations/asset-purchase-orders.ts | 5 + v2/src/generated/operations/asset-types.ts | 5 + v2/src/generated/operations/assets.ts | 8 + v2/src/generated/operations/brokers.ts | 5 + v2/src/generated/operations/build-monitor.ts | 2 + .../generated/operations/chat-gpt-plugin.ts | 3 + v2/src/generated/operations/chat-gpt.ts | 3 + v2/src/generated/operations/cluster.ts | 4 + v2/src/generated/operations/domains.ts | 6 + v2/src/generated/operations/drivers.ts | 9 + v2/src/generated/operations/edges.ts | 17 + v2/src/generated/operations/flux.ts | 1 + v2/src/generated/operations/groups-history.ts | 2 + .../operations/groups-invitations.ts | 5 + v2/src/generated/operations/groups-users.ts | 5 + v2/src/generated/operations/groups-zones.ts | 5 + v2/src/generated/operations/groups.ts | 8 + v2/src/generated/operations/history.ts | 3 + .../operations/ldap-authentications.ts | 5 + v2/src/generated/operations/map-ai.ts | 7 + v2/src/generated/operations/metadata.ts | 8 + v2/src/generated/operations/modules.ts | 16 + v2/src/generated/operations/mqtt.ts | 2 + .../operations/oauth-applications.ts | 5 + .../operations/oauth-authentications.ts | 5 + v2/src/generated/operations/pending-mails.ts | 6 + v2/src/generated/operations/playlist-media.ts | 11 + v2/src/generated/operations/playlist.ts | 15 + v2/src/generated/operations/public-events.ts | 3 + .../operations/push-notifications.ts | 2 + v2/src/generated/operations/repositories.ts | 20 + v2/src/generated/operations/root.ts | 8 + .../operations/saml-authentications.ts | 5 + v2/src/generated/operations/schema.ts | 5 + v2/src/generated/operations/settings.ts | 6 + v2/src/generated/operations/short-url.ts | 9 + .../operations/signage-ai-providers.ts | 6 + v2/src/generated/operations/signage-ai.ts | 8 + .../generated/operations/signage-plugins.ts | 5 + .../operations/signage-template-mappings.ts | 5 + .../generated/operations/signage-templates.ts | 10 + v2/src/generated/operations/signage.ts | 5 + v2/src/generated/operations/storages.ts | 5 + .../generated/operations/system-triggers.ts | 5 + v2/src/generated/operations/systems.ts | 18 + v2/src/generated/operations/tenant-consent.ts | 3 + v2/src/generated/operations/triggers.ts | 6 + v2/src/generated/operations/uploads.ts | 12 + v2/src/generated/operations/url-proxy.ts | 1 + v2/src/generated/operations/users.ts | 13 + v2/src/generated/operations/web-rtc.ts | 8 + v2/src/generated/operations/webhook.ts | 1 + v2/src/generated/operations/zones.ts | 9 + v2/src/generated/schemas.ts | 15 + v2/src/migrate/cli.ts | 3 +- v2/src/migrate/migrate.ts | 475 +++++++++++++++++- v2/src/migrate/v1-map.ts | 34 +- v2/src/mock/index.ts | 180 +++++++ v2/test/auth.test.ts | 1 + v2/test/client.test.ts | 2 + v2/test/compat.test.ts | 174 +++++++ v2/test/loose/consumer.ts | 11 +- v2/test/migrate.test.ts | 118 ++++- v2/test/mock.test.ts | 94 ++++ v2/test/style.test.ts | 12 +- 81 files changed, 2488 insertions(+), 144 deletions(-) delete mode 100644 v2/src/compat.ts rename v2/src/{migrate/v1-enums.ts => compat/enums.ts} (96%) create mode 100644 v2/src/compat/http-mock.ts create mode 100644 v2/src/compat/index.ts create mode 100644 v2/src/compat/realtime-mock.ts create mode 100644 v2/src/compat/result.ts create mode 100644 v2/src/mock/index.ts create mode 100644 v2/test/compat.test.ts create mode 100644 v2/test/mock.test.ts diff --git a/v2/README.md b/v2/README.md index dfe581a6a..513ec59da 100644 --- a/v2/README.md +++ b/v2/README.md @@ -112,6 +112,75 @@ const client = createClient({ const result = await zones.show({ id: 'zone-1' }, { client }); ``` +### Typed mocks + +`@placeos/ts-client/mock` answers the calls of an endpoint without a request. The compiler checks +the name of the endpoint, the input that the handler gets, and the data that it gives: + +```ts +import { endpointMocks, httpError, mockEndpoint, respond } from '@placeos/ts-client/mock'; + +configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); + +mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); +mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 1 })); +mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 300 }); +mockEndpoint('zones.destroy', () => { + throw httpError(403); +}); +``` + +- The client checks the input first, as for a request. Then it parses the data of the handler with + the response schema of the endpoint, as it parses a response. The data can leave out fields: a + missing required field gets its empty value, such as `''`, `0` or `[]`. A field with the wrong + type is a `response_invalid` error. +- `respond(data, { status, headers, total })` sets the status and the headers. `total` is the + `X-Total-Count` that `pageInfo` and `orThrowPage` read. +- `mockEndpoint` returns the function that removes the mock. `clearEndpointMocks()` removes all. +- A call to an endpoint without a mock goes to the `fetch` of the client. Give `mockFetch` of + `@placeos/ts-client/compat` to answer it from the v1 mock endpoints. +- `mock` of the client is a function. A test can give its own, which gets the name of the endpoint + (such as `zones.show`) and the input, and returns an answer or `null`. + +A test double of a v2 call gives a `Result`. `mockReply` and `mockPage` of +`@placeos/ts-client/compat` make one: + +```ts +vi.mock('@placeos/ts-client', { spy: true }); +vi.mocked(zones.show).mockResolvedValue(mockReply(zone)); +vi.mocked(zones.index).mockResolvedValue(mockPage({ data: [zone], total: 1 })); +``` + +### Mock mode + +For new mocks, use [typed mocks](#typed-mocks). The v1 mock endpoints and mock systems are in +`@placeos/ts-client/compat`, with the same names. +Give `mockFetch` to the client, and `mockRealtimeEnvironment()` to the realtime client: + +```ts +registerMockEndpoint({ + path: '/api/engine/v2/zones/:id', + method: 'GET', + callback: (request) => ({ id: request.route_params['id'], name: 'Level 1' }), +}); +registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); + +configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch, missingFields: 'zero' }); +const realtime = createRealtime({ + baseUrl: '', + auth: { kind: 'none' }, + environment: mockRealtimeEnvironment(), +}); +``` + +- v2 parses each mock response with the schema of the operation. Mock data often has only some + fields. `missingFields: 'zero'` gives each missing required field its empty value, such as `''`, + `0` or `[]`, as the v1 classes did. A field with the wrong type is still an error, because the + real server does not send it. +- A mock endpoint that throws an error with a `status`, such as `404`, gives that HTTP status. +- A change to a variable of a mock module, such as `mockSystem('sys-1')['Display'][0]['power'] += true`, notifies its bindings. + ## Log in `createAuthSession` does the OAuth login of PlaceOS and gives the client its credential: @@ -183,8 +252,9 @@ Other parts of the session: login with `authorization_denied`. v1 sent the user to the authorize page again. - `/auth/authority` gets `AUTHORITY_ATTEMPTS_MAX` attempts, not an unlimited number. Then `start` gives `authority_unavailable`. Call `start` again to try again. -- Not ported: `revokeToken`, the mock mode (give a `fetch` to the client), the state of the - application in `authorise(state)`, and the ACA Engine API path. +- Not ported: `revokeToken`, the state of the application in `authorise(state)`, and the ACA + Engine API path. The mock mode is in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). + It does not need a login: give `auth: { kind: 'none' }`. ## Realtime @@ -229,8 +299,8 @@ release(); - Server errors have the correct code name. v1 read the HTTP style status as the error code. - `iface: true` addresses an interface, such as `Interface::Sensor`. - After 40 failed attempts, the status is `failed`. v1 reloaded the page. -- Not ported: the mock systems (give an `environment` with a fake socket), the - `connectionState` signal, and the `/control/websocket` path of ACA Engine. +- Not ported: the `connectionState` signal and the `/control/websocket` path of ACA Engine. The + mock systems are in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). ## Types @@ -244,6 +314,21 @@ Each schema of the API document has a value and two types with the same base nam The parser removes the fields that the schema does not have. A request that has a field that the schema does not have stops with an error, because a typing error in a field name is a bug. +Some schemas have a name from the server code that does not say what they are. These have a +short name too. The short name is the same value and type: + +| Short name | Name in the API document | +| ------------------------ | ------------------------------- | +| `User` | `UserAdminMetadataResponse` | +| `System` | `ControlSystem` | +| `Application` | `DoorkeeperApplication` | +| `Domain` | `Authority` | +| `Metadata` | `MetadataInterface` | +| `ShortUrl` | `Shortener` | +| `SignageTemplateMapping` | `SignageTemplateSystemTemplate` | + +`TYPE_ALIASES` in `scripts/generate.ts` has the list. + ## Differences from the API document The generator changes some parts of the document. Each change has a comment in @@ -329,19 +414,43 @@ The tool makes these changes: - A new import gets another name when the file has the name. For example, a file with a `zones` variable gets `zones as zonesV2`. +The tool also changes the test doubles, so that the tests of the app still work: + +- `vi.mocked(showZone)`, `expect(showZone)`, `vi.spyOn(client, 'showZone')` and, in a spec file, + each other use of `showZone` become `zones.show`. +- A value of `mockResolvedValue` gets `mockReply` or `mockPage`. The arguments of + `toHaveBeenCalledWith` become the v2 input. +- A v1 implementation, such as the value of `mockImplementation`, gets `fromV1Mock`. It gives the + implementation the v1 arguments, and makes a v2 result of its value. +- The v1 functions of a `vi.mock('@placeos/ts-client', () => ({ ... }))` factory become v2 + namespaces: `showZone: vi.fn(impl)` becomes `zones: { show: vi.fn(fromV1Mock(impl, ['id', +'...'])) }`. The factory runs before the imports, so the tool adds `fromV1Mock` with + `vi.hoisted`. +- The imports of the mock endpoints and mock systems move to `@placeos/ts-client/compat`. See + [Mock mode](#mock-mode). + The tool does not change a use that it cannot rewrite safely. It shows each one with a hint, and it keeps its v1 import, so the compiler also shows it. These uses are: - the login and the realtime functions, such as `setup`, `token` and `getModule`; -- `get`, `post` and the other HTTP functions, and the mock endpoints of tests; -- `new` on a v1 class, because v2 has plain objects; -- a function that is not called, such as a test double of `showZone`; +- `get`, `post` and the other HTTP functions; +- `new` and `instanceof` on a v1 class, because v2 has plain objects; +- the `next` function of a v1 page. v2 gives `nextOffset`; +- a function that is not called, out of a test; +- a `vi.mock` without a factory or `{ spy: true }`: its v2 functions give `undefined`, and + `.then(orThrow)` fails; +- a `jest.mock` factory with v1 functions; - an argument that has no place in v2, and an argument with side effects that v2 uses two times. +On a copy of backoffice, 329 of the 399 tests pass after the tool. v1 passes 394. The other tests +use v1 classes, the v1 `next` function or the v1 `createSignal`, or wait for one microtask only. +These are the uses that the tool shows. + After the tool: 1. Run Prettier, or your formatter. The tool writes long imports on one line. -2. Install v2, and call `configure` once before the first call (see [Log in](#log-in)). +2. Install v2, and call `configure` once before the first call (see [Log in](#log-in)). For a + mock mode, give `fetch: mockFetch` (see [Mock mode](#mock-mode)). 3. Run the compiler. It shows the differences of the data. For example, a field that can be `null`, an array that is `readonly`, or a query parameter that has a different type in v2. 4. Change the uses that the tool showed. @@ -354,13 +463,15 @@ arguments, and it finds the v2 operation with the same method and path. ## What v1 has that v2 does not have -- The mock systems. Give `createClient` a `fetch` function. - Classes with methods for each model. v2 has plain data and functions. ## Where v2 does not follow TigerStyle - `orThrow` and `orThrowPage` of `@placeos/ts-client/compat` throw. They are for code that moves from v1. +- The v1 mock types of `@placeos/ts-client/compat` (`MockHttpRequest.body`, `metadata` and + `MockModule`) keep `any`, so that the mocks of an app still compile. +- `missingFields: 'zero'` accepts data without its required fields. It is for mock data only. - `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove that the parser output has the type of the schema. The tests check the parser. - `configure` keeps one client in module state, so a call does not need a client argument. A diff --git a/v2/package.json b/v2/package.json index 58c97f142..691fdabd4 100644 --- a/v2/package.json +++ b/v2/package.json @@ -15,8 +15,12 @@ "default": "./dist/index.js" }, "./compat": { - "types": "./dist/compat.d.ts", - "default": "./dist/compat.js" + "types": "./dist/compat/index.d.ts", + "default": "./dist/compat/index.js" + }, + "./mock": { + "types": "./dist/mock/index.d.ts", + "default": "./dist/mock/index.js" } }, "bin": { diff --git a/v2/scripts/generate.ts b/v2/scripts/generate.ts index 70afb7fbf..602c63791 100644 --- a/v2/scripts/generate.ts +++ b/v2/scripts/generate.ts @@ -162,6 +162,20 @@ const JSON_RESPONSE_OPERATIONS: ReadonlySet = new Set([ 'PlaceOS::Api::Systems_execute', ]); +/** + * Short names for schemas with a name from the server code that does not say what they are. The + * app name is an alias: `User` and `UserAdminMetadataResponse` are the same value and type. + */ +const TYPE_ALIASES: ReadonlyMap = new Map([ + ['UserAdminMetadataResponse', 'User'], + ['ControlSystem', 'System'], + ['DoorkeeperApplication', 'Application'], + ['Authority', 'Domain'], + ['MetadataInterface', 'Metadata'], + ['Shortener', 'ShortUrl'], + ['SignageTemplateSystemTemplate', 'SignageTemplateMapping'], +]); + /** Names that the core modules export. A generated name must not hide one. */ const CORE_NAMES: ReadonlySet = new Set([ 'AnyOperation', @@ -902,7 +916,25 @@ function writeSchemasFile(named: ReadonlyMap named.get(name)?.code ?? '').join('\n'); - return `${HEADER}${importLine([...combinators], '../core/schema.ts')}\n${body}`; + return `${HEADER}${importLine([...combinators], '../core/schema.ts')}\n${body}\n${aliasExports(named)}`; +} + +/** The exports of `TYPE_ALIASES`, for the value, the type and the input type. */ +function aliasExports(named: ReadonlyMap): string { + const taken = new Set(); + for (const name of named.keys()) + for (const suffix of ['', 'Input', 'Schema']) taken.add(name + suffix); + const lines = ['/** Short names. Each one is the same value and type as the long name. */']; + for (const [name, alias] of TYPE_ALIASES) { + assert(named.has(name), `the alias ${alias} has the schema ${name}`); + for (const generated of [alias, `${alias}Input`]) { + assert(!taken.has(generated), `the alias ${generated} is not a schema name`); + assert(!CORE_NAMES.has(generated), `the alias ${generated} is not a core name`); + taken.add(generated); + } + lines.push(`export { ${name} as ${alias}, type ${name}Input as ${alias}Input };`); + } + return `${lines.join('\n')}\n`; } function writeOperationsFile(controller: string, plans: readonly OperationPlan[]): string { @@ -936,6 +968,7 @@ function writeOperationsFile(controller: string, plans: readonly OperationPlan[] `params: ${plan.params},\n` + `body: ${plan.body ?? 'null'},\n` + `response: ${plan.response ?? 'null'},\n` + + `name: '${camelCase(controllerWords(controller))}.${functionName}',\n` + `});\n`, ); } diff --git a/v2/scripts/v1-map.ts b/v2/scripts/v1-map.ts index 124799345..e47038453 100644 --- a/v2/scripts/v1-map.ts +++ b/v2/scripts/v1-map.ts @@ -22,7 +22,8 @@ const V1_SOURCE = join(ROOT, '..', 'src'); const V1_INDEX = join(V1_SOURCE, 'index.ts'); const OPERATIONS_DIR = join(ROOT, 'src', 'generated', 'operations'); const OUTPUT = join(ROOT, 'src', 'migrate', 'v1-map.ts'); -const ENUMS_OUTPUT = join(ROOT, 'src', 'migrate', 'v1-enums.ts'); +const ENUMS_OUTPUT = join(ROOT, 'src', 'compat', 'enums.ts'); +const COMPAT_INDEX = join(ROOT, 'src', 'compat', 'index.ts'); /** The v1 API host in the recorded URLs. */ const HOST = 'https://v1-map.invalid'; /** The v1 modules that are not REST functions. The tool reports their names with a hint. */ @@ -109,9 +110,17 @@ async function main(): Promise { types[model] = first[0]; } } + // The short name of a schema is the better v2 name, such as `User`. + const schemas = await readFile(join(ROOT, 'src', 'generated', 'schemas.ts'), 'utf8'); + const aliases = new Map(); + for (const [, name = '', alias = ''] of schemas.matchAll(/export \{\s*(\w+) as (\w+),/g)) { + aliases.set(name, alias); + } + for (const [model, name] of Object.entries(types)) types[model] = aliases.get(name) ?? name; const enums = readV1Enums(); - const compat: Record = { QueryResponse: 'type' }; - for (const name of enums.keys()) compat[name] = 'value'; + // A v1 name that the compat module also exports, such as `registerMockEndpoint`, moves there. + const compat = readCompatExports(new Set([...enums.keys(), ...v1Exports().exports.keys()])); + for (const name of Object.keys(compat)) delete unmapped[name]; for (const name of readV1OtherExports()) { if (name in calls || name in unmapped || name in types || name in compat) continue; unmapped[name] = 'v2 has no replacement'; @@ -153,6 +162,35 @@ async function main(): Promise { console.log(check ? `The v1 map is up to date (${count}).` : `The v1 map has ${count}.`); } +/** + * The exports of `src/compat` that v1 also has, with `value` or `type`. The enums are generated + * into `src/compat/enums.ts` by this script, so they count before the file exists. + */ +function readCompatExports(v1Names: ReadonlySet): Record { + const program = ts.createProgram([COMPAT_INDEX], { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.Preserve, + moduleResolution: ts.ModuleResolutionKind.Bundler, + allowImportingTsExtensions: true, + noEmit: true, + skipLibCheck: true, + }); + const checker = program.getTypeChecker(); + const source = program.getSourceFile(COMPAT_INDEX); + assert(source !== undefined, 'the compat index exists'); + const moduleSymbol = checker.getSymbolAtLocation(source); + assert(moduleSymbol !== undefined, 'the compat index is a module'); + const compat: Record = {}; + for (const exported of checker.getExportsOfModule(moduleSymbol)) { + const name = exported.getName(); + if (!v1Names.has(name)) continue; + const symbol = + exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; + compat[name] = symbol.flags & ts.SymbolFlags.Value ? 'value' : 'type'; + } + return compat; +} + /** The v1 enums with names as values, where the server sends numbers. v2 has the numbers. */ const NUMBER_ENUMS: Readonly>>> = { MediaAnimation: ANIMATIONS, @@ -190,7 +228,7 @@ function enumsCode( ): string { let code = '// Generated by scripts/v1-map.ts from the v1 source. Do not edit.\n' + - '/**\n * The enums of v1, for `@placeos/ts-client/compat`.\n *\n * @module\n */\n'; + '/**\n * The enums of v1, with the values of v2, for `@placeos/ts-client/compat`.\n *\n * @module\n */\n'; for (const [name, members] of [...enums].sort(([a], [b]) => a.localeCompare(b))) { const fields = members.map((member) => `${member.key}: ${JSON.stringify(member.value)}`); code += diff --git a/v2/src/compat.ts b/v2/src/compat.ts deleted file mode 100644 index 20b07bae8..000000000 --- a/v2/src/compat.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Helpers for code that moves from v1, at `@placeos/ts-client/compat`. The migration tool uses - * them. - * - * A v1 function gives a promise that rejects on an error. `orThrow` does the same for a v2 call: - * - * ```ts - * const zone = await zones.show({ id }).then(orThrow); - * ``` - * - * New code checks the `Result`. Then the compiler shows each error that a call can give. - * - * @module - */ -import type { CallError, Reply } from './core/client.ts'; -import { pageInfo } from './core/pagination.ts'; -import type { Result } from './core/result.ts'; - -export * from './migrate/v1-enums.ts'; - -/** The error of `orThrow`. `error` is the v2 error. `status` is the HTTP status, as in v1. */ -export class CallFailed extends Error { - readonly error: CallError; - readonly status: number | null; - - constructor(error: CallError) { - super(describe(error)); - this.name = 'CallFailed'; - this.error = error; - this.status = - error.kind === 'http' || error.kind === 'response_invalid' ? error.status : null; - } -} - -/** Gives the data of a call, or throws `CallFailed`. */ -export function orThrow(result: Result, CallError>): T { - if (!result.ok) throw new CallFailed(result.error); - return result.value.data; -} - -/** The page of a v1 query function. v1 also gave `next`. v2 gives `nextOffset`. */ -export interface Page { - readonly data: T; - /** The `X-Total-Count` header, or `0` without it, as in v1. */ - readonly total: number; - /** Give it as the `offset` of the next call. `null` on the last page. */ - readonly nextOffset: number | null; -} - -/** The v1 type of a query function, such as `QueryResponse`. */ -export type QueryResponse = Promise>; - -/** Gives the data and the totals of an index call, or throws `CallFailed`. */ -export function orThrowPage(result: Result, CallError>): Page { - if (!result.ok) throw new CallFailed(result.error); - const page = pageInfo(result.value.headers); - return { data: result.value.data, total: page.total ?? 0, nextOffset: page.nextOffset }; -} - -function describe(error: CallError): string { - switch (error.kind) { - case 'http': - return `HTTP ${error.status}${error.message === null ? '' : `: ${error.message}`}`; - case 'response_invalid': - return `the response is not valid at ${error.path}: expected ${error.expected}`; - case 'timeout': - return `no response in ${error.timeoutMs} ms`; - case 'network': - return `network error: ${error.message}`; - case 'response_too_large': - return `the response is larger than ${error.bytesMax} bytes`; - case 'auth_missing': - return 'no token or credential'; - case 'aborted': - return 'aborted'; - } -} diff --git a/v2/src/migrate/v1-enums.ts b/v2/src/compat/enums.ts similarity index 96% rename from v2/src/migrate/v1-enums.ts rename to v2/src/compat/enums.ts index d19352e34..6f1840ca2 100644 --- a/v2/src/migrate/v1-enums.ts +++ b/v2/src/compat/enums.ts @@ -1,6 +1,6 @@ // Generated by scripts/v1-map.ts from the v1 source. Do not edit. /** - * The enums of v1, for `@placeos/ts-client/compat`. + * The enums of v1, with the values of v2, for `@placeos/ts-client/compat`. * * @module */ diff --git a/v2/src/compat/http-mock.ts b/v2/src/compat/http-mock.ts new file mode 100644 index 000000000..e83dd4910 --- /dev/null +++ b/v2/src/compat/http-mock.ts @@ -0,0 +1,261 @@ +/** + * The mock endpoints of v1, for the v2 client. Give `mockFetch` to the client, and the v2 calls + * go to the endpoints that `registerMockEndpoint` adds: + * + * ```ts + * registerMockEndpoint({ path: '/api/engine/v2/zones/:id', method: 'GET', callback: (request) => ({ + * id: request.route_params.id, + * name: 'Zone', + * }) }); + * configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch }); + * ``` + * + * The behavior is the same as v1: a path segment `:name` is a route parameter, the response comes + * after a delay (300 ms by default), and an endpoint that is not registered gives a 404. One + * difference: v2 parses each response with the schema of the operation, so the mock data must + * match the API document. + * + * @module + */ +import { assert } from '../core/assert.ts'; +import type { FetchFunction } from '../core/client.ts'; + +/** More endpoints is a leak, such as a test that registers in a loop and never removes them. */ +export const MOCK_ENDPOINTS_MAX = 10_000; +const DELAY_MS_DEFAULT = 300; +const DELAY_VARIANCE_MS_DEFAULT = 100; +/** v1 waits at least this long, so that a mock response is never synchronous. */ +const DELAY_MS_MIN = 200; + +export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + +/** A request to a mock endpoint. */ +export interface MockHttpRequest { + /** The URL of the request. */ + readonly url: string; + /** The path of the endpoint that matched. */ + readonly path: string; + readonly method: HttpVerb; + /** The `metadata` of the endpoint. As in v1, it has no type. */ + readonly metadata: any; + /** The values of the `:name` segments of the path. */ + readonly route_params: Record; + readonly query_params: Record; + /** The JSON body. As in v1, it has no type. */ + readonly body: any; +} + +export interface MockHttpRequestHandlerOptions { + /** The path, such as `/api/engine/v2/zones/:id`. A `:name` segment matches each value. */ + path: string; + method: HttpVerb; + /** The response body when there is no `callback`. */ + metadata?: any; + /** Gives the response body. Throw an error with a `status` to send that status. */ + callback?: (request: MockHttpRequest) => T; + /** Milliseconds before the response. */ + delay?: number; + /** The delay changes by up to this many milliseconds. */ + delay_variance?: number; + /** Response headers, such as `x-total-count`. */ + headers?: Record | ((request: MockHttpRequest) => Record); +} + +export interface MockHttpRequestHandler extends MockHttpRequestHandlerOptions { + /** The segments of the path. */ + path_parts: string[]; + /** The parameter name of each segment, or `''` for a fixed segment. */ + path_structure: string[]; +} + +/** The response of a mock endpoint. */ +export interface MockHttpResponse { + readonly body: unknown; + /** The keys are lowercase. */ + readonly headers: Record; +} + +type NotFoundHandler = (method: HttpVerb, url: string) => Promise | null; + +const handlers = new Map(); + +let notFound: NotFoundHandler = (method, url) => + Promise.reject( + Object.assign(new Error(`Mock endpoint not found: ${method} ${url}`), { status: 404 }), + ); + +/** Adds an endpoint. An endpoint with the same method and path is replaced. */ +export function registerMockEndpoint(options: MockHttpRequestHandlerOptions): void { + const key = handlerKey(options.method, options.path); + assert(handlers.has(key) || handlers.size < MOCK_ENDPOINTS_MAX, 'fewer mock endpoints'); + const path_parts = pathParts(options.path); + const path_structure = path_parts.map((part) => (part.startsWith(':') ? part.slice(1) : '')); + // The map holds handlers of each response type. The callback result is only sent as JSON. + const handler: MockHttpRequestHandler = { ...options, path_parts, path_structure }; + handlers.set(key, handler); +} + +export function deregisterMockEndpoint(method: string, path: string): void { + handlers.delete(handlerKey(method, path)); +} + +export function clearMockEndpoints(): void { + handlers.clear(); +} + +/** The `method|path` of each endpoint. */ +export function listMockedEndpoints(): string[] { + return [...handlers.keys()]; +} + +/** + * Changes what happens for a request that has no endpoint. Return `null` to send the real + * request with `fetch`. + */ +export function setMockNotFoundHandler(handler: NotFoundHandler): void { + notFound = handler; +} + +/** A `fetch` for the v2 client that answers from the mock endpoints. */ +export const mockFetch: FetchFunction = async (url, init) => { + const method = verb(init.method); + const handler = findHandler(method, url); + if (handler === null) { + const fallback = notFound(method, url); + if (fallback === null) return fetch(url, init); + return fallback.then( + () => errorResponse(404, 'not found'), + (error: unknown) => thrownResponse(error), + ); + } + const request = makeRequest(url, handler, method, init.body); + let body: unknown; + let headers: Record; + try { + body = await (handler.callback === undefined + ? handler.metadata + : handler.callback(request)); + const raw = + typeof handler.headers === 'function' ? handler.headers(request) : handler.headers; + headers = lowerKeys(raw ?? {}); + } catch (error) { + return thrownResponse(error); + } + await delay(handler, init.signal ?? null); + if (body === undefined) return new Response(null, { status: 204, headers }); + const text = typeof body === 'string' ? body : JSON.stringify(body); + return new Response(text, { + status: 200, + headers: { 'content-type': 'application/json', ...headers }, + }); +}; + +function handlerKey(method: string, path: string): string { + return `${method}|${path}`; +} + +/** The path segments, without the origin, the query and the first `/`. */ +function pathParts(url: string): string[] { + const path = url.replace(/^https?:\/\/[^/]*/, '').split('?')[0] ?? ''; + return path.replace(/^\//, '').split('/'); +} + +function verb(method: string | undefined): HttpVerb { + const upper = (method ?? 'GET').toUpperCase(); + assert( + upper === 'GET' || + upper === 'POST' || + upper === 'PUT' || + upper === 'PATCH' || + upper === 'DELETE', + `the mock supports the method ${upper}`, + ); + return upper; +} + +function findHandler(method: HttpVerb, url: string): MockHttpRequestHandler | null { + const parts = pathParts(url); + for (const handler of handlers.values()) { + if (handler.method !== method || handler.path_parts.length !== parts.length) continue; + const matches = handler.path_structure.every( + (parameter, index) => parameter !== '' || handler.path_parts[index] === parts[index], + ); + if (matches) return handler; + } + return null; +} + +function makeRequest( + url: string, + handler: MockHttpRequestHandler, + method: HttpVerb, + body: RequestInit['body'], +): MockHttpRequest { + const parts = pathParts(url); + const route_params: Record = {}; + for (const [index, name] of handler.path_structure.entries()) { + if (name !== '') route_params[name] = decodeURIComponent(parts[index] ?? ''); + } + const query_params: Record = {}; + const query = url.split('?')[1] ?? ''; + for (const [key, value] of new URLSearchParams(query)) { + // v1 leaves out the parameters with no value. + if (value !== '') query_params[key] = value; + } + return { + url, + path: handler.path, + method, + metadata: handler.metadata, + route_params, + query_params, + body: typeof body === 'string' ? parseJson(body) : undefined, + }; +} + +function parseJson(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return text; + } +} + +function lowerKeys(headers: Record): Record { + const lower: Record = {}; + for (const [key, value] of Object.entries(headers)) lower[key.toLowerCase()] = value; + return lower; +} + +/** A thrown value with a `status` gives that status. Another one is a network error, as in v1. */ +function thrownResponse(error: unknown): Response { + const status = + typeof error === 'object' && error !== null ? Reflect.get(error, 'status') : undefined; + if (typeof status !== 'number' || status < 400 || status > 599) throw error; + return errorResponse(status, error instanceof Error ? error.message : String(status)); +} + +function errorResponse(status: number, message: string): Response { + return new Response(JSON.stringify({ error: message }), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +function delay(handler: MockHttpRequestHandler, signal: AbortSignal | null): Promise { + const variance = handler.delay_variance ?? DELAY_VARIANCE_MS_DEFAULT; + const base = handler.delay ?? DELAY_MS_DEFAULT; + const ms = Math.max(DELAY_MS_MIN, Math.floor(Math.random() * variance - variance / 2) + base); + return new Promise((resolve, reject) => { + const aborted = () => { + clearTimeout(timer); + reject(new DOMException('The request was aborted.', 'AbortError')); + }; + const timer = setTimeout(() => { + signal?.removeEventListener('abort', aborted); + resolve(); + }, ms); + if (signal?.aborted === true) aborted(); + else signal?.addEventListener('abort', aborted, { once: true }); + }); +} diff --git a/v2/src/compat/index.ts b/v2/src/compat/index.ts new file mode 100644 index 000000000..0e48c98c3 --- /dev/null +++ b/v2/src/compat/index.ts @@ -0,0 +1,16 @@ +/** + * Helpers for code that moves from v1, at `@placeos/ts-client/compat`. The migration tool moves + * the v1 imports of these names here. + * + * - `orThrow` and `orThrowPage` give the data of a v2 call, and throw on an error, as v1 did. + * - `mockReply` and `mockPage` make v2 results for the test doubles of v2 calls. + * - `registerMockEndpoint` and `mockFetch` are the v1 mock endpoints, for the v2 client. + * - `registerSystem` and `mockRealtimeEnvironment` are the v1 mock systems, for `createRealtime`. + * - The v1 enums, with the values of v2. + * + * @module + */ +export * from './enums.ts'; +export * from './http-mock.ts'; +export * from './realtime-mock.ts'; +export * from './result.ts'; diff --git a/v2/src/compat/realtime-mock.ts b/v2/src/compat/realtime-mock.ts new file mode 100644 index 000000000..1563156ea --- /dev/null +++ b/v2/src/compat/realtime-mock.ts @@ -0,0 +1,249 @@ +/** + * The mock systems of v1, for the v2 realtime client. Give `mockRealtimeEnvironment()` to + * `createRealtime`, and the bindings and calls go to the systems that `registerSystem` adds: + * + * ```ts + * registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); + * const realtime = createRealtime({ baseUrl: '', auth, environment: mockRealtimeEnvironment() }); + * const display = mockSystem('sys-1')?.['Display']?.[0]; + * if (display !== undefined) display['power'] = true; // The bindings of `power` get `true`. + * ``` + * + * As in v1, a function of a module is a property with a function value. Its name can start with + * `$`. `exec` of a function that the module does not have gives `null`. + * + * @module + */ +import { assert } from '../core/assert.ts'; +import type { + RealtimeEnvironment, + RealtimeSocket, + SocketHandlers, +} from '../realtime/environment.ts'; +import { ERROR_CODE_NAMES } from '../realtime/realtime.ts'; + +/** More systems is a leak, such as a test that registers in a loop and never removes them. */ +export const MOCK_SYSTEMS_MAX = 10_000; + +/** A mock module: its status variables and its functions. As in v1, the values have no type. */ +export type MockModule = Record; +/** The modules of a mock system, by class. `Display: [first, second]` is `Display_1` and `Display_2`. */ +export type MockSystem = Record; +/** The v1 names of the types. */ +export type MockPlaceWebsocketSystem = MockSystem; +export type MockPlaceWebsocketModule = MockModule; + +type Listener = (value: unknown) => void; + +interface ModuleState { + readonly module: MockModule; + readonly values: Map; + readonly listeners: Map>; +} + +const systems = new Map }>(); + +/** Adds a mock system, or replaces the system with this ID. Gives the system. */ +export function registerSystem(id: string, details: Record): MockSystem { + assert(systems.has(id) || systems.size < MOCK_SYSTEMS_MAX, 'fewer mock systems'); + const system: MockSystem = {}; + const modules = new Map(); + for (const [name, list] of Object.entries(details)) { + const states = list.map(mockModule); + modules.set(name, states); + system[name] = states.map((state) => state.module); + } + systems.set(id, { system, modules }); + return system; +} + +/** The mock system with this ID, or `undefined`. */ +export function mockSystem(id: string): MockSystem | undefined { + return systems.get(id)?.system; +} + +export function deregisterSystem(id: string): void { + systems.delete(id); +} + +/** + * Each property that is not a function becomes a status variable. A change to it notifies the + * bindings of the variable. + */ +function mockModule(properties: object): ModuleState { + const module: MockModule = {}; + const values = new Map(); + const listeners = new Map>(); + const state: ModuleState = { module, values, listeners }; + // v1 also takes the `$` functions of a class prototype. + const prototype: unknown = Object.getPrototypeOf(properties); + const inherited = + prototype === null || prototype === Object.prototype + ? [] + : Object.getOwnPropertyNames(prototype).filter((name) => name.startsWith('$')); + for (const key of [...Object.keys(properties), ...inherited]) { + const value: unknown = Reflect.get(properties, key); + if (typeof value === 'function') { + // `execute` calls it with the module as `this`, as v1 does. + module[key.startsWith('$') ? key : `$${key}`] = value; + continue; + } + addVariable(state, key.replace(/^\$/, ''), value); + } + return state; +} + +function addVariable(state: ModuleState, name: string, value: unknown): void { + state.values.set(name, value); + Object.defineProperty(state.module, name, { + enumerable: true, + get: () => state.values.get(name), + set: (next: unknown) => { + state.values.set(name, next); + for (const listener of [...(state.listeners.get(name) ?? [])]) listener(next); + }, + }); +} + +/** A realtime environment with a fake socket that answers from the mock systems. */ +export function mockRealtimeEnvironment(): RealtimeEnvironment { + return { + createSocket, + currentUrl: () => (typeof location === 'undefined' ? 'http://localhost/' : location.href), + tokenTransport: 'query', + setCookie: () => {}, + now: () => Date.now(), + setTimer: (milliseconds, callback) => { + const timer = setTimeout(callback, milliseconds); + return () => clearTimeout(timer); + }, + }; +} + +/** The request of the client (`PlaceOS::Api::WebSocket::Session::Request`). */ +interface Request { + readonly id: number; + readonly cmd: string; + readonly sys: string; + readonly mod: string; + readonly index: number; + readonly name: string; + readonly args: readonly unknown[]; +} + +function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket { + let open = true; + /** The listener of each binding, by the JSON of its target. */ + const bound = new Map void>(); + // The socket answers later, as a real one does. + const later = (work: () => void) => + setTimeout(() => { + if (open) work(); + }, 0); + const reply = (message: object) => later(() => handlers.message(JSON.stringify(message))); + later(() => handlers.open()); + + function handle(request: Request): void { + const meta = { + sys: request.sys, + mod: request.mod, + index: request.index, + name: request.name, + }; + const key = JSON.stringify(meta); + const found = systems.get(request.sys); + const state = found?.modules.get(request.mod)?.[request.index - 1]; + if (state === undefined) { + const code = found === undefined ? 'system_not_found' : 'module_not_found'; + reply({ + id: request.id, + type: 'error', + error_code: ERROR_CODE_NAMES.indexOf(code), + msg: `mock ${code.replace('_', ' ')}: ${request.sys} ${request.mod}_${request.index}`, + }); + return; + } + switch (request.cmd) { + case 'bind': { + if (!state.values.has(request.name)) addVariable(state, request.name, null); + const notify: Listener = (value) => + reply({ id: request.id, type: 'notify', value: value ?? null, meta }); + bound.get(key)?.(); + const listeners = state.listeners.get(request.name) ?? new Set(); + listeners.add(notify); + state.listeners.set(request.name, listeners); + bound.set(key, () => listeners.delete(notify)); + reply({ id: request.id, type: 'success' }); + notify(state.values.get(request.name)); + return; + } + case 'unbind': + bound.get(key)?.(); + bound.delete(key); + reply({ id: request.id, type: 'success' }); + return; + case 'exec': + void execute(state, request).then( + (value) => reply({ id: request.id, type: 'success', value: value ?? null }), + (error: unknown) => + reply({ + id: request.id, + type: 'error', + error_code: ERROR_CODE_NAMES.indexOf('request_failed'), + msg: error instanceof Error ? error.message : String(error), + }), + ); + return; + default: + // `debug` and `ignore`: the mock has no logs. + reply({ id: request.id, type: 'success' }); + } + } + + return { + send: (text) => { + assert(open, 'the mock socket is open'); + if (text === 'ping') { + later(() => handlers.message('pong')); + return; + } + const request = parseRequest(text); + if (request !== null) handle(request); + }, + close: () => { + if (!open) return; + for (const release of bound.values()) release(); + bound.clear(); + open = false; + setTimeout(() => handlers.close(), 0); + }, + }; +} + +async function execute(state: ModuleState, request: Request): Promise { + const fn: unknown = state.module[`$${request.name}`]; + if (typeof fn !== 'function') return null; + return Reflect.apply(fn, state.module, [...request.args]); +} + +function parseRequest(text: string): Request | null { + let value: unknown; + try { + value = JSON.parse(text); + } catch { + return null; + } + if (typeof value !== 'object' || value === null) return null; + const field = (key: string): unknown => Reflect.get(value, key); + const id = field('id'); + const cmd = field('cmd'); + const sys = field('sys'); + const mod = field('mod'); + const index = field('index'); + const name = field('name'); + const args = field('args'); + if (typeof id !== 'number' || typeof cmd !== 'string' || typeof sys !== 'string') return null; + if (typeof mod !== 'string' || typeof index !== 'number' || typeof name !== 'string') + return null; + return { id, cmd, sys, mod, index, name, args: Array.isArray(args) ? args : [] }; +} diff --git a/v2/src/compat/result.ts b/v2/src/compat/result.ts new file mode 100644 index 000000000..a6d6bf03c --- /dev/null +++ b/v2/src/compat/result.ts @@ -0,0 +1,155 @@ +/** + * The result helpers of `@placeos/ts-client/compat`. + * + * A v1 function gives a promise that rejects on an error. `orThrow` does the same for a v2 call: + * + * ```ts + * const zone = await zones.show({ id }).then(orThrow); + * ``` + * + * New code checks the `Result`. Then the compiler shows each error that a call can give. + * + * @module + */ +import type { CallError, Reply } from '../core/client.ts'; +import { pageInfo } from '../core/pagination.ts'; +import type { Result } from '../core/result.ts'; + +/** The error of `orThrow`. `error` is the v2 error. `status` is the HTTP status, as in v1. */ +export class CallFailed extends Error { + readonly error: CallError; + readonly status: number | null; + + constructor(error: CallError) { + super(describe(error)); + this.name = 'CallFailed'; + this.error = error; + this.status = + error.kind === 'http' || error.kind === 'response_invalid' ? error.status : null; + } +} + +/** Gives the data of a call, or throws `CallFailed`. */ +export function orThrow(result: Result, CallError>): T { + if (!result.ok) throw new CallFailed(result.error); + return result.value.data; +} + +/** The page of a v1 query function. v1 also gave `next`. v2 gives `nextOffset`. */ +export interface Page { + readonly data: T; + /** The `X-Total-Count` header, or `0` without it, as in v1. */ + readonly total: number; + /** Give it as the `offset` of the next call. `null` on the last page. */ + readonly nextOffset: number | null; +} + +/** The v1 type of a query function, such as `QueryResponse`. */ +export type QueryResponse = Promise>; + +/** Gives the data and the totals of an index call, or throws `CallFailed`. */ +export function orThrowPage(result: Result, CallError>): Page { + if (!result.ok) throw new CallFailed(result.error); + const page = pageInfo(result.value.headers); + return { data: result.value.data, total: page.total ?? 0, nextOffset: page.nextOffset }; +} + +/** + * A successful v2 result with this data, for a test double of a v2 call: + * + * ```ts + * vi.mocked(zones.show).mockResolvedValue(mockReply(zone)); + * ``` + */ +export function mockReply(data: T, status = 200): Result, CallError> { + return { ok: true, value: { status, headers: new Headers(), data } }; +} + +/** + * The v2 result for a v1 page, for a test double of an index call. `total` goes in the + * `X-Total-Count` header, so `orThrowPage` gives it back. + * + * ```ts + * vi.mocked(zones.index).mockResolvedValue(mockPage({ data: [zone], total: 1 })); + * ``` + */ +export function mockPage(page: { + readonly data: T; + readonly total?: number; + /** The `next` of a v1 page. v2 has no use for it. */ + readonly next?: unknown; +}): Result, CallError> { + const headers = new Headers(); + if (page.total !== undefined) headers.set('x-total-count', String(page.total)); + return { ok: true, value: { status: 200, headers, data: page.data } }; +} + +/** In the arguments of `fromV1Mock`, the input values that no other argument has. */ +export const REST = '...'; + +/** + * A v2 test double from the implementation of a v1 test double. It calls `implementation` with + * the v1 arguments, and gives its value as a v2 result. The migration tool writes these in the + * `vi.mock` factories: + * + * ```ts + * // v1: showZone: vi.fn((id, query) => Promise.resolve({ id })), + * zones: { show: vi.fn(fromV1Mock((id, query) => Promise.resolve({ id }), ['id', '...'])) }, + * ``` + * + * `args` gives the input key of each v1 argument: `null` for none, and `'...'` for the other + * values of the input, such as the query of `showZone`. An empty last argument is left out, as + * the v1 call left it out. `key` is for a v1 function that selects a key of the data, such as the + * `name` of `showMetadata`. + * + * Without an implementation, the data is `undefined`, as the value of a v1 `vi.fn()` was. + */ +export function fromV1Mock( + implementation: ((...args: never[]) => unknown) | undefined, + args: readonly (string | null)[], + result: 'data' | 'page' = 'data', + key?: string, +): (input: Readonly>) => Promise, CallError>> { + const named = new Set(args.filter((arg) => arg !== null && arg !== REST)); + return async (input) => { + const values = args.map((arg) => { + if (arg === null) return undefined; + if (arg !== REST) return input[arg]; + const rest = Object.entries(input).filter( + ([name, value]) => !named.has(name) && value !== undefined, + ); + return rest.length === 0 ? undefined : Object.fromEntries(rest); + }); + while (values.length > 0 && values.at(-1) === undefined) values.pop(); + const value: unknown = + implementation === undefined + ? undefined + : await Reflect.apply(implementation, undefined, values); + if (key !== undefined) return mockReply({ [String(input[key])]: value }); + if (result === 'data') return mockReply(value); + // A v1 page is `{ data, total, next }`. + const page = typeof value === 'object' && value !== null ? value : {}; + const total: unknown = Reflect.get(page, 'total'); + const data: unknown = Reflect.get(page, 'data'); + return mockPage(typeof total === 'number' ? { data, total } : { data }); + }; +} + +function describe(error: CallError): string { + switch (error.kind) { + case 'http': + return `HTTP ${error.status}${error.message === null ? '' : `: ${error.message}`}`; + case 'response_invalid': + return `the response is not valid at ${error.path}: expected ${error.expected}`; + case 'timeout': + return `no response in ${error.timeoutMs} ms`; + case 'network': + return `network error: ${error.message}`; + case 'response_too_large': + return `the response is larger than ${error.bytesMax} bytes`; + case 'auth_missing': + return 'no token or credential'; + case 'aborted': + return 'aborted'; + } +} diff --git a/v2/src/core/client.ts b/v2/src/core/client.ts index b7a31aef4..f331e29d6 100644 --- a/v2/src/core/client.ts +++ b/v2/src/core/client.ts @@ -64,6 +64,33 @@ export interface ClientConfig { /** The maximum size of a response body. A larger body gives a `response_too_large` error. */ readonly responseBytesMax?: number; readonly fetch?: FetchFunction; + /** + * `zero` fills a missing required field of a response with its empty value, such as `''`. + * Only for mock data, such as the mock endpoints of `@placeos/ts-client/compat`. + */ + readonly missingFields?: 'error' | 'zero'; + /** + * Answers calls without a request, for tests and a mock mode. `@placeos/ts-client/mock` has + * one with a typed handler for each endpoint. + */ + readonly mock?: CallMock; +} + +/** + * Gives the answer to a call, or `null` to send the request. The client parses the data with the + * response schema of the operation, as it parses a response of the server. A missing required + * field gets its empty value. + */ +export type CallMock = (call: { + readonly name: string; + readonly input: Readonly>; +}) => Promise | null; + +export interface MockAnswer { + readonly status: number; + readonly headers: Headers; + /** The JSON data, or the bytes for an operation without a response schema. */ + readonly data: unknown; } /** The settings that each request uses. Make one with `createClient`. */ @@ -74,6 +101,8 @@ export interface Client { readonly timeoutMs: number; readonly responseBytesMax: number; readonly fetch: FetchFunction; + readonly missingFields: 'error' | 'zero'; + readonly mock: CallMock | null; } export interface CallOptions { @@ -130,6 +159,8 @@ export interface Operation< readonly params: P; readonly body: B; readonly response: R; + /** The namespace and the function, for example `zones.show`. */ + readonly name: string; } export type AnyOperation = Operation; @@ -187,6 +218,8 @@ export function createClient(config: ClientConfig): Client { timeoutMs, responseBytesMax, fetch: fetchFunction, + missingFields: config.missingFields ?? 'error', + mock: config.mock ?? null, }); } @@ -217,6 +250,7 @@ export function operation< R extends AnySchema | null, >(definition: Operation): Operation { assert(definition.path.startsWith('/'), 'the path starts with a slash'); + assert(/^\w+\.\w+$/.test(definition.name), 'the name is .'); assert(definition.params.node.kind === 'object', 'the params schema is an object'); // `[^{}]` cannot match a brace, so the match is linear also for a path with many braces. const templateKeys = [...definition.path.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]); @@ -270,6 +304,10 @@ async function send( bodyText = JSON.stringify(bodyChecked.value); } + // A mock gets the input after the checks, so a test finds the same errors as the server. + const answer = client.mock?.({ name: operation.name, input }) ?? null; + if (answer !== null) return mockResult(operation, await answer); + const timeoutMs = options.timeoutMs ?? client.timeoutMs; assertPositiveInteger(timeoutMs, 'timeoutMs'); // One deadline for the call. The credential, a renewal and each fetch share it, so a slow @@ -337,7 +375,54 @@ async function send( error: { kind: 'response_invalid', status: reply.status, path: '$', expected: 'JSON' }, }; } - const data = parseResponse(operation.response, parsed.value); + const data = parseResponse(operation.response, parsed.value, { + missingFields: client.missingFields, + }); + if (!data.ok) { + return { + ok: false, + error: { kind: 'response_invalid', status: reply.status, ...data.error }, + }; + } + return { ok: true, value: { ...reply, data: data.value } }; +} + +/** The result of a mock answer. The data goes through JSON, as the data of a response does. */ +function mockResult( + operation: AnyOperation, + answer: MockAnswer, +): Result, CallError> { + const reply = { status: answer.status, headers: answer.headers }; + const bytes = + answer.data instanceof Uint8Array + ? answer.data + : new TextEncoder().encode( + typeof answer.data === 'string' && operation.response === null + ? answer.data + : (JSON.stringify(answer.data) ?? 'null'), + ); + if (answer.status < 200 || answer.status > 299) { + const parsed = decodeJson(bytes); + const body = parsed.ok ? parseResponse(json(), parsed.value) : null; + const errorBody = body !== null && body.ok ? body.value : null; + const message = + isRecord(errorBody) && typeof errorBody['error'] === 'string' + ? errorBody['error'] + : null; + return { + ok: false, + error: { kind: 'http', status: answer.status, message, body: errorBody }, + }; + } + if (operation.response === null) return { ok: true, value: { ...reply, data: bytes } }; + const parsed = decodeJson(bytes); + if (!parsed.ok) { + return { + ok: false, + error: { kind: 'response_invalid', status: reply.status, path: '$', expected: 'JSON' }, + }; + } + const data = parseResponse(operation.response, parsed.value, { missingFields: 'zero' }); if (!data.ok) { return { ok: false, diff --git a/v2/src/core/schema.ts b/v2/src/core/schema.ts index 1ee5d06d8..53c3d9a51 100644 --- a/v2/src/core/schema.ts +++ b/v2/src/core/schema.ts @@ -227,9 +227,14 @@ export function union( * The output is a new value. It has each field of the schema, in the order of the schema, and no * other fields. */ -export function parseResponse(schema: Schema, value: unknown): Result { +export function parseResponse( + schema: Schema, + value: unknown, + options: ParseOptions = {}, +): Result { const failure: Failure = { expected: '', segments: [] }; - const parsed = walk(schema.node, value, 'response', failure, 0); + const direction = options.missingFields === 'zero' ? 'response_zero' : 'response'; + const parsed = walk(schema.node, value, direction, failure, 0); if (parsed === FAIL) return { ok: false, error: describeFailure(failure) }; // The walk built `parsed` from the same nodes that give `O` its shape. This is one of the two // places where the compiler must trust the parser. The tests check the parser. @@ -255,7 +260,17 @@ export function isRecord(value: unknown): value is Readonly zeroValue(item, depth + 1)); + case 'record': + return {}; + case 'object': { + const output: Record = {}; + for (const field of node.fields) { + output[field.key] = field.requiredInResponse + ? zeroValue(field.node, depth + 1) + : null; + } + return output; + } + case 'union': { + const [first] = node.variants; + return first === undefined ? null : zeroValue(first, depth + 1); + } + } +} + function isJsonValue(value: unknown): boolean { const stack: { readonly value: unknown; readonly depth: number }[] = [{ value, depth: 0 }]; for (let visited = 0; visited < JSON_NODES_MAX; visited += 1) { diff --git a/v2/src/generated/operations/alert-dashboards.ts b/v2/src/generated/operations/alert-dashboards.ts index aa62ae23b..4e9881081 100644 --- a/v2/src/generated/operations/alert-dashboards.ts +++ b/v2/src/generated/operations/alert-dashboards.ts @@ -38,6 +38,7 @@ const ALERTS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Alert), + name: 'alertDashboards.alerts', }); /** @@ -59,6 +60,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: AlertDashboard, response: AlertDashboard, + name: 'alertDashboards.create', }); /** @@ -85,6 +87,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'alertDashboards.destroy', }); /** @@ -122,6 +125,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AlertDashboard), + name: 'alertDashboards.index', }); /** @@ -148,6 +152,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AlertDashboard, + name: 'alertDashboards.show', }); /** @@ -174,4 +179,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AlertDashboard, response: AlertDashboard, + name: 'alertDashboards.update', }); diff --git a/v2/src/generated/operations/alerts.ts b/v2/src/generated/operations/alerts.ts index 5922ed23a..4b2bc8f94 100644 --- a/v2/src/generated/operations/alerts.ts +++ b/v2/src/generated/operations/alerts.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Alert, response: Alert, + name: 'alerts.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'alerts.destroy', }); /** @@ -102,6 +104,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Alert), + name: 'alerts.index', }); /** @@ -130,6 +133,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Alert, + name: 'alerts.show', }); /** @@ -156,4 +160,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Alert, response: Alert, + name: 'alerts.update', }); diff --git a/v2/src/generated/operations/api-keys.ts b/v2/src/generated/operations/api-keys.ts index 8c52e1765..b05f4869a 100644 --- a/v2/src/generated/operations/api-keys.ts +++ b/v2/src/generated/operations/api-keys.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: ApiKey, response: ApiKeysResponse, + name: 'apiKeys.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'apiKeys.destroy', }); /** @@ -96,6 +98,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ApiKeysResponse), + name: 'apiKeys.index', }); /** @@ -117,6 +120,7 @@ const INSPECT_KEY = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: UserJwt, + name: 'apiKeys.inspectKey', }); /** @@ -143,6 +147,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: ApiKeysResponse, + name: 'apiKeys.show', }); /** @@ -169,4 +174,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: ApiKey, response: ApiKeysResponse, + name: 'apiKeys.update', }); diff --git a/v2/src/generated/operations/asset-categories.ts b/v2/src/generated/operations/asset-categories.ts index ac16ad11e..322e295a6 100644 --- a/v2/src/generated/operations/asset-categories.ts +++ b/v2/src/generated/operations/asset-categories.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: AssetCategory, response: AssetCategory, + name: 'assetCategories.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'assetCategories.destroy', }); /** @@ -99,6 +101,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetCategory), + name: 'assetCategories.index', }); /** @@ -125,6 +128,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetCategory, + name: 'assetCategories.show', }); /** @@ -151,4 +155,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetCategory, response: AssetCategory, + name: 'assetCategories.update', }); diff --git a/v2/src/generated/operations/asset-purchase-orders.ts b/v2/src/generated/operations/asset-purchase-orders.ts index 76419d4ad..8b20975ca 100644 --- a/v2/src/generated/operations/asset-purchase-orders.ts +++ b/v2/src/generated/operations/asset-purchase-orders.ts @@ -34,6 +34,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: AssetPurchaseOrder, response: AssetPurchaseOrder, + name: 'assetPurchaseOrders.create', }); /** @@ -60,6 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'assetPurchaseOrders.destroy', }); /** @@ -95,6 +97,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetPurchaseOrder), + name: 'assetPurchaseOrders.index', }); /** @@ -121,6 +124,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetPurchaseOrder, + name: 'assetPurchaseOrders.show', }); /** @@ -148,4 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetPurchaseOrder, response: AssetPurchaseOrder, + name: 'assetPurchaseOrders.update', }); diff --git a/v2/src/generated/operations/asset-types.ts b/v2/src/generated/operations/asset-types.ts index 67e5f1667..7b2c5cc35 100644 --- a/v2/src/generated/operations/asset-types.ts +++ b/v2/src/generated/operations/asset-types.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: AssetType, response: AssetType, + name: 'assetTypes.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'assetTypes.destroy', }); /** @@ -106,6 +108,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetType), + name: 'assetTypes.index', }); /** @@ -132,6 +135,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetType, + name: 'assetTypes.show', }); /** @@ -158,4 +162,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetType, response: AssetType, + name: 'assetTypes.update', }); diff --git a/v2/src/generated/operations/assets.ts b/v2/src/generated/operations/assets.ts index b77f041d9..808b6421c 100644 --- a/v2/src/generated/operations/assets.ts +++ b/v2/src/generated/operations/assets.ts @@ -33,6 +33,7 @@ const BULK_CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), + name: 'assets.bulkCreate', }); /** @@ -54,6 +55,7 @@ const BULK_DESTROY = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(/* @__PURE__ */ string()), response: null, + name: 'assets.bulkDestroy', }); /** @@ -75,6 +77,7 @@ const BULK_UPDATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), + name: 'assets.bulkUpdate', }); /** @@ -96,6 +99,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Asset, response: Asset, + name: 'assets.create', }); /** @@ -122,6 +126,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'assets.destroy', }); /** @@ -177,6 +182,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Asset), + name: 'assets.index', }); /** @@ -203,6 +209,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Asset, + name: 'assets.show', }); /** @@ -229,4 +236,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Asset, response: Asset, + name: 'assets.update', }); diff --git a/v2/src/generated/operations/brokers.ts b/v2/src/generated/operations/brokers.ts index afb4752ba..3244895f8 100644 --- a/v2/src/generated/operations/brokers.ts +++ b/v2/src/generated/operations/brokers.ts @@ -33,6 +33,7 @@ const COLLECTION = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(Broker), + name: 'brokers.collection', }); /** @@ -54,6 +55,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Broker, response: Broker, + name: 'brokers.create', }); /** @@ -80,6 +82,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'brokers.destroy', }); /** @@ -106,6 +109,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Broker, + name: 'brokers.show', }); /** @@ -132,4 +136,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Broker, response: Broker, + name: 'brokers.update', }); diff --git a/v2/src/generated/operations/build-monitor.ts b/v2/src/generated/operations/build-monitor.ts index a41781b0d..3f009da83 100644 --- a/v2/src/generated/operations/build-monitor.ts +++ b/v2/src/generated/operations/build-monitor.ts @@ -35,6 +35,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: BuildMonitorCancelStatus, + name: 'buildMonitor.cancel', }); /** `GET /api/engine/v2/build/monitor` */ @@ -61,4 +62,5 @@ const MONITOR = /* @__PURE__ */ operation({ /* @__PURE__ */ array(BuildMonitorTaskStatus), /* @__PURE__ */ string(), ]), + name: 'buildMonitor.monitor', }); diff --git a/v2/src/generated/operations/chat-gpt-plugin.ts b/v2/src/generated/operations/chat-gpt-plugin.ts index d7d74a58e..b4424c6dd 100644 --- a/v2/src/generated/operations/chat-gpt-plugin.ts +++ b/v2/src/generated/operations/chat-gpt-plugin.ts @@ -57,6 +57,7 @@ const CALL_FUNCTION = /* @__PURE__ */ operation({ }, ['response'], ), + name: 'chatGptPlugin.callFunction', }); /** @@ -85,6 +86,7 @@ const CAPABILITIES = /* @__PURE__ */ operation({ ), body: null, response: ChatGptPluginDetails, + name: 'chatGptPlugin.capabilities', }); /** @@ -123,4 +125,5 @@ const FUNCTION_SCHEMA = /* @__PURE__ */ operation({ ['function', 'description', 'parameters'], ), ), + name: 'chatGptPlugin.functionSchema', }); diff --git a/v2/src/generated/operations/chat-gpt.ts b/v2/src/generated/operations/chat-gpt.ts index 9af325c86..01f16b9bc 100644 --- a/v2/src/generated/operations/chat-gpt.ts +++ b/v2/src/generated/operations/chat-gpt.ts @@ -39,6 +39,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'chatGpt.destroy', }); /** @@ -74,6 +75,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Chat), + name: 'chatGpt.index', }); /** @@ -110,4 +112,5 @@ const SHOW = /* @__PURE__ */ operation({ ['role', 'timestamp'], ), ), + name: 'chatGpt.show', }); diff --git a/v2/src/generated/operations/cluster.ts b/v2/src/generated/operations/cluster.ts index 2f1d7e028..f530edd5a 100644 --- a/v2/src/generated/operations/cluster.ts +++ b/v2/src/generated/operations/cluster.ts @@ -41,6 +41,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'cluster.destroy', }); /** @@ -65,6 +66,7 @@ const NODES = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ClusterNodeStatus), + name: 'cluster.nodes', }); /** @@ -89,6 +91,7 @@ const REBALANCE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: ClusterVersions, + name: 'cluster.rebalance', }); /** @@ -118,4 +121,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(ClusterDriverStatus), + name: 'cluster.show', }); diff --git a/v2/src/generated/operations/domains.ts b/v2/src/generated/operations/domains.ts index 2329759f3..95bb1a491 100644 --- a/v2/src/generated/operations/domains.ts +++ b/v2/src/generated/operations/domains.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Authority, response: Authority, + name: 'domains.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'domains.destroy', }); /** @@ -94,6 +96,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Authority), + name: 'domains.index', }); /** @@ -121,6 +124,7 @@ const LOOKUP = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'domains.lookup', }); /** @@ -147,6 +151,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Authority, + name: 'domains.show', }); /** @@ -173,4 +178,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Authority, response: Authority, + name: 'domains.update', }); diff --git a/v2/src/generated/operations/drivers.ts b/v2/src/generated/operations/drivers.ts index c74ff4d07..f862dd167 100644 --- a/v2/src/generated/operations/drivers.ts +++ b/v2/src/generated/operations/drivers.ts @@ -38,6 +38,7 @@ const COMPILED = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'drivers.compiled', }); /** @@ -59,6 +60,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Driver, response: Driver, + name: 'drivers.create', }); /** @@ -85,6 +87,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'drivers.destroy', }); /** @@ -124,6 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Driver), + name: 'drivers.index', }); /** @@ -150,6 +154,7 @@ const README = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'drivers.readme', }); /** @@ -176,6 +181,7 @@ const RECOMPILE = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'drivers.recompile', }); /** @@ -202,6 +208,7 @@ const RELOAD = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'drivers.reload', }); /** @@ -230,6 +237,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Driver, + name: 'drivers.show', }); /** @@ -256,4 +264,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Driver, response: Driver, + name: 'drivers.update', }); diff --git a/v2/src/generated/operations/edges.ts b/v2/src/generated/operations/edges.ts index c56d70dd9..cd9a8ae9b 100644 --- a/v2/src/generated/operations/edges.ts +++ b/v2/src/generated/operations/edges.ts @@ -54,6 +54,7 @@ const CLEANUP_ERRORS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), + name: 'edges.cleanupErrors', }); /** @@ -75,6 +76,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: EdgeCreateBody, response: EdgeKeyResponse, + name: 'edges.create', }); /** @@ -101,6 +103,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'edges.destroy', }); /** @@ -127,6 +130,7 @@ const EDGE_CONNECTIONS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ nullable(ConnectionMetrics), + name: 'edges.edgeConnections', }); /** @@ -157,6 +161,7 @@ const EDGE_ERRORS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(EdgeError), + name: 'edges.edgeErrors', }); /** @@ -183,6 +188,7 @@ const EDGE_HEALTH = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ nullable(EdgeHealth), + name: 'edges.edgeHealth', }); /** @@ -209,6 +215,7 @@ const EDGE_MODULE_STATUS = /* @__PURE__ */ operation({ ), body: null, response: EdgeModuleStatus, + name: 'edges.edgeModuleStatus', }); /** @@ -230,6 +237,7 @@ const EDGES_CONNECTIONS = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(ConnectionMetrics), + name: 'edges.edgesConnections', }); /** @@ -256,6 +264,7 @@ const EDGES_ERRORS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ array(EdgeError)), + name: 'edges.edgesErrors', }); /** @@ -277,6 +286,7 @@ const EDGES_HEALTH = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(EdgeHealth), + name: 'edges.edgesHealth', }); /** @@ -300,6 +310,7 @@ const EDGES_MODULE_FAILURES = /* @__PURE__ */ operation({ response: /* @__PURE__ */ record( /* @__PURE__ */ array(/* @__PURE__ */ record(/* @__PURE__ */ json())), ), + name: 'edges.edgesModuleFailures', }); /** @@ -321,6 +332,7 @@ const EDGES_STATISTICS = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: EdgeStatistics, + name: 'edges.edgesStatistics', }); /** @@ -359,6 +371,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Edge), + name: 'edges.index', }); /** @@ -380,6 +393,7 @@ const MONITORING_SUMMARY = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), + name: 'edges.monitoringSummary', }); /** @@ -406,6 +420,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Edge, + name: 'edges.show', }); /** @@ -437,6 +452,7 @@ const TOKEN = /* @__PURE__ */ operation({ }, ['token'], ), + name: 'edges.token', }); /** @@ -463,4 +479,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Edge, response: Edge, + name: 'edges.update', }); diff --git a/v2/src/generated/operations/flux.ts b/v2/src/generated/operations/flux.ts index 2c20c9c7f..4d07a8d96 100644 --- a/v2/src/generated/operations/flux.ts +++ b/v2/src/generated/operations/flux.ts @@ -32,4 +32,5 @@ const QUERY = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ string(), response: null, + name: 'flux.query', }); diff --git a/v2/src/generated/operations/groups-history.ts b/v2/src/generated/operations/groups-history.ts index 4d570b44f..ca4d3bdbe 100644 --- a/v2/src/generated/operations/groups-history.ts +++ b/v2/src/generated/operations/groups-history.ts @@ -52,6 +52,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(History), + name: 'groupsHistory.index', }); /** `GET /api/engine/v2/group_history/{id}` */ @@ -74,4 +75,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: History, + name: 'groupsHistory.show', }); diff --git a/v2/src/generated/operations/groups-invitations.ts b/v2/src/generated/operations/groups-invitations.ts index 8889ea9c1..55cd03213 100644 --- a/v2/src/generated/operations/groups-invitations.ts +++ b/v2/src/generated/operations/groups-invitations.ts @@ -46,6 +46,7 @@ const ACCEPT = /* @__PURE__ */ operation({ ), body: null, response: GroupUser, + name: 'groupsInvitations.accept', }); /** @@ -70,6 +71,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: GroupsInvitationsInvitationCreatePayload, response: GroupsInvitationsInvitationCreatedResponse, + name: 'groupsInvitations.create', }); /** `DELETE /api/engine/v2/group_invitations/{id}` */ @@ -92,6 +94,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'groupsInvitations.destroy', }); /** @@ -129,6 +132,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupInvitation), + name: 'groupsInvitations.index', }); /** `GET /api/engine/v2/group_invitations/{id}` */ @@ -151,4 +155,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupInvitation, + name: 'groupsInvitations.show', }); diff --git a/v2/src/generated/operations/groups-users.ts b/v2/src/generated/operations/groups-users.ts index 9c2c18452..abe16a531 100644 --- a/v2/src/generated/operations/groups-users.ts +++ b/v2/src/generated/operations/groups-users.ts @@ -29,6 +29,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: GroupUser, response: GroupUser, + name: 'groupsUsers.create', }); /** `DELETE /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -52,6 +53,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'groupsUsers.destroy', }); /** @@ -90,6 +92,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupUser), + name: 'groupsUsers.index', }); /** `GET /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -113,6 +116,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupUser, + name: 'groupsUsers.show', }); /** `PATCH /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -136,4 +140,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: GroupUser, response: GroupUser, + name: 'groupsUsers.update', }); diff --git a/v2/src/generated/operations/groups-zones.ts b/v2/src/generated/operations/groups-zones.ts index f6d189e8e..a2fd38792 100644 --- a/v2/src/generated/operations/groups-zones.ts +++ b/v2/src/generated/operations/groups-zones.ts @@ -29,6 +29,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: GroupZone, response: GroupZone, + name: 'groupsZones.create', }); /** `DELETE /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -52,6 +53,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'groupsZones.destroy', }); /** @@ -87,6 +89,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupZone), + name: 'groupsZones.index', }); /** `GET /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -110,6 +113,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupZone, + name: 'groupsZones.show', }); /** `PATCH /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -133,4 +137,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: GroupZone, response: GroupZone, + name: 'groupsZones.update', }); diff --git a/v2/src/generated/operations/groups.ts b/v2/src/generated/operations/groups.ts index 378a0688c..49ee7bebd 100644 --- a/v2/src/generated/operations/groups.ts +++ b/v2/src/generated/operations/groups.ts @@ -45,6 +45,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Group, response: Group, + name: 'groups.create', }); /** `GET /api/engine/v2/groups/current` */ @@ -65,6 +66,7 @@ const CURRENT = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupsCurrentGroup), + name: 'groups.current', }); /** @@ -91,6 +93,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'groups.destroy', }); /** @@ -122,6 +125,7 @@ const FEATURES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), + name: 'groups.features', }); /** @@ -161,6 +165,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Group), + name: 'groups.index', }); /** @@ -187,6 +192,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Group, + name: 'groups.show', }); /** @@ -213,6 +219,7 @@ const SYNC_AD_GROUPS = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: GroupsAdGroupSync, response: /* @__PURE__ */ array(GroupUser), + name: 'groups.syncAdGroups', }); /** @@ -242,4 +249,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Group, response: Group, + name: 'groups.update', }); diff --git a/v2/src/generated/operations/history.ts b/v2/src/generated/operations/history.ts index ec6d727d3..0e7dff754 100644 --- a/v2/src/generated/operations/history.ts +++ b/v2/src/generated/operations/history.ts @@ -65,6 +65,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(History), + name: 'history.index', }); /** `GET /api/engine/v2/history/{id}` */ @@ -87,6 +88,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: History, + name: 'history.show', }); /** @@ -119,4 +121,5 @@ const UNDELETE = /* @__PURE__ */ operation({ ), body: null, response: PgOrmBase, + name: 'history.undelete', }); diff --git a/v2/src/generated/operations/ldap-authentications.ts b/v2/src/generated/operations/ldap-authentications.ts index 684a8d569..aaad5e908 100644 --- a/v2/src/generated/operations/ldap-authentications.ts +++ b/v2/src/generated/operations/ldap-authentications.ts @@ -34,6 +34,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: LdapAuthentication, response: LdapAuthentication, + name: 'ldapAuthentications.create', }); /** @@ -60,6 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'ldapAuthentications.destroy', }); /** @@ -97,6 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(LdapAuthentication), + name: 'ldapAuthentications.index', }); /** @@ -123,6 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: LdapAuthentication, + name: 'ldapAuthentications.show', }); /** @@ -149,4 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: LdapAuthentication, response: LdapAuthentication, + name: 'ldapAuthentications.update', }); diff --git a/v2/src/generated/operations/map-ai.ts b/v2/src/generated/operations/map-ai.ts index d90800b71..2c42a1a55 100644 --- a/v2/src/generated/operations/map-ai.ts +++ b/v2/src/generated/operations/map-ai.ts @@ -44,6 +44,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: MapAiJobResponse, + name: 'mapAi.cancel', }); /** @@ -65,6 +66,7 @@ const CAPABILITIES = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: MapAiCapabilities, + name: 'mapAi.capabilities', }); /** @@ -86,6 +88,7 @@ const EDIT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: MapAiEditParams, response: MapAiJobResponse, + name: 'mapAi.edit', }); /** @@ -115,6 +118,7 @@ const INDEX_JOBS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(MapAiJobResponse), + name: 'mapAi.indexJobs', }); /** @@ -144,6 +148,7 @@ const RESOLVE = /* @__PURE__ */ operation({ ), body: MapAiResolveParams, response: MapAiJobResponse, + name: 'mapAi.resolve', }); /** @@ -174,6 +179,7 @@ const SHOW_JOB = /* @__PURE__ */ operation({ ), body: null, response: MapAiJobResponse, + name: 'mapAi.showJob', }); /** @@ -200,4 +206,5 @@ const USAGE = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobUsageRow), + name: 'mapAi.usage', }); diff --git a/v2/src/generated/operations/metadata.ts b/v2/src/generated/operations/metadata.ts index 04cb5bb3f..1bb2338fb 100644 --- a/v2/src/generated/operations/metadata.ts +++ b/v2/src/generated/operations/metadata.ts @@ -53,6 +53,7 @@ const BULK_FETCH = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ nullable(MetadataInterface)), + name: 'metadata.bulkFetch', }); /** @@ -89,6 +90,7 @@ const CHILDREN_METADATA = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(MetadataChildren), + name: 'metadata.childrenMetadata', }); /** @@ -118,6 +120,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'metadata.destroy', }); /** @@ -151,6 +154,7 @@ const HISTORY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ array(MetadataInterface)), + name: 'metadata.history', }); /** @@ -181,6 +185,7 @@ const MERGE = /* @__PURE__ */ operation({ ), body: MetadataInterface, response: MetadataInterface, + name: 'metadata.merge', }); /** @@ -210,6 +215,7 @@ const RENAME = /* @__PURE__ */ operation({ ), body: MetadataRename, response: MetadataInterface, + name: 'metadata.rename', }); /** @@ -243,6 +249,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(MetadataInterface), + name: 'metadata.show', }); /** @@ -273,4 +280,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: MetadataInterface, response: MetadataInterface, + name: 'metadata.update', }); diff --git a/v2/src/generated/operations/modules.ts b/v2/src/generated/operations/modules.ts index 2b89dd9ad..cd80a9cc5 100644 --- a/v2/src/generated/operations/modules.ts +++ b/v2/src/generated/operations/modules.ts @@ -45,6 +45,7 @@ const CREATE = /* @__PURE__ */ operation({ }), body: Module, response: Module, + name: 'modules.create', }); /** @@ -71,6 +72,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'modules.destroy', }); /** @@ -102,6 +104,7 @@ const EXECUTE = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ array(/* @__PURE__ */ json()), response: /* @__PURE__ */ json(), + name: 'modules.execute', }); /** @@ -149,6 +152,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Module), + name: 'modules.index', }); /** @@ -178,6 +182,7 @@ const LOAD = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ boolean(), + name: 'modules.load', }); /** @@ -216,6 +221,7 @@ const LOGS = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'modules.logs', }); /** @@ -242,6 +248,7 @@ const PING = /* @__PURE__ */ operation({ ), body: null, response: ModulesPingResult, + name: 'modules.ping', }); /** @@ -268,6 +275,7 @@ const SETTINGS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Settings), + name: 'modules.settings', }); /** @@ -296,6 +304,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Module, + name: 'modules.show', }); /** @@ -322,6 +331,7 @@ const SHOW_ERROR = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'modules.showError', }); /** @@ -348,6 +358,7 @@ const START = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'modules.start', }); /** @@ -374,6 +385,7 @@ const STATE = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ string()), + name: 'modules.state', }); /** @@ -402,6 +414,7 @@ const STATE_LOOKUP = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'modules.stateLookup', }); /** @@ -433,6 +446,7 @@ const STATE_VALUE = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ json(), + name: 'modules.stateValue', }); /** @@ -459,6 +473,7 @@ const STOP = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'modules.stop', }); /** @@ -485,4 +500,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Module, response: Module, + name: 'modules.update', }); diff --git a/v2/src/generated/operations/mqtt.ts b/v2/src/generated/operations/mqtt.ts index ddb3e793d..f6c3709f4 100644 --- a/v2/src/generated/operations/mqtt.ts +++ b/v2/src/generated/operations/mqtt.ts @@ -45,6 +45,7 @@ const MQTT_ACCESS = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'mqtt.mqttAccess', }); /** @@ -69,4 +70,5 @@ const MQTT_USER = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: null, + name: 'mqtt.mqttUser', }); diff --git a/v2/src/generated/operations/oauth-applications.ts b/v2/src/generated/operations/oauth-applications.ts index b99fce13f..1327efffe 100644 --- a/v2/src/generated/operations/oauth-applications.ts +++ b/v2/src/generated/operations/oauth-applications.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: DoorkeeperApplication, response: DoorkeeperApplication, + name: 'oauthApplications.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'oauthApplications.destroy', }); /** @@ -100,6 +102,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), + name: 'oauthApplications.index', }); /** @@ -126,6 +129,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: DoorkeeperApplication, + name: 'oauthApplications.show', }); /** @@ -152,4 +156,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: DoorkeeperApplication, response: DoorkeeperApplication, + name: 'oauthApplications.update', }); diff --git a/v2/src/generated/operations/oauth-authentications.ts b/v2/src/generated/operations/oauth-authentications.ts index 2ed6b9dec..bf089d4a9 100644 --- a/v2/src/generated/operations/oauth-authentications.ts +++ b/v2/src/generated/operations/oauth-authentications.ts @@ -34,6 +34,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: OauthAuthentication, response: OauthAuthentication, + name: 'oauthAuthentications.create', }); /** @@ -60,6 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'oauthAuthentications.destroy', }); /** @@ -97,6 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(OauthAuthentication), + name: 'oauthAuthentications.index', }); /** @@ -123,6 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: OauthAuthentication, + name: 'oauthAuthentications.show', }); /** @@ -149,4 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: OauthAuthentication, response: OauthAuthentication, + name: 'oauthAuthentications.update', }); diff --git a/v2/src/generated/operations/pending-mails.ts b/v2/src/generated/operations/pending-mails.ts index a3b1202a6..b1b61ac5b 100644 --- a/v2/src/generated/operations/pending-mails.ts +++ b/v2/src/generated/operations/pending-mails.ts @@ -36,6 +36,7 @@ const CLEANUP = /* @__PURE__ */ operation({ }), body: null, response: null, + name: 'pendingMails.cleanup', }); /** @@ -62,6 +63,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'pendingMails.destroy', }); /** @@ -125,6 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PendingMail), + name: 'pendingMails.index', }); /** @@ -153,6 +156,7 @@ const REJECT = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, + name: 'pendingMails.reject', }); /** @@ -181,6 +185,7 @@ const SENT = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, + name: 'pendingMails.sent', }); /** @@ -207,4 +212,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, + name: 'pendingMails.show', }); diff --git a/v2/src/generated/operations/playlist-media.ts b/v2/src/generated/operations/playlist-media.ts index 31dc74236..bca39b548 100644 --- a/v2/src/generated/operations/playlist-media.ts +++ b/v2/src/generated/operations/playlist-media.ts @@ -49,6 +49,7 @@ const CREATE = /* @__PURE__ */ operation({ }), body: PlaylistItem, response: PlaylistItem, + name: 'playlistMedia.create', }); /** @@ -85,6 +86,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'playlistMedia.destroy', }); /** @@ -125,6 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PlaylistItem), + name: 'playlistMedia.index', }); /** @@ -166,6 +169,7 @@ const REMOVE_TAG = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'playlistMedia.removeTag', }); /** @@ -203,6 +207,7 @@ const RENAME_TAG = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'playlistMedia.renameTag', }); /** @@ -248,6 +253,7 @@ const SHARE = /* @__PURE__ */ operation({ }, ['linked', 'already_present'], ), + name: 'playlistMedia.share', }); /** @@ -277,6 +283,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: PlaylistItem, + name: 'playlistMedia.show', }); /** @@ -306,6 +313,7 @@ const TAG_COUNTS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + name: 'playlistMedia.tagCounts', }); /** @@ -335,6 +343,7 @@ const TAGS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'playlistMedia.tags', }); /** @@ -361,6 +370,7 @@ const THUMBNAIL = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'playlistMedia.thumbnail', }); /** @@ -387,4 +397,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: PlaylistItem, response: PlaylistItem, + name: 'playlistMedia.update', }); diff --git a/v2/src/generated/operations/playlist.ts b/v2/src/generated/operations/playlist.ts index 171f740eb..2cf69b712 100644 --- a/v2/src/generated/operations/playlist.ts +++ b/v2/src/generated/operations/playlist.ts @@ -53,6 +53,7 @@ const APPROVE_MEDIA = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ boolean(), + name: 'playlist.approveMedia', }); /** @@ -83,6 +84,7 @@ const APPROVERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(PlaylistApprover), + name: 'playlist.approvers', }); /** @@ -112,6 +114,7 @@ const CREATE = /* @__PURE__ */ operation({ }), body: Playlist, response: Playlist, + name: 'playlist.create', }); /** @@ -148,6 +151,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'playlist.destroy', }); /** @@ -202,6 +206,7 @@ const HISTORY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(History), + name: 'playlist.history', }); /** @@ -240,6 +245,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Playlist), + name: 'playlist.index', }); /** @@ -266,6 +272,7 @@ const MEDIA = /* @__PURE__ */ operation({ ), body: null, response: PlaylistRevision, + name: 'playlist.media', }); /** @@ -293,6 +300,7 @@ const MEDIA_REVISIONS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(PlaylistRevision), + name: 'playlist.mediaRevisions', }); /** @@ -327,6 +335,7 @@ const REQUEST_APPROVAL = /* @__PURE__ */ operation({ ), body: PlaylistApprovalMessage, response: null, + name: 'playlist.requestApproval', }); /** @@ -353,6 +362,7 @@ const SCHEDULE_MEDIA = /* @__PURE__ */ operation({ ), body: PlaylistItemSchedule, response: PlaylistRevision, + name: 'playlist.scheduleMedia', }); /** @@ -398,6 +408,7 @@ const SHARE = /* @__PURE__ */ operation({ }, ['linked', 'already_present'], ), + name: 'playlist.share', }); /** @@ -426,6 +437,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Playlist, + name: 'playlist.show', }); /** @@ -452,6 +464,7 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Playlist, response: Playlist, + name: 'playlist.update', }); /** @@ -478,6 +491,7 @@ const UPDATE_MEDIA = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ array(/* @__PURE__ */ string()), response: PlaylistRevision, + name: 'playlist.updateMedia', }); /** `PATCH /api/engine/v2/signage/playlists/{id}/media/schedule/{item_id}` */ @@ -501,4 +515,5 @@ const UPDATE_SCHEDULE = /* @__PURE__ */ operation({ ), body: PlaylistItemSchedule, response: PlaylistItemSchedule, + name: 'playlist.updateSchedule', }); diff --git a/v2/src/generated/operations/public-events.ts b/v2/src/generated/operations/public-events.ts index b5217b3f4..ccae2a4ad 100644 --- a/v2/src/generated/operations/public-events.ts +++ b/v2/src/generated/operations/public-events.ts @@ -47,6 +47,7 @@ const GUEST_TOKEN = /* @__PURE__ */ operation({ ), body: PublicEventsTokenRequest, response: /* @__PURE__ */ string(), + name: 'publicEvents.guestToken', }); /** @@ -96,6 +97,7 @@ const INDEX = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), + name: 'publicEvents.index', }); /** @@ -129,4 +131,5 @@ const REGISTER = /* @__PURE__ */ operation({ ), body: PublicEventsRegistrationRequest, response: null, + name: 'publicEvents.register', }); diff --git a/v2/src/generated/operations/push-notifications.ts b/v2/src/generated/operations/push-notifications.ts index 429062909..f679b242f 100644 --- a/v2/src/generated/operations/push-notifications.ts +++ b/v2/src/generated/operations/push-notifications.ts @@ -29,6 +29,7 @@ const GOOGLE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: null, + name: 'pushNotifications.google', }); /** `POST /api/engine/v2/notifications/office365` */ @@ -46,4 +47,5 @@ const MICROSOFT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: MicrosoftNotification, response: null, + name: 'pushNotifications.microsoft', }); diff --git a/v2/src/generated/operations/repositories.ts b/v2/src/generated/operations/repositories.ts index b514f286b..585254bcf 100644 --- a/v2/src/generated/operations/repositories.ts +++ b/v2/src/generated/operations/repositories.ts @@ -47,6 +47,7 @@ const BRANCHES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.branches', }); /** @@ -79,6 +80,7 @@ const COMMITS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(GitRepositoryCommit), + name: 'repositories.commits', }); /** @@ -100,6 +102,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Repository, response: Repository, + name: 'repositories.create', }); /** @@ -126,6 +129,7 @@ const DEFAULT_BRANCH = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'repositories.defaultBranch', }); /** @@ -152,6 +156,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'repositories.destroy', }); /** @@ -186,6 +191,7 @@ const DETAILS = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'repositories.details', }); /** @@ -212,6 +218,7 @@ const DRIVERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.drivers', }); /** @@ -247,6 +254,7 @@ const FILES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.files', }); /** @@ -275,6 +283,7 @@ const FOLDERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.folders', }); /** @@ -310,6 +319,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Repository), + name: 'repositories.index', }); /** @@ -335,6 +345,7 @@ const LOADED_INTERFACES = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ string()), + name: 'repositories.loadedInterfaces', }); /** @@ -366,6 +377,7 @@ const PULL = /* @__PURE__ */ operation({ }, ['commit_hash'], ), + name: 'repositories.pull', }); /** @@ -392,6 +404,7 @@ const RELEASES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.releases', }); /** @@ -423,6 +436,7 @@ const REMOTE_BRANCHES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.remoteBranches', }); /** @@ -458,6 +472,7 @@ const REMOTE_COMMITS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(GitRepositoryCommit), + name: 'repositories.remoteCommits', }); /** @@ -489,6 +504,7 @@ const REMOTE_DEFAULT_BRANCH = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ string(), + name: 'repositories.remoteDefaultBranch', }); /** @@ -520,6 +536,7 @@ const REMOTE_TAGS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.remoteTags', }); /** @@ -546,6 +563,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Repository, + name: 'repositories.show', }); /** @@ -572,6 +590,7 @@ const TAGS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'repositories.tags', }); /** @@ -598,4 +617,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Repository, response: Repository, + name: 'repositories.update', }); diff --git a/v2/src/generated/operations/root.ts b/v2/src/generated/operations/root.ts index 7a04ad137..46c56cf97 100644 --- a/v2/src/generated/operations/root.ts +++ b/v2/src/generated/operations/root.ts @@ -33,6 +33,7 @@ const CLUSTER_VERSION = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(Version), + name: 'root.clusterVersion', }); /** @@ -54,6 +55,7 @@ const PLATFORM_INFO = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: RootPlatformInfo, + name: 'root.platformInfo', }); /** @@ -75,6 +77,7 @@ const ROOT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: null, + name: 'root.root', }); /** @@ -96,6 +99,7 @@ const SCOPES = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'root.scopes', }); /** @@ -126,6 +130,7 @@ const SIGNAL = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'root.signal', }); /** @@ -155,6 +160,7 @@ const SOURCE_RESYNC = /* @__PURE__ */ operation({ }), body: null, response: RootSourceResyncStatus, + name: 'root.sourceResync', }); /** @@ -176,6 +182,7 @@ const SOURCE_RESYNC_STATUS = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: RootSourceResyncStatus, + name: 'root.sourceResyncStatus', }); /** @@ -197,4 +204,5 @@ const VERSION = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: Version, + name: 'root.version', }); diff --git a/v2/src/generated/operations/saml-authentications.ts b/v2/src/generated/operations/saml-authentications.ts index f393db62e..07851ae34 100644 --- a/v2/src/generated/operations/saml-authentications.ts +++ b/v2/src/generated/operations/saml-authentications.ts @@ -34,6 +34,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: SamlAuthentication, response: SamlAuthentication, + name: 'samlAuthentications.create', }); /** @@ -60,6 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'samlAuthentications.destroy', }); /** @@ -97,6 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SamlAuthentication), + name: 'samlAuthentications.index', }); /** @@ -123,6 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SamlAuthentication, + name: 'samlAuthentications.show', }); /** @@ -149,4 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SamlAuthentication, response: SamlAuthentication, + name: 'samlAuthentications.update', }); diff --git a/v2/src/generated/operations/schema.ts b/v2/src/generated/operations/schema.ts index 3bb38eea0..687bb5ba7 100644 --- a/v2/src/generated/operations/schema.ts +++ b/v2/src/generated/operations/schema.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: JsonSchema, response: JsonSchema, + name: 'schema.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'schema.destroy', }); /** @@ -96,6 +98,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(JsonSchema), + name: 'schema.index', }); /** @@ -122,6 +125,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: JsonSchema, + name: 'schema.show', }); /** @@ -148,4 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: JsonSchema, response: JsonSchema, + name: 'schema.update', }); diff --git a/v2/src/generated/operations/settings.ts b/v2/src/generated/operations/settings.ts index 28080101e..624c062d2 100644 --- a/v2/src/generated/operations/settings.ts +++ b/v2/src/generated/operations/settings.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Settings, response: Settings, + name: 'settings.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'settings.destroy', }); /** @@ -89,6 +91,7 @@ const HISTORY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Settings), + name: 'settings.history', }); /** @@ -125,6 +128,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Settings), + name: 'settings.index', }); /** @@ -151,6 +155,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Settings, + name: 'settings.show', }); /** @@ -177,4 +182,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Settings, response: Settings, + name: 'settings.update', }); diff --git a/v2/src/generated/operations/short-url.ts b/v2/src/generated/operations/short-url.ts index bebbbd482..88794fee5 100644 --- a/v2/src/generated/operations/short-url.ts +++ b/v2/src/generated/operations/short-url.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Shortener, response: Shortener, + name: 'shortUrl.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'shortUrl.destroy', }); /** @@ -91,6 +93,7 @@ const GENERATE_QR_CODE = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'shortUrl.generateQrCode', }); /** @@ -126,6 +129,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Shortener), + name: 'shortUrl.index', }); /** @@ -154,6 +158,7 @@ const PNG_QR = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'shortUrl.pngQr', }); /** @@ -180,6 +185,7 @@ const REDIRECT = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'shortUrl.redirect', }); /** @@ -206,6 +212,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Shortener, + name: 'shortUrl.show', }); /** @@ -232,6 +239,7 @@ const SVG_QR = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'shortUrl.svgQr', }); /** @@ -258,4 +266,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Shortener, response: Shortener, + name: 'shortUrl.update', }); diff --git a/v2/src/generated/operations/signage-ai-providers.ts b/v2/src/generated/operations/signage-ai-providers.ts index 40f50a822..fdc881b50 100644 --- a/v2/src/generated/operations/signage-ai-providers.ts +++ b/v2/src/generated/operations/signage-ai-providers.ts @@ -66,6 +66,7 @@ const CREATE = /* @__PURE__ */ operation({ 'updated_at', ], ), + name: 'signageAiProviders.create', }); /** `DELETE /api/engine/v2/signage/ai/providers/{id}` */ @@ -88,6 +89,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signageAiProviders.destroy', }); /** @@ -161,6 +163,7 @@ const INDEX = /* @__PURE__ */ operation({ ], ), ), + name: 'signageAiProviders.index', }); /** `GET /api/engine/v2/signage/ai/providers/{id}` */ @@ -211,6 +214,7 @@ const SHOW = /* @__PURE__ */ operation({ 'updated_at', ], ), + name: 'signageAiProviders.show', }); /** @@ -242,6 +246,7 @@ const TEST = /* @__PURE__ */ operation({ ), body: null, response: SignageAiProvidersTestResult, + name: 'signageAiProviders.test', }); /** `PATCH /api/engine/v2/signage/ai/providers/{id}` */ @@ -292,4 +297,5 @@ const UPDATE = /* @__PURE__ */ operation({ 'updated_at', ], ), + name: 'signageAiProviders.update', }); diff --git a/v2/src/generated/operations/signage-ai.ts b/v2/src/generated/operations/signage-ai.ts index 488200d37..5d5e98563 100644 --- a/v2/src/generated/operations/signage-ai.ts +++ b/v2/src/generated/operations/signage-ai.ts @@ -45,6 +45,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: SignageAiJobResponse, + name: 'signageAi.cancel', }); /** @@ -66,6 +67,7 @@ const CAPABILITIES = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: SignageAiCapabilities, + name: 'signageAi.capabilities', }); /** @@ -92,6 +94,7 @@ const CLAIM = /* @__PURE__ */ operation({ ), body: SignageAiClaimParams, response: SignageAiJobResponse, + name: 'signageAi.claim', }); /** @@ -113,6 +116,7 @@ const EDIT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: SignageAiEditParams, response: SignageAiJobResponse, + name: 'signageAi.edit', }); /** @@ -134,6 +138,7 @@ const GENERATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: SignageAiGenerateParams, response: SignageAiJobResponse, + name: 'signageAi.generate', }); /** @@ -161,6 +166,7 @@ const INDEX_JOBS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobResponse), + name: 'signageAi.indexJobs', }); /** @@ -191,6 +197,7 @@ const SHOW_JOB = /* @__PURE__ */ operation({ ), body: null, response: SignageAiJobResponse, + name: 'signageAi.showJob', }); /** @@ -217,4 +224,5 @@ const USAGE = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobUsageRow), + name: 'signageAi.usage', }); diff --git a/v2/src/generated/operations/signage-plugins.ts b/v2/src/generated/operations/signage-plugins.ts index 591e8e602..6e72f4642 100644 --- a/v2/src/generated/operations/signage-plugins.ts +++ b/v2/src/generated/operations/signage-plugins.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: SignagePlugin, response: SignagePlugin, + name: 'signagePlugins.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signagePlugins.destroy', }); /** @@ -98,6 +100,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignagePlugin), + name: 'signagePlugins.index', }); /** @@ -124,6 +127,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignagePlugin, + name: 'signagePlugins.show', }); /** @@ -150,4 +154,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignagePlugin, response: SignagePlugin, + name: 'signagePlugins.update', }); diff --git a/v2/src/generated/operations/signage-template-mappings.ts b/v2/src/generated/operations/signage-template-mappings.ts index c273f292d..c13f1e323 100644 --- a/v2/src/generated/operations/signage-template-mappings.ts +++ b/v2/src/generated/operations/signage-template-mappings.ts @@ -38,6 +38,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: SignageTemplateSystemTemplate, response: SignageTemplateSystemTemplate, + name: 'signageTemplateMappings.create', }); /** @@ -64,6 +65,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signageTemplateMappings.destroy', }); /** @@ -112,6 +114,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplateSystemTemplate), + name: 'signageTemplateMappings.index', }); /** @@ -140,6 +143,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplateSystemTemplate, + name: 'signageTemplateMappings.show', }); /** @@ -170,4 +174,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignageTemplateSystemTemplate, response: SignageTemplateSystemTemplate, + name: 'signageTemplateMappings.update', }); diff --git a/v2/src/generated/operations/signage-templates.ts b/v2/src/generated/operations/signage-templates.ts index cfe67f523..4c00a1bb4 100644 --- a/v2/src/generated/operations/signage-templates.ts +++ b/v2/src/generated/operations/signage-templates.ts @@ -53,6 +53,7 @@ const APPROVE = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplate, + name: 'signageTemplates.approve', }); /** @@ -83,6 +84,7 @@ const APPROVERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(SignageTemplatesApprover), + name: 'signageTemplates.approvers', }); /** @@ -112,6 +114,7 @@ const CREATE = /* @__PURE__ */ operation({ }), body: SignageTemplate, response: SignageTemplate, + name: 'signageTemplates.create', }); /** @@ -149,6 +152,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signageTemplates.destroy', }); /** @@ -175,6 +179,7 @@ const DESTROY_DRAFT = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signageTemplates.destroyDraft', }); /** @@ -217,6 +222,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplate), + name: 'signageTemplates.index', }); /** @@ -251,6 +257,7 @@ const REQUEST_APPROVAL = /* @__PURE__ */ operation({ ), body: SignageTemplatesApprovalMessage, response: null, + name: 'signageTemplates.requestApproval', }); /** @@ -296,6 +303,7 @@ const SHARE = /* @__PURE__ */ operation({ }, ['linked', 'already_present'], ), + name: 'signageTemplates.share', }); /** @@ -328,6 +336,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplate, + name: 'signageTemplates.show', }); /** @@ -359,4 +368,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignageTemplate, response: SignageTemplate, + name: 'signageTemplates.update', }); diff --git a/v2/src/generated/operations/signage.ts b/v2/src/generated/operations/signage.ts index a5f3d38e6..1b48509f6 100644 --- a/v2/src/generated/operations/signage.ts +++ b/v2/src/generated/operations/signage.ts @@ -42,6 +42,7 @@ const DISPLAY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ nullable(ControlSystem), + name: 'signage.display', }); /** @@ -76,6 +77,7 @@ const FETCH_STATIC_MEDIA = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'signage.fetchStaticMedia', }); /** @@ -110,6 +112,7 @@ const SAMSUNG_EINK_MANIFEST = /* @__PURE__ */ operation({ ), body: null, response: SignageSamsungEinkManifest, + name: 'signage.samsungEinkManifest', }); /** @@ -142,6 +145,7 @@ const SAMSUNG_EINK_MANIFEST_WITHOUT_EXPIRES_AFTER = /* @__PURE__ */ operation({ ), body: null, response: SignageSamsungEinkManifest, + name: 'signage.samsungEinkManifestWithoutExpiresAfter', }); /** @@ -168,4 +172,5 @@ const UPDATE_METRICS = /* @__PURE__ */ operation({ ), body: SignageMetrics, response: null, + name: 'signage.updateMetrics', }); diff --git a/v2/src/generated/operations/storages.ts b/v2/src/generated/operations/storages.ts index 08a071812..54611f026 100644 --- a/v2/src/generated/operations/storages.ts +++ b/v2/src/generated/operations/storages.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Storage, response: Storage, + name: 'storages.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'storages.destroy', }); /** @@ -96,6 +98,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Storage), + name: 'storages.index', }); /** @@ -122,6 +125,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Storage, + name: 'storages.show', }); /** @@ -148,4 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Storage, response: Storage, + name: 'storages.update', }); diff --git a/v2/src/generated/operations/system-triggers.ts b/v2/src/generated/operations/system-triggers.ts index c15ade3df..665d6badd 100644 --- a/v2/src/generated/operations/system-triggers.ts +++ b/v2/src/generated/operations/system-triggers.ts @@ -39,6 +39,7 @@ const CREATE = /* @__PURE__ */ operation({ ), body: TriggerInstance, response: TriggerInstance, + name: 'systemTriggers.create', }); /** @@ -67,6 +68,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'systemTriggers.destroy', }); /** @@ -119,6 +121,7 @@ const INDEX = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(TriggerInstance), + name: 'systemTriggers.index', }); /** @@ -148,6 +151,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: TriggerInstance, + name: 'systemTriggers.show', }); /** @@ -176,4 +180,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SystemTriggersUpdateParams, response: TriggerInstance, + name: 'systemTriggers.update', }); diff --git a/v2/src/generated/operations/systems.ts b/v2/src/generated/operations/systems.ts index b66b5eb74..987569c60 100644 --- a/v2/src/generated/operations/systems.ts +++ b/v2/src/generated/operations/systems.ts @@ -54,6 +54,7 @@ const ADD_MODULE = /* @__PURE__ */ operation({ ), body: null, response: ControlSystem, + name: 'systems.addModule', }); /** @@ -75,6 +76,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: ControlSystem, response: ControlSystem, + name: 'systems.create', }); /** @@ -101,6 +103,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'systems.destroy', }); /** @@ -131,6 +134,7 @@ const EXECUTE = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ array(/* @__PURE__ */ json()), response: /* @__PURE__ */ json(), + name: 'systems.execute', }); /** @@ -158,6 +162,7 @@ const FIND_BY_EMAIL = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(ControlSystem), + name: 'systems.findByEmail', }); /** @@ -188,6 +193,7 @@ const FUNCTIONS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(SystemsFunctionDetails), + name: 'systems.functions', }); /** @@ -252,6 +258,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ControlSystem), + name: 'systems.index', }); /** @@ -279,6 +286,7 @@ const METADATA = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(MetadataInterface), + name: 'systems.metadata', }); /** @@ -306,6 +314,7 @@ const REMOVE_MODULE = /* @__PURE__ */ operation({ ), body: null, response: ControlSystem, + name: 'systems.removeModule', }); /** @@ -332,6 +341,7 @@ const SETTINGS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Settings), + name: 'systems.settings', }); /** @@ -360,6 +370,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: ControlSystem, + name: 'systems.show', }); /** @@ -388,6 +399,7 @@ const START = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'systems.start', }); /** @@ -416,6 +428,7 @@ const STATE = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ string()), + name: 'systems.state', }); /** @@ -449,6 +462,7 @@ const STATE_LOOKUP = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ json(), + name: 'systems.stateLookup', }); /** @@ -477,6 +491,7 @@ const STOP = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'systems.stop', }); /** @@ -503,6 +518,7 @@ const SYS_ZONES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Zone), + name: 'systems.sysZones', }); /** @@ -529,6 +545,7 @@ const TYPES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + name: 'systems.types', }); /** @@ -561,4 +578,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: ControlSystem, response: ControlSystem, + name: 'systems.update', }); diff --git a/v2/src/generated/operations/tenant-consent.ts b/v2/src/generated/operations/tenant-consent.ts index ad3ca0a12..1472aaa78 100644 --- a/v2/src/generated/operations/tenant-consent.ts +++ b/v2/src/generated/operations/tenant-consent.ts @@ -48,6 +48,7 @@ const AZURE_ADMIN_CONSENT_CALLBACK = /* @__PURE__ */ operation({ }), body: null, response: null, + name: 'tenantConsent.azureAdminConsentCallback', }); /** @@ -78,6 +79,7 @@ const FLOW_STATUS = /* @__PURE__ */ operation({ ), body: null, response: AdminConsentFlow, + name: 'tenantConsent.flowStatus', }); /** `GET /api/engine/v2/admin_consent/{id}` */ @@ -120,4 +122,5 @@ const INDEX = /* @__PURE__ */ operation({ }, ['url'], ), + name: 'tenantConsent.index', }); diff --git a/v2/src/generated/operations/triggers.ts b/v2/src/generated/operations/triggers.ts index 8f16fa94f..65d0c1d95 100644 --- a/v2/src/generated/operations/triggers.ts +++ b/v2/src/generated/operations/triggers.ts @@ -33,6 +33,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Trigger, response: Trigger, + name: 'triggers.create', }); /** @@ -59,6 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'triggers.destroy', }); /** @@ -94,6 +96,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Trigger), + name: 'triggers.index', }); /** @@ -120,6 +123,7 @@ const INSTANCES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(TriggerInstance), + name: 'triggers.instances', }); /** @@ -148,6 +152,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Trigger, + name: 'triggers.show', }); /** @@ -174,4 +179,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Trigger, response: Trigger, + name: 'triggers.update', }); diff --git a/v2/src/generated/operations/uploads.ts b/v2/src/generated/operations/uploads.ts index 91d280cf8..43dd702dc 100644 --- a/v2/src/generated/operations/uploads.ts +++ b/v2/src/generated/operations/uploads.ts @@ -79,6 +79,7 @@ const CREATE = /* @__PURE__ */ operation({ ['type', 'signature', 'residence'], ), ]), + name: 'uploads.create', }); /** @@ -106,6 +107,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'uploads.destroy', }); /** @@ -137,6 +139,7 @@ const DOWNLOAD_PROXY_FILE_CONTENTS = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'uploads.downloadProxyFileContents', }); /** @@ -171,6 +174,7 @@ const DOWNLOAD_SIMPLE_ROUTE = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'uploads.downloadSimpleRoute', }); /** @@ -204,6 +208,7 @@ const DOWNLOAD_SIMPLE_ROUTE_WITHOUT_FILE_NAME = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'uploads.downloadSimpleRouteWithoutFileName', }); /** @@ -255,6 +260,7 @@ const EDIT = /* @__PURE__ */ operation({ }, ['type', 'signature'], ), + name: 'uploads.edit', }); /** @@ -287,6 +293,7 @@ const FINISHED = /* @__PURE__ */ operation({ }, ['ok'], ), + name: 'uploads.finished', }); /** @@ -316,6 +323,7 @@ const GET_LINK = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'uploads.getLink', }); /** @@ -357,6 +365,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Upload), + name: 'uploads.index', }); /** @@ -384,6 +393,7 @@ const SCREENSHOT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: UploadsScreenshotInfo, response: Upload, + name: 'uploads.screenshot', }); /** @@ -420,6 +430,7 @@ const STORAGE_NAME = /* @__PURE__ */ operation({ }, ['residence'], ), + name: 'uploads.storageName', }); /** @@ -474,4 +485,5 @@ const UPDATE = /* @__PURE__ */ operation({ ['type', 'signature'], ), ]), + name: 'uploads.update', }); diff --git a/v2/src/generated/operations/url-proxy.ts b/v2/src/generated/operations/url-proxy.ts index e0c8cadf0..fff3e730a 100644 --- a/v2/src/generated/operations/url-proxy.ts +++ b/v2/src/generated/operations/url-proxy.ts @@ -41,4 +41,5 @@ const PROXY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'urlProxy.proxy', }); diff --git a/v2/src/generated/operations/users.ts b/v2/src/generated/operations/users.ts index 83c309faa..b73f97397 100644 --- a/v2/src/generated/operations/users.ts +++ b/v2/src/generated/operations/users.ts @@ -56,6 +56,7 @@ const CREATE = /* @__PURE__ */ operation({ UserPublicMetadataResponse, UserPublicResponse, ]), + name: 'users.create', }); /** @@ -77,6 +78,7 @@ const CURRENT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: UserAdminMetadataResponse, + name: 'users.current', }); /** @@ -106,6 +108,7 @@ const DELETE_RESOURCE_TOKEN = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'users.deleteResourceToken', }); /** @@ -134,6 +137,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'users.destroy', }); /** @@ -161,6 +165,7 @@ const GROUPS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(UserGroupResponse), + name: 'users.groups', }); /** @@ -209,6 +214,7 @@ const INDEX = /* @__PURE__ */ operation({ UserPublicResponse, ]), ), + name: 'users.index', }); /** @@ -238,6 +244,7 @@ const METADATA = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(MetadataInterface), + name: 'users.metadata', }); /** @@ -263,6 +270,7 @@ const RESOURCE_TOKEN = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: UserResourceToken, + name: 'users.resourceToken', }); /** @@ -290,6 +298,7 @@ const REVIVE = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'users.revive', }); /** @@ -331,6 +340,7 @@ const SEARCH = /* @__PURE__ */ operation({ UserPublicResponse, ]), ), + name: 'users.search', }); /** @@ -365,6 +375,7 @@ const SHOW = /* @__PURE__ */ operation({ UserPublicMetadataResponse, UserPublicResponse, ]), + name: 'users.show', }); /** @@ -397,6 +408,7 @@ const UPDATE = /* @__PURE__ */ operation({ UserPublicMetadataResponse, UserPublicResponse, ]), + name: 'users.update', }); /** @@ -427,4 +439,5 @@ const USER_RESOURCE_TOKEN = /* @__PURE__ */ operation({ ), body: null, response: UserResourceToken, + name: 'users.userResourceToken', }); diff --git a/v2/src/generated/operations/web-rtc.ts b/v2/src/generated/operations/web-rtc.ts index 08fdb34a7..321ff92df 100644 --- a/v2/src/generated/operations/web-rtc.ts +++ b/v2/src/generated/operations/web-rtc.ts @@ -43,6 +43,7 @@ const GUEST_ENTRY = /* @__PURE__ */ operation({ ), body: GuestParticipant, response: null, + name: 'webRtc.guestEntry', }); /** @@ -67,6 +68,7 @@ const GUEST_EXIT = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: null, + name: 'webRtc.guestExit', }); /** @@ -102,6 +104,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ControlSystem), + name: 'webRtc.index', }); /** @@ -132,6 +135,7 @@ const KICK_USER = /* @__PURE__ */ operation({ ), body: KickReason, response: null, + name: 'webRtc.kickUser', }); /** @@ -158,6 +162,7 @@ const MEMBERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'webRtc.members', }); /** @@ -188,6 +193,7 @@ const PUBLIC_ROOM = /* @__PURE__ */ operation({ ), body: null, response: WebRtcRoomDetails, + name: 'webRtc.publicRoom', }); /** @@ -218,6 +224,7 @@ const TRANSFER_GUEST = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), response: null, + name: 'webRtc.transferGuest', }); /** @@ -247,4 +254,5 @@ const TRANSFER_GUEST_WITHOUT_SESSION_ID = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), response: null, + name: 'webRtc.transferGuestWithoutSessionId', }); diff --git a/v2/src/generated/operations/webhook.ts b/v2/src/generated/operations/webhook.ts index 61ef4b453..fb4a8cd4a 100644 --- a/v2/src/generated/operations/webhook.ts +++ b/v2/src/generated/operations/webhook.ts @@ -39,4 +39,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Trigger, + name: 'webhook.show', }); diff --git a/v2/src/generated/operations/zones.ts b/v2/src/generated/operations/zones.ts index 65596154d..55de5ea72 100644 --- a/v2/src/generated/operations/zones.ts +++ b/v2/src/generated/operations/zones.ts @@ -42,6 +42,7 @@ const CREATE = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: Zone, response: Zone, + name: 'zones.create', }); /** @@ -68,6 +69,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, + name: 'zones.destroy', }); /** @@ -121,6 +123,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Zone), + name: 'zones.index', }); /** @@ -149,6 +152,7 @@ const METADATA = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ record(MetadataInterface), + name: 'zones.metadata', }); /** @@ -177,6 +181,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Zone, + name: 'zones.show', }); /** @@ -198,6 +203,7 @@ const TAGS = /* @__PURE__ */ operation({ params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'zones.tags', }); /** @@ -224,6 +230,7 @@ const TRIGGER_INSTANCES = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Trigger), + name: 'zones.triggerInstances', }); /** @@ -250,6 +257,7 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Zone, response: Zone, + name: 'zones.update', }); /** @@ -280,4 +288,5 @@ const ZONE_EXECUTE = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ array(/* @__PURE__ */ json()), response: ZonesZoneExecResponse, + name: 'zones.zoneExecute', }); diff --git a/v2/src/generated/schemas.ts b/v2/src/generated/schemas.ts index 94a7d2358..24209c149 100644 --- a/v2/src/generated/schemas.ts +++ b/v2/src/generated/schemas.ts @@ -3133,3 +3133,18 @@ export interface ZonesZoneExecResponse extends Output {} export const ZonesZoneExecResponse: Schema = ZonesZoneExecResponseSchema; + +/** Short names. Each one is the same value and type as the long name. */ +export { UserAdminMetadataResponse as User, type UserAdminMetadataResponseInput as UserInput }; +export { ControlSystem as System, type ControlSystemInput as SystemInput }; +export { + DoorkeeperApplication as Application, + type DoorkeeperApplicationInput as ApplicationInput, +}; +export { Authority as Domain, type AuthorityInput as DomainInput }; +export { MetadataInterface as Metadata, type MetadataInterfaceInput as MetadataInput }; +export { Shortener as ShortUrl, type ShortenerInput as ShortUrlInput }; +export { + SignageTemplateSystemTemplate as SignageTemplateMapping, + type SignageTemplateSystemTemplateInput as SignageTemplateMappingInput, +}; diff --git a/v2/src/migrate/cli.ts b/v2/src/migrate/cli.ts index 1353bb721..5df354d9d 100644 --- a/v2/src/migrate/cli.ts +++ b/v2/src/migrate/cli.ts @@ -111,7 +111,8 @@ async function main(argv: readonly string[]): Promise { console.log( `\nNext:\n` + ` 1. Install v2: npm install @placeos/ts-client@2\n` + - ` 2. Call configure() once, before the first call (README: Log in).\n` + + ` 2. Call configure() once, before the first call (README: Log in). For a mock mode,\n` + + ` give fetch: mockFetch and missingFields: 'zero' (README: Mock mode).\n` + ` 3. Run the compiler. It shows the changes to the data, such as a field that can be null.\n` + ` 4. orThrow from ${COMPAT_MODULE} keeps the v1 errors. Check the Result in new code.`, ); diff --git a/v2/src/migrate/migrate.ts b/v2/src/migrate/migrate.ts index 0d93cbaea..66c37f371 100644 --- a/v2/src/migrate/migrate.ts +++ b/v2/src/migrate/migrate.ts @@ -9,6 +9,9 @@ * - A call of a mapped v1 function becomes the v2 operation with `.then(orThrow)`, so the code * still gets the data, and an error still rejects the promise. * - A type reference to a v1 class becomes the v2 type, such as `PlaceZone` to `Zone`. + * - A test double of a v1 function, such as `vi.mocked(showZone)` or the functions of a `vi.mock` + * factory, becomes the test double of the v2 operation. `mockReply` and `fromV1Mock` make v2 + * results of the v1 values. * - The tool does not change other uses of v1. Each one is a finding, with a hint. * * The tool only parses the file. It does not type check it. After the migration, the compiler @@ -18,10 +21,41 @@ */ import type * as TS from 'typescript-5'; import { assert } from '../core/assert.ts'; -import type { CallMap, CallMapping, Template } from './map.ts'; +import type { CallMap, CallMapping, ObjectEntry, Template } from './map.ts'; export const V1_MODULE = '@placeos/ts-client'; export const COMPAT_MODULE = '@placeos/ts-client/compat'; +/** The objects of the test frameworks: `vi` of Vitest and `jest` of Jest. */ +const TEST_GLOBALS: ReadonlySet = new Set(['vi', 'jest']); +/** The mock methods that set the value of a promise. The value becomes a v2 result. */ +const RESOLVED_VALUE_METHODS: ReadonlySet = new Set([ + 'mockResolvedValue', + 'mockResolvedValueOnce', +]); +/** The checks of the arguments. The arguments become the v2 input. */ +const CALLED_WITH_METHODS: ReadonlySet = new Set([ + 'toHaveBeenCalledWith', + 'toHaveBeenCalledOnceWith', + 'toHaveBeenCalledExactlyOnceWith', + 'toHaveBeenLastCalledWith', + 'toBeCalledWith', + 'lastCalledWith', +]); +/** + * The mock methods that take a v1 implementation or value, and the method for the v2 one. A + * value becomes an implementation, and so does a resolved value of a v1 function that selects a + * key, such as `showMetadata`. + */ +const VALUE_TO_IMPLEMENTATION: Readonly> = { + mockImplementation: 'mockImplementation', + mockImplementationOnce: 'mockImplementationOnce', + mockReturnValue: 'mockImplementation', + mockReturnValueOnce: 'mockImplementationOnce', + mockResolvedValue: 'mockImplementation', + mockResolvedValueOnce: 'mockImplementationOnce', +}; +/** A chain such as `vi.mocked(f).mockResolvedValueOnce(a).mockResolvedValueOnce(b)` is shorter. */ +const CHAIN_DEPTH_MAX = 32; /** A name that collides gets a suffix. A file has fewer names with the same base. */ const ALIASES_MAX = 100; @@ -123,6 +157,18 @@ export function migrateSource( return name; } + /** The local name of a compat export that a namespace import used, such as `PlaceDriverRole`. */ + const compatLocals = new Map(); + function compatLocal(name: string): string { + const known = compatLocals.get(name); + if (known !== undefined) return known; + const local = localName(name); + compatLocals.set(name, local); + const specifier = local === name ? name : `${name} as ${local}`; + compatNames.add(tables.compat[name] === 'type' ? `type ${specifier}` : specifier); + return local; + } + function typeLocal(v2Name: string): string { for (const [local, name] of typeNames) if (name === v2Name) return local; const local = localName(v2Name); @@ -157,7 +203,7 @@ export function migrateSource( function rewriteCall(call: TS.CallExpression, name: string, prefix: string | null): boolean { const mapping = tables.calls[name]; assert(mapping !== undefined, `${name} has a mapping`); - const rendered = renderCall(ts, call, mapping, textOf); + const rendered = renderCall(ts, call.arguments, mapping, textOf); if (typeof rendered === 'string') { find(call, name, rendered); return false; @@ -179,12 +225,254 @@ export function migrateSource( return true; } + /** The test doubles that the tool changed, by the call that holds the v2 function. */ + const doubles = new Map(); + /** A spec file. There a reference to a v1 function that is not a call is a test double. */ + const testFile = /\.(spec|test)\.[cm]?[jt]sx?$/.test(fileName); + /** `true` when a call on a test double uses `fromV1Mock`, out of a `vi.mock` factory. */ + let importsFromV1Mock = false; + + /** + * Changes the function of a test double, such as `vi.mocked(showZone)` to + * `vi.mocked(zones.show)`. `visit` changes the calls on it later, at each call of the chain. + */ + function rewriteDouble( + node: TS.Expression, + wrapper: TS.Node, + name: string, + prefix: string | null, + ): void { + const mapping = tables.calls[name]; + assert(mapping !== undefined, `${name} has a mapping`); + const namespace = + prefix === null ? namespaceLocal(mapping.namespace) : `${prefix}.${mapping.namespace}`; + replace(node, `${namespace}.${mapping.operation}`); + doubles.set(wrapper, { name, mapping }); + migrated.add(name); + changes += 1; + } + + /** The test double at the base of a chain such as `vi.mocked(f).mockResolvedValue(...)`. */ + function doubleOf(callee: TS.Expression): { name: string; mapping: CallMapping } | null { + let current: TS.Expression = callee; + for (let depth = 0; depth < CHAIN_DEPTH_MAX; depth += 1) { + const found = doubles.get(current); + if (found !== undefined) return found; + // `(queryZones as Mock).mockResolvedValue(...)` is a chain on the same double. + if ( + ts.isCallExpression(current) || + ts.isPropertyAccessExpression(current) || + ts.isParenthesizedExpression(current) || + ts.isAsExpression(current) || + ts.isNonNullExpression(current) || + ts.isSatisfiesExpression(current) || + ts.isTypeAssertionExpression(current) + ) { + current = current.expression; + } else { + return null; + } + } + return null; + } + + /** Changes one call on a test double: the value of a mock, or the arguments of a check. */ + function rewriteDoubleCall( + call: TS.CallExpression, + method: string, + double: { name: string; mapping: CallMapping }, + ): void { + const { name, mapping } = double; + const [value] = call.arguments; + const callee = call.expression; + if (RESOLVED_VALUE_METHODS.has(method) && value !== undefined && mapping.pick === null) { + const helper = mapping.result === 'page' ? 'mockPage' : 'mockReply'; + compatNames.add(helper); + replace(value, `${helper}(${textOf(value)})`); + return; + } + // A v1 implementation or value: `fromV1Mock` gives it the v1 arguments, and makes a v2 + // result of its value. A value becomes an implementation that gives it. + const implementation = VALUE_TO_IMPLEMENTATION[method]; + if ( + value !== undefined && + ts.isPropertyAccessExpression(callee) && + implementation !== undefined + ) { + const v1 = method.startsWith('mockImplementation') + ? textOf(value) + : `() => (${textOf(value)})`; + importsFromV1Mock = true; + replace( + call, + `${textOf(callee.expression)}.${implementation}(fromV1Mock(${v1}, ${fromV1MockArgs(mapping)}))`, + ); + return; + } + if (CALLED_WITH_METHODS.has(method)) { + const rendered = renderCall(ts, call.arguments, mapping, textOf, true); + if (typeof rendered === 'string') { + find(call, name, rendered); + return; + } + replace(call, `${textOf(call.expression)}(${rendered.input})`); + return; + } + } + + /** `true` when a `vi.mock` factory uses `fromV1Mock`. The file then imports it. */ + let usesFromV1Mock = false; + + /** + * Changes the v1 functions of a `vi.mock` factory to v2 namespaces. `fromV1Mock` keeps the + * v1 implementation: `showZone: vi.fn(impl)` becomes `zones: { show: vi.fn(fromV1Mock(impl, + * ...)) }`. A Jest factory cannot import the compat module, so it is a finding. + */ + function rewriteFactory( + call: TS.CallExpression, + factory: TS.ArrowFunction | TS.FunctionExpression, + vitest: boolean, + ): void { + const objects = factoryObjects(ts, factory); + const mapped = objects.some((object) => + object.properties.some((property) => mappingOf(property) !== null), + ); + if (!mapped) return; + if (!vitest) { + find( + call, + V1_MODULE, + 'a mock factory with v1 names: give the v2 namespaces, such as zones: { show: jest.fn() }', + ); + return; + } + for (const object of objects) rewriteFactoryObject(object); + } + + function mappingOf(property: TS.ObjectLiteralElementLike): CallMapping | null { + const name = property.name; + if (name === undefined || !(ts.isIdentifier(name) || ts.isStringLiteral(name))) return null; + if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) { + return null; + } + return tables.calls[name.text] ?? null; + } + + function rewriteFactoryObject(object: TS.ObjectLiteralExpression): void { + const kept: string[] = []; + const groups = new Map(); + let spread: string | null = null; + for (const property of object.properties) { + if (ts.isSpreadAssignment(property) && ts.isIdentifier(property.expression)) { + spread = property.expression.text; + } + const mapping = mappingOf(property); + const name = property.name; + if ( + mapping === null || + name === undefined || + !(ts.isIdentifier(name) || ts.isStringLiteral(name)) + ) { + kept.push(textOf(property)); + continue; + } + const value = ts.isPropertyAssignment(property) ? property.initializer : null; + const entries = groups.get(mapping.namespace) ?? []; + entries.push(`${mapping.operation}: ${mockValue(value, name.text, mapping)}`); + groups.set(mapping.namespace, entries); + migrated.add(name.text); + changes += 1; + } + if (groups.size === 0) return; + usesFromV1Mock = true; + for (const [namespace, entries] of groups) { + const base = spread === null ? '' : `...${spread}.${namespace}, `; + kept.push(`${namespace}: { ${base}${entries.join(', ')} }`); + } + replace(object, `{ ${kept.join(', ')} }`); + } + + /** The v2 value of one v1 function of a factory. `null` is a shorthand property. */ + function mockValue(value: TS.Expression | null, name: string, mapping: CallMapping): string { + const extra = fromV1MockArgs(mapping); + if ( + value !== null && + ts.isCallExpression(value) && + isTestCall(ts, value.expression, 'fn') + ) { + const [implementation] = value.arguments; + const text = implementation === undefined ? 'undefined' : textOf(implementation); + return `${textOf(value.expression)}(fromV1Mock(${text}, ${extra}))`; + } + return `fromV1Mock(${value === null ? name : textOf(value)}, ${extra})`; + } + + /** `vi.mocked(f)`, `jest.mocked(f)` or `expect(f)`, with `f` as the first argument. */ + function doubleWrapper(node: TS.Expression): TS.CallExpression | null { + const parent = node.parent; + if (!ts.isCallExpression(parent) || parent.arguments[0] !== node) return null; + const callee = parent.expression; + if (ts.isIdentifier(callee) && callee.text === 'expect') return parent; + const isMocked = + ts.isPropertyAccessExpression(callee) && + ts.isIdentifier(callee.expression) && + TEST_GLOBALS.has(callee.expression.text) && + callee.name.text === 'mocked'; + return isMocked ? parent : null; + } + function visit(node: TS.Node): void { // The children first, so that a call in an argument is changed before the outer call. ts.forEachChild(node, visit); if (ts.isCallExpression(node)) { const callee = node.expression; + const double = doubleOf(callee); + if (double !== null && ts.isPropertyAccessExpression(callee)) { + rewriteDoubleCall(node, callee.name.text, double); + return; + } + if (isTestCall(ts, callee, 'spyOn')) { + const [target, method] = node.arguments; + if ( + target !== undefined && + method !== undefined && + ts.isIdentifier(target) && + imports.namespaces.has(target.text) && + ts.isStringLiteral(method) + ) { + const mapping = tables.calls[method.text]; + if (mapping !== undefined) { + replace(method, `'${mapping.operation}'`); + replace(target, `${target.text}.${mapping.namespace}`); + doubles.set(node, { name: method.text, mapping }); + migrated.add(method.text); + changes += 1; + } + } + return; + } + if (isTestCall(ts, callee, 'mock')) { + const [module, second] = node.arguments; + if ( + module === undefined || + !ts.isStringLiteral(module) || + module.text !== V1_MODULE + ) { + return; + } + if (second === undefined) { + find( + node, + V1_MODULE, + 'an automock gives undefined from v2 calls, so .then(orThrow) fails: ' + + 'give { spy: true }, and set values with mockResolvedValue(mockReply(...))', + ); + } else if (ts.isArrowFunction(second) || ts.isFunctionExpression(second)) { + rewriteFactory(node, second, isTestCall(ts, callee, 'mock', 'vi')); + } + return; + } if (ts.isIdentifier(callee)) { const imported = imports.named.get(callee.text); if (imported !== undefined && imported in tables.calls) { @@ -215,14 +503,15 @@ export function migrateSource( return; } const left = typeName.left; - const v2Name = tables.types[typeName.right.text]; - if ( - ts.isIdentifier(left) && - imports.namespaces.has(left.text) && - v2Name !== undefined - ) { + const right = typeName.right.text; + const v2Name = tables.types[right]; + if (!ts.isIdentifier(left) || !imports.namespaces.has(left.text)) return; + if (v2Name !== undefined) { replace(typeName.right, v2Name); changes += 1; + } else if (right in tables.compat) { + replace(typeName, compatLocal(right)); + changes += 1; } return; } @@ -234,6 +523,21 @@ export function migrateSource( // v1 and v2 have the same module name. A name that v1 does not export is from v2. if (!isV1Name(tables, imported)) return; if (isCountedAtParent(ts, node, imported, tables)) return; + const wrapper = doubleWrapper(node); + if (wrapper !== null && imported in tables.calls) { + rewriteDouble(node, wrapper, imported, null); + countUse(node.text, true); + return; + } + if ( + testFile && + imported in tables.calls && + !ts.isShorthandPropertyAssignment(node.parent) + ) { + rewriteDouble(node, node, imported, null); + countUse(node.text, true); + return; + } countUse(node.text, false); find(node, imported, hint(tables, imported)); return; @@ -246,15 +550,41 @@ export function migrateSource( !(ts.isCallExpression(node.parent) && node.parent.expression === node) ) { const name = node.name.text; - if (name in tables.compat) find(node, name, `import it from ${COMPAT_MODULE}`); - else if (name in tables.calls || name in tables.unmapped || name in tables.types) { + const wrapper = doubleWrapper(node); + if (wrapper !== null && name in tables.calls) { + rewriteDouble(node, wrapper, name, node.expression.text); + return; + } + if (testFile && name in tables.calls) { + rewriteDouble(node, node, name, node.expression.text); + return; + } + if (name in tables.compat) { + // `client.PlaceDriverRole.Logic` reads the compat enum, as the app code now does. + replace(node, compatLocal(name)); + changes += 1; + } else if (name in tables.calls || name in tables.unmapped || name in tables.types) { find(node, name, hint(tables, name)); } return; } - // A test double names the function in a string: `vi.spyOn(ts_client, 'showZone')`. + // A test can load a file of the v1 build: `vi.importActual('@placeos/ts-client/dist/index.es.js')`. + if (ts.isStringLiteral(node) && node.text.startsWith(`${V1_MODULE}/dist/`)) { + replace(node, `'${V1_MODULE}'`); + changes += 1; + return; + } + + // A test double names the function in a string, such as `jest.spyOn(module, 'showZone')`. + // The tool changes `vi.spyOn(client, 'showZone')` on a namespace import above. if (ts.isStringLiteral(node) && imports.namespaces.size > 0 && node.text in tables.calls) { + const parent = node.parent; + const spyOnNamespace = + ts.isCallExpression(parent) && + isTestCall(ts, parent.expression, 'spyOn') && + parent.arguments[1] === node; + if (spyOnNamespace) return; const mapping = tables.calls[node.text]; const target = mapping === undefined ? '' : ` (${mapping.namespace}.${mapping.operation})`; @@ -263,6 +593,9 @@ export function migrateSource( } visit(source); + // The hoisted `fromV1Mock` of a factory is also there for the tests. + if (importsFromV1Mock && !usesFromV1Mock) compatNames.add('fromV1Mock'); + // The new import of the v2 namespaces and types, and of the helpers. const added = [ ...[...namespaceNames].map(([name, local]) => @@ -296,6 +629,17 @@ export function migrateSource( }); } + if (usesFromV1Mock) { + // `vi.mock` runs before the imports, so its factory gets the helper from `vi.hoisted`. + const lastImport = source.statements.filter(ts.isImportDeclaration).at(-1); + assert(lastImport !== undefined, 'the file has an import'); + edits.push({ + start: lastImport.end, + end: lastImport.end, + text: `\nconst { fromV1Mock } = await vi.hoisted(() => import('${COMPAT_MODULE}'));`, + }); + } + findings.sort((a, b) => a.line - b.line || a.column - b.column); return { text: applyEdits(text, edits, 0), changes, findings, migrated }; } @@ -340,6 +684,80 @@ function declaredNames(ts: typeof TS, source: TS.SourceFile): Set { return names; } +/** `vi.` or `jest.`, or only `.`. */ +function isTestCall( + ts: typeof TS, + callee: TS.Expression, + method: string, + global: string | null = null, +): boolean { + return ( + ts.isPropertyAccessExpression(callee) && + ts.isIdentifier(callee.expression) && + (global === null + ? TEST_GLOBALS.has(callee.expression.text) + : callee.expression.text === global) && + callee.name.text === method + ); +} + +/** The objects that a `vi.mock` factory returns: its expression, or its top `return`s. */ +function factoryObjects( + ts: typeof TS, + factory: TS.ArrowFunction | TS.FunctionExpression, +): TS.ObjectLiteralExpression[] { + const unwrap = (node: TS.Expression | undefined): TS.ObjectLiteralExpression | null => { + let current = node; + for (let depth = 0; depth < CHAIN_DEPTH_MAX && current !== undefined; depth += 1) { + if (ts.isObjectLiteralExpression(current)) return current; + if (!ts.isParenthesizedExpression(current)) return null; + current = current.expression; + } + return null; + }; + const body = factory.body; + if (!ts.isBlock(body)) { + const object = unwrap(body); + return object === null ? [] : [object]; + } + const objects: TS.ObjectLiteralExpression[] = []; + for (const statement of body.statements) { + if (!ts.isReturnStatement(statement)) continue; + const object = unwrap(statement.expression); + if (object !== null) objects.push(object); + } + return objects; +} + +/** The arguments of `fromV1Mock` after the implementation: the input keys of the v1 arguments. */ +function fromV1MockArgs(mapping: CallMapping): string { + const keys = mapping.parameters.map((_parameter, index) => inputKey(mapping, index)); + while (keys.at(-1) === null) keys.pop(); + const list = `[${keys.map((key) => (key === null ? 'null' : quote(key))).join(', ')}]`; + const pickKey = mapping.pick?.kind === 'arg' ? inputKey(mapping, mapping.pick.index) : null; + return [ + list, + ...(mapping.result === 'page' || pickKey !== null ? [`'${mapping.result}'`] : []), + ...(pickKey === null ? [] : [quote(pickKey)]), + ].join(', '); +} + +/** The input key of a v1 argument: the inverse of the input template. `...` is a spread. */ +function inputKey(mapping: CallMapping, index: number): string | null { + if (mapping.input.kind !== 'object') return null; + for (const entry of mapping.input.entries) { + if (entry.kind === 'spread' && entry.index === index) return '...'; + if ( + entry.kind === 'property' && + entry.value.kind === 'arg' && + entry.value.index === index + ) { + return entry.key; + } + } + return null; +} + /** `false` for the name of a property or a member, such as `name` in `a.name` or `{ name: 1 }`. */ function isReference(ts: typeof TS, node: TS.Identifier): boolean { const parent = node.parent; @@ -405,11 +823,19 @@ interface RenderedCall { /** The v2 input of a v1 call, or the reason that the tool cannot make it. */ function renderCall( ts: typeof TS, - call: TS.CallExpression, + args: readonly TS.Expression[], mapping: CallMapping, textOf: (node: TS.Node) => string, + expectation = false, ): RenderedCall | string { - const args = call.arguments; + // A check does not know the `version` that v2 reads from the data, so it checks the rest. + const isMember = (entry: ObjectEntry) => + entry.kind === 'property' && entry.value.kind === 'member'; + const entriesOf = mapping.input.kind === 'object' ? mapping.input.entries : []; + const loose = expectation && entriesOf.some(isMember); + const template: Template = loose + ? { kind: 'object', entries: entriesOf.filter((entry) => !isMember(entry)) } + : mapping.input; if (args.some((arg) => ts.isSpreadElement(arg))) return 'a spread argument: change the call by hand'; if (args.length > mapping.parameters.length) @@ -427,8 +853,8 @@ function renderCall( } // An argument that the v2 call uses twice is evaluated twice. Only a simple one can be. const counts = new Map(); - countArgs(mapping.input, counts); - if (mapping.pick !== null) countArgs(mapping.pick, counts); + countArgs(template, counts); + if (mapping.pick !== null && !expectation) countArgs(mapping.pick, counts); for (const [index, count] of counts) { const arg = given[index]; if (count > 1 && arg !== null && arg !== undefined && !isSimple(ts, arg)) { @@ -444,22 +870,31 @@ function renderCall( return initializer === null ? null : { text: initializer, node: null }; }; // An input that is only a spread of one argument is that argument: `zones.index(query)`. - const [only] = mapping.input.kind === 'object' ? mapping.input.entries : []; + const [only] = template.kind === 'object' ? template.entries : []; const whole = - mapping.input.kind === 'object' && - mapping.input.entries.length === 1 && - only?.kind === 'spread' + template.kind === 'object' && template.entries.length === 1 && only?.kind === 'spread' ? value(only.index) : null; + // A matcher such as `expect.objectContaining(...)` is one value. It cannot be spread. + const spreads = template.kind === 'object' ? template.entries : []; + if (expectation && whole === null) { + for (const entry of spreads) { + const node = entry.kind === 'spread' ? given[entry.index] : null; + if (node !== null && node !== undefined && ts.isCallExpression(node)) { + return 'a matcher in the arguments: change the expectation by hand'; + } + } + } const input = whole !== null && whole.node !== null && !ts.isObjectLiteralExpression(whole.node) ? whole.text - : (renderTemplate(ts, mapping.input, value, textOf) ?? '{}'); + : (renderTemplate(ts, template, value, textOf) ?? '{}'); const pick = mapping.pick === null ? null : renderTemplate(ts, mapping.pick, value, textOf); const pickText = pick ?? ''; const pickParameter = ['data', 'value', 'response'].find((name) => !new RegExp(`\\b${name}\\b`).test(pickText)) ?? 'v2Data'; + if (loose) return { input: `expect.objectContaining(${input})`, pick, pickParameter }; return { input, pick, pickParameter }; } diff --git a/v2/src/migrate/v1-map.ts b/v2/src/migrate/v1-map.ts index 7dabf1dc3..2c6c53207 100644 --- a/v2/src/migrate/v1-map.ts +++ b/v2/src/migrate/v1-map.ts @@ -4533,12 +4533,12 @@ export const V1_TYPES: Readonly> = { PlaceAlert: 'Alert', PlaceAlertDashboard: 'AlertDashboard', PlaceApiKey: 'ApiKeysResponse', - PlaceApplication: 'DoorkeeperApplication', + PlaceApplication: 'Application', PlaceAsset: 'Asset', PlaceAssetCategory: 'AssetCategory', PlaceAssetPurchaseOrder: 'AssetPurchaseOrder', PlaceAssetType: 'AssetType', - PlaceDomain: 'Authority', + PlaceDomain: 'Domain', PlaceDriver: 'Driver', PlaceEdge: 'Edge', PlaceGroup: 'Group', @@ -4547,18 +4547,18 @@ export const V1_TYPES: Readonly> = { PlaceGroupZone: 'GroupZone', PlaceHistory: 'History', PlaceLDAPSource: 'LdapAuthentication', - PlaceMetadata: 'MetadataInterface', + PlaceMetadata: 'Metadata', PlaceModule: 'Module', PlaceMQTTBroker: 'Broker', PlaceOAuthSource: 'OauthAuthentication', PlaceRepository: 'Repository', PlaceSAMLSource: 'SamlAuthentication', PlaceSettings: 'Settings', - PlaceShortUrl: 'Shortener', + PlaceShortUrl: 'ShortUrl', PlaceStorage: 'Storage', - PlaceSystem: 'ControlSystem', + PlaceSystem: 'System', PlaceTrigger: 'Trigger', - PlaceUser: 'UserAdminMetadataResponse', + PlaceUser: 'User', PlaceZone: 'Zone', SignageMedia: 'PlaylistItem', SignagePlaylist: 'Playlist', @@ -4566,17 +4566,29 @@ export const V1_TYPES: Readonly> = { SignagePlaylistMedia: 'PlaylistRevision', SignagePlugin: 'SignagePlugin', SignageTemplate: 'SignageTemplate', - SignageTemplateMapping: 'SignageTemplateSystemTemplate', + SignageTemplateMapping: 'SignageTemplateMapping', }; /** The v1 names that `@placeos/ts-client/compat` has. The tool moves their imports. */ export const V1_COMPAT: Readonly> = { AuthType: 'value', + deregisterMockEndpoint: 'value', + deregisterSystem: 'value', EncryptionLevel: 'value', MediaAnimation: 'value', + MockHttpRequest: 'type', + MockHttpRequestHandler: 'type', + MockHttpRequestHandlerOptions: 'type', + MockHttpResponse: 'type', + MockPlaceWebsocketModule: 'type', + MockPlaceWebsocketSystem: 'type', + mockSystem: 'value', PlaceDriverRole: 'value', PlaceRepositoryType: 'value', QueryResponse: 'type', + registerMockEndpoint: 'value', + registerSystem: 'value', + setMockNotFoundHandler: 'value', TriggerConditionOperator: 'value', TriggerTimeConditionType: 'value', TriggerWebhookType: 'value', @@ -4607,8 +4619,6 @@ export const V1_UNMAPPED: Readonly> = { debug: 'use createRealtime (README: Realtime)', debug_events: 'v2 has no replacement', del: 'use a generated operation, or fetch', - deregisterMockEndpoint: 'use a generated operation, or fetch', - deregisterSystem: 'use createRealtime (README: Realtime)', edgeControlUrl: 'it sends 0 requests', edgeErrorsStreamUrl: 'it sends 0 requests', edgeErrorsStreamUrlFor: 'it sends 0 requests', @@ -4641,9 +4651,6 @@ export const V1_UNMAPPED: Readonly> = { log: 'v2 has no replacement', logout: 'use createAuthSession and configure (README: Log in)', mediaThumbnail: 'it sends 0 requests', - MockPlaceWebsocketModule: 'v2 has no replacement', - MockPlaceWebsocketSystem: 'v2 has no replacement', - mockSystem: 'use createRealtime (README: Realtime)', onlineState: 'use createAuthSession and configure (README: Log in)', parseLinkHeader: 'v2 has no replacement', patch: 'use a generated operation, or fetch', @@ -4668,8 +4675,6 @@ export const V1_UNMAPPED: Readonly> = { redirectUri: 'use createAuthSession and configure (README: Log in)', refreshAuthority: 'use createAuthSession and configure (README: Log in)', refreshToken: 'use createAuthSession and configure (README: Log in)', - registerMockEndpoint: 'use a generated operation, or fetch', - registerSystem: 'use createRealtime (README: Realtime)', remove: 'a v1 request helper: use the generated operation', removeFragment: 'v2 has no replacement', removeInvitation: 'no v2 operation for DELETE /api/staff/v1/surveys/invitations/s0zq', @@ -4680,7 +4685,6 @@ export const V1_UNMAPPED: Readonly> = { scoped_log: 'v2 has no replacement', setAPI_Key: 'use createAuthSession and configure (README: Log in)', setAppHeaders: 'use createAuthSession and configure (README: Log in)', - setMockNotFoundHandler: 'use a generated operation, or fetch', setStorage: 'use createAuthSession and configure (README: Log in)', setToken: 'use createAuthSession and configure (README: Log in)', setup: 'use createAuthSession and configure (README: Log in)', diff --git a/v2/src/mock/index.ts b/v2/src/mock/index.ts new file mode 100644 index 000000000..4396e0418 --- /dev/null +++ b/v2/src/mock/index.ts @@ -0,0 +1,180 @@ +/** + * Typed mocks of the API endpoints, at `@placeos/ts-client/mock`. A mock answers the calls of one + * endpoint without a request. The compiler checks the name of the endpoint, the input that the + * handler gets and the data that it gives: + * + * ```ts + * import { configure, zones } from '@placeos/ts-client'; + * import { endpointMocks, mockEndpoint, respond } from '@placeos/ts-client/mock'; + * + * configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); + * mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); + * mockEndpoint('zones.index', (input) => respond([{ id: 'zone-1' }], { total: 1 })); + * + * const result = await zones.show({ id: 'zone-1' }); // `ok`, with a `Zone` + * ``` + * + * - The client checks the input first, as for a request, so a mock finds the same input errors. + * - The data can leave out fields. The client parses it with the response schema of the endpoint, + * and a missing required field gets its empty value, such as `''`, `0` or `[]`. + * - `throw httpError(404)` in a handler gives an `http` error with that status. + * - A call to an endpoint without a mock sends the request with the `fetch` of the client. Give + * `mockFetch` of `@placeos/ts-client/compat` to answer those from the v1 mock endpoints. + * + * @module + */ +import { assert } from '../core/assert.ts'; +import type { CallError, CallMock, MockAnswer, Reply } from '../core/client.ts'; +import type { Result } from '../core/result.ts'; +import type * as Operations from '../generated/operations/index.ts'; + +type Namespaces = typeof Operations; + +/** The name of each endpoint, such as `zones.show`. */ +export type EndpointName = { + [N in keyof Namespaces]: { + [F in keyof Namespaces[N]]: `${N & string}.${F & string}`; + }[keyof Namespaces[N]]; +}[keyof Namespaces]; + +/** The function of an endpoint, such as `zones.show` for `'zones.show'`. */ +type EndpointFunction = K extends `${infer N}.${infer F}` + ? N extends keyof Namespaces + ? F extends keyof Namespaces[N] + ? Namespaces[N][F] + : never + : never + : never; + +/** The input of an endpoint: its path and query parameters, and `body` if it has one. */ +export type EndpointInput = + EndpointFunction extends (...args: infer A) => unknown ? NonNullable : never; + +/** The data of a successful call of an endpoint, such as `Zone` for `zones.show`. */ +export type EndpointData = + EndpointFunction extends (...args: never[]) => Promise, CallError>> + ? D + : never; + +/** + * Data that can leave out fields, at each level. An endpoint without a response schema gives + * bytes: its mock can give a `Uint8Array`, a string or nothing. + */ +export type MockData = T extends Uint8Array + ? Uint8Array | string | undefined + : T extends readonly (infer E)[] + ? readonly MockData[] + : T extends object + ? { readonly [K in keyof T]?: MockData } + : T; + +const RESPONSE: unique symbol = Symbol('mock-response'); + +/** Data with a status or headers. Make one with `respond`. */ +export interface MockResponse { + readonly [RESPONSE]: true; + readonly data: T; + readonly status: number; + readonly headers: Readonly>; +} + +export type MockHandler = ( + input: EndpointInput, +) => MockResult | Promise>; + +type MockResult = + MockData> | MockResponse>>; + +export interface MockOptions { + /** Milliseconds before the answer, to show the loading state of an app. The default is 0. */ + readonly delayMs?: number; +} + +/** More mocks is a leak, such as a test that adds mocks in a loop and never removes them. */ +export const ENDPOINT_MOCKS_MAX = 10_000; + +interface Entry { + readonly handler: (input: Readonly>) => unknown; + readonly delayMs: number; +} + +const mocks = new Map(); + +/** + * Answers the calls of an endpoint with `handler`. A new mock of the same endpoint replaces the + * old one. Returns the function that removes the mock. + */ +export function mockEndpoint( + name: K, + handler: MockHandler, + options: MockOptions = {}, +): () => void { + assert(mocks.has(name) || mocks.size < ENDPOINT_MOCKS_MAX, 'fewer endpoint mocks'); + const delayMs = options.delayMs ?? 0; + assert(Number.isSafeInteger(delayMs) && delayMs >= 0, 'delayMs is a whole number'); + // The client gives the input of this endpoint, which the type of `handler` describes. + const entry: Entry = { + handler: (input) => Reflect.apply(handler, undefined, [input]), + delayMs, + }; + mocks.set(name, entry); + return () => { + if (mocks.get(name) === entry) mocks.delete(name); + }; +} + +/** Removes each endpoint mock. */ +export function clearEndpointMocks(): void { + mocks.clear(); +} + +/** Data with a status, headers, or the `X-Total-Count` of a page. */ +export function respond( + data: T, + options: { + readonly status?: number; + readonly headers?: Readonly>; + /** The number of items on all pages. `pageInfo` reads it. */ + readonly total?: number; + } = {}, +): MockResponse { + const headers: Record = { ...options.headers }; + if (options.total !== undefined) headers['x-total-count'] = String(options.total); + return { [RESPONSE]: true, data, status: options.status ?? 200, headers }; +} + +/** An error for a handler to throw: `throw httpError(404)` gives an `http` error with 404. */ +export function httpError(status: number, message = `HTTP ${status}`): Error & { status: number } { + assert(Number.isInteger(status) && status >= 400 && status <= 599, 'an error status'); + return Object.assign(new Error(message), { status }); +} + +/** The mock of the client: give it as `mock` to `configure` or `createClient`. */ +export const endpointMocks: CallMock = ({ name, input }) => { + const entry = mocks.get(name); + if (entry === undefined) return null; + return answer(entry, input); +}; + +async function answer(entry: Entry, input: Readonly>): Promise { + if (entry.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, entry.delayMs)); + let value: unknown; + try { + value = await entry.handler(input); + } catch (error) { + const status = + typeof error === 'object' && error !== null ? Reflect.get(error, 'status') : null; + // Another error is a bug in the test, so it goes to the caller. + if (typeof status !== 'number') throw error; + const message = error instanceof Error ? error.message : `HTTP ${status}`; + return { status, headers: new Headers(), data: { error: message } }; + } + if (isResponse(value)) { + return { status: value.status, headers: new Headers(value.headers), data: value.data }; + } + return { status: 200, headers: new Headers(), data: value }; +} + +function isResponse(value: unknown): value is MockResponse { + return typeof value === 'object' && value !== null && RESPONSE in value; +} diff --git a/v2/test/auth.test.ts b/v2/test/auth.test.ts index ec5d69809..dde8f58fb 100644 --- a/v2/test/auth.test.ts +++ b/v2/test/auth.test.ts @@ -522,6 +522,7 @@ describe('the session with the client', () => { params: parameters({ id: string() }, ['id']), body: null, response: object({ id: string() }, ['id']), + name: 'zones.show', }); test('a 401 renews the token one time, and parallel requests share the renewal', async () => { diff --git a/v2/test/client.test.ts b/v2/test/client.test.ts index f8a407f82..478d847e0 100644 --- a/v2/test/client.test.ts +++ b/v2/test/client.test.ts @@ -72,6 +72,7 @@ const UPDATE = operation({ ), body: Item, response: Item, + name: 'items.update', }); const DOWNLOAD = operation({ @@ -81,6 +82,7 @@ const DOWNLOAD = operation({ params: parameters({}), body: null, response: null, + name: 'items.download', }); describe('call', () => { diff --git a/v2/test/compat.test.ts b/v2/test/compat.test.ts new file mode 100644 index 000000000..ee94b252b --- /dev/null +++ b/v2/test/compat.test.ts @@ -0,0 +1,174 @@ +/** + * Goal: the v1 mocks of `@placeos/ts-client/compat` work with the v2 client and the v2 realtime + * client, so that a mock mode and the tests of an app still work after the migration. + * Method: register v1 style endpoints and systems, and use them through v2 calls. + */ +import { afterEach, expect, test } from 'bun:test'; +import { + clearMockEndpoints, + deregisterSystem, + mockFetch, + mockPage, + mockRealtimeEnvironment, + mockReply, + mockSystem, + orThrow, + orThrowPage, + registerMockEndpoint, + registerSystem, + type MockHttpRequest, +} from '../src/compat/index.ts'; +import { createClient } from '../src/core/client.ts'; +import { createRealtime, type BindingState } from '../src/realtime/realtime.ts'; +import { zones } from '../src/generated/operations/index.ts'; + +// An app gives `baseUrl: ''`. Outside a browser, a URL needs an origin. v1 mock data often has +// only some fields. `missingFields: 'zero'` fills the others, as the v1 classes did. +const client = createClient({ + baseUrl: 'http://mock.invalid', + auth: { kind: 'none' }, + fetch: mockFetch, + missingFields: 'zero', +}); +const options = { client }; + +afterEach(() => { + clearMockEndpoints(); + deregisterSystem('sys-1'); +}); + +test('a v2 call gets the response of a v1 mock endpoint', async () => { + const requests: MockHttpRequest[] = []; + registerMockEndpoint({ + path: '/api/engine/v2/zones/:id', + method: 'GET', + callback: (request) => { + requests.push(request); + return { id: request.route_params['id'], name: 'Level 1', tags: ['level'] }; + }, + }); + registerMockEndpoint({ + path: '/api/engine/v2/zones', + method: 'GET', + metadata: [{ id: 'zone-1', name: 'Level 1' }], + headers: { 'X-Total-Count': '7' }, + }); + const [zone, page] = await Promise.all([ + zones.show({ id: 'zone-1', complete: true }, options).then(orThrow), + zones.index({ tags: ['level'] }, options).then(orThrowPage), + ]); + expect(zone).toMatchObject({ id: 'zone-1', name: 'Level 1', tags: ['level'] }); + // A required field that the mock leaves out gets its empty value. + expect(zone.update_systems).toBe(false); + expect(requests[0]?.query_params).toEqual({ complete: 'true' }); + expect(page.total).toBe(7); + expect(page.data.map((item) => item.id)).toEqual(['zone-1']); +}); + +test('the body of a request reaches the mock endpoint', async () => { + let body: unknown; + registerMockEndpoint({ + path: '/api/engine/v2/zones', + method: 'POST', + callback: (request) => { + body = request.body; + return { id: 'zone-2', ...request.body }; + }, + }); + const zone = await zones.create({ body: { name: 'New' } }, options).then(orThrow); + expect(body).toEqual({ name: 'New' }); + expect(zone.id).toBe('zone-2'); +}); + +test('a missing endpoint is a 404, and a thrown status is that status', async () => { + registerMockEndpoint({ + path: '/api/engine/v2/zones/:id', + method: 'DELETE', + callback: () => { + throw Object.assign(new Error('Forbidden'), { status: 403 }); + }, + }); + const missing = await zones.show({ id: 'zone-1' }, options); + const refused = await zones.destroy({ id: 'zone-1' }, options); + expect(missing.ok === false && missing.error.kind === 'http' && missing.error.status).toBe(404); + expect(refused.ok === false && refused.error.kind === 'http' && refused.error.status).toBe(403); +}); + +test('without missingFields: zero, partial mock data is not valid', async () => { + registerMockEndpoint({ + path: '/api/engine/v2/zones/:id', + method: 'GET', + metadata: { id: 'z' }, + }); + const strict = createClient({ + baseUrl: 'http://mock.invalid', + auth: { kind: 'none' }, + fetch: mockFetch, + }); + const result = await zones.show({ id: 'z' }, { client: strict }); + expect(result.ok === false && result.error.kind).toBe('response_invalid'); +}); + +test('mockReply and mockPage make the results of test doubles', () => { + const zone = { id: 'zone-1' }; + expect(orThrow(mockReply(zone))).toBe(zone); + expect(orThrowPage(mockPage({ data: [zone], total: 3 }))).toEqual({ + data: [zone], + total: 3, + nextOffset: null, + }); +}); + +test('a v2 binding and call use a v1 mock system', async () => { + registerSystem('sys-1', { + Display: [ + { + power: false, + $power(this: { power: boolean }, on: boolean) { + this.power = on; + return on; + }, + }, + ], + }); + const realtime = createRealtime({ + baseUrl: 'http://mock.invalid', + auth: { kind: 'none' }, + environment: mockRealtimeEnvironment(), + }); + const states: BindingState[] = []; + const power = { sys: 'sys-1', mod: 'Display', index: 1, name: 'power' }; + const release = realtime.bind(power, (state) => states.push(state)); + await waitFor(() => states.length > 0); + expect(states.at(-1)).toEqual({ kind: 'value', value: false }); + + // A function changes the variable, and the binding gets the new value. + expect(await realtime.exec(power, [true])).toEqual({ ok: true, value: true }); + await waitFor(() => lastValue(states) === true); + + // A change in the test also notifies the binding. + const display = mockSystem('sys-1')?.['Display']?.[0]; + if (display !== undefined) display['power'] = false; + await waitFor(() => lastValue(states) === false); + + const missing = await realtime.exec({ ...power, mod: 'Camera' }, []); + expect(missing.ok === false && missing.error.kind === 'server' && missing.error.code).toBe( + 'module_not_found', + ); + release(); + realtime.stop(); +}); + +function lastValue(states: readonly BindingState[]): unknown { + const last = states.at(-1); + return last?.kind === 'value' ? last.value : undefined; +} + +/** Waits for the mock socket. It answers on timers. */ +async function waitFor(done: () => boolean): Promise { + for (let attempt = 0; attempt < 100; attempt += 1) { + if (done()) return; + await new Promise((resolve) => setTimeout(resolve, 5)); + } + throw new Error('the condition did not become true'); +} diff --git a/v2/test/loose/consumer.ts b/v2/test/loose/consumer.ts index b7cf574b0..da60123fe 100644 --- a/v2/test/loose/consumer.ts +++ b/v2/test/loose/consumer.ts @@ -3,8 +3,9 @@ * Method: `bun run build` compiles these calls against `dist`. Each `@ts-expect-error` line must * be an error. */ -import { orThrow, orThrowPage, PlaceDriverRole } from '../../dist/compat.js'; +import { orThrow, orThrowPage, PlaceDriverRole } from '../../dist/compat/index.js'; import { metadata, zones, type Driver, type Zone } from '../../dist/index.js'; +import { mockEndpoint, respond } from '../../dist/mock/index.js'; export async function calls(): Promise { // An operation without a body does not ask for one. @@ -18,6 +19,14 @@ export async function calls(): Promise { await zones.update({ id: 'zone-1' }); // @ts-expect-error a parameter that the operation does not have await zones.show({ id: 'zone-1', no_such_parameter: true }); + // A typed mock: the input and the data have the types of the endpoint. + mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); + mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 1 })); + mockEndpoint('metadata.show', () => ({ settings: { details: { theme: 'dark' } } })); + // @ts-expect-error there is no such endpoint + mockEndpoint('zones.no_such_endpoint', () => ({})); + // @ts-expect-error `name` of a zone is a string + mockEndpoint('zones.show', () => ({ name: 1 })); // Without `strictNullChecks`, `ok === false` narrows the result. `!result.ok` does not. const result = await zones.show({ id: 'zone-1' }); if (result.ok === false) return result.error.kind; diff --git a/v2/test/migrate.test.ts b/v2/test/migrate.test.ts index 26da57e3e..30979d44c 100644 --- a/v2/test/migrate.test.ts +++ b/v2/test/migrate.test.ts @@ -15,8 +15,8 @@ const TABLES: MigrateTables = { unmapped: V1_UNMAPPED, }; -function migrate(text: string) { - return migrateSource(ts, 'file.ts', text, TABLES); +function migrate(text: string, fileName = 'file.ts') { + return migrateSource(ts, fileName, text, TABLES); } test('rewrites calls, types and imports', () => { @@ -93,25 +93,44 @@ test('gives a new import another name when the file has the name', () => { ); }); -test('rewrites calls on a namespace import, and finds test doubles', () => { +test('rewrites calls and spies on a namespace import', () => { const result = migrate( [ "import * as client from '@placeos/ts-client';", 'client.showZone(id);', "vi.spyOn(client, 'showZone');", + "jest.fn().mockName('showZone');", ].join('\n'), ); expect(result.text.split('\n')).toEqual([ "import * as client from '@placeos/ts-client';", "import { orThrow } from '@placeos/ts-client/compat';", 'client.zones.show({ id }).then(orThrow);', - "vi.spyOn(client, 'showZone');", + "vi.spyOn(client.zones, 'show');", + "jest.fn().mockName('showZone');", ]); + // Another string with a v1 name can be a test double that the tool does not know. expect(result.findings.map((finding) => finding.message)).toEqual([ 'a test double of v1: make it for the v2 call (zones.show)', ]); }); +test('a namespace import reads the v1 enums and types from the compat module', () => { + const result = migrate( + [ + "import * as client from '@placeos/ts-client';", + 'const role = client.PlaceDriverRole.Logic;', + 'let page: client.QueryResponse;', + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import * as client from '@placeos/ts-client';", + "import { PlaceDriverRole, type QueryResponse } from '@placeos/ts-client/compat';", + 'const role = PlaceDriverRole.Logic;', + 'let page: QueryResponse;', + ]); +}); + test('moves the v1 enums and the QueryResponse type to the compat module', () => { const result = migrate( [ @@ -140,3 +159,94 @@ test('a second run changes nothing', () => { // The v2 names of the first run are not findings. expect(second.findings.map((finding) => finding.name)).toEqual(['getModule']); }); + +test('rewrites test doubles: the function, the mock values and the argument checks', () => { + const result = migrate( + [ + "import { queryZones, showMetadata, showZone, updateSystem } from '@placeos/ts-client';", + "vi.mock('@placeos/ts-client', { spy: true });", + "vi.mocked(showZone).mockResolvedValue({ id: 'zone-1' } as any);", + 'vi.mocked(queryZones).mockResolvedValueOnce({ data: [], total: 0 });', + "vi.mocked(showZone).mockRejectedValue(new Error('403'));", + "expect(showZone).toHaveBeenCalledWith('zone-1');", + 'expect(showZone).not.toHaveBeenCalled();', + '(showZone as Mock).mockImplementation((id) => Promise.resolve({ id }));', + 'vi.mocked(showMetadata).mockResolvedValue({ details: {} });', + "expect(updateSystem).toHaveBeenCalledWith('sys-1', expect.objectContaining({ name: 'A' }));", + ].join('\n'), + 'zone.spec.ts', + ); + expect(result.text.split('\n')).toEqual([ + "import { metadata, systems, zones } from '@placeos/ts-client';", + "import { fromV1Mock, mockPage, mockReply } from '@placeos/ts-client/compat';", + "vi.mock('@placeos/ts-client', { spy: true });", + "vi.mocked(zones.show).mockResolvedValue(mockReply({ id: 'zone-1' } as any));", + 'vi.mocked(zones.index).mockResolvedValueOnce(mockPage({ data: [], total: 0 }));', + "vi.mocked(zones.show).mockRejectedValue(new Error('403'));", + "expect(zones.show).toHaveBeenCalledWith({ id: 'zone-1' });", + 'expect(zones.show).not.toHaveBeenCalled();', + // An implementation gets the v1 arguments, and its value becomes a v2 result. + "(zones.show as Mock).mockImplementation(fromV1Mock((id) => Promise.resolve({ id }), ['id', '...']));", + // The v2 call gives the data by key, so the value goes under the key. + "vi.mocked(metadata.show).mockImplementation(fromV1Mock(() => ({ details: {} }), ['id', 'name'], 'data', 'name'));", + // The check leaves out the `version` that v2 reads from the data. + "expect(systems.update).toHaveBeenCalledWith(expect.objectContaining({ sys_id: 'sys-1', body: expect.objectContaining({ name: 'A' }) }));", + ]); + expect(result.findings).toEqual([]); +}); + +test('rewrites a spy on a namespace import, and finds an automock', () => { + const result = migrate( + [ + "import * as client from '@placeos/ts-client';", + "vi.mock('@placeos/ts-client');", + "vi.spyOn(client, 'showZone').mockResolvedValue(zone);", + ].join('\n'), + ); + expect(result.text.split('\n').at(-1)).toBe( + "vi.spyOn(client.zones, 'show').mockResolvedValue(mockReply(zone));", + ); + expect(result.findings.map((finding) => finding.name)).toEqual(['@placeos/ts-client']); +}); + +test('rewrites the v1 functions of a vi.mock factory to v2 namespaces', () => { + const result = migrate( + [ + "import { authority, queryZones, showMetadata, showZone } from '@placeos/ts-client';", + "vi.mock('@placeos/ts-client', () => ({", + ' authority: vi.fn(() => null),', + ' showZone: vi.fn((id: string) => Promise.resolve({ id })),', + ' queryZones: vi.fn(),', + ' showMetadata: vi.fn(() => ({ details: {} })),', + '}));', + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import { authority } from '@placeos/ts-client';", + "const { fromV1Mock } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", + "vi.mock('@placeos/ts-client', () => ({ authority: vi.fn(() => null), " + + "zones: { show: vi.fn(fromV1Mock((id: string) => Promise.resolve({ id }), ['id', '...'])), " + + "index: vi.fn(fromV1Mock(undefined, ['...'], 'page')) }, " + + "metadata: { show: vi.fn(fromV1Mock(() => ({ details: {} }), ['id', 'name'], 'data', 'name')) } }));", + ]); +}); + +test('fromV1Mock gives the v1 arguments and a v2 result', async () => { + const { fromV1Mock, orThrow, orThrowPage } = await import('../src/compat/index.ts'); + const calls: unknown[][] = []; + const record = (...args: unknown[]) => { + calls.push(args); + return { id: 'zone-1' }; + }; + const show = fromV1Mock(record, ['id', '...']); + expect(orThrow(await show({ id: 'zone-1' }))).toEqual({ id: 'zone-1' }); + await show({ id: 'zone-1', complete: true }); + // An empty last argument is left out, as the v1 call left it out. + expect(calls).toEqual([['zone-1'], ['zone-1', { complete: true }]]); + const index = fromV1Mock(() => ({ data: [1], total: 9 }), ['...'], 'page'); + expect(orThrowPage(await index({})).total).toBe(9); + const meta = fromV1Mock(() => ({ details: 1 }), ['id', 'name'], 'data', 'name'); + expect(orThrow(await meta({ id: 'z', name: 'settings' }))).toEqual({ + settings: { details: 1 }, + }); +}); diff --git a/v2/test/mock.test.ts b/v2/test/mock.test.ts new file mode 100644 index 000000000..83866e5a2 --- /dev/null +++ b/v2/test/mock.test.ts @@ -0,0 +1,94 @@ +/** + * Goal: a typed endpoint mock answers the calls of its endpoint, with the same checks and parse as + * a response of the server. The compiler checks the name, the input and the data. + * Method: mock endpoints on a client without a server, and call them. + */ +import { afterEach, expect, test } from 'bun:test'; +import { createClient } from '../src/core/client.ts'; +import { pageInfo } from '../src/core/pagination.ts'; +import { metadata, systems, zones } from '../src/generated/operations/index.ts'; +import { + clearEndpointMocks, + endpointMocks, + httpError, + mockEndpoint, + respond, +} from '../src/mock/index.ts'; + +// No `fetch` can answer: a call that a mock does not answer fails as a network error. +const client = createClient({ + baseUrl: 'http://mock.invalid', + auth: { kind: 'none' }, + mock: endpointMocks, + fetch: () => Promise.reject(new Error('no server')), +}); +const options = { client }; + +afterEach(() => clearEndpointMocks()); + +test('a mock gets the typed input and gives the parsed data', async () => { + const inputs: { id: string; complete?: boolean }[] = []; + mockEndpoint('zones.show', (input) => { + inputs.push(input); + return { id: input.id, name: 'Level 1', tags: ['level'] }; + }); + const result = await zones.show({ id: 'zone-1', complete: true }, options); + expect(inputs).toEqual([{ id: 'zone-1', complete: true }]); + if (!result.ok) throw new Error(JSON.stringify(result.error)); + expect(result.value.data).toMatchObject({ id: 'zone-1', name: 'Level 1', tags: ['level'] }); + // A required field that the mock leaves out gets its empty value. An optional one is null. + expect(result.value.data.update_systems).toBe(false); + expect(result.value.data.description).toBeNull(); +}); + +test('respond sets the status and the page total, and the body reaches the mock', async () => { + mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 25 })); + mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { + delayMs: 1, + }); + const page = await zones.index({ limit: 1 }, options); + expect(page.ok && pageInfo(page.value.headers).total).toBe(25); + const updated = await systems.update( + { sys_id: 'sys-1', version: 2, body: { name: 'Room' } }, + options, + ); + expect(updated.ok && updated.value.data.name).toBe('Room'); +}); + +test('httpError gives an http error, and data with a wrong type is invalid', async () => { + mockEndpoint('zones.show', () => { + throw httpError(404, 'zone not found'); + }); + // The client parses the data of a mock as it parses a response: a string is not an array. + mockEndpoint('metadata.show', () => ({ settings: { details: {}, editors: 'admin' } }) as never); + const missing = await zones.show({ id: 'zone-1' }, options); + expect(missing.ok === false && missing.error).toMatchObject({ + kind: 'http', + status: 404, + message: 'zone not found', + }); + const invalid = await metadata.show({ id: 'zone-1' }, options); + expect(invalid.ok === false && invalid.error.kind).toBe('response_invalid'); +}); + +test('a call without a mock sends the request, and a removed mock stops', async () => { + const remove = mockEndpoint('zones.show', () => ({ id: 'zone-1' })); + expect((await zones.show({ id: 'zone-1' }, options)).ok).toBe(true); + remove(); + const sent = await zones.show({ id: 'zone-1' }, options); + expect(sent.ok === false && sent.error.kind).toBe('network'); +}); + +test('the compiler checks the name, the input and the data', () => { + // @ts-expect-error there is no such endpoint + mockEndpoint('zones.no_such_endpoint', () => ({})); + // @ts-expect-error `name` of a zone is a string + mockEndpoint('zones.show', () => ({ name: 1 })); + mockEndpoint('zones.show', (input) => { + // @ts-expect-error `zones.show` has no `sys_id` + void input.sys_id; + return {}; + }); + // An endpoint without a response schema gives bytes, text or nothing. + mockEndpoint('zones.destroy', () => undefined); +}); diff --git a/v2/test/style.test.ts b/v2/test/style.test.ts index 2294c3ea0..ab40d81ea 100644 --- a/v2/test/style.test.ts +++ b/v2/test/style.test.ts @@ -9,6 +9,13 @@ import { join } from 'node:path'; const SOURCE_DIR = join(import.meta.dir, '..', 'src'); const ALLOWED_CASTS = ['parsed as O', 'checked as I', 'result as CallResult']; +/** The v1 mock types of the compat module keep `any`, so that the mocks of an app still compile. */ +const ALLOWED_ANY = [ + 'compat/http-mock.ts: readonly metadata: any;', + 'compat/http-mock.ts: readonly body: any;', + 'compat/http-mock.ts: metadata?: any;', + 'compat/realtime-mock.ts: export type MockModule = Record;', +]; test('the source has no escape from the type checks', async () => { const problems: string[] = []; @@ -18,13 +25,16 @@ test('the source has no escape from the type checks', async () => { // Comments and strings are text, not code. const code = line.replace(/\/\*.*?\*\/|\/\/.*$|^\s*\/?\*.*$|'[^']*'|`[^`]*`/g, ''); const where = `${file}:${index + 1}: ${line.trim()}`; - if (/(?]+)/.exec(code); if (cast !== null && !ALLOWED_CASTS.includes(cast[0])) { From dc8515fadd7e367b334d4d8d8d73a78626cb9449 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 17 Nov 2026 20:41:54 +1100 Subject: [PATCH 08/29] feat(v2): generate the staff API client, and name list operations query Apps call the staff API (bookings, events, guests, surveys) as much as the REST API, and v2 had no client for it. - The generator also reads `OPENAPI_DOC.yml` of PlaceOS/staff-api and writes `src/generated/staff`, at `@placeos/ts-client/staff`: 145 operations, 87 schemas. - Numbered routes of one action merge: PATCH and PUT stay one `update`, an alias path such as `checkin` is dropped, and a longer path gets a name from its segments, such as `bookings.showInstance`. - The `body` query parameter of `events.book` is `body_text` in the input. Operations have `wireNames` for this. - The staff time fields are classified from PlaceOS/models, PlaceOS/calendar and PlaceOS/office365. - Typed mocks have the staff endpoints (`staff.bookings.show`), and the migration tool maps the v1 staff functions, such as `querySurveys`, to the staff client. - The list operation of each controller is `query`, not `index`: `zones.query(...)`. A live test against a local PlaceOS stack passes: 70 REST API checks and 34 staff API checks, with a booking create, show and destroy. Co-Authored-By: Claude Opus 5.5 --- v2/README.md | 60 +- v2/package.json | 4 + v2/scripts/generate.ts | 267 ++- v2/scripts/v1-map.ts | 43 +- v2/src/compat/result.ts | 6 +- v2/src/core/client.ts | 13 +- v2/src/core/pagination.ts | 8 +- .../generated/operations/alert-dashboards.ts | 12 +- v2/src/generated/operations/alerts.ts | 12 +- v2/src/generated/operations/api-keys.ts | 56 +- .../generated/operations/asset-categories.ts | 12 +- .../operations/asset-purchase-orders.ts | 12 +- v2/src/generated/operations/asset-types.ts | 12 +- v2/src/generated/operations/assets.ts | 12 +- v2/src/generated/operations/chat-gpt.ts | 12 +- v2/src/generated/operations/domains.ts | 68 +- v2/src/generated/operations/drivers.ts | 12 +- v2/src/generated/operations/edges.ts | 56 +- v2/src/generated/operations/groups-history.ts | 12 +- .../operations/groups-invitations.ts | 12 +- v2/src/generated/operations/groups-users.ts | 12 +- v2/src/generated/operations/groups-zones.ts | 12 +- v2/src/generated/operations/groups.ts | 12 +- v2/src/generated/operations/history.ts | 12 +- .../operations/ldap-authentications.ts | 12 +- v2/src/generated/operations/modules.ts | 96 +- .../operations/oauth-applications.ts | 12 +- .../operations/oauth-authentications.ts | 12 +- v2/src/generated/operations/pending-mails.ts | 12 +- v2/src/generated/operations/playlist-media.ts | 12 +- v2/src/generated/operations/playlist.ts | 78 +- v2/src/generated/operations/public-events.ts | 12 +- v2/src/generated/operations/repositories.ts | 72 +- .../operations/saml-authentications.ts | 12 +- v2/src/generated/operations/schema.ts | 12 +- v2/src/generated/operations/settings.ts | 12 +- v2/src/generated/operations/short-url.ts | 70 +- .../operations/signage-ai-providers.ts | 12 +- .../generated/operations/signage-plugins.ts | 12 +- .../operations/signage-template-mappings.ts | 12 +- .../generated/operations/signage-templates.ts | 12 +- v2/src/generated/operations/storages.ts | 12 +- .../generated/operations/system-triggers.ts | 12 +- v2/src/generated/operations/systems.ts | 68 +- v2/src/generated/operations/tenant-consent.ts | 12 +- v2/src/generated/operations/triggers.ts | 66 +- v2/src/generated/operations/uploads.ts | 12 +- v2/src/generated/operations/users.ts | 72 +- v2/src/generated/operations/web-rtc.ts | 72 +- v2/src/generated/operations/zones.ts | 70 +- .../staff/operations/asset-categories.ts | 159 ++ .../staff/operations/asset-purchase-orders.ts | 156 ++ .../generated/staff/operations/asset-types.ts | 153 ++ v2/src/generated/staff/operations/assets.ts | 267 +++ v2/src/generated/staff/operations/bookings.ts | 1255 +++++++++++++ .../generated/staff/operations/calendars.ts | 185 ++ v2/src/generated/staff/operations/desks.ts | 164 ++ v2/src/generated/staff/operations/events.ts | 962 ++++++++++ v2/src/generated/staff/operations/groups.ts | 96 + v2/src/generated/staff/operations/guests.ts | 378 ++++ .../staff/operations/health-check.ts | 37 + v2/src/generated/staff/operations/index.ts | 24 + v2/src/generated/staff/operations/place.ts | 52 + v2/src/generated/staff/operations/spaces.ts | 242 +++ v2/src/generated/staff/operations/staff.ts | 237 +++ .../staff/operations/surveys-answers.ts | 74 + .../staff/operations/surveys-invitations.ts | 151 ++ .../staff/operations/surveys-questions.ts | 156 ++ v2/src/generated/staff/operations/surveys.ts | 146 ++ v2/src/generated/staff/operations/teams.ts | 111 ++ v2/src/generated/staff/operations/tenants.ts | 265 +++ v2/src/generated/staff/operations/users.ts | 37 + v2/src/generated/staff/schemas.ts | 1660 +++++++++++++++++ v2/src/migrate/map.ts | 8 + v2/src/migrate/migrate.ts | 148 +- v2/src/migrate/v1-map.ts | 443 ++++- v2/src/mock/index.ts | 34 +- v2/src/staff.ts | 19 + v2/test/compat.test.ts | 2 +- v2/test/loose/consumer.ts | 4 +- v2/test/migrate.test.ts | 47 +- v2/test/mock.test.ts | 16 +- 82 files changed, 8433 insertions(+), 872 deletions(-) create mode 100644 v2/src/generated/staff/operations/asset-categories.ts create mode 100644 v2/src/generated/staff/operations/asset-purchase-orders.ts create mode 100644 v2/src/generated/staff/operations/asset-types.ts create mode 100644 v2/src/generated/staff/operations/assets.ts create mode 100644 v2/src/generated/staff/operations/bookings.ts create mode 100644 v2/src/generated/staff/operations/calendars.ts create mode 100644 v2/src/generated/staff/operations/desks.ts create mode 100644 v2/src/generated/staff/operations/events.ts create mode 100644 v2/src/generated/staff/operations/groups.ts create mode 100644 v2/src/generated/staff/operations/guests.ts create mode 100644 v2/src/generated/staff/operations/health-check.ts create mode 100644 v2/src/generated/staff/operations/index.ts create mode 100644 v2/src/generated/staff/operations/place.ts create mode 100644 v2/src/generated/staff/operations/spaces.ts create mode 100644 v2/src/generated/staff/operations/staff.ts create mode 100644 v2/src/generated/staff/operations/surveys-answers.ts create mode 100644 v2/src/generated/staff/operations/surveys-invitations.ts create mode 100644 v2/src/generated/staff/operations/surveys-questions.ts create mode 100644 v2/src/generated/staff/operations/surveys.ts create mode 100644 v2/src/generated/staff/operations/teams.ts create mode 100644 v2/src/generated/staff/operations/tenants.ts create mode 100644 v2/src/generated/staff/operations/users.ts create mode 100644 v2/src/generated/staff/schemas.ts create mode 100644 v2/src/staff.ts diff --git a/v2/README.md b/v2/README.md index 513ec59da..edda4aff7 100644 --- a/v2/README.md +++ b/v2/README.md @@ -1,8 +1,9 @@ # @placeos/ts-client v2 -A typed client for the PlaceOS REST API. A script generates the types and the request functions -from the [OpenAPI document](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) of -the API. The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) +A typed client for the PlaceOS REST API and the staff API. A script generates the types and the +request functions from the OpenAPI documents of +[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) and +[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api/blob/master/OPENAPI_DOC.yml). The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) where possible. The library has no runtime dependencies. It runs in browsers, in Node 20.3 and later, and in Bun. @@ -71,7 +72,7 @@ with `createClient` and give it in the options. The configured client does not c ```ts const other = createClient({ baseUrl: 'https://other.example.com', auth: { kind: 'none' } }); -await zones.index({}, { client: other }); +await zones.query({}, { client: other }); ``` ### Timeouts and cancel @@ -82,7 +83,7 @@ for one request: ```ts configure({ baseUrl: '', auth: { kind: 'none' }, timeoutMs: 10_000 }); const controller = new AbortController(); -await zones.index({}, { signal: controller.signal, timeoutMs: 60_000 }); +await zones.query({}, { signal: controller.signal, timeoutMs: 60_000 }); ``` ### Pages @@ -92,7 +93,7 @@ An `index` operation returns one page. Use `pageInfo` to get the total and the n ```ts import { pageInfo, zones } from '@placeos/ts-client'; -const result = await zones.index({ limit: 100 }); +const result = await zones.query({ limit: 100 }); if (result.ok) { const { total, nextOffset } = pageInfo(result.value.headers); } @@ -123,7 +124,7 @@ import { endpointMocks, httpError, mockEndpoint, respond } from '@placeos/ts-cli configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); -mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 1 })); +mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 1 })); mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 300 }); mockEndpoint('zones.destroy', () => { throw httpError(403); @@ -148,7 +149,7 @@ A test double of a v2 call gives a `Result`. `mockReply` and `mockPage` of ```ts vi.mock('@placeos/ts-client', { spy: true }); vi.mocked(zones.show).mockResolvedValue(mockReply(zone)); -vi.mocked(zones.index).mockResolvedValue(mockPage({ data: [zone], total: 1 })); +vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); ``` ### Mock mode @@ -181,6 +182,24 @@ const realtime = createRealtime({ - A change to a variable of a mock module, such as `mockSystem('sys-1')['Display'][0]['power'] = true`, notifies its bindings. +## Staff API + +The staff API (bookings, events, guests, desks, surveys and more) is at +`@placeos/ts-client/staff`. It uses the client of `configure`, as the REST API functions do: + +```ts +import { bookings } from '@placeos/ts-client/staff'; + +const now = Math.floor(Date.now() / 1000); +const result = await bookings.query({ period_start: now, period_end: now + 86_400, type: 'desk' }); +``` + +- The staff API has its own schemas, such as `Booking` and `Guest`. A schema that both APIs have, + such as `Zone`, is in both entries with the same shape. +- The typed mocks of the staff API start with `staff.`: `mockEndpoint('staff.bookings.show', ...)`. +- Some routes of the staff API have an occurrence of a recurring booking: `bookings.showInstance` + is `GET /bookings/{id}/instance/{instance}`, the occurrence of `bookings.show`. + ## Log in `createAuthSession` does the OAuth login of PlaceOS and gives the client its credential: @@ -348,6 +367,13 @@ The generator changes some parts of the document. Each change has a comment in `zone_id=a,b`. The items of an array parameter must not contain commas. - **PATCH and PUT.** The server sends PATCH and PUT of `update` to the same method. The client has only `update`, which sends PATCH. +- **Numbered routes.** The document numbers the routes of one action: `show` and `show_2`. A second + path with the same signature is an alias, such as `checkin` for `check_in` in the staff API. The + client has only the first path. A path with more segments gets a name from them, such as + `showInstance` for `bookings/{id}/instance/{instance}`. +- **A query parameter named `body`.** `body` of the input is the request body, so the `body` query + parameter of `staff.events.book` (the description of the meeting) is `body_text` in the input. + The query keeps the name `body`. - **Responses without a schema.** The data is a `Uint8Array` with the raw body. `systems.execute`, `modules.execute` and `modules.stateValue` are exceptions: they return a `JsonValue`. - **WebSocket endpoints** (`systems/control`, `webrtc/signaller` and others) are not in the @@ -355,13 +381,15 @@ The generator changes some parts of the document. Each change has a comment in ## Change the generated code -Do not edit `src/generated`. The generator downloads the API document from the master branch of -[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api) on each run. It does not keep a copy in -this repository. +Do not edit `src/generated`. The generator downloads the API documents from the master branches of +[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api) and +[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api) on each run. It does not keep a copy in +this repository. `APIS` in `scripts/generate.ts` has the list: the repository, the output folder +and the prefix of the operation IDs and names. ```sh -bun run generate # Downloads the document and writes src/generated. -bun run generate:check # Fails if src/generated does not match the current document. +bun run generate # Downloads the documents and writes src/generated and src/generated/staff. +bun run generate:check # Fails if the generated files do not match the current documents. ``` The generated files are in the repository, so a change to the API shows as a diff. Examine the @@ -404,13 +432,13 @@ The tool makes these changes: const list = await queryZones({ limit: 10 }); // v2, after the tool const zone = await zones.show({ id, complete: true }).then(orThrow); - const list = await zones.index({ limit: 10 }).then(orThrowPage); + const list = await zones.query({ limit: 10 }).then(orThrowPage); ``` - A type reference to a v1 class becomes the v2 type. For example, `PlaceZone` becomes `Zone`. - The imports of the v1 enums, such as `PlaceDriverRole`, and of `QueryResponse` move to `@placeos/ts-client/compat`. The enums have the v2 values, so they fit the v2 fields of the - data. A query parameter takes the name: the `role` of `drivers.index` is `'logic'`, not `99`. + data. A query parameter takes the name: the `role` of `drivers.query` is `'logic'`, not `99`. - A new import gets another name when the file has the name. For example, a file with a `zones` variable gets `zones as zonesV2`. @@ -426,6 +454,8 @@ The tool also changes the test doubles, so that the tests of the app still work: namespaces: `showZone: vi.fn(impl)` becomes `zones: { show: vi.fn(fromV1Mock(impl, ['id', '...'])) }`. The factory runs before the imports, so the tool adds `fromV1Mock` with `vi.hoisted`. +- The v1 staff functions, such as `querySurveys`, become the operations of + `@placeos/ts-client/staff`, with their own import. - The imports of the mock endpoints and mock systems move to `@placeos/ts-client/compat`. See [Mock mode](#mock-mode). diff --git a/v2/package.json b/v2/package.json index 691fdabd4..63360d08e 100644 --- a/v2/package.json +++ b/v2/package.json @@ -18,6 +18,10 @@ "types": "./dist/compat/index.d.ts", "default": "./dist/compat/index.js" }, + "./staff": { + "types": "./dist/staff.d.ts", + "default": "./dist/staff.js" + }, "./mock": { "types": "./dist/mock/index.d.ts", "default": "./dist/mock/index.js" diff --git a/v2/scripts/generate.ts b/v2/scripts/generate.ts index 602c63791..1f7d5bc1f 100644 --- a/v2/scripts/generate.ts +++ b/v2/scripts/generate.ts @@ -1,6 +1,7 @@ /** - * Generates `src/generated` from the OpenAPI document of the PlaceOS REST API. It downloads the - * document from the master branch of PlaceOS/rest-api on each run, so the output follows the API. + * Generates the client code from the OpenAPI documents of the PlaceOS APIs: `src/generated` from + * PlaceOS/rest-api, and `src/generated/staff` from PlaceOS/staff-api. It downloads each document + * from the master branch on each run, so the output follows the APIs. * * bun run generate Writes the generated files. * bun scripts/generate.ts --check Fails if a generated file is not up to date. @@ -21,16 +22,10 @@ import { isRecord } from '../src/core/schema.ts'; import { ANIMATIONS } from './value-enums.ts'; const ROOT = join(import.meta.dir, '..'); -const SPEC_URL = - 'https://raw.githubusercontent.com/PlaceOS/rest-api/refs/heads/master/OPENAPI_DOC.yml'; const SPEC_TIMEOUT_MS = 30_000; -const GENERATED_DIR = join(ROOT, 'src', 'generated'); -const OPERATIONS_DIR = join(GENERATED_DIR, 'operations'); const SPEC_BYTES_MAX = 16 * 1024 * 1024; const EMIT_DEPTH_MAX = 32; const LINE_WIDTH_MAX = 100; -const HEADER = - '// Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit.\n'; /** * The spec generator of the server loses the `type: "integer"` hint of a `Time` field that has an @@ -78,6 +73,17 @@ const EPOCH_FIELDS: ReadonlyMap = new Map([ ['PlaceOS.Model.User.AdminMetadataResponse', ['created_at', 'last_login']], ['PlaceOS.Model.User.AdminResponse', ['created_at', 'last_login']], ['PlaceOS.Model.User.PublicMetadataResponse', ['created_at', 'last_login']], + // The staff API. Its models are `ModelWithAutoKey`, which has the epoch `Timestamps`. + ['PlaceOS.Model.Attendee', TIMESTAMPS], + ['PlaceOS.Model.Booking', TIMESTAMPS], + ['PlaceOS.Model.EventMetadata', TIMESTAMPS], + ['PlaceOS.Model.Guest', TIMESTAMPS], + ['PlaceOS.Model.Survey', TIMESTAMPS], + ['PlaceOS.Model.Survey.Answer', TIMESTAMPS], + ['PlaceOS.Model.Survey.Invitation', TIMESTAMPS], + ['PlaceOS.Model.Survey.Question', TIMESTAMPS], + // PlaceOS/calendar: `Time::EpochConverter` on a `Time?`. + ['PlaceCalendar.Event', ['event_end']], ['PlaceOS.Model.User.PublicResponse', ['created_at', 'last_login']], ['PlaceOS.Model.Zone', TIMESTAMPS], ]); @@ -102,6 +108,13 @@ const STRING_TIME_FIELDS: ReadonlyMap = new Map([ ['PlaceOS.Model.SignageTemplate', TIMESTAMPS], ['PlaceOS.Model.SignageTemplate.SystemTemplate', TIMESTAMPS], ['PlaceOS.Model.Upload', ['cache_modified']], + // The staff API. PlaceOS/calendar and PlaceOS/office365 have no converter on these. + ['PlaceCalendar.Event', ['created', 'updated']], + [ + 'Office365.ChatMessage', + ['createdDateTime', 'deletedDateTime', 'lastModifiedDateTime', 'lastEditedDateTime'], + ], + ['Office365.ChatMessageHistoryItem', ['modifiedDateTime']], ]); /** @@ -176,6 +189,16 @@ const TYPE_ALIASES: ReadonlyMap = new Map([ ['SignageTemplateSystemTemplate', 'SignageTemplateMapping'], ]); +/** + * Input keys for parameters with a name that the input uses for something else. `body` of the + * input is the request body, so a query parameter `body` gets another key. The query keeps the + * name of the document. + */ +const PARAMETER_KEYS: ReadonlyMap>> = new Map([ + // The description of the meeting. + ['Events_book', { body: 'body_text' }], +]); + /** Names that the core modules export. A generated name must not hide one. */ const CORE_NAMES: ReadonlySet = new Set([ 'AnyOperation', @@ -301,6 +324,8 @@ interface OperationPlan { readonly paramsRequired: boolean; readonly body: string | null; readonly response: string | null; + /** Input key to query name, from `PARAMETER_KEYS`. */ + readonly wireNames: Readonly>; readonly imports: Imports; } @@ -310,11 +335,60 @@ interface Imports { readonly schemas: Set; } +/** One API and its output. */ +interface ApiSource { + /** The GitHub repository of the server. It has `OPENAPI_DOC.yml` at its root. */ + readonly repository: string; + readonly dir: string; + /** The part of each `operationId` before the controller, such as `PlaceOS::Api::`. */ + readonly idPrefix: string; + /** The part of each operation name before the namespace, such as `staff.`. */ + readonly namePrefix: string; + /** The path from `dir` to `src/core`. */ + readonly core: string; + readonly aliases: ReadonlyMap; +} + +const APIS: readonly ApiSource[] = [ + { + repository: 'PlaceOS/rest-api', + dir: join(ROOT, 'src', 'generated'), + idPrefix: 'PlaceOS::Api::', + namePrefix: '', + core: '../core', + aliases: TYPE_ALIASES, + }, + { + repository: 'PlaceOS/staff-api', + dir: join(ROOT, 'src', 'generated', 'staff'), + idPrefix: '', + namePrefix: 'staff.', + core: '../../core', + aliases: new Map(), + }, +]; + await main(); async function main(): Promise { const check = process.argv.includes('--check'); - const specText = await downloadSpec(); + const stale: string[] = []; + for (const api of APIS) stale.push(...(await generate(api, check))); + if (check && stale.length > 0) { + console.error(`Not up to date. Run \`bun run generate\`:\n ${stale.join('\n ')}`); + process.exit(1); + } + console.log(check ? 'Up to date.' : `Wrote ${stale.length} files.`); +} + +function header(api: ApiSource): string { + return `// Generated by scripts/generate.ts from the ${api.repository} OpenAPI document. Do not edit.\n`; +} + +/** Generates the code of one API. Returns the files that changed, or that would change. */ +async function generate(api: ApiSource, check: boolean): Promise { + const operationsDir = join(api.dir, 'operations'); + const specText = await downloadSpec(api); const spec = asNode(Bun.YAML.parse(specText), 'the document'); assert(asString(field(spec, 'openapi'), 'openapi').startsWith('3.'), 'the document is 3.x'); const components = asNode(field(spec, 'components'), 'components'); @@ -333,7 +407,7 @@ async function main(): Promise { for (const method of METHODS) { const operationValue = field(item, method); if (operationValue === undefined) continue; - const plan = planOperation(schemas, path, method, asNode(operationValue, path)); + const plan = planOperation(api, schemas, path, method, asNode(operationValue, path)); if (plan === null) { skipped.push(`${method.toUpperCase()} ${path}`); } else { @@ -342,8 +416,8 @@ async function main(): Promise { } } - // A controller sends PATCH and PUT of an update to one action. Keep the PATCH only. - const kept = removeDuplicateUpdates(operations); + // The numbered routes of one action, such as PATCH and PUT of an update, become one. + const kept = mergeRoutes(operations); // Emit each named schema that an operation uses, and the schemas that those use. const named = new Map(); @@ -375,7 +449,7 @@ async function main(): Promise { } const files = new Map(); - files.set(join(GENERATED_DIR, 'schemas.ts'), writeSchemasFile(named)); + files.set(join(api.dir, 'schemas.ts'), writeSchemasFile(api, named)); const controllers = new Map(); for (const plan of kept) { const list = controllers.get(plan.controller) ?? []; @@ -386,15 +460,18 @@ async function main(): Promise { for (const controller of [...controllers.keys()].sort()) { const plans = controllers.get(controller) ?? []; const fileName = kebabCase(controllerWords(controller)); - files.set(join(OPERATIONS_DIR, `${fileName}.ts`), writeOperationsFile(controller, plans)); + files.set( + join(operationsDir, `${fileName}.ts`), + writeOperationsFile(api, controller, plans), + ); namespaces.push( `export * as ${camelCase(controllerWords(controller))} from './${fileName}.ts';`, ); } const indexIntro = '/** One namespace for each controller of the API. */'; files.set( - join(OPERATIONS_DIR, 'index.ts'), - `${HEADER}\n${indexIntro}\n${namespaces.join('\n')}\n`, + join(operationsDir, 'index.ts'), + `${header(api)}\n${indexIntro}\n${namespaces.join('\n')}\n`, ); // Format, then write or compare. @@ -414,30 +491,30 @@ async function main(): Promise { } } // Remove generated files of controllers that the document does not have now. - for (const entry of await readdir(OPERATIONS_DIR)) { - const filePath = join(OPERATIONS_DIR, entry); + for (const entry of await readdir(operationsDir).catch(() => [])) { + const filePath = join(operationsDir, entry); if (files.has(filePath)) continue; const text = await readFile(filePath, 'utf8'); - assert(text.startsWith(HEADER), `${filePath} is a generated file`); + assert(text.startsWith(header(api)), `${filePath} is a generated file`); stale.push(filePath); if (!check) await rm(filePath); } console.log( - `${kept.length} operations in ${controllers.size} controllers, ${named.size} schemas.`, + `${api.repository}: ${kept.length} operations in ${controllers.size} controllers, ` + + `${named.size} schemas.`, ); - console.log(`Skipped ${skipped.length} WebSocket endpoints: ${skipped.join(', ')}.`); - if (check && stale.length > 0) { - console.error(`Not up to date. Run \`bun run generate\`:\n ${stale.join('\n ')}`); - process.exit(1); + if (skipped.length > 0) { + console.log(`Skipped ${skipped.length} WebSocket endpoints: ${skipped.join(', ')}.`); } - console.log(check ? 'Up to date.' : `Wrote ${stale.length} files.`); + return stale; } /** Downloads the document. The generator stops if the download fails. */ -async function downloadSpec(): Promise { - const response = await fetch(SPEC_URL, { signal: AbortSignal.timeout(SPEC_TIMEOUT_MS) }); - assert(response.ok, `the download of ${SPEC_URL} succeeds (status ${response.status})`); +async function downloadSpec(api: ApiSource): Promise { + const url = `https://raw.githubusercontent.com/${api.repository}/refs/heads/master/OPENAPI_DOC.yml`; + const response = await fetch(url, { signal: AbortSignal.timeout(SPEC_TIMEOUT_MS) }); + assert(response.ok, `the download of ${url} succeeds (status ${response.status})`); const lengthText = response.headers.get('content-length'); if (lengthText !== null) { assert(Number(lengthText) <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); @@ -449,16 +526,19 @@ async function downloadSpec(): Promise { /** Reads one operation of the document. Returns `null` for a WebSocket endpoint. */ function planOperation( + api: ApiSource, schemas: SpecNode, path: string, method: (typeof METHODS)[number], operation: SpecNode, ): OperationPlan | null { const operationId = asString(field(operation, 'operationId'), `${path} operationId`); - const idMatch = /^PlaceOS::Api::([A-Za-z:]+)_([a-z0-9_]+)$/.exec(operationId); - assert(idMatch !== null, `${operationId} has the form PlaceOS::Api::Controller_action`); + const id = operationId.startsWith(api.idPrefix) ? operationId.slice(api.idPrefix.length) : ''; + const idMatch = /^([A-Za-z:]+)_([a-z0-9_]+)$/.exec(id); + assert(idMatch !== null, `${operationId} has the form ${api.idPrefix}Controller_action`); const controller = idMatch[1] ?? ''; - const action = idMatch[2] ?? ''; + // The list action of a controller is `index` in the server. The client calls it `query`. + const action = (idMatch[2] ?? '').replace(/^index(?=_\d+$|$)/, 'query'); // The success response. The API has one for each operation. const responses = asNode(field(operation, 'responses'), `${operationId} responses`); @@ -485,24 +565,30 @@ function planOperation( const fields: string[] = []; const required: string[] = []; const parameterNames = new Set(); + const wireNames: Record = {}; for (const parameterValue of asArray(field(operation, 'parameters') ?? [], operationId)) { const parameter = asNode(parameterValue, `${operationId} parameter`); const name = asString(field(parameter, 'name'), `${operationId} parameter name`); const location = asString(field(parameter, 'in'), `${operationId} ${name} in`); assert(location === 'path' || location === 'query', `${operationId} ${name} is supported`); assert(!parameterNames.has(name), `${operationId} ${name} is unique`); - assert(name !== 'body', `${operationId} has no parameter named body`); + const key = PARAMETER_KEYS.get(operationId)?.[name] ?? name; + assert(key !== 'body', `${operationId} has no parameter named body, or a key for it`); + if (key !== name) { + assert(location === 'query', `${operationId} renames only a query parameter`); + wireNames[key] = name; + } parameterNames.add(name); if (location === 'path') { assert(pathKeys.includes(name), `${operationId} ${name} is in the path`); required.push(name); } else if (field(parameter, 'required') === true) { - required.push(name); + required.push(key); } const schema = asNode(field(parameter, 'schema'), `${operationId} ${name} schema`); const expression = emitSchema(schemas, schema, imports, 0); const description = optionalString(field(parameter, 'description'), name) ?? ''; - fields.push(`${docComment(description, 4)}${propertyKey(name)}: ${expression},`); + fields.push(`${docComment(description, 4)}${propertyKey(key)}: ${expression},`); } for (const key of pathKeys) { assert(parameterNames.has(key), `${operationId} has a path parameter ${key}`); @@ -536,41 +622,79 @@ function planOperation( paramsRequired: required.length > 0 || body !== null, body, response, + wireNames, imports, }; } /** - * The server routes PATCH and PUT of `update` to one method. The document has both, as `update` - * and `update_2`. This keeps the PATCH, with the name of the action without `_2`. + * The document numbers the routes of one action: `update` and `update_2`. This keeps one function + * for each route that has its own signature: + * + * - PATCH and PUT of one path go to one method of the server. The PATCH stays. + * - A second path with the same signature is an alias, such as `checkin` for `check_in`. The first + * path stays. + * - Another path gets a name from its extra segments: `bookings/{id}/instance/{instance}` of + * `show` is `showInstance`. */ -function removeDuplicateUpdates(operations: readonly OperationPlan[]): OperationPlan[] { - const byKey = new Map(); - for (const plan of operations) byKey.set(`${plan.controller}#${plan.action}`, plan); - const kept: OperationPlan[] = []; +function mergeRoutes(operations: readonly OperationPlan[]): OperationPlan[] { + const groups = new Map(); for (const plan of operations) { - const pairAction = plan.action.endsWith('_2') - ? plan.action.slice(0, -2) - : `${plan.action}_2`; - const pair = byKey.get(`${plan.controller}#${pairAction}`); - if (pair === undefined) { - kept.push(plan); - continue; + const key = `${plan.controller}#${plan.action.replace(/_\d+$/, '')}`; + groups.set(key, [...(groups.get(key) ?? []), plan]); + } + const kept: OperationPlan[] = []; + for (const group of groups.values()) { + const action = (group[0]?.action ?? '').replace(/_\d+$/, ''); + const byPath = new Map(); + for (const plan of group) byPath.set(plan.path, [...(byPath.get(plan.path) ?? []), plan]); + const routes: OperationPlan[] = []; + for (const plans of byPath.values()) { + const [first, second] = plans; + assert(first !== undefined, 'a path has a plan'); + if (second === undefined) { + routes.push(first); + continue; + } + assert(plans.length === 2, `${first.operationId} has at most two methods on its path`); + assert( + sameSignature(first, second), + `${first.operationId} has the same signature as ${second.operationId}`, + ); + const methods = [first.method, second.method].sort().join(); + assert(methods === 'patch,put', `${first.operationId} is a PATCH and PUT pair`); + routes.push(first.method === 'patch' ? first : second); + } + const distinct: OperationPlan[] = []; + for (const route of routes) { + const alias = distinct.some( + (other) => other.method === route.method && sameSignature(other, route), + ); + if (!alias) distinct.push(route); + } + distinct.sort((a, b) => a.path.length - b.path.length); + const [base, ...others] = distinct; + assert(base !== undefined, 'an action has a route'); + kept.push({ ...base, action }); + const baseSegments = new Set(base.path.split('/')); + for (const other of others) { + const extra = other.path + .split('/') + .filter((segment) => !baseSegments.has(segment)) + .map((segment) => segment.replace(/[{}]/g, '')); + const words = [...new Set(extra)]; + assert(words.length > 0, `${other.operationId} has a path with more segments`); + kept.push({ ...other, action: `${action}_${words.join('_')}` }); } - const same = - pair.path === plan.path && - pair.params === plan.params && - pair.body === plan.body && - pair.response === plan.response; - assert(same, `${plan.operationId} has the same signature as ${pair.operationId}`); - const methods = [plan.method, pair.method].sort().join(); - assert(methods === 'patch,put', `${plan.operationId} is a PATCH and PUT pair`); - if (plan.method === 'put') continue; - kept.push({ ...plan, action: plan.action.replace(/_2$/, '') }); } return kept; } +/** The same parameters, body and response. The path can differ. */ +function sameSignature(a: OperationPlan, b: OperationPlan): boolean { + return a.params === b.params && a.body === b.body && a.response === b.response; +} + /** The emit of a named schema. It applies the time field patches to its properties. */ function emitNamedSchema( schemas: SpecNode, @@ -893,7 +1017,10 @@ function jsonContentSchema(content: unknown, operationId: string): unknown { return field(asNode(field(contentNode, 'application/json'), operationId), 'schema'); } -function writeSchemasFile(named: ReadonlyMap): string { +function writeSchemasFile( + api: ApiSource, + named: ReadonlyMap, +): string { // A `const` must come after the schemas that it uses. The document has no cycles. const order: string[] = []; const state = new Map(); @@ -916,16 +1043,17 @@ function writeSchemasFile(named: ReadonlyMap named.get(name)?.code ?? '').join('\n'); - return `${HEADER}${importLine([...combinators], '../core/schema.ts')}\n${body}\n${aliasExports(named)}`; + const aliases = api.aliases.size > 0 ? `\n${aliasExports(api, named)}` : ''; + return `${header(api)}${importLine([...combinators], `${api.core}/schema.ts`)}\n${body}${aliases}`; } /** The exports of `TYPE_ALIASES`, for the value, the type and the input type. */ -function aliasExports(named: ReadonlyMap): string { +function aliasExports(api: ApiSource, named: ReadonlyMap): string { const taken = new Set(); for (const name of named.keys()) for (const suffix of ['', 'Input', 'Schema']) taken.add(name + suffix); const lines = ['/** Short names. Each one is the same value and type as the long name. */']; - for (const [name, alias] of TYPE_ALIASES) { + for (const [name, alias] of api.aliases) { assert(named.has(name), `the alias ${alias} has the schema ${name}`); for (const generated of [alias, `${alias}Input`]) { assert(!taken.has(generated), `the alias ${generated} is not a schema name`); @@ -937,7 +1065,11 @@ function aliasExports(named: ReadonlyMap): string { return `${lines.join('\n')}\n`; } -function writeOperationsFile(controller: string, plans: readonly OperationPlan[]): string { +function writeOperationsFile( + api: ApiSource, + controller: string, + plans: readonly OperationPlan[], +): string { const combinators = new Set(); const schemaImports = new Set(); const functionNames = new Set(); @@ -968,7 +1100,10 @@ function writeOperationsFile(controller: string, plans: readonly OperationPlan[] `params: ${plan.params},\n` + `body: ${plan.body ?? 'null'},\n` + `response: ${plan.response ?? 'null'},\n` + - `name: '${camelCase(controllerWords(controller))}.${functionName}',\n` + + `name: '${api.namePrefix}${camelCase(controllerWords(controller))}.${functionName}',\n` + + (Object.keys(plan.wireNames).length > 0 + ? `wireNames: ${JSON.stringify(plan.wireNames)},\n` + : '') + `});\n`, ); } @@ -981,10 +1116,10 @@ function writeOperationsFile(controller: string, plans: readonly OperationPlan[] ? `import { ${[...schemaImports].sort().join(', ')} } from '../schemas.ts';\n` : ''; return ( - `${HEADER}${intro}` + + `${header(api)}${intro}` + `import { call, operation, type CallOptions, type CallResult, ` + - `type OperationInput } from '../../core/client.ts';\n` + - importLine([...combinators], '../../core/schema.ts') + + `type OperationInput } from '../${api.core}/client.ts';\n` + + importLine([...combinators], `../${api.core}/schema.ts`) + `${schemaLine}\n${blocks.join('\n')}` ); } diff --git a/v2/scripts/v1-map.ts b/v2/scripts/v1-map.ts index e47038453..9c4fa92dc 100644 --- a/v2/scripts/v1-map.ts +++ b/v2/scripts/v1-map.ts @@ -14,13 +14,20 @@ import { join, relative } from 'node:path'; import { format, resolveConfig } from 'prettier'; import * as ts from 'typescript-5'; import { assert } from '../src/core/assert.ts'; -import type { CallMapping, ObjectEntry, Template, V1Parameter } from '../src/migrate/map.ts'; +import type { + CallMapping, + ObjectEntry, + Template, + TypeMapping, + V1Parameter, +} from '../src/migrate/map.ts'; import { ANIMATIONS } from './value-enums.ts'; const ROOT = join(import.meta.dir, '..'); const V1_SOURCE = join(ROOT, '..', 'src'); const V1_INDEX = join(V1_SOURCE, 'index.ts'); const OPERATIONS_DIR = join(ROOT, 'src', 'generated', 'operations'); +const STAFF_OPERATIONS_DIR = join(ROOT, 'src', 'generated', 'staff', 'operations'); const OUTPUT = join(ROOT, 'src', 'migrate', 'v1-map.ts'); const ENUMS_OUTPUT = join(ROOT, 'src', 'compat', 'enums.ts'); const COMPAT_INDEX = join(ROOT, 'src', 'compat', 'index.ts'); @@ -51,6 +58,8 @@ interface V1Function { } interface V2Operation { + /** `staff` for the staff API. */ + readonly module: 'staff' | null; readonly namespace: string; readonly name: string; readonly method: string; @@ -79,7 +88,10 @@ const HINTS: Readonly> = { async function main(): Promise { const check = process.argv.includes('--check'); const functions = readV1Functions(); - const operations = await readV2Operations(); + const operations = [ + ...(await readV2Operations(OPERATIONS_DIR, null)), + ...(await readV2Operations(STAFF_OPERATIONS_DIR, 'staff')), + ]; const record = await loadRecorder(); const calls: Record = {}; @@ -98,17 +110,18 @@ async function main(): Promise { calls[fn.name] = mapped.call; if (fn.model !== null && mapped.model !== null) { const votes = models.get(fn.model) ?? new Map(); - votes.set(mapped.model, (votes.get(mapped.model) ?? 0) + 1); + const key = `${mapped.call.module ?? ''}:${mapped.model}`; + votes.set(key, (votes.get(key) ?? 0) + 1); models.set(fn.model, votes); } } // A v1 class becomes the v2 schema that most of its functions give. A tie has no type. - const types: Record = {}; + const types: Record = {}; for (const [model, votes] of models) { const [first, second] = [...votes].sort(([, a], [, b]) => b - a); - if (first !== undefined && (second === undefined || first[1] > second[1])) { - types[model] = first[0]; - } + if (first === undefined || (second !== undefined && first[1] <= second[1])) continue; + const [module = '', name = ''] = first[0].split(':'); + types[model] = module === 'staff' ? { name, module } : { name }; } // The short name of a schema is the better v2 name, such as `User`. const schemas = await readFile(join(ROOT, 'src', 'generated', 'schemas.ts'), 'utf8'); @@ -116,7 +129,9 @@ async function main(): Promise { for (const [, name = '', alias = ''] of schemas.matchAll(/export \{\s*(\w+) as (\w+),/g)) { aliases.set(name, alias); } - for (const [model, name] of Object.entries(types)) types[model] = aliases.get(name) ?? name; + for (const [model, type] of Object.entries(types)) { + if (type.module === undefined) types[model] = { name: aliases.get(type.name) ?? type.name }; + } const enums = readV1Enums(); // A v1 name that the compat module also exports, such as `registerMockEndpoint`, moves there. const compat = readCompatExports(new Set([...enums.keys(), ...v1Exports().exports.keys()])); @@ -128,11 +143,11 @@ async function main(): Promise { const code = '// Generated by scripts/v1-map.ts from the v1 source and the v2 operations. Do not edit.\n' + - "import type { CallMap } from './map.ts';\n\n" + + "import type { CallMap, TypeMapping } from './map.ts';\n\n" + '/** The v2 call for each v1 REST function. */\n' + `export const V1_CALLS: CallMap = ${JSON.stringify(sortKeys(calls))};\n\n` + '/** The v2 type for each v1 class, such as `Zone` for `PlaceZone`. */\n' + - `export const V1_TYPES: Readonly> = ${JSON.stringify(sortKeys(types))};\n\n` + + `export const V1_TYPES: Readonly> = ${JSON.stringify(sortKeys(types))};\n\n` + '/** The v1 names that `@placeos/ts-client/compat` has. The tool moves their imports. */\n' + `export const V1_COMPAT: Readonly> = ${JSON.stringify(sortKeys(compat))};\n\n` + '/** The v1 exports that the tool does not change, with a hint. */\n' + @@ -325,13 +340,13 @@ function parameterKind(checker: ts.TypeChecker, type: ts.Type): ParameterKind { } /** Reads the method, the path and the parameter names of each generated operation. */ -async function readV2Operations(): Promise { - const index = await readFile(join(OPERATIONS_DIR, 'index.ts'), 'utf8'); +async function readV2Operations(dir: string, module: 'staff' | null): Promise { + const index = await readFile(join(dir, 'index.ts'), 'utf8'); const operations: V2Operation[] = []; for (const [, namespace = '', file = ''] of index.matchAll( /export \* as (\w+) from '\.\/([\w-]+\.ts)'/g, )) { - const text = await readFile(join(OPERATIONS_DIR, file), 'utf8'); + const text = await readFile(join(dir, file), 'utf8'); const names = new Map(); for (const [, name = '', constant = ''] of text.matchAll( /export function (\w+)\([\s\S]*?return call\((\w+),/g, @@ -358,6 +373,7 @@ async function readV2Operations(): Promise { ); const model = /^(?:array\()?([A-Z]\w*)\)?$/.exec(response)?.[1] ?? null; operations.push({ + module, namespace, name, method, @@ -606,6 +622,7 @@ async function mapFunction( notes.push(`v2 sends ${operation.method}, v1 sent ${request.method}`); } const call: CallMapping = { + ...(operation.module === null ? {} : { module: operation.module }), namespace: operation.namespace, operation: operation.name, parameters, diff --git a/v2/src/compat/result.ts b/v2/src/compat/result.ts index a6d6bf03c..fbc4d2e0c 100644 --- a/v2/src/compat/result.ts +++ b/v2/src/compat/result.ts @@ -47,7 +47,7 @@ export interface Page { /** The v1 type of a query function, such as `QueryResponse`. */ export type QueryResponse = Promise>; -/** Gives the data and the totals of an index call, or throws `CallFailed`. */ +/** Gives the data and the totals of a `query` call, or throws `CallFailed`. */ export function orThrowPage(result: Result, CallError>): Page { if (!result.ok) throw new CallFailed(result.error); const page = pageInfo(result.value.headers); @@ -66,11 +66,11 @@ export function mockReply(data: T, status = 200): Result, CallError> } /** - * The v2 result for a v1 page, for a test double of an index call. `total` goes in the + * The v2 result for a v1 page, for a test double of a `query` call. `total` goes in the * `X-Total-Count` header, so `orThrowPage` gives it back. * * ```ts - * vi.mocked(zones.index).mockResolvedValue(mockPage({ data: [zone], total: 1 })); + * vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); * ``` */ export function mockPage(page: { diff --git a/v2/src/core/client.ts b/v2/src/core/client.ts index f331e29d6..1d6a81702 100644 --- a/v2/src/core/client.ts +++ b/v2/src/core/client.ts @@ -161,6 +161,11 @@ export interface Operation< readonly response: R; /** The namespace and the function, for example `zones.show`. */ readonly name: string; + /** + * The query name of a parameter that has another key in the input. A query parameter named + * `body` is an example, because `body` of the input is the request body. + */ + readonly wireNames?: Readonly>; } export type AnyOperation = Operation; @@ -250,7 +255,8 @@ export function operation< R extends AnySchema | null, >(definition: Operation): Operation { assert(definition.path.startsWith('/'), 'the path starts with a slash'); - assert(/^\w+\.\w+$/.test(definition.name), 'the name is .'); + // `staff.` is the prefix of the staff API. + assert(/^(staff\.)?\w+\.\w+$/.test(definition.name), 'the name is .'); assert(definition.params.node.kind === 'object', 'the params schema is an object'); // `[^{}]` cannot match a brace, so the match is linear also for a path with many braces. const templateKeys = [...definition.path.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]); @@ -458,11 +464,12 @@ function buildUrl( if (operation.pathKeys.includes(field.key)) continue; const value = params[field.key]; if (value === undefined || value === null) continue; + const name = operation.wireNames?.[field.key] ?? field.key; if (Array.isArray(value)) { const items: readonly unknown[] = value; - query.append(field.key, items.map(queryScalar).join(',')); + query.append(name, items.map(queryScalar).join(',')); } else { - query.append(field.key, queryScalar(value)); + query.append(name, queryScalar(value)); } } const queryText = query.toString(); diff --git a/v2/src/core/pagination.ts b/v2/src/core/pagination.ts index b070a0628..6a04ff15a 100644 --- a/v2/src/core/pagination.ts +++ b/v2/src/core/pagination.ts @@ -1,7 +1,7 @@ /** A longer `Link` header is not from this API. The parser ignores it. */ export const LINK_HEADER_LENGTH_MAX = 8_192; -/** The pagination data of an index response. */ +/** The pagination data of a `query` response. */ export interface PageInfo { /** The `X-Total-Count` header: the number of results for all pages. */ readonly total: number | null; @@ -10,14 +10,14 @@ export interface PageInfo { } /** - * Reads the pagination headers of an index response. + * Reads the pagination headers of a `query` response. * * ```ts - * const first = await zones.index({ limit: 100 }); + * const first = await zones.query({ limit: 100 }); * if (first.ok) { * const page = pageInfo(first.value.headers); * if (page.nextOffset !== null) { - * const second = await zones.index({ limit: 100, offset: page.nextOffset }); + * const second = await zones.query({ limit: 100, offset: page.nextOffset }); * } * } * ``` diff --git a/v2/src/generated/operations/alert-dashboards.ts b/v2/src/generated/operations/alert-dashboards.ts index 4e9881081..8d4578266 100644 --- a/v2/src/generated/operations/alert-dashboards.ts +++ b/v2/src/generated/operations/alert-dashboards.ts @@ -95,14 +95,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/alert_dashboards` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alert_dashboards', pathKeys: [], @@ -125,7 +125,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AlertDashboard), - name: 'alertDashboards.index', + name: 'alertDashboards.query', }); /** diff --git a/v2/src/generated/operations/alerts.ts b/v2/src/generated/operations/alerts.ts index 4b2bc8f94..654676e7c 100644 --- a/v2/src/generated/operations/alerts.ts +++ b/v2/src/generated/operations/alerts.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/alerts` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alerts', pathKeys: [], @@ -104,7 +104,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Alert), - name: 'alerts.index', + name: 'alerts.query', }); /** diff --git a/v2/src/generated/operations/api-keys.ts b/v2/src/generated/operations/api-keys.ts index b05f4869a..fe2cde44f 100644 --- a/v2/src/generated/operations/api-keys.ts +++ b/v2/src/generated/operations/api-keys.ts @@ -63,19 +63,41 @@ const DESTROY = /* @__PURE__ */ operation({ name: 'apiKeys.destroy', }); +/** + * Obtain the a JSON JWT representation of the API key permissions. + * + * `GET /api/engine/v2/api_keys/inspect` + */ +export function inspectKey( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(INSPECT_KEY, input, options); +} + +const INSPECT_KEY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/api_keys/inspect', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: UserJwt, + name: 'apiKeys.inspectKey', +}); + /** * Returns a list of the API keys associated with the provided domain, otherwise all domains. * * `GET /api/engine/v2/api_keys` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/api_keys', pathKeys: [], @@ -98,29 +120,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ApiKeysResponse), - name: 'apiKeys.index', -}); - -/** - * Obtain the a JSON JWT representation of the API key permissions. - * - * `GET /api/engine/v2/api_keys/inspect` - */ -export function inspectKey( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(INSPECT_KEY, input, options); -} - -const INSPECT_KEY = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/api_keys/inspect', - pathKeys: [], - params: /* @__PURE__ */ parameters({}), - body: null, - response: UserJwt, - name: 'apiKeys.inspectKey', + name: 'apiKeys.query', }); /** diff --git a/v2/src/generated/operations/asset-categories.ts b/v2/src/generated/operations/asset-categories.ts index 322e295a6..3bdfbd000 100644 --- a/v2/src/generated/operations/asset-categories.ts +++ b/v2/src/generated/operations/asset-categories.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/asset_categories` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_categories', pathKeys: [], @@ -101,7 +101,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetCategory), - name: 'assetCategories.index', + name: 'assetCategories.query', }); /** diff --git a/v2/src/generated/operations/asset-purchase-orders.ts b/v2/src/generated/operations/asset-purchase-orders.ts index 8b20975ca..df5e2cfc4 100644 --- a/v2/src/generated/operations/asset-purchase-orders.ts +++ b/v2/src/generated/operations/asset-purchase-orders.ts @@ -69,14 +69,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/asset_purchase_orders` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_purchase_orders', pathKeys: [], @@ -97,7 +97,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetPurchaseOrder), - name: 'assetPurchaseOrders.index', + name: 'assetPurchaseOrders.query', }); /** diff --git a/v2/src/generated/operations/asset-types.ts b/v2/src/generated/operations/asset-types.ts index 7b2c5cc35..dcd633df5 100644 --- a/v2/src/generated/operations/asset-types.ts +++ b/v2/src/generated/operations/asset-types.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/asset_types` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_types', pathKeys: [], @@ -108,7 +108,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetType), - name: 'assetTypes.index', + name: 'assetTypes.query', }); /** diff --git a/v2/src/generated/operations/assets.ts b/v2/src/generated/operations/assets.ts index 808b6421c..202696bfc 100644 --- a/v2/src/generated/operations/assets.ts +++ b/v2/src/generated/operations/assets.ts @@ -134,14 +134,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/assets` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/assets', pathKeys: [], @@ -182,7 +182,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Asset), - name: 'assets.index', + name: 'assets.query', }); /** diff --git a/v2/src/generated/operations/chat-gpt.ts b/v2/src/generated/operations/chat-gpt.ts index 01f16b9bc..71c46c0d5 100644 --- a/v2/src/generated/operations/chat-gpt.ts +++ b/v2/src/generated/operations/chat-gpt.ts @@ -47,14 +47,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/chatgpt` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/chatgpt', pathKeys: [], @@ -75,7 +75,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Chat), - name: 'chatGpt.index', + name: 'chatGpt.query', }); /** diff --git a/v2/src/generated/operations/domains.ts b/v2/src/generated/operations/domains.ts index 95bb1a491..e9af82b53 100644 --- a/v2/src/generated/operations/domains.ts +++ b/v2/src/generated/operations/domains.ts @@ -63,19 +63,47 @@ const DESTROY = /* @__PURE__ */ operation({ name: 'domains.destroy', }); +/** + * Find the domain name by looking into domain registerd email domains. + * + * `GET /api/engine/v2/domains/lookup/{email}` + */ +export function lookup( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(LOOKUP, input, options); +} + +const LOOKUP = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/domains/lookup/{email}', + pathKeys: ['email'], + params: /* @__PURE__ */ parameters( + { + /** User email to lookup domain for */ + email: /* @__PURE__ */ string(), + }, + ['email'], + ), + body: null, + response: /* @__PURE__ */ string(), + name: 'domains.lookup', +}); + /** * List the domains. * * `GET /api/engine/v2/domains` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/domains', pathKeys: [], @@ -96,35 +124,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Authority), - name: 'domains.index', -}); - -/** - * Find the domain name by looking into domain registerd email domains. - * - * `GET /api/engine/v2/domains/lookup/{email}` - */ -export function lookup( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(LOOKUP, input, options); -} - -const LOOKUP = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/domains/lookup/{email}', - pathKeys: ['email'], - params: /* @__PURE__ */ parameters( - { - /** User email to lookup domain for */ - email: /* @__PURE__ */ string(), - }, - ['email'], - ), - body: null, - response: /* @__PURE__ */ string(), - name: 'domains.lookup', + name: 'domains.query', }); /** diff --git a/v2/src/generated/operations/drivers.ts b/v2/src/generated/operations/drivers.ts index f862dd167..4bbf010b6 100644 --- a/v2/src/generated/operations/drivers.ts +++ b/v2/src/generated/operations/drivers.ts @@ -95,14 +95,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/drivers` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/drivers', pathKeys: [], @@ -127,7 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Driver), - name: 'drivers.index', + name: 'drivers.query', }); /** diff --git a/v2/src/generated/operations/edges.ts b/v2/src/generated/operations/edges.ts index cd9a8ae9b..33fd3346d 100644 --- a/v2/src/generated/operations/edges.ts +++ b/v2/src/generated/operations/edges.ts @@ -335,6 +335,28 @@ const EDGES_STATISTICS = /* @__PURE__ */ operation({ name: 'edges.edgesStatistics', }); +/** + * Real-time error summary. + * + * `GET /api/engine/v2/edges/monitoring/summary` + */ +export function monitoringSummary( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(MONITORING_SUMMARY, input, options); +} + +const MONITORING_SUMMARY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/edges/monitoring/summary', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), + name: 'edges.monitoringSummary', +}); + /** * List the edges in the system. * @@ -343,14 +365,14 @@ const EDGES_STATISTICS = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/edges` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges', pathKeys: [], @@ -371,29 +393,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Edge), - name: 'edges.index', -}); - -/** - * Real-time error summary. - * - * `GET /api/engine/v2/edges/monitoring/summary` - */ -export function monitoringSummary( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(MONITORING_SUMMARY, input, options); -} - -const MONITORING_SUMMARY = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/edges/monitoring/summary', - pathKeys: [], - params: /* @__PURE__ */ parameters({}), - body: null, - response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), - name: 'edges.monitoringSummary', + name: 'edges.query', }); /** diff --git a/v2/src/generated/operations/groups-history.ts b/v2/src/generated/operations/groups-history.ts index ca4d3bdbe..4726fbf17 100644 --- a/v2/src/generated/operations/groups-history.ts +++ b/v2/src/generated/operations/groups-history.ts @@ -22,14 +22,14 @@ import { History } from '../schemas.ts'; * * `GET /api/engine/v2/group_history` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_history', pathKeys: [], @@ -52,7 +52,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(History), - name: 'groupsHistory.index', + name: 'groupsHistory.query', }); /** `GET /api/engine/v2/group_history/{id}` */ diff --git a/v2/src/generated/operations/groups-invitations.ts b/v2/src/generated/operations/groups-invitations.ts index 55cd03213..ad3d93724 100644 --- a/v2/src/generated/operations/groups-invitations.ts +++ b/v2/src/generated/operations/groups-invitations.ts @@ -105,14 +105,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/group_invitations` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_invitations', pathKeys: [], @@ -132,7 +132,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupInvitation), - name: 'groupsInvitations.index', + name: 'groupsInvitations.query', }); /** `GET /api/engine/v2/group_invitations/{id}` */ diff --git a/v2/src/generated/operations/groups-users.ts b/v2/src/generated/operations/groups-users.ts index abe16a531..48564c0d5 100644 --- a/v2/src/generated/operations/groups-users.ts +++ b/v2/src/generated/operations/groups-users.ts @@ -64,14 +64,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/group_users` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_users', pathKeys: [], @@ -92,7 +92,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupUser), - name: 'groupsUsers.index', + name: 'groupsUsers.query', }); /** `GET /api/engine/v2/group_users/{user_id}/{group_id}` */ diff --git a/v2/src/generated/operations/groups-zones.ts b/v2/src/generated/operations/groups-zones.ts index a2fd38792..9efe7e7b6 100644 --- a/v2/src/generated/operations/groups-zones.ts +++ b/v2/src/generated/operations/groups-zones.ts @@ -61,14 +61,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/group_zones` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_zones', pathKeys: [], @@ -89,7 +89,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupZone), - name: 'groupsZones.index', + name: 'groupsZones.query', }); /** `GET /api/engine/v2/group_zones/{group_id}/{zone_id}` */ diff --git a/v2/src/generated/operations/groups.ts b/v2/src/generated/operations/groups.ts index 49ee7bebd..78cf182b2 100644 --- a/v2/src/generated/operations/groups.ts +++ b/v2/src/generated/operations/groups.ts @@ -138,14 +138,14 @@ const FEATURES = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/groups` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/groups', pathKeys: [], @@ -165,7 +165,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Group), - name: 'groups.index', + name: 'groups.query', }); /** diff --git a/v2/src/generated/operations/history.ts b/v2/src/generated/operations/history.ts index 0e7dff754..b3051ceb1 100644 --- a/v2/src/generated/operations/history.ts +++ b/v2/src/generated/operations/history.ts @@ -19,14 +19,14 @@ import { History, PgOrmBase } from '../schemas.ts'; * * `GET /api/engine/v2/history` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/history', pathKeys: [], @@ -65,7 +65,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(History), - name: 'history.index', + name: 'history.query', }); /** `GET /api/engine/v2/history/{id}` */ diff --git a/v2/src/generated/operations/ldap-authentications.ts b/v2/src/generated/operations/ldap-authentications.ts index aaad5e908..519efd49a 100644 --- a/v2/src/generated/operations/ldap-authentications.ts +++ b/v2/src/generated/operations/ldap-authentications.ts @@ -69,14 +69,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/ldap_auths` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/ldap_auths', pathKeys: [], @@ -99,7 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(LdapAuthentication), - name: 'ldapAuthentications.index', + name: 'ldapAuthentications.query', }); /** diff --git a/v2/src/generated/operations/modules.ts b/v2/src/generated/operations/modules.ts index cd80a9cc5..58f2e6485 100644 --- a/v2/src/generated/operations/modules.ts +++ b/v2/src/generated/operations/modules.ts @@ -107,54 +107,6 @@ const EXECUTE = /* @__PURE__ */ operation({ name: 'modules.execute', }); -/** - * Return a list of modules configured on the cluster. - * - * `GET /api/engine/v2/modules` - */ -export function index( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(INDEX, input, options); -} - -const INDEX = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/modules', - pathKeys: [], - params: /* @__PURE__ */ parameters({ - /** only return modules updated before this time (unix epoch) */ - as_of: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** - * only return modules running in this system (query params are ignored if this is provided) - */ - control_system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** only return instances of this driver */ - driver_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** do not return logic modules (return only modules that can exist in multiple systems) */ - no_logic: /* @__PURE__ */ boolean(), - /** return only running modules */ - running: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), - /** - * filters results by the given text: a record matches when any word matches its searchable - * fields as a whole word, and the last word also matches as a prefix (search as you type) - */ - q: /* @__PURE__ */ string(), - /** the maximum number of results to return */ - limit: /* @__PURE__ */ integer('UInt32'), - /** the starting offset of the result set, used to implement pagination */ - offset: /* @__PURE__ */ integer('UInt32'), - /** deprecated, ignored — pagination follows the `Link` header's offset */ - ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** deprecated, ignored — search covers the resource's indexed fields */ - fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), - }), - body: null, - response: /* @__PURE__ */ array(Module), - name: 'modules.index', -}); - /** * Loads the module if not already loaded. * @@ -251,6 +203,54 @@ const PING = /* @__PURE__ */ operation({ name: 'modules.ping', }); +/** + * Return a list of modules configured on the cluster. + * + * `GET /api/engine/v2/modules` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/modules', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return modules updated before this time (unix epoch) */ + as_of: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * only return modules running in this system (query params are ignored if this is provided) + */ + control_system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return instances of this driver */ + driver_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** do not return logic modules (return only modules that can exist in multiple systems) */ + no_logic: /* @__PURE__ */ boolean(), + /** return only running modules */ + running: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(Module), + name: 'modules.query', +}); + /** * Receive the collated settings for a module. * diff --git a/v2/src/generated/operations/oauth-applications.ts b/v2/src/generated/operations/oauth-applications.ts index 1327efffe..9990d59dd 100644 --- a/v2/src/generated/operations/oauth-applications.ts +++ b/v2/src/generated/operations/oauth-applications.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/oauth_apps` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_apps', pathKeys: [], @@ -102,7 +102,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), - name: 'oauthApplications.index', + name: 'oauthApplications.query', }); /** diff --git a/v2/src/generated/operations/oauth-authentications.ts b/v2/src/generated/operations/oauth-authentications.ts index bf089d4a9..a72d2d171 100644 --- a/v2/src/generated/operations/oauth-authentications.ts +++ b/v2/src/generated/operations/oauth-authentications.ts @@ -69,14 +69,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/oauth_auths` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_auths', pathKeys: [], @@ -99,7 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(OauthAuthentication), - name: 'oauthAuthentications.index', + name: 'oauthAuthentications.query', }); /** diff --git a/v2/src/generated/operations/pending-mails.ts b/v2/src/generated/operations/pending-mails.ts index b1b61ac5b..6b67c993b 100644 --- a/v2/src/generated/operations/pending-mails.ts +++ b/v2/src/generated/operations/pending-mails.ts @@ -71,14 +71,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/emails` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/emails', pathKeys: [], @@ -127,7 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PendingMail), - name: 'pendingMails.index', + name: 'pendingMails.query', }); /** diff --git a/v2/src/generated/operations/playlist-media.ts b/v2/src/generated/operations/playlist-media.ts index bca39b548..b83ebeaf2 100644 --- a/v2/src/generated/operations/playlist-media.ts +++ b/v2/src/generated/operations/playlist-media.ts @@ -100,14 +100,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/signage/media` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media', pathKeys: [], @@ -127,7 +127,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PlaylistItem), - name: 'playlistMedia.index', + name: 'playlistMedia.query', }); /** diff --git a/v2/src/generated/operations/playlist.ts b/v2/src/generated/operations/playlist.ts index 2cf69b712..0f1794363 100644 --- a/v2/src/generated/operations/playlist.ts +++ b/v2/src/generated/operations/playlist.ts @@ -209,45 +209,6 @@ const HISTORY = /* @__PURE__ */ operation({ name: 'playlist.history', }); -/** - * List media playlists in the current authority. - * - * list media playlists in the current authority. - * - * Non-admin callers see only playlists linked to groups they're a member of (direct or transitive). - * Pass `group_id=...` to scope to a specific group (caller must have Read on that group). Pass - * `q=...` for a case-insensitive substring search over `name` and `description`. - * - * `GET /api/engine/v2/signage/playlists` - */ -export function index( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(INDEX, input, options); -} - -const INDEX = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/signage/playlists', - pathKeys: [], - params: /* @__PURE__ */ parameters({ - /** filter to playlists linked to this group (caller must have Read on the group) */ - group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** case-insensitive substring search on name and description (SQL ILIKE) */ - q: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - limit: /* @__PURE__ */ integer('Int32'), - offset: /* @__PURE__ */ integer('Int32'), - /** deprecated, ignored — pagination follows the `Link` header's offset */ - ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** deprecated, ignored — search covers the resource's indexed fields */ - fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), - }), - body: null, - response: /* @__PURE__ */ array(Playlist), - name: 'playlist.index', -}); - /** * Get the current list of media for the playlist. * @@ -303,6 +264,45 @@ const MEDIA_REVISIONS = /* @__PURE__ */ operation({ name: 'playlist.mediaRevisions', }); +/** + * List media playlists in the current authority. + * + * list media playlists in the current authority. + * + * Non-admin callers see only playlists linked to groups they're a member of (direct or transitive). + * Pass `group_id=...` to scope to a specific group (caller must have Read on that group). Pass + * `q=...` for a case-insensitive substring search over `name` and `description`. + * + * `GET /api/engine/v2/signage/playlists` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/signage/playlists', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** filter to playlists linked to this group (caller must have Read on the group) */ + group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** case-insensitive substring search on name and description (SQL ILIKE) */ + q: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + limit: /* @__PURE__ */ integer('Int32'), + offset: /* @__PURE__ */ integer('Int32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(Playlist), + name: 'playlist.query', +}); + /** * Request approval for the current playlist's media. Notifies the group's. * diff --git a/v2/src/generated/operations/public-events.ts b/v2/src/generated/operations/public-events.ts index ccae2a4ad..4b91077c6 100644 --- a/v2/src/generated/operations/public-events.ts +++ b/v2/src/generated/operations/public-events.ts @@ -63,14 +63,14 @@ const GUEST_TOKEN = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/public_events/{system_id}/events` */ -export function index( - input: OperationInput, +export function query( + input: OperationInput, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/public_events/{system_id}/events', pathKeys: ['system_id'], @@ -97,7 +97,7 @@ const INDEX = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), - name: 'publicEvents.index', + name: 'publicEvents.query', }); /** diff --git a/v2/src/generated/operations/repositories.ts b/v2/src/generated/operations/repositories.ts index 585254bcf..0448d5feb 100644 --- a/v2/src/generated/operations/repositories.ts +++ b/v2/src/generated/operations/repositories.ts @@ -286,42 +286,6 @@ const FOLDERS = /* @__PURE__ */ operation({ name: 'repositories.folders', }); -/** - * Lists the repositories added to the system. - * - * `GET /api/engine/v2/repositories` - */ -export function index( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(INDEX, input, options); -} - -const INDEX = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/repositories', - pathKeys: [], - params: /* @__PURE__ */ parameters({ - /** - * filters results by the given text: a record matches when any word matches its searchable - * fields as a whole word, and the last word also matches as a prefix (search as you type) - */ - q: /* @__PURE__ */ string(), - /** the maximum number of results to return */ - limit: /* @__PURE__ */ integer('UInt32'), - /** the starting offset of the result set, used to implement pagination */ - offset: /* @__PURE__ */ integer('UInt32'), - /** deprecated, ignored — pagination follows the `Link` header's offset */ - ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** deprecated, ignored — search covers the resource's indexed fields */ - fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), - }), - body: null, - response: /* @__PURE__ */ array(Repository), - name: 'repositories.index', -}); - /** * Determine loaded interfaces and their current commit. * @@ -380,6 +344,42 @@ const PULL = /* @__PURE__ */ operation({ name: 'repositories.pull', }); +/** + * Lists the repositories added to the system. + * + * `GET /api/engine/v2/repositories` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/repositories', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(Repository), + name: 'repositories.query', +}); + /** * Returns the list of releases in the repository, i.e. github releases. * diff --git a/v2/src/generated/operations/saml-authentications.ts b/v2/src/generated/operations/saml-authentications.ts index 07851ae34..f003e3f17 100644 --- a/v2/src/generated/operations/saml-authentications.ts +++ b/v2/src/generated/operations/saml-authentications.ts @@ -69,14 +69,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/saml_auths` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/saml_auths', pathKeys: [], @@ -99,7 +99,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SamlAuthentication), - name: 'samlAuthentications.index', + name: 'samlAuthentications.query', }); /** diff --git a/v2/src/generated/operations/schema.ts b/v2/src/generated/operations/schema.ts index 687bb5ba7..038092d95 100644 --- a/v2/src/generated/operations/schema.ts +++ b/v2/src/generated/operations/schema.ts @@ -70,14 +70,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/schema` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/schema', pathKeys: [], @@ -98,7 +98,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(JsonSchema), - name: 'schema.index', + name: 'schema.query', }); /** diff --git a/v2/src/generated/operations/settings.ts b/v2/src/generated/operations/settings.ts index 624c062d2..38a1bdc22 100644 --- a/v2/src/generated/operations/settings.ts +++ b/v2/src/generated/operations/settings.ts @@ -99,14 +99,14 @@ const HISTORY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/settings` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/settings', pathKeys: [], @@ -128,7 +128,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Settings), - name: 'settings.index', + name: 'settings.query', }); /** diff --git a/v2/src/generated/operations/short-url.ts b/v2/src/generated/operations/short-url.ts index 88794fee5..5c190b944 100644 --- a/v2/src/generated/operations/short-url.ts +++ b/v2/src/generated/operations/short-url.ts @@ -96,19 +96,48 @@ const GENERATE_QR_CODE = /* @__PURE__ */ operation({ name: 'shortUrl.generateQrCode', }); +/** + * Obtains an PNG QR code for the specified short URL with optional resolution. + * + * `GET /api/engine/v2/short_url/{id}/qr_code.png` + */ +export function pngQr( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(PNG_QR, input, options); +} + +const PNG_QR = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/short_url/{id}/qr_code.png', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + /** size of the QR code in pixels. Between 72px and 512px */ + size: /* @__PURE__ */ integer('Int32'), + }, + ['id'], + ), + body: null, + response: null, + name: 'shortUrl.pngQr', +}); + /** * List the short URLs for this domain. * * `GET /api/engine/v2/short_url` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url', pathKeys: [], @@ -129,36 +158,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Shortener), - name: 'shortUrl.index', -}); - -/** - * Obtains an PNG QR code for the specified short URL with optional resolution. - * - * `GET /api/engine/v2/short_url/{id}/qr_code.png` - */ -export function pngQr( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(PNG_QR, input, options); -} - -const PNG_QR = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/short_url/{id}/qr_code.png', - pathKeys: ['id'], - params: /* @__PURE__ */ parameters( - { - id: /* @__PURE__ */ string(), - /** size of the QR code in pixels. Between 72px and 512px */ - size: /* @__PURE__ */ integer('Int32'), - }, - ['id'], - ), - body: null, - response: null, - name: 'shortUrl.pngQr', + name: 'shortUrl.query', }); /** diff --git a/v2/src/generated/operations/signage-ai-providers.ts b/v2/src/generated/operations/signage-ai-providers.ts index fdc881b50..f9fed9b4c 100644 --- a/v2/src/generated/operations/signage-ai-providers.ts +++ b/v2/src/generated/operations/signage-ai-providers.ts @@ -103,14 +103,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/signage/ai/providers` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/providers', pathKeys: [], @@ -163,7 +163,7 @@ const INDEX = /* @__PURE__ */ operation({ ], ), ), - name: 'signageAiProviders.index', + name: 'signageAiProviders.query', }); /** `GET /api/engine/v2/signage/ai/providers/{id}` */ diff --git a/v2/src/generated/operations/signage-plugins.ts b/v2/src/generated/operations/signage-plugins.ts index 6e72f4642..5906f717c 100644 --- a/v2/src/generated/operations/signage-plugins.ts +++ b/v2/src/generated/operations/signage-plugins.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/signage/plugins` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/plugins', pathKeys: [], @@ -100,7 +100,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignagePlugin), - name: 'signagePlugins.index', + name: 'signagePlugins.query', }); /** diff --git a/v2/src/generated/operations/signage-template-mappings.ts b/v2/src/generated/operations/signage-template-mappings.ts index c13f1e323..549652c76 100644 --- a/v2/src/generated/operations/signage-template-mappings.ts +++ b/v2/src/generated/operations/signage-template-mappings.ts @@ -78,14 +78,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/signage/template_mappings` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/template_mappings', pathKeys: [], @@ -114,7 +114,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplateSystemTemplate), - name: 'signageTemplateMappings.index', + name: 'signageTemplateMappings.query', }); /** diff --git a/v2/src/generated/operations/signage-templates.ts b/v2/src/generated/operations/signage-templates.ts index 4c00a1bb4..7ab4dc85b 100644 --- a/v2/src/generated/operations/signage-templates.ts +++ b/v2/src/generated/operations/signage-templates.ts @@ -195,14 +195,14 @@ const DESTROY_DRAFT = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/signage/templates` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/templates', pathKeys: [], @@ -222,7 +222,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplate), - name: 'signageTemplates.index', + name: 'signageTemplates.query', }); /** diff --git a/v2/src/generated/operations/storages.ts b/v2/src/generated/operations/storages.ts index 54611f026..4c9674eb4 100644 --- a/v2/src/generated/operations/storages.ts +++ b/v2/src/generated/operations/storages.ts @@ -68,14 +68,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/storages` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/storages', pathKeys: [], @@ -98,7 +98,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Storage), - name: 'storages.index', + name: 'storages.query', }); /** diff --git a/v2/src/generated/operations/system-triggers.ts b/v2/src/generated/operations/system-triggers.ts index 665d6badd..fb003b3da 100644 --- a/v2/src/generated/operations/system-triggers.ts +++ b/v2/src/generated/operations/system-triggers.ts @@ -76,14 +76,14 @@ const DESTROY = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/systems/{sys_id}/triggers` */ -export function index( - input: OperationInput, +export function query( + input: OperationInput, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/triggers', pathKeys: ['sys_id'], @@ -121,7 +121,7 @@ const INDEX = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(TriggerInstance), - name: 'systemTriggers.index', + name: 'systemTriggers.query', }); /** diff --git a/v2/src/generated/operations/systems.ts b/v2/src/generated/operations/systems.ts index 987569c60..38d7a771e 100644 --- a/v2/src/generated/operations/systems.ts +++ b/v2/src/generated/operations/systems.ts @@ -196,19 +196,47 @@ const FUNCTIONS = /* @__PURE__ */ operation({ name: 'systems.functions', }); +/** + * Return metadata for the system. + * + * `GET /api/engine/v2/systems/{sys_id}/metadata` + */ +export function metadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(METADATA, input, options); +} + +const METADATA = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/systems/{sys_id}/metadata', + pathKeys: ['sys_id'], + params: /* @__PURE__ */ parameters( + { + sys_id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['sys_id'], + ), + body: null, + response: /* @__PURE__ */ record(MetadataInterface), + name: 'systems.metadata', +}); + /** * List the systems in a cluster. * * `GET /api/engine/v2/systems` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems', pathKeys: [], @@ -258,35 +286,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ControlSystem), - name: 'systems.index', -}); - -/** - * Return metadata for the system. - * - * `GET /api/engine/v2/systems/{sys_id}/metadata` - */ -export function metadata( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(METADATA, input, options); -} - -const METADATA = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/systems/{sys_id}/metadata', - pathKeys: ['sys_id'], - params: /* @__PURE__ */ parameters( - { - sys_id: /* @__PURE__ */ string(), - name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - }, - ['sys_id'], - ), - body: null, - response: /* @__PURE__ */ record(MetadataInterface), - name: 'systems.metadata', + name: 'systems.query', }); /** diff --git a/v2/src/generated/operations/tenant-consent.ts b/v2/src/generated/operations/tenant-consent.ts index 1472aaa78..902f5f1cd 100644 --- a/v2/src/generated/operations/tenant-consent.ts +++ b/v2/src/generated/operations/tenant-consent.ts @@ -83,14 +83,14 @@ const FLOW_STATUS = /* @__PURE__ */ operation({ }); /** `GET /api/engine/v2/admin_consent/{id}` */ -export function index( - input: OperationInput, +export function query( + input: OperationInput, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/admin_consent/{id}', pathKeys: ['id'], @@ -122,5 +122,5 @@ const INDEX = /* @__PURE__ */ operation({ }, ['url'], ), - name: 'tenantConsent.index', + name: 'tenantConsent.query', }); diff --git a/v2/src/generated/operations/triggers.ts b/v2/src/generated/operations/triggers.ts index 65d0c1d95..960b78643 100644 --- a/v2/src/generated/operations/triggers.ts +++ b/v2/src/generated/operations/triggers.ts @@ -63,19 +63,46 @@ const DESTROY = /* @__PURE__ */ operation({ name: 'triggers.destroy', }); +/** + * Get instances of a trigger, how many systems are using a trigger. + * + * `GET /api/engine/v2/triggers/{id}/instances` + */ +export function instances( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(INSTANCES, input, options); +} + +const INSTANCES = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/triggers/{id}/instances', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(TriggerInstance), + name: 'triggers.instances', +}); + /** * Returns the list of available triggers. * * `GET /api/engine/v2/triggers` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/triggers', pathKeys: [], @@ -96,34 +123,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Trigger), - name: 'triggers.index', -}); - -/** - * Get instances of a trigger, how many systems are using a trigger. - * - * `GET /api/engine/v2/triggers/{id}/instances` - */ -export function instances( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(INSTANCES, input, options); -} - -const INSTANCES = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/triggers/{id}/instances', - pathKeys: ['id'], - params: /* @__PURE__ */ parameters( - { - id: /* @__PURE__ */ string(), - }, - ['id'], - ), - body: null, - response: /* @__PURE__ */ array(TriggerInstance), - name: 'triggers.instances', + name: 'triggers.query', }); /** diff --git a/v2/src/generated/operations/uploads.ts b/v2/src/generated/operations/uploads.ts index 43dd702dc..740cd87d6 100644 --- a/v2/src/generated/operations/uploads.ts +++ b/v2/src/generated/operations/uploads.ts @@ -331,14 +331,14 @@ const GET_LINK = /* @__PURE__ */ operation({ * * `GET /api/engine/v2/uploads` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads', pathKeys: [], @@ -365,7 +365,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Upload), - name: 'uploads.index', + name: 'uploads.query', }); /** diff --git a/v2/src/generated/operations/users.ts b/v2/src/generated/operations/users.ts index b73f97397..a9a17d4a5 100644 --- a/v2/src/generated/operations/users.ts +++ b/v2/src/generated/operations/users.ts @@ -168,19 +168,49 @@ const GROUPS = /* @__PURE__ */ operation({ name: 'users.groups', }); +/** + * Return a users metadata. + * + * `GET /api/engine/v2/users/{id}/metadata` + */ +export function metadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(METADATA, input, options); +} + +const METADATA = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/users/{id}/metadata', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the id of the user */ + id: /* @__PURE__ */ string(), + /** filter metadata by a particular entry */ + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ record(MetadataInterface), + name: 'users.metadata', +}); + /** * Returns a list of users. * * `GET /api/engine/v2/users` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users', pathKeys: [], @@ -214,37 +244,7 @@ const INDEX = /* @__PURE__ */ operation({ UserPublicResponse, ]), ), - name: 'users.index', -}); - -/** - * Return a users metadata. - * - * `GET /api/engine/v2/users/{id}/metadata` - */ -export function metadata( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(METADATA, input, options); -} - -const METADATA = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/users/{id}/metadata', - pathKeys: ['id'], - params: /* @__PURE__ */ parameters( - { - /** the id of the user */ - id: /* @__PURE__ */ string(), - /** filter metadata by a particular entry */ - name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - }, - ['id'], - ), - body: null, - response: /* @__PURE__ */ record(MetadataInterface), - name: 'users.metadata', + name: 'users.query', }); /** diff --git a/v2/src/generated/operations/web-rtc.ts b/v2/src/generated/operations/web-rtc.ts index 321ff92df..8b01d33b5 100644 --- a/v2/src/generated/operations/web-rtc.ts +++ b/v2/src/generated/operations/web-rtc.ts @@ -71,42 +71,6 @@ const GUEST_EXIT = /* @__PURE__ */ operation({ name: 'webRtc.guestExit', }); -/** - * This route provides a list of public chat rooms for the current domain. - * - * `GET /api/engine/v2/webrtc/rooms` - */ -export function index( - input: OperationInput = {}, - options?: CallOptions, -): Promise> { - return call(INDEX, input, options); -} - -const INDEX = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/webrtc/rooms', - pathKeys: [], - params: /* @__PURE__ */ parameters({ - /** - * filters results by the given text: a record matches when any word matches its searchable - * fields as a whole word, and the last word also matches as a prefix (search as you type) - */ - q: /* @__PURE__ */ string(), - /** the maximum number of results to return */ - limit: /* @__PURE__ */ integer('UInt32'), - /** the starting offset of the result set, used to implement pagination */ - offset: /* @__PURE__ */ integer('UInt32'), - /** deprecated, ignored — pagination follows the `Link` header's offset */ - ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** deprecated, ignored — search covers the resource's indexed fields */ - fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), - }), - body: null, - response: /* @__PURE__ */ array(ControlSystem), - name: 'webRtc.index', -}); - /** * Call ended for the user. * @@ -196,6 +160,42 @@ const PUBLIC_ROOM = /* @__PURE__ */ operation({ name: 'webRtc.publicRoom', }); +/** + * This route provides a list of public chat rooms for the current domain. + * + * `GET /api/engine/v2/webrtc/rooms` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/webrtc/rooms', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(ControlSystem), + name: 'webRtc.query', +}); + /** * For authorised users to move people from one chat to another. * diff --git a/v2/src/generated/operations/zones.ts b/v2/src/generated/operations/zones.ts index 55de5ea72..835a7aa12 100644 --- a/v2/src/generated/operations/zones.ts +++ b/v2/src/generated/operations/zones.ts @@ -72,19 +72,48 @@ const DESTROY = /* @__PURE__ */ operation({ name: 'zones.destroy', }); +/** + * Return metadata associcated with the selected zone. + * + * `GET /api/engine/v2/zones/{id}/metadata` + */ +export function metadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(METADATA, input, options); +} + +const METADATA = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/engine/v2/zones/{id}/metadata', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + /** only return the metadata key we are interested in */ + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ record(MetadataInterface), + name: 'zones.metadata', +}); + /** * List the configured zones. * * `GET /api/engine/v2/zones` */ -export function index( - input: OperationInput = {}, +export function query( + input: OperationInput = {}, options?: CallOptions, -): Promise> { - return call(INDEX, input, options); +): Promise> { + return call(QUERY, input, options); } -const INDEX = /* @__PURE__ */ operation({ +const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones', pathKeys: [], @@ -123,36 +152,7 @@ const INDEX = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Zone), - name: 'zones.index', -}); - -/** - * Return metadata associcated with the selected zone. - * - * `GET /api/engine/v2/zones/{id}/metadata` - */ -export function metadata( - input: OperationInput, - options?: CallOptions, -): Promise> { - return call(METADATA, input, options); -} - -const METADATA = /* @__PURE__ */ operation({ - method: 'GET', - path: '/api/engine/v2/zones/{id}/metadata', - pathKeys: ['id'], - params: /* @__PURE__ */ parameters( - { - id: /* @__PURE__ */ string(), - /** only return the metadata key we are interested in */ - name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - }, - ['id'], - ), - body: null, - response: /* @__PURE__ */ record(MetadataInterface), - name: 'zones.metadata', + name: 'zones.query', }); /** diff --git a/v2/src/generated/staff/operations/asset-categories.ts b/v2/src/generated/staff/operations/asset-categories.ts new file mode 100644 index 000000000..578b21f82 --- /dev/null +++ b/v2/src/generated/staff/operations/asset-categories.ts @@ -0,0 +1,159 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `AssetCategories` controller of the API. Import it as the `assetCategories` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { AssetCategory } from '../schemas.ts'; + +/** + * Create an asset category. + * + * `POST /api/staff/v1/asset_categories` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/asset_categories', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: AssetCategory, + response: AssetCategory, + name: 'staff.assetCategories.create', +}); + +/** + * Delete an asset category. + * + * `DELETE /api/staff/v1/asset_categories/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/asset_categories/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.assetCategories.destroy', +}); + +/** + * List asset categories. + * + * `GET /api/staff/v1/asset_categories` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_categories', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * true returns only hidden categories, false only non-hidden categories; omit to return all + * categories + */ + hidden: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(AssetCategory), + name: 'staff.assetCategories.query', +}); + +/** + * Get a single asset category. + * + * `GET /api/staff/v1/asset_categories/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_categories/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: AssetCategory, + name: 'staff.assetCategories.show', +}); + +/** + * Update an asset category with the fields in the request body and return the saved category. + * + * `PATCH /api/staff/v1/asset_categories/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/asset_categories/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: AssetCategory, + response: AssetCategory, + name: 'staff.assetCategories.update', +}); diff --git a/v2/src/generated/staff/operations/asset-purchase-orders.ts b/v2/src/generated/staff/operations/asset-purchase-orders.ts new file mode 100644 index 000000000..8f7a48b5a --- /dev/null +++ b/v2/src/generated/staff/operations/asset-purchase-orders.ts @@ -0,0 +1,156 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `AssetPurchaseOrders` controller of the API. Import it as the `assetPurchaseOrders` + * namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { AssetPurchaseOrder } from '../schemas.ts'; + +/** + * Create an asset purchase order. + * + * `POST /api/staff/v1/asset_purchase_orders` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/asset_purchase_orders', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: AssetPurchaseOrder, + response: AssetPurchaseOrder, + name: 'staff.assetPurchaseOrders.create', +}); + +/** + * Delete an asset purchase order. + * + * `DELETE /api/staff/v1/asset_purchase_orders/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.assetPurchaseOrders.destroy', +}); + +/** + * List asset purchase orders. + * + * `GET /api/staff/v1/asset_purchase_orders` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_purchase_orders', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(AssetPurchaseOrder), + name: 'staff.assetPurchaseOrders.query', +}); + +/** + * Get a single asset purchase order. + * + * `GET /api/staff/v1/asset_purchase_orders/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: AssetPurchaseOrder, + name: 'staff.assetPurchaseOrders.show', +}); + +/** + * Update an asset purchase order with the fields in the request body and return the saved purchase + * order. + * + * `PATCH /api/staff/v1/asset_purchase_orders/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/asset_purchase_orders/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: AssetPurchaseOrder, + response: AssetPurchaseOrder, + name: 'staff.assetPurchaseOrders.update', +}); diff --git a/v2/src/generated/staff/operations/asset-types.ts b/v2/src/generated/staff/operations/asset-types.ts new file mode 100644 index 000000000..615490df5 --- /dev/null +++ b/v2/src/generated/staff/operations/asset-types.ts @@ -0,0 +1,153 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `AssetTypes` controller of the API. Import it as the `assetTypes` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, nullable, parameters, string } from '../../../core/schema.ts'; +import { AssetType } from '../schemas.ts'; + +/** + * Create an asset type. + * + * `POST /api/staff/v1/asset_types` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/asset_types', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: AssetType, + response: AssetType, + name: 'staff.assetTypes.create', +}); + +/** + * Delete an asset type. + * + * `DELETE /api/staff/v1/asset_types/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/asset_types/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.assetTypes.destroy', +}); + +/** + * List asset types, each with a count of its assets. + * + * `GET /api/staff/v1/asset_types` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_types', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return asset types with exactly this brand */ + brand: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return asset types with exactly this model number */ + model_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return asset types in this asset category id */ + category_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * limits asset_count to assets whose zone_id is this zone id; does not filter the asset + * types + * returned + */ + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(AssetType), + name: 'staff.assetTypes.query', +}); + +/** + * Get a single asset type. + * + * `GET /api/staff/v1/asset_types/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/asset_types/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: AssetType, + name: 'staff.assetTypes.show', +}); + +/** + * Update an asset type with the fields in the request body and return the saved asset type. + * + * `PATCH /api/staff/v1/asset_types/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/asset_types/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: AssetType, + response: AssetType, + name: 'staff.assetTypes.update', +}); diff --git a/v2/src/generated/staff/operations/assets.ts b/v2/src/generated/staff/operations/assets.ts new file mode 100644 index 000000000..a022d0af5 --- /dev/null +++ b/v2/src/generated/staff/operations/assets.ts @@ -0,0 +1,267 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Assets` controller of the API. Import it as the `assets` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { Asset } from '../schemas.ts'; + +/** + * Create several assets; the body is a JSON array of assets. + * + * `POST /api/staff/v1/assets/bulk` + */ +export function bulkCreate( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_CREATE, input, options); +} + +const BULK_CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/assets/bulk', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: /* @__PURE__ */ array(Asset), + response: /* @__PURE__ */ array(Asset), + name: 'staff.assets.bulkCreate', +}); + +/** + * Delete several assets; the body is a JSON array of asset ids. + * + * `DELETE /api/staff/v1/assets/bulk` + */ +export function bulkDestroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_DESTROY, input, options); +} + +const BULK_DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/assets/bulk', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: /* @__PURE__ */ array(/* @__PURE__ */ string()), + response: null, + name: 'staff.assets.bulkDestroy', +}); + +/** + * Update several assets; the body is a JSON array of assets, each with its `id`. + * + * `PATCH /api/staff/v1/assets/bulk` + */ +export function bulkUpdate( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BULK_UPDATE, input, options); +} + +const BULK_UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/assets/bulk', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: /* @__PURE__ */ array(Asset), + response: /* @__PURE__ */ array(Asset), + name: 'staff.assets.bulkUpdate', +}); + +/** + * Create an asset. + * + * `POST /api/staff/v1/assets` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/assets', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: Asset, + response: Asset, + name: 'staff.assets.create', +}); + +/** + * Delete an asset. + * + * `DELETE /api/staff/v1/assets/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/assets/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.assets.destroy', +}); + +/** + * Get the asset's level map, an SVG, with the asset's position in the X-Map-Pin header. + * + * `GET /api/staff/v1/assets/{id}/map` + */ +export function map( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MAP, input, options); +} + +const MAP = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/assets/{id}/map', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.assets.map', +}); + +/** + * List assets, filtered by the params provided. + * + * `GET /api/staff/v1/assets` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/assets', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return assets whose zone_id field is this zone id */ + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * comma separated zone ids; only return assets whose zones list contains every one of them + */ + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** only return assets of this asset type id */ + type_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return assets acquired on this asset purchase order id */ + order_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return assets with exactly this barcode */ + barcode: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return assets with exactly this serial number */ + serial_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** true returns only bookable assets, false only non-bookable assets; omit for both */ + bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** true returns only accessible assets, false only non-accessible assets; omit for both */ + accessible: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** comma separated features; returns assets that have any of these features */ + features: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(Asset), + name: 'staff.assets.query', +}); + +/** + * Get a single asset. + * + * `GET /api/staff/v1/assets/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/assets/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: Asset, + name: 'staff.assets.show', +}); + +/** + * Update an asset with the fields in the request body and return the saved asset. + * + * `PATCH /api/staff/v1/assets/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/assets/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: Asset, + response: Asset, + name: 'staff.assets.update', +}); diff --git a/v2/src/generated/staff/operations/bookings.ts b/v2/src/generated/staff/operations/bookings.ts new file mode 100644 index 000000000..2017651f3 --- /dev/null +++ b/v2/src/generated/staff/operations/bookings.ts @@ -0,0 +1,1255 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Bookings` controller of the API. Import it as the `bookings` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { + array, + boolean, + integer, + json, + nullable, + parameters, + record, + string, +} from '../../../core/schema.ts'; +import { + Attendee, + Booking, + BookingInduction, + Guest, + PlaceCalendarEventAttendee, +} from '../schemas.ts'; + +/** + * Add an attendee to a booking. + * + * `POST /api/staff/v1/bookings/{id}/attendee` + */ +export function addAttendee( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(ADD_ATTENDEE, input, options); +} + +const ADD_ATTENDEE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/attendee', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: PlaceCalendarEventAttendee, + response: Attendee, + name: 'staff.bookings.addAttendee', +}); + +/** + * Approve a booking. + * + * `POST /api/staff/v1/bookings/{id}/approve` + */ +export function approve( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(APPROVE, input, options); +} + +const APPROVE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/approve', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.approve', +}); + +/** + * Approve a booking. + * + * `POST /api/staff/v1/bookings/{id}/approve/{instance}` + */ +export function approveInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(APPROVE_INSTANCE, input, options); +} + +const APPROVE_INSTANCE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/approve/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance'], + ), + body: null, + response: Booking, + name: 'staff.bookings.approveInstance', +}); + +/** + * Book a desk or other asset for yourself, the zones (level, building) are taken from the asset. + * + * `POST /api/staff/v1/bookings/book` + */ +export function book( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BOOK, input, options); +} + +const BOOK = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/book', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** the asset id to book, i.e. a desk id from desks_index */ + asset_id: /* @__PURE__ */ string(), + /** + * start as a unix epoch in seconds, defaults to now; a start earlier today moves to now + */ + booking_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** end as a unix epoch in seconds, defaults to the end of the start's day */ + booking_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the kind of asset, such as desk, parking or locker */ + booking_type: /* @__PURE__ */ string(), + /** a title for the booking, defaults to the asset's name */ + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** comma separated zone ids to file the booking under, added to the asset's zones */ + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** IANA timezone of the booking, defaults to the asset's level or building timezone */ + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['asset_id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.book', +}); + +/** + * List the ids of assets booked in a time period. + * + * `GET /api/staff/v1/bookings/booked` + */ +export function booked( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(BOOKED, input, options); +} + +const BOOKED = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/bookings/booked', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** start of the period to search, unix epoch in seconds. Defaults to now */ + period_start: /* @__PURE__ */ integer(), + /** end of the period to search, unix epoch in seconds. Defaults to one hour from now */ + period_end: /* @__PURE__ */ integer(), + /** + * the booking type to search, such as desk, parking, locker, visitor or group-event. + * Required + * unless event_id or ical_uid is provided + */ + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * only include bookings in any of these zones (e.g. a building or level), comma separated + * zone + * ids. When provided, bookings of all users in the zones are returned unless `user` or + * `email` + * is also set + */ + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * only include bookings owned by the user with this email. If none of `user`, `email` or + * `zones` is set the signed in user's bookings are returned + */ + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings owned by this user id, use `current` for the signed in user */ + user: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * when `email` or `user` is set (or defaulted to the signed in user), also include bookings + * that user made on behalf of others + */ + include_booked_by: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * true only includes checked in bookings, false only includes bookings that have been + * checked + * out + */ + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** only include bookings last changed before this time, unix epoch in seconds */ + created_before: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** only include bookings last changed after this time, unix epoch in seconds */ + created_after: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * true only includes approved bookings, false only includes bookings that are not approved + */ + approved: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * only include bookings whose extension data contains all of these key/value pairs, as a + * JSON + * object + */ + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings in this process state, a user defined value (see update_state) */ + state: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings belonging to this department, a user defined value */ + department: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * return the bookings linked to this calendar event id (e.g. an Office365 or Google event + * id). + * When set, `type` is optional and the period, zone and user filters are ignored + */ + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * return the bookings linked to the calendar event with this iCal UID. When set, `type` is + * optional and the period, zone and user filters are ignored + */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the maximum number of bookings to inspect, defaults to 100000 */ + limit: /* @__PURE__ */ integer('Int32'), + /** + * the number of bookings to skip, used for pagination (take the next value from the `Link` + * header) + */ + offset: /* @__PURE__ */ integer('Int32'), + /** + * only include bookings with this permission level: PRIVATE, OPEN or PUBLIC. Ignored for + * unauthenticated requests, which only see PUBLIC bookings + */ + permission: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'staff.bookings.booked', +}); + +/** + * Check a booking in, or out with state=false. + * + * `POST /api/staff/v1/bookings/{id}/check_in` + */ +export function checkIn( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CHECK_IN, input, options); +} + +const CHECK_IN = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/check_in', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** true to check in, false to check out. Defaults to true */ + state: /* @__PURE__ */ boolean(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.checkIn', +}); + +/** + * Check a booking in, or out with state=false. + * + * `POST /api/staff/v1/bookings/{id}/check_in/{instance}` + */ +export function checkInInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CHECK_IN_INSTANCE, input, options); +} + +const CHECK_IN_INSTANCE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/check_in/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** true to check in, false to check out. Defaults to true */ + state: /* @__PURE__ */ boolean(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance'], + ), + body: null, + response: Booking, + name: 'staff.bookings.checkInInstance', +}); + +/** + * List the assets already booked during a booking's time range. + * + * `POST /api/staff/v1/bookings/clashing-assets` + */ +export function clashingAssets( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CLASHING_ASSETS, input, options); +} + +const CLASHING_ASSETS = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/clashing-assets', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * when true, return the assets from the booking's asset_ids that are NOT booked, so + * asset_ids + * must contain every candidate asset + */ + return_available: /* @__PURE__ */ boolean(), + /** + * when true, return objects with asset_id, booking_start and booking_end for each clash + * rather + * than plain asset ids. Cannot be combined with return_available + */ + include_clash_time: /* @__PURE__ */ boolean(), + }), + body: Booking, + response: /* @__PURE__ */ array(/* @__PURE__ */ json()), + name: 'staff.bookings.clashingAssets', +}); + +/** + * Create a booking. + * + * `POST /api/staff/v1/bookings` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the maximum number of concurrent bookings of this type the user may hold in the booking's + * zones, used instead of the tenant's configured booking limit + */ + limit_override: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** + * link the booking to this calendar event id (e.g. an Office365 or Google event id). The + * event + * must already have staff-api metadata, otherwise 422 is returned + */ + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * link the booking to the calendar event with this iCal UID. The event must already have + * staff-api metadata, otherwise 422 is returned + */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: Booking, + response: Booking, + name: 'staff.bookings.create', +}); + +/** + * Cancel a booking. + * + * `DELETE /api/staff/v1/bookings/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/bookings/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.bookings.destroy', +}); + +/** + * Remove an attendee from a booking. + * + * `DELETE /api/staff/v1/bookings/{id}/attendee/{attendee_id}` + */ +export function destroyAttendee( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY_ATTENDEE, input, options); +} + +const DESTROY_ATTENDEE = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/bookings/{id}/attendee/{attendee_id}', + pathKeys: ['id', 'attendee_id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the email address of the attendee to remove */ + attendee_id: /* @__PURE__ */ string(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id', 'attendee_id'], + ), + body: null, + response: null, + name: 'staff.bookings.destroyAttendee', +}); + +/** + * Cancel a booking. + * + * `DELETE /api/staff/v1/bookings/{id}/instance/{instance}` + */ +export function destroyInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY_INSTANCE, input, options); +} + +const DESTROY_INSTANCE = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/bookings/{id}/instance/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance'], + ), + body: null, + response: null, + name: 'staff.bookings.destroyInstance', +}); + +/** + * Change a booking's title, description or times. + * + * `PATCH /api/staff/v1/bookings/{id}/edit` + */ +export function edit( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDIT, input, options); +} + +const EDIT = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/bookings/{id}/edit', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the new title */ + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the new description */ + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the new start as a unix epoch in seconds */ + booking_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the new end as a unix epoch in seconds */ + booking_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.edit', +}); + +/** + * Check a guest of a booking in, or out with state=false. + * + * `POST /api/staff/v1/bookings/{id}/guests/{guest_id}/check_in` + */ +export function guestCheckin( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GUEST_CHECKIN, input, options); +} + +const GUEST_CHECKIN = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/guests/{guest_id}/check_in', + pathKeys: ['id', 'guest_id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the email address of the guest to check in or out */ + guest_id: /* @__PURE__ */ string(), + /** true to check the guest in, false to check them out. Defaults to true */ + state: /* @__PURE__ */ boolean(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id', 'guest_id'], + ), + body: null, + response: Guest, + name: 'staff.bookings.guestCheckin', +}); + +/** + * List the guests attending a booking. + * + * `GET /api/staff/v1/bookings/{id}/guests` + */ +export function guestList( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GUEST_LIST, input, options); +} + +const GUEST_LIST = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/bookings/{id}/guests', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * when true and this is a parent booking, also include guests from its linked (child) + * bookings. + * Defaults to false + */ + include_linked: /* @__PURE__ */ boolean(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(Guest), + name: 'staff.bookings.guestList', +}); + +/** + * Merge the keys in the request body into a booking's extension data. + * + * `PATCH /api/staff/v1/bookings/{id}/ext_data` + */ +export function patchExtdata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(PATCH_EXTDATA, input, options); +} + +const PATCH_EXTDATA = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/bookings/{id}/ext_data', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * when true, publish a `staff/booking/changed` signal (action extdata_changed) so other + * services are notified, defaults to false + */ + signal_changes: /* @__PURE__ */ boolean(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ json()), + response: Booking, + name: 'staff.bookings.patchExtdata', +}); + +/** + * Merge the keys in the request body into a booking's extension data. + * + * `PATCH /api/staff/v1/bookings/{id}/ext_data/{instance}` + */ +export function patchExtdataInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(PATCH_EXTDATA_INSTANCE, input, options); +} + +const PATCH_EXTDATA_INSTANCE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/bookings/{id}/ext_data/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * when true, publish a `staff/booking/changed` signal (action extdata_changed) so other + * services are notified, defaults to false + */ + signal_changes: /* @__PURE__ */ boolean(), + }, + ['id', 'instance'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ json()), + response: Booking, + name: 'staff.bookings.patchExtdataInstance', +}); + +/** + * List bookings in a time period. + * + * `GET /api/staff/v1/bookings` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/bookings', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** start of the period to search, unix epoch in seconds. Defaults to now */ + period_start: /* @__PURE__ */ integer(), + /** end of the period to search, unix epoch in seconds. Defaults to one hour from now */ + period_end: /* @__PURE__ */ integer(), + /** + * the booking type to search, such as desk, parking, locker, visitor or group-event. + * Required + * unless event_id or ical_uid is provided + */ + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** when true, deleted and non-deleted bookings are returned (overrides `deleted`) */ + include_deleted: /* @__PURE__ */ boolean(), + /** when true, only deleted bookings are returned. Ignored if `include_deleted=true` */ + deleted: /* @__PURE__ */ boolean(), + /** + * when true, checked out and not checked out bookings are returned (overrides + * `checked_out`) + */ + include_checked_out: /* @__PURE__ */ boolean(), + /** + * when true, only checked out bookings are returned. Ignored if `include_checked_out=true` + */ + checked_out: /* @__PURE__ */ boolean(), + /** + * only include bookings in any of these zones (e.g. a building or level), comma separated + * zone + * ids. When provided, bookings of all users in the zones are returned unless `user` or + * `email` + * is also set + */ + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * only include bookings owned by the user with this email. If none of `user`, `email` or + * `zones` is set the signed in user's bookings are returned + */ + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings owned by this user id, use `current` for the signed in user */ + user: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * when `email` or `user` is set (or defaulted to the signed in user), also include bookings + * that user made on behalf of others + */ + include_booked_by: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * true only includes checked in bookings, false only includes bookings that have been + * checked + * out + */ + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** only include bookings last changed before this time, unix epoch in seconds */ + created_before: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** only include bookings last changed after this time, unix epoch in seconds */ + created_after: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * true only includes approved bookings, false only includes bookings that are not approved + */ + approved: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** true only includes rejected bookings, false excludes them. Defaults to including both */ + rejected: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** + * only include bookings whose extension data contains all of these key/value pairs, as a + * JSON + * object + */ + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings in this process state, a user defined value (see update_state) */ + state: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only include bookings belonging to this department, a user defined value */ + department: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * return the bookings linked to this calendar event id (e.g. an Office365 or Google event + * id). + * When set, `type` is optional and the period, zone and user filters are ignored + */ + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * return the bookings linked to the calendar event with this iCal UID. When set, `type` is + * optional and the period, zone and user filters are ignored + */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the maximum number of bookings to return, defaults to 100 */ + limit: /* @__PURE__ */ integer('Int32'), + /** + * the number of bookings to skip, used for pagination (take the next value from the `Link` + * header) + */ + offset: /* @__PURE__ */ integer('Int32'), + /** + * position within the expanded recurring bookings, used for pagination (take the next value + * from the `Link` header) + */ + recurrence: /* @__PURE__ */ integer('Int32'), + /** + * only include bookings with this permission level: PRIVATE, OPEN or PUBLIC. Ignored for + * unauthenticated requests, which only see PUBLIC bookings + */ + permission: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** internal use, a path suffix appended to the pagination `Link` header URL */ + link_ext: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** when true, linked (child) bookings in the results include their parent booking */ + include_parent_bookings: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }), + body: null, + response: /* @__PURE__ */ array(Booking), + name: 'staff.bookings.query', +}); + +/** + * Reject a booking. + * + * `POST /api/staff/v1/bookings/{id}/reject` + */ +export function reject( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(REJECT, input, options); +} + +const REJECT = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/reject', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.reject', +}); + +/** + * Reject a booking. + * + * `POST /api/staff/v1/bookings/{id}/reject/{instance}` + */ +export function rejectInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(REJECT_INSTANCE, input, options); +} + +const REJECT_INSTANCE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/reject/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance'], + ), + body: null, + response: Booking, + name: 'staff.bookings.rejectInstance', +}); + +/** + * Get a single booking. + * + * `GET /api/staff/v1/bookings/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/bookings/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: Booking, + name: 'staff.bookings.show', +}); + +/** + * Get a single booking. + * + * `GET /api/staff/v1/bookings/{id}/instance/{instance}` + */ +export function showInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW_INSTANCE, input, options); +} + +const SHOW_INSTANCE = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/bookings/{id}/instance/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id', 'instance'], + ), + body: null, + response: Booking, + name: 'staff.bookings.showInstance', +}); + +/** + * Update a booking with the fields in the request body and return the saved booking. + * + * `PATCH /api/staff/v1/bookings/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/bookings/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the maximum number of concurrent bookings of this type the user may hold in the + * booking's + * zones, used instead of the tenant's configured booking limit + */ + limit_override: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: Booking, + response: Booking, + name: 'staff.bookings.update', +}); + +/** + * Set a booking's induction status. + * + * `POST /api/staff/v1/bookings/{id}/update_induction` + */ +export function updateInduction( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_INDUCTION, input, options); +} + +const UPDATE_INDUCTION = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/update_induction', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the induction status: tentative, accepted or declined */ + induction: BookingInduction, + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id', 'induction'], + ), + body: null, + response: Booking, + name: 'staff.bookings.updateInduction', +}); + +/** + * Set a booking's induction status. + * + * `POST /api/staff/v1/bookings/{id}/update_induction/{instance}` + */ +export function updateInductionInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_INDUCTION_INSTANCE, input, options); +} + +const UPDATE_INDUCTION_INSTANCE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/update_induction/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the induction status: tentative, accepted or declined */ + induction: BookingInduction, + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance', 'induction'], + ), + body: null, + response: Booking, + name: 'staff.bookings.updateInductionInstance', +}); + +/** + * Update a booking with the fields in the request body and return the saved booking. + * + * `PATCH /api/staff/v1/bookings/{id}/instance/{instance}` + */ +export function updateInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_INSTANCE, input, options); +} + +const UPDATE_INSTANCE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/bookings/{id}/instance/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * the maximum number of concurrent bookings of this type the user may hold in the + * booking's + * zones, used instead of the tenant's configured booking limit + */ + limit_override: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + }, + ['id', 'instance'], + ), + body: Booking, + response: Booking, + name: 'staff.bookings.updateInstance', +}); + +/** + * Set a booking's process state. + * + * `POST /api/staff/v1/bookings/{id}/update_state` + */ +export function updateState( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_STATE, input, options); +} + +const UPDATE_STATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/update_state', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** the new user defined process state of the booking */ + state: /* @__PURE__ */ string(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id', 'state'], + ), + body: null, + response: Booking, + name: 'staff.bookings.updateState', +}); + +/** + * Set a booking's process state. + * + * `POST /api/staff/v1/bookings/{id}/update_state/{instance}` + */ +export function updateStateInstance( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_STATE_INSTANCE, input, options); +} + +const UPDATE_STATE_INSTANCE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/bookings/{id}/update_state/{instance}', + pathKeys: ['id', 'instance'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * the occurrence of a recurring booking to act on, the instance id (the occurrence + * start time + * as a unix epoch in seconds) as returned in the booking `instance` field. Omit to act + * on the + * booking or whole series + */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the new user defined process state of the booking */ + state: /* @__PURE__ */ string(), + /** the client or channel making the change, recorded for analytics */ + utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'instance', 'state'], + ), + body: null, + response: Booking, + name: 'staff.bookings.updateStateInstance', +}); diff --git a/v2/src/generated/staff/operations/calendars.ts b/v2/src/generated/staff/operations/calendars.ts new file mode 100644 index 000000000..6808abf40 --- /dev/null +++ b/v2/src/generated/staff/operations/calendars.ts @@ -0,0 +1,185 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Calendars` controller of the API. Import it as the `calendars` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { + array, + boolean, + integer, + nullable, + object, + parameters, + string, +} from '../../../core/schema.ts'; +import { CalendarsAvailability, PlaceCalendarCalendar } from '../schemas.ts'; + +/** + * Find the rooms or people that are free for a whole time period. + * + * `GET /api/staff/v1/calendars/availability` + */ +export function availability( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(AVAILABILITY, input, options); +} + +const AVAILABILITY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/calendars/availability', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** search period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** search period end as a unix epoch in seconds */ + period_end: /* @__PURE__ */ integer(), + /** + * a comma separated list of calendar ids (email addresses) to include; for room + * resource + * calendars prefer `system_ids` + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * a comma separated list of zone ids (buildings or levels); all rooms (systems with a + * calendar + * email) in any of these zones are checked + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** a comma separated list of room system ids to check */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * a comma separated list of room features, rooms found via `zone_ids` must have all of + * them + */ + features: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** only return bookable (true) or non-bookable (false) rooms found via `zone_ids` */ + bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }, + ['period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(CalendarsAvailability), + name: 'staff.calendars.availability', +}); + +/** + * Check whether the current user can edit another user's calendar. + * + * `GET /api/staff/v1/calendars/{user_email}/permission` + */ +export function checkPermission( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CHECK_PERMISSION, input, options); +} + +const CHECK_PERMISSION = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/calendars/{user_email}/permission', + pathKeys: ['user_email'], + params: /* @__PURE__ */ parameters( + { + /** email or UPN of the calendar owner */ + user_email: /* @__PURE__ */ string(), + }, + ['user_email'], + ), + body: null, + response: /* @__PURE__ */ object( + { + can_edit: /* @__PURE__ */ boolean(), + }, + ['can_edit'], + ), + name: 'staff.calendars.checkPermission', +}); + +/** + * Get the busy times of rooms or people in a time period. + * + * `GET /api/staff/v1/calendars/free_busy` + */ +export function freeBusy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(FREE_BUSY, input, options); +} + +const FREE_BUSY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/calendars/free_busy', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** search period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** + * search period end as a unix epoch in seconds, must be at least 5 minutes after + * period_start + */ + period_end: /* @__PURE__ */ integer(), + /** + * a comma separated list of calendar ids (email addresses) to include; for room + * resource + * calendars prefer `system_ids` + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * a comma separated list of zone ids (buildings or levels); all rooms (systems with a + * calendar + * email) in any of these zones are checked + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** a comma separated list of room system ids to check */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * a comma separated list of room features, rooms found via `zone_ids` must have all of + * them + */ + features: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** only return bookable (true) or non-bookable (false) rooms found via `zone_ids` */ + bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }, + ['period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(CalendarsAvailability), + name: 'staff.calendars.freeBusy', +}); + +/** + * List the calendars available to the current user. + * + * `GET /api/staff/v1/calendars` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/calendars', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarCalendar), + name: 'staff.calendars.query', +}); diff --git a/v2/src/generated/staff/operations/desks.ts b/v2/src/generated/staff/operations/desks.ts new file mode 100644 index 000000000..2fd5d54df --- /dev/null +++ b/v2/src/generated/staff/operations/desks.ts @@ -0,0 +1,164 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Desks` controller of the API. Import it as the `desks` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { DesksFreeDesks, DesksNearColleagues, DesksNearbyDesks } from '../schemas.ts'; + +/** + * List the features of the bookable desks, i.e. standing or dual-monitor. + * + * `GET /api/staff/v1/desks/features` + */ +export function features( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(FEATURES, input, options); +} + +const FEATURES = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/desks/features', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only desks in this zone, a building or level */ + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'staff.desks.features', +}); + +/** + * Rank the free desks near where your colleagues are sitting, by level, defaulting to your + * contacts. + * + * `GET /api/staff/v1/desks/near_colleagues` + */ +export function nearColleagues( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(NEAR_COLLEAGUES, input, options); +} + +const NEAR_COLLEAGUES = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/desks/near_colleagues', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** comma separated colleague emails, defaults to your saved contacts */ + emails: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** period start as a unix epoch in seconds, defaults to now */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** period end as a unix epoch in seconds, defaults to the end of the period start's day */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the maximum number of desks to return per level, up to 100 */ + limit: /* @__PURE__ */ integer('Int32'), + }), + body: null, + response: DesksNearColleagues, + name: 'staff.desks.nearColleagues', +}); + +/** + * List the free desks nearest to a desk, or to the desk a colleague has booked. + * + * `GET /api/staff/v1/desks/nearby` + */ +export function nearby( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(NEARBY, input, options); +} + +const NEARBY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/desks/nearby', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** the desk (asset id) to search near, required unless email is provided */ + asset_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** a colleague's email, searches near the desk they've booked */ + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * period start as a unix epoch in seconds, defaults to now, or to the start of the + * colleague's + * desk booking + */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * period end as a unix epoch in seconds, defaults to the end of the day, or of the + * colleague's + * desk booking + */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the maximum number of desks to return, up to 100 */ + limit: /* @__PURE__ */ integer('Int32'), + }), + body: null, + response: DesksNearbyDesks, + name: 'staff.desks.nearby', +}); + +/** + * List the free desks on a level for a period, with your own desk bookings in that period. + * + * `GET /api/staff/v1/desks` + */ +export function query( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/desks', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** the level zone id */ + zone_id: /* @__PURE__ */ string(), + /** comma separated features, desks must have every feature */ + features: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** period start as a unix epoch in seconds, defaults to now */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * period end as a unix epoch in seconds, defaults to the end of the period start's day + */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * filters results by the given text: a record matches when any word matches its + * searchable + * fields as a whole word, and the last word also matches as a prefix (search as you + * type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }, + ['zone_id'], + ), + body: null, + response: DesksFreeDesks, + name: 'staff.desks.query', +}); diff --git a/v2/src/generated/staff/operations/events.ts b/v2/src/generated/staff/operations/events.ts new file mode 100644 index 000000000..d46f6638e --- /dev/null +++ b/v2/src/generated/staff/operations/events.ts @@ -0,0 +1,962 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Events` controller of the API. Import it as the `events` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { + array, + boolean, + integer, + json, + nullable, + parameters, + record, + string, + union, +} from '../../../core/schema.ts'; +import { + Attendee, + EventMetadata, + EventsChangeType, + EventsStrict, + Guest, + History, + PlaceCalendarEvent, + PlaceCalendarEventAttendee, +} from '../schemas.ts'; + +/** + * Add an attendee to an event. + * + * `POST /api/staff/v1/events/{id}/attendee` + */ +export function addAttendee( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(ADD_ATTENDEE, input, options); +} + +const ADD_ATTENDEE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/attendee', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** + * the room (system) id the event is booked in, its resource calendar is searched when + * `calendar` isn't provided + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the calendar the event id belongs to */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * (office365 only) when true, existing attendees are also emailed about the change, + * otherwise + * only the new attendee is notified + */ + notify_existing_attendees: /* @__PURE__ */ boolean(), + }, + ['id'], + ), + body: PlaceCalendarEventAttendee, + response: /* @__PURE__ */ union([PlaceCalendarEventAttendee, Attendee]), + name: 'staff.events.addAttendee', +}); + +/** + * Accept a meeting on behalf of a room. + * + * `POST /api/staff/v1/events/{id}/approve` + */ +export function approve( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(APPROVE, input, options); +} + +const APPROVE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/approve', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id on the room's resource calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) accepting the meeting */ + system_id: /* @__PURE__ */ string(), + }, + ['id', 'system_id'], + ), + body: null, + response: /* @__PURE__ */ boolean(), + name: 'staff.events.approve', +}); + +/** + * Accept every meeting in a time period on behalf of the selected rooms. + * + * `POST /api/staff/v1/events/approve_all` + */ +export function approveAll( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(APPROVE_ALL, input, options); +} + +const APPROVE_ALL = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/approve_all', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** period end as a unix epoch in seconds */ + period_end: /* @__PURE__ */ integer(), + /** + * comma separated resource calendar emails; only those resolving to a room (system) are + * approved + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * comma separated list of zone ids, approves events for every room (system) in these + * zones + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** comma separated list of room (system) ids to approve events for */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only approve the event with this ical uid */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'staff.events.approveAll', +}); + +/** + * Book a meeting in the user's calendar, optionally in a room (system). + * + * `POST /api/staff/v1/events/book` + */ +export function book( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BOOK, input, options); +} + +const BOOK = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/book', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** the meeting title */ + title: /* @__PURE__ */ string(), + /** start as a unix epoch in seconds */ + event_start: /* @__PURE__ */ integer(), + /** end as a unix epoch in seconds */ + event_end: /* @__PURE__ */ integer(), + /** comma separated attendee emails, the user is added as the host */ + attendees: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** the room (system) id to book */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the meeting's IANA timezone, defaults to the room's */ + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the meeting description */ + body_text: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['title', 'event_start', 'event_end'], + ), + body: null, + response: PlaceCalendarEvent, + name: 'staff.events.book', + wireNames: { body_text: 'body' }, +}); + +/** + * List the rooms already booked during an event's time range. + * + * `POST /api/staff/v1/events/clashing-assets` + */ +export function clashingAssets( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CLASHING_ASSETS, input, options); +} + +const CLASHING_ASSETS = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/clashing-assets', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * return the system if it is available instead of clashes, requires `system_id` on the + * event, + * defaults to false + */ + return_available: /* @__PURE__ */ boolean(), + /** + * return the start and end time of each clash, can't be combined with `return_available`, + * defaults to false + */ + include_clash_time: /* @__PURE__ */ boolean(), + }), + body: PlaceCalendarEvent, + response: /* @__PURE__ */ array(/* @__PURE__ */ json()), + name: 'staff.events.clashingAssets', +}); + +/** + * Create a calendar event. + * + * `POST /api/staff/v1/events` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: PlaceCalendarEvent, + response: PlaceCalendarEvent, + name: 'staff.events.create', +}); + +/** + * Decline (cancel) a calendar event, leaving it on the calendar. + * + * `POST /api/staff/v1/events/{id}/decline` + */ +export function decline( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DECLINE, input, options); +} + +const DECLINE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/decline', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** + * the room (system) id the event is booked in, its resource calendar is searched when + * `calendar` isn't provided + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * calendar the event is on, defaults to the current user's calendar; the user needs + * write + * access to it + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set to `false` to prevent attendees being notified, defaults to true */ + notify: /* @__PURE__ */ boolean(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.events.decline', +}); + +/** + * Remove an attendee from an event. + * + * `DELETE /api/staff/v1/events/{id}/attendee/{email}` + */ +export function deleteAttendee( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DELETE_ATTENDEE, input, options); +} + +const DELETE_ATTENDEE = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/events/{id}/attendee/{email}', + pathKeys: ['id', 'email'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** the email of the attendee to delete */ + email: /* @__PURE__ */ string(), + /** + * the room (system) id the event is booked in, its resource calendar is searched when + * `calendar` isn't provided + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the calendar the event id belongs to */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'email'], + ), + body: null, + response: null, + name: 'staff.events.deleteAttendee', +}); + +/** + * Delete a calendar event. + * + * `DELETE /api/staff/v1/events/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/events/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** + * the room (system) id the event is booked in, its resource calendar is searched when + * `calendar` isn't provided + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * calendar the event is on, defaults to the current user's calendar; the user needs + * write + * access to it + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set to `false` to prevent attendees being notified, defaults to true */ + notify: /* @__PURE__ */ boolean(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.events.destroy', +}); + +/** + * Change a calendar event's title, times or attendees. + * + * `PATCH /api/staff/v1/events/{id}/edit` + */ +export function edit( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EDIT, input, options); +} + +const EDIT = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/events/{id}/edit', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** + * the room (system) id the event is booked in, its resource calendar is searched when + * `calendar` isn't provided + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** calendar the event is on, defaults to the user's calendar */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the new title */ + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the new start as a unix epoch in seconds */ + event_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** the new end as a unix epoch in seconds */ + event_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** comma separated attendee emails, replaces the people invited (rooms are kept) */ + attendees: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }, + ['id'], + ), + body: null, + response: PlaceCalendarEvent, + name: 'staff.events.edit', +}); + +/** + * Search event metadata by an extension data field. + * + * `GET /api/staff/v1/events/extension_metadata/{system_id}` + */ +export function extensionMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(EXTENSION_METADATA, input, options); +} + +const EXTENSION_METADATA = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/extension_metadata/{system_id}', + pathKeys: ['system_id'], + params: /* @__PURE__ */ parameters( + { + /** only return metadata for this room (system) */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the extension data field to match, used together with `value` */ + field_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the value `field_name` must have */ + value: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only events ending after this time, unix epoch in seconds */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** only events starting before this time, unix epoch in seconds */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** comma separated list of event ids, recurring master ids or ical uids to match */ + event_ref: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }, + ['system_id'], + ), + body: null, + response: /* @__PURE__ */ array(EventMetadata), + name: 'staff.events.extensionMetadata', +}); + +/** + * Search event metadata by an extension data field. + * + * `GET /api/staff/v1/events/extension_metadata` + */ +export function extensionMetadataWithoutSystemId( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(EXTENSION_METADATA_WITHOUT_SYSTEM_ID, input, options); +} + +const EXTENSION_METADATA_WITHOUT_SYSTEM_ID = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/extension_metadata', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return metadata for this room (system) */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the extension data field to match, used together with `value` */ + field_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the value `field_name` must have */ + value: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only events ending after this time, unix epoch in seconds */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** only events starting before this time, unix epoch in seconds */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** comma separated list of event ids, recurring master ids or ical uids to match */ + event_ref: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }), + body: null, + response: /* @__PURE__ */ array(EventMetadata), + name: 'staff.events.extensionMetadataWithoutSystemId', +}); + +/** + * Get the PlaceOS metadata of an event booked in a room. + * + * `GET /api/staff/v1/events/{id}/metadata/{system_id}` + */ +export function getMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GET_METADATA, input, options); +} + +const GET_METADATA = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/{id}/metadata/{system_id}', + pathKeys: ['id', 'system_id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, on the host's or the room's calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) id the event is booked in */ + system_id: /* @__PURE__ */ string(), + /** the event's ical uid, an alternative lookup for when the event id doesn't match */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'system_id'], + ), + body: null, + response: /* @__PURE__ */ json(), + name: 'staff.events.getMetadata', +}); + +/** + * Check a visitor in to, or out of, an event booked in a room. + * + * `POST /api/staff/v1/events/{id}/guests/{guest_id}/check_in` + */ +export function guestCheckin( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GUEST_CHECKIN, input, options); +} + +const GUEST_CHECKIN = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/guests/{guest_id}/check_in', + pathKeys: ['id', 'guest_id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** the email (or numeric id) of the guest to check in */ + guest_id: /* @__PURE__ */ string(), + /** the room (system) id the event is booked in, required except for guest tokens */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * calendar to look the event up on, defaults to the room's resource calendar; the user + * needs + * write access to it + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** `true` to check in (default), `false` to check out */ + state: /* @__PURE__ */ boolean(), + }, + ['id', 'guest_id'], + ), + body: null, + response: Guest, + name: 'staff.events.guestCheckin', +}); + +/** + * List the visitors expected at an event booked in a room. + * + * `GET /api/staff/v1/events/{id}/guests` + */ +export function guestList( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GUEST_LIST, input, options); +} + +const GUEST_LIST = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/{id}/guests', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id on the room's resource calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) id the event is booked in */ + system_id: /* @__PURE__ */ string(), + /** + * the event's ical uid, when provided the metadata is found without querying the + * calendar + */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'system_id'], + ), + body: null, + response: /* @__PURE__ */ array(Guest), + name: 'staff.events.guestList', +}); + +/** + * List the change history of events in a time period. + * + * `GET /api/staff/v1/events/history` + */ +export function history( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(HISTORY, input, options); +} + +const HISTORY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/history', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** period end as a unix epoch in seconds */ + period_end: /* @__PURE__ */ integer(), + /** + * comma separated list of resource calendar ids (email addresses) to filter by, prefer + * `system_ids` + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * comma separated list of zone ids, includes events for every room (system) in these + * zones + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** comma separated list of room (system) ids to filter by */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return history for the event with this ical uid */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(History), + name: 'staff.events.history', +}); + +/** + * Link the room's recurring master event id to its metadata. + * + * `POST /api/staff/v1/events/{id}/metadata/{system_id}/link/{ical_uid}` + */ +export function linkMasterMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(LINK_MASTER_METADATA, input, options); +} + +const LINK_MASTER_METADATA = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/metadata/{system_id}/link/{ical_uid}', + pathKeys: ['id', 'system_id', 'ical_uid'], + params: /* @__PURE__ */ parameters( + { + /** the event id to link */ + id: /* @__PURE__ */ string(), + /** the event space associated with this event */ + system_id: /* @__PURE__ */ string(), + /** the ical_uid of the event */ + ical_uid: /* @__PURE__ */ string(), + }, + ['id', 'system_id', 'ical_uid'], + ), + body: null, + response: null, + name: 'staff.events.linkMasterMetadata', +}); + +/** + * Notify that a room's calendar event was created, updated or deleted. + * + * `POST /api/staff/v1/events/notify/{change}/{system_id}/{event_id}` + */ +export function notifyChange( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(NOTIFY_CHANGE, input, options); +} + +const NOTIFY_CHANGE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/notify/{change}/{system_id}/{event_id}', + pathKeys: ['change', 'system_id', 'event_id'], + params: /* @__PURE__ */ parameters( + { + /** the type of change that has occured */ + change: EventsChangeType, + /** the event space associated with this event */ + system_id: /* @__PURE__ */ string(), + /** the event space associated with this event */ + event_id: /* @__PURE__ */ string(), + }, + ['change', 'system_id', 'event_id'], + ), + body: /* @__PURE__ */ nullable(PlaceCalendarEvent), + response: null, + name: 'staff.events.notifyChange', +}); + +/** + * Merge the keys in the request body into the PlaceOS metadata of an event booked in a room. + * + * `PATCH /api/staff/v1/events/{id}/metadata/{system_id}` + */ +export function patchMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(PATCH_METADATA, input, options); +} + +const PATCH_METADATA = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/events/{id}/metadata/{system_id}', + pathKeys: ['id', 'system_id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, on the host's or the room's calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) id the event is booked in */ + system_id: /* @__PURE__ */ string(), + /** + * calendar to look the event up on when metadata doesn't exist yet, defaults to the + * room's + * resource calendar + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the event's ical uid, an alternative lookup for when the event id doesn't match */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set the setup time stored against the event, before it starts */ + setup_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** set the breakdown time stored against the event, after it ends */ + breakdown_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** set the id of the calendar event blocking the room for setup */ + setup_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set the id of the calendar event blocking the room for breakdown */ + breakdown_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'system_id'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ json()), + response: /* @__PURE__ */ json(), + name: 'staff.events.patchMetadata', +}); + +/** + * List calendar events in a time period. + * + * `GET /api/staff/v1/events` + */ +export function query( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** period end as a unix epoch in seconds */ + period_end: /* @__PURE__ */ integer(), + /** + * comma separated list of calendar ids (email addresses) to list events from, prefer + * `system_ids` for room resource calendars + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * comma separated list of zone ids, events are listed for every room (system) in these + * zones + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * comma separated list of room (system) ids, events are listed from each room's + * resource + * calendar + */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** include cancelled events, defaults to false */ + include_cancelled: /* @__PURE__ */ boolean(), + /** only return events with this ical uid */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * optional advanced search filter in Microsoft Graph (Azure AD) OData filter syntax, + * passed to + * the calendar provider + */ + filter: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * how to respond to calendar errors: `notify` (default) returns 206 with + * X-Calendar-Errors + * headers, `limit` returns 429 if any calendar was rate limited, `all` returns 500 on + * any + * calendar error + */ + strict: EventsStrict, + }, + ['period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarEvent), + name: 'staff.events.query', +}); + +/** + * Decline a meeting on behalf of a room. + * + * `POST /api/staff/v1/events/{id}/reject` + */ +export function reject( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(REJECT, input, options); +} + +const REJECT = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/events/{id}/reject', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id on the room's resource calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) declining the meeting */ + system_id: /* @__PURE__ */ string(), + }, + ['id', 'system_id'], + ), + body: null, + response: /* @__PURE__ */ boolean(), + name: 'staff.events.reject', +}); + +/** + * Replace the PlaceOS metadata of an event booked in a room. + * + * `PUT /api/staff/v1/events/{id}/metadata/{system_id}` + */ +export function replaceMetadata( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(REPLACE_METADATA, input, options); +} + +const REPLACE_METADATA = /* @__PURE__ */ operation({ + method: 'PUT', + path: '/api/staff/v1/events/{id}/metadata/{system_id}', + pathKeys: ['id', 'system_id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, on the host's or the room's calendar */ + id: /* @__PURE__ */ string(), + /** the room (system) id the event is booked in */ + system_id: /* @__PURE__ */ string(), + /** + * calendar to look the event up on when metadata doesn't exist yet, defaults to the + * room's + * resource calendar + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** the event's ical uid, an alternative lookup for when the event id doesn't match */ + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set the setup time stored against the event, before it starts */ + setup_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** set the breakdown time stored against the event, after it ends */ + breakdown_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** set the id of the calendar event blocking the room for setup */ + setup_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** set the id of the calendar event blocking the room for breakdown */ + breakdown_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'system_id'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ json()), + response: /* @__PURE__ */ json(), + name: 'staff.events.replaceMetadata', +}); + +/** + * Get a single calendar event. + * + * `GET /api/staff/v1/events/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/events/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** room (system) id, looks the event up on the room's resource calendar */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** calendar to look the event up on, defaults to the current user's calendar */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], + ), + body: null, + response: PlaceCalendarEvent, + name: 'staff.events.show', +}); + +/** + * Update a calendar event with the changes in the request body and return the updated event. + * + * `PATCH /api/staff/v1/events/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/events/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the event id, as found on the calendar being searched */ + id: /* @__PURE__ */ string(), + /** + * the room (system) id the event is currently booked in, its resource calendar is + * searched when + * `calendar` isn't provided and its metadata is updated + */ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the calendar the event id belongs to, defaults to the current user's calendar; the + * user needs + * write access to it + */ + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * (office365 only) set to false when the only change is adding attendees, so that + * existing + * attendees aren't notified by email. Warning: while false, only the attendee changes + * are + * propagated to the provider - any other edits in the request body are ignored + */ + notify_existing_attendees: /* @__PURE__ */ boolean(), + }, + ['id'], + ), + body: PlaceCalendarEvent, + response: PlaceCalendarEvent, + name: 'staff.events.update', +}); diff --git a/v2/src/generated/staff/operations/groups.ts b/v2/src/generated/staff/operations/groups.ts new file mode 100644 index 000000000..b5ebf3faa --- /dev/null +++ b/v2/src/generated/staff/operations/groups.ts @@ -0,0 +1,96 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Groups` controller of the API. Import it as the `groups` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, nullable, parameters, string } from '../../../core/schema.ts'; +import { PlaceCalendarGroup, PlaceCalendarMember } from '../schemas.ts'; + +/** + * List the members of a directory group. + * + * `GET /api/staff/v1/groups/{id}/members` + */ +export function members( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MEMBERS, input, options); +} + +const MEMBERS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/groups/{id}/members', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the directory group id */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarMember), + name: 'staff.groups.members', +}); + +/** + * List the groups in the organisation directory. + * + * `GET /api/staff/v1/groups` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/groups', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** optional search query, matches groups whose display name starts with this text */ + q: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarGroup), + name: 'staff.groups.query', +}); + +/** + * Get a directory group. + * + * `GET /api/staff/v1/groups/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/groups/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the directory group id */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: PlaceCalendarGroup, + name: 'staff.groups.show', +}); diff --git a/v2/src/generated/staff/operations/guests.ts b/v2/src/generated/staff/operations/guests.ts new file mode 100644 index 000000000..3e24b72eb --- /dev/null +++ b/v2/src/generated/staff/operations/guests.ts @@ -0,0 +1,378 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Guests` controller of the API. Import it as the `guests` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { + array, + boolean, + integer, + json, + nullable, + parameters, + record, + string, + union, +} from '../../../core/schema.ts'; +import { Booking, Guest, GuestsChildren, PlaceCalendarEvent } from '../schemas.ts'; + +/** + * List the bookings a guest is attending. + * + * `GET /api/staff/v1/guests/{id}/bookings` + */ +export function bookings( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(BOOKINGS, input, options); +} + +const BOOKINGS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests/{id}/bookings', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** include bookings that have already finished, defaults to false */ + include_past: /* @__PURE__ */ boolean(), + /** maximum number of bookings to return, defaults to 10 */ + limit: /* @__PURE__ */ integer('Int32'), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(Booking), + name: 'staff.guests.bookings', +}); + +/** + * Get a visitor's catering selection. + * + * `GET /api/staff/v1/guests/{id}/catering` + */ +export function catering( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CATERING, input, options); +} + +const CATERING = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests/{id}/catering', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** + * the id of the visitor's booking, optional for guest access tokens which default to + * the + * booking the token was issued for, otherwise required + */ + booking_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ record(/* @__PURE__ */ json()), + name: 'staff.guests.catering', +}); + +/** + * Remove a visitor's catering selection. + * + * `DELETE /api/staff/v1/guests/{id}/catering` + */ +export function cateringDestroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CATERING_DESTROY, input, options); +} + +const CATERING_DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/guests/{id}/catering', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** + * the id of the visitor's booking, optional for guest access tokens which default to + * the + * booking the token was issued for, otherwise required + */ + booking_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.guests.cateringDestroy', +}); + +/** + * List the catering menus available to a visitor. + * + * `GET /api/staff/v1/guests/{id}/catering/menu` + */ +export function cateringMenu( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CATERING_MENU, input, options); +} + +const CATERING_MENU = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests/{id}/catering/menu', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** + * the id of the visitor's booking, optional for guest access tokens which default to + * the + * booking the token was issued for, otherwise required + */ + booking_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(GuestsChildren), + name: 'staff.guests.cateringMenu', +}); + +/** + * Set a visitor's catering selection. + * + * `PATCH /api/staff/v1/guests/{id}/catering` + */ +export function cateringUpdate( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CATERING_UPDATE, input, options); +} + +const CATERING_UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/guests/{id}/catering', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** + * the id of the visitor's booking, optional for guest access tokens which default to + * the + * booking the token was issued for, otherwise required + */ + booking_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ json()), + response: /* @__PURE__ */ record(/* @__PURE__ */ json()), + name: 'staff.guests.cateringUpdate', +}); + +/** + * Create a guest. + * + * `POST /api/staff/v1/guests` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/guests', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: Guest, + response: Guest, + name: 'staff.guests.create', +}); + +/** + * Delete a guest. + * + * `DELETE /api/staff/v1/guests/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/guests/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.guests.destroy', +}); + +/** + * List the meetings a guest is attending. + * + * `GET /api/staff/v1/guests/{id}/meetings` + */ +export function meetings( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MEETINGS, input, options); +} + +const MEETINGS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests/{id}/meetings', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + /** include events that have already finished, defaults to false */ + include_past: /* @__PURE__ */ boolean(), + /** maximum number of events to return, defaults to 10 */ + limit: /* @__PURE__ */ integer('Int32'), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarEvent), + name: 'staff.guests.meetings', +}); + +/** + * Search guests, or list the visitors expected in a time period. + * + * `GET /api/staff/v1/guests` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * space separated search query matching guest name, email etc, ignored when a period is + * provided + */ + q: /* @__PURE__ */ string(), + /** visit period start as a unix epoch in seconds, requires period_end */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** visit period end as a unix epoch in seconds, requires period_start */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * [deprecated] a comma separated list of calendar ids to search for events with visitors, + * prefer `system_ids` for room calendars + */ + calendars: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * [deprecated] a comma separated list of zone ids, filters bookings and selects the rooms + * whose + * events are searched + */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** [deprecated] a comma separated list of room system ids whose events are searched */ + system_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** a comma separated list of zone ids, only bookings in these zones are included */ + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }), + body: null, + response: /* @__PURE__ */ array(Guest), + name: 'staff.guests.query', +}); + +/** + * Get a guest, including any visit expected today. + * + * `GET /api/staff/v1/guests/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/guests/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + }, + ['id'], + ), + body: null, + response: Guest, + name: 'staff.guests.show', +}); + +/** + * Update a guest with the fields in the request body and return the saved guest. + * + * `PATCH /api/staff/v1/guests/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/guests/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** looks up a guest using either their id or email */ + id: /* @__PURE__ */ union([/* @__PURE__ */ integer(), /* @__PURE__ */ string()]), + }, + ['id'], + ), + body: Guest, + response: Guest, + name: 'staff.guests.update', +}); diff --git a/v2/src/generated/staff/operations/health-check.ts b/v2/src/generated/staff/operations/health-check.ts new file mode 100644 index 000000000..207566eeb --- /dev/null +++ b/v2/src/generated/staff/operations/health-check.ts @@ -0,0 +1,37 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `HealthCheck` controller of the API. Import it as the `healthCheck` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { parameters } from '../../../core/schema.ts'; +import { HealthCheckBuildInfo } from '../schemas.ts'; + +/** + * Get the service build details. + * + * `GET /api/staff/v1` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: HealthCheckBuildInfo, + name: 'staff.healthCheck.query', +}); diff --git a/v2/src/generated/staff/operations/index.ts b/v2/src/generated/staff/operations/index.ts new file mode 100644 index 000000000..0de6e537e --- /dev/null +++ b/v2/src/generated/staff/operations/index.ts @@ -0,0 +1,24 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. + +/** One namespace for each controller of the API. */ +export * as assetCategories from './asset-categories.ts'; +export * as assetPurchaseOrders from './asset-purchase-orders.ts'; +export * as assetTypes from './asset-types.ts'; +export * as assets from './assets.ts'; +export * as bookings from './bookings.ts'; +export * as calendars from './calendars.ts'; +export * as desks from './desks.ts'; +export * as events from './events.ts'; +export * as groups from './groups.ts'; +export * as guests from './guests.ts'; +export * as healthCheck from './health-check.ts'; +export * as place from './place.ts'; +export * as spaces from './spaces.ts'; +export * as staff from './staff.ts'; +export * as surveys from './surveys.ts'; +export * as surveysAnswers from './surveys-answers.ts'; +export * as surveysInvitations from './surveys-invitations.ts'; +export * as surveysQuestions from './surveys-questions.ts'; +export * as teams from './teams.ts'; +export * as tenants from './tenants.ts'; +export * as users from './users.ts'; diff --git a/v2/src/generated/staff/operations/place.ts b/v2/src/generated/staff/operations/place.ts new file mode 100644 index 000000000..60f90923f --- /dev/null +++ b/v2/src/generated/staff/operations/place.ts @@ -0,0 +1,52 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Place` controller of the API. Import it as the `place` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { Office365Room } from '../schemas.ts'; + +/** + * List the rooms in the Office365 directory. + * + * `GET /api/staff/v1/place` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/place', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * optional comma separated list of room properties to return (maps to the graph `$select` + * parameter) + */ + match: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** optional filter using Azure AD filter syntax (maps to the graph `$filter` parameter) */ + filter: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * optional maximum number of rooms to return (maps to the graph `$top` parameter, graph + * defaults to 100) + */ + top: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** optional number of rooms to skip, for paging (maps to the graph `$skip` parameter) */ + skip: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + }), + body: null, + response: /* @__PURE__ */ array(Office365Room), + name: 'staff.place.query', +}); diff --git a/v2/src/generated/staff/operations/spaces.ts b/v2/src/generated/staff/operations/spaces.ts new file mode 100644 index 000000000..2aa3da360 --- /dev/null +++ b/v2/src/generated/staff/operations/spaces.ts @@ -0,0 +1,242 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Spaces` controller of the API. Import it as the `spaces` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { SpacesFreeSpaces, SpacesSpace, SpacesSpaceSchedule, SpacesSpaceZone } from '../schemas.ts'; + +/** + * List the unique features of the bookable spaces, i.e. whiteboard or vidconf. + * + * `GET /api/staff/v1/spaces/features` + */ +export function features( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(FEATURES, input, options); +} + +const FEATURES = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/features', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** comma separated zone ids, only features of spaces in every zone */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }), + body: null, + response: /* @__PURE__ */ array(/* @__PURE__ */ string()), + name: 'staff.spaces.features', +}); + +/** + * Find the rooms in a building or level that are free for a whole meeting. + * + * `GET /api/staff/v1/spaces/free` + */ +export function free( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(FREE, input, options); +} + +const FREE = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/free', + pathKeys: [], + params: /* @__PURE__ */ parameters( + { + /** meeting start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** meeting end as a unix epoch in seconds, at most a day after the start */ + period_end: /* @__PURE__ */ integer(), + /** the building or level to look in, defaults to the only building */ + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** minimum number of people the room seats */ + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + }, + ['period_start', 'period_end'], + ), + body: null, + response: SpacesFreeSpaces, + name: 'staff.spaces.free', +}); + +/** + * Get one of the space's images. + * + * `GET /api/staff/v1/spaces/{id}/images/{index}` + */ +export function image( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(IMAGE, input, options); +} + +const IMAGE = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/{id}/images/{index}', + pathKeys: ['id', 'index'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + /** the image's position in the space's images, from 0 */ + index: /* @__PURE__ */ integer('Int32'), + }, + ['id', 'index'], + ), + body: null, + response: null, + name: 'staff.spaces.image', +}); + +/** + * Get the space's level map, an SVG, with the space's position in the X-Map-Pin header. + * + * `GET /api/staff/v1/spaces/{id}/map` + */ +export function map( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MAP, input, options); +} + +const MAP = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/{id}/map', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.spaces.map', +}); + +/** + * List the bookable spaces (rooms), filtered by zones, features and capacity. + * + * `GET /api/staff/v1/spaces` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** comma separated zone ids, spaces must be in every zone, i.e. a building and a level */ + zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** comma separated features, spaces must have every feature */ + features: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** minimum number of people the space seats */ + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** + * filters results by the given text: a record matches when any word matches its searchable + * fields as a whole word, and the last word also matches as a prefix (search as you type) + */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + /** deprecated, ignored — pagination follows the `Link` header's offset */ + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** deprecated, ignored — search covers the resource's indexed fields */ + fields: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(SpacesSpace), + name: 'staff.spaces.query', +}); + +/** + * Show a space and its meetings, defaulting to today, with a card for booking it. + * + * `GET /api/staff/v1/spaces/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ string(), + /** + * period start as a unix epoch in seconds, defaults to the start of today in the + * space's + * timezone + */ + period_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * period end as a unix epoch in seconds, defaults to the end of the period start's day + */ + period_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }, + ['id'], + ), + body: null, + response: SpacesSpaceSchedule, + name: 'staff.spaces.show', +}); + +/** + * List the zones (campuses, buildings, levels and areas) that spaces are in. + * + * `GET /api/staff/v1/spaces/zones` + */ +export function zones( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(ZONES, input, options); +} + +const ZONES = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/spaces/zones', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** comma separated tags, zones must have every tag, i.e. building or level */ + tags: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** only the child zones of this zone, i.e. the levels of a building */ + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** filters zones by name, the last word matches as a prefix */ + q: /* @__PURE__ */ string(), + /** the maximum number of results to return */ + limit: /* @__PURE__ */ integer('UInt32'), + /** the starting offset of the result set, used to implement pagination */ + offset: /* @__PURE__ */ integer('UInt32'), + }), + body: null, + response: /* @__PURE__ */ array(SpacesSpaceZone), + name: 'staff.spaces.zones', +}); diff --git a/v2/src/generated/staff/operations/staff.ts b/v2/src/generated/staff/operations/staff.ts new file mode 100644 index 000000000..2e604ca11 --- /dev/null +++ b/v2/src/generated/staff/operations/staff.ts @@ -0,0 +1,237 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Staff` controller of the API. Import it as the `staff` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { + PlaceCalendarCalendar, + PlaceCalendarGroup, + PlaceCalendarUser, + StaffBusy, +} from '../schemas.ts'; + +/** + * List a person's calendars. + * + * `GET /api/staff/v1/people/{id}/calendars` + */ +export function calendars( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CALENDARS, input, options); +} + +const CALENDARS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}/calendars', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the user's email address */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarCalendar), + name: 'staff.staff.calendars', +}); + +/** + * Get the busy times of a person and the signed in user, for picking a meeting time. + * + * `GET /api/staff/v1/people/{id}/free_busy` + */ +export function freeBusy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(FREE_BUSY, input, options); +} + +const FREE_BUSY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}/free_busy', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the person's email address */ + id: /* @__PURE__ */ string(), + /** period start as a unix epoch in seconds */ + period_start: /* @__PURE__ */ integer(), + /** period end as a unix epoch in seconds, at most a week after the start */ + period_end: /* @__PURE__ */ integer(), + }, + ['id', 'period_start', 'period_end'], + ), + body: null, + response: /* @__PURE__ */ array(StaffBusy), + name: 'staff.staff.freeBusy', +}); + +/** + * List the directory groups a person is a member of. + * + * `GET /api/staff/v1/people/{id}/groups` + */ +export function groups( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(GROUPS, input, options); +} + +const GROUPS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}/groups', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** a user id OR user email address */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarGroup), + name: 'staff.staff.groups', +}); + +/** + * Get a person's manager. + * + * `GET /api/staff/v1/people/{id}/manager` + */ +export function manager( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(MANAGER, input, options); +} + +const MANAGER = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}/manager', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** a user id OR user email address */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: PlaceCalendarUser, + name: 'staff.staff.manager', +}); + +/** + * Get a person's photo. + * + * `GET /api/staff/v1/people/{id}/photo` + */ +export function photo( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(PHOTO, input, options); +} + +const PHOTO = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}/photo', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** a user id OR user email address */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.staff.photo', +}); + +/** + * Search the organisation directory for people. + * + * `GET /api/staff/v1/people` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** + * An optional search query to filter users by name or email. If both 'q' and 'filter' + * parameters are provided, 'filter' takes precedence. + */ + q: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * An optional advanced search filter using Azure AD filter syntax. Provides more control + * over + * the search criteria and takes precedence over the 'q' parameter. Supports both Azure AD + * and + * Google providers. + */ + filter: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * the next page of results, a google page token or graph api URI. Normally taken from the + * `Link` header of the previous response + */ + next_page: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** a comma separated list of additional user fields to return (Office365 only) */ + additional_fields: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(/* @__PURE__ */ string()), + ), + }), + body: null, + response: /* @__PURE__ */ array(PlaceCalendarUser), + name: 'staff.staff.query', +}); + +/** + * Get a person from the directory. + * + * `GET /api/staff/v1/people/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/people/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** a user id OR user email address */ + id: /* @__PURE__ */ string(), + }, + ['id'], + ), + body: null, + response: PlaceCalendarUser, + name: 'staff.staff.show', +}); diff --git a/v2/src/generated/staff/operations/surveys-answers.ts b/v2/src/generated/staff/operations/surveys-answers.ts new file mode 100644 index 000000000..1b131eadc --- /dev/null +++ b/v2/src/generated/staff/operations/surveys-answers.ts @@ -0,0 +1,74 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Surveys::Answers` controller of the API. Import it as the `surveysAnswers` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters } from '../../../core/schema.ts'; +import { SurveyAnswer } from '../schemas.ts'; + +/** + * Submit a response to a survey, as a set of answers. + * + * `POST /api/staff/v1/surveys/answers` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/surveys/answers', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: /* @__PURE__ */ array(SurveyAnswer), + response: /* @__PURE__ */ array(SurveyAnswer), + name: 'staff.surveysAnswers.create', +}); + +/** + * List survey answers. + * + * `GET /api/staff/v1/surveys/answers` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/answers', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return answers submitted for this survey id */ + survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * only return answers created at or after this time, as a unix timestamp in seconds + * (defaults + * to 0) + */ + created_after: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * only return answers created at or before this time, as a unix timestamp in seconds + * (defaults + * to now) + */ + created_before: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + }), + body: null, + response: /* @__PURE__ */ array(SurveyAnswer), + name: 'staff.surveysAnswers.query', +}); diff --git a/v2/src/generated/staff/operations/surveys-invitations.ts b/v2/src/generated/staff/operations/surveys-invitations.ts new file mode 100644 index 000000000..df40b9f8d --- /dev/null +++ b/v2/src/generated/staff/operations/surveys-invitations.ts @@ -0,0 +1,151 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Surveys::Invitations` controller of the API. Import it as the `surveysInvitations` + * namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, boolean, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { SurveyInvitation } from '../schemas.ts'; + +/** + * Invite an email address to respond to a survey. + * + * `POST /api/staff/v1/surveys/invitations` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/surveys/invitations', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: SurveyInvitation, + response: SurveyInvitation, + name: 'staff.surveysInvitations.create', +}); + +/** + * Delete a survey invitation. + * + * `DELETE /api/staff/v1/surveys/invitations/{token}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/surveys/invitations/{token}', + pathKeys: ['token'], + params: /* @__PURE__ */ parameters( + { + /** the unique invitation token (a ULID) */ + token: /* @__PURE__ */ string(), + }, + ['token'], + ), + body: null, + response: null, + name: 'staff.surveysInvitations.destroy', +}); + +/** + * List survey invitations. + * + * `GET /api/staff/v1/surveys/invitations` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/invitations', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return invitations for this survey id */ + survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * true returns only invitations marked as sent, false returns those not yet sent (including + * unset); omit for all + */ + sent: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }), + body: null, + response: /* @__PURE__ */ array(SurveyInvitation), + name: 'staff.surveysInvitations.query', +}); + +/** + * Get a survey invitation by its token. + * + * `GET /api/staff/v1/surveys/invitations/{token}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/invitations/{token}', + pathKeys: ['token'], + params: /* @__PURE__ */ parameters( + { + /** the unique invitation token (a ULID) */ + token: /* @__PURE__ */ string(), + }, + ['token'], + ), + body: null, + response: SurveyInvitation, + name: 'staff.surveysInvitations.show', +}); + +/** + * Update a survey invitation. + * + * `PATCH /api/staff/v1/surveys/invitations/{token}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/surveys/invitations/{token}', + pathKeys: ['token'], + params: /* @__PURE__ */ parameters( + { + token: /* @__PURE__ */ string(), + }, + ['token'], + ), + body: SurveyInvitation, + response: SurveyInvitation, + name: 'staff.surveysInvitations.update', +}); diff --git a/v2/src/generated/staff/operations/surveys-questions.ts b/v2/src/generated/staff/operations/surveys-questions.ts new file mode 100644 index 000000000..c26e2925c --- /dev/null +++ b/v2/src/generated/staff/operations/surveys-questions.ts @@ -0,0 +1,156 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Surveys::Questions` controller of the API. Import it as the `surveysQuestions` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, boolean, integer, nullable, parameters } from '../../../core/schema.ts'; +import { SurveyQuestion } from '../schemas.ts'; + +/** + * Create a survey question. + * + * `POST /api/staff/v1/surveys/questions` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/surveys/questions', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: SurveyQuestion, + response: SurveyQuestion, + name: 'staff.surveysQuestions.create', +}); + +/** + * Delete a survey question. + * + * `DELETE /api/staff/v1/surveys/questions/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/surveys/questions/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.surveysQuestions.destroy', +}); + +/** + * List survey questions. + * + * `GET /api/staff/v1/surveys/questions` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/questions', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return questions referenced by this survey's pages */ + survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** + * true returns only soft-deleted (superseded or retired) questions, false only active ones; + * omit for all + */ + deleted: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }), + body: null, + response: /* @__PURE__ */ array(SurveyQuestion), + name: 'staff.surveysQuestions.query', +}); + +/** + * Get a survey question. + * + * `GET /api/staff/v1/surveys/questions/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/questions/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the numeric id of the question */ + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: SurveyQuestion, + name: 'staff.surveysQuestions.show', +}); + +/** + * Update a survey question and return it; changing an answered question creates a new version with + * a new id. + * + * `PATCH /api/staff/v1/surveys/questions/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/surveys/questions/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + /** + * when a new version is created, move the answers of the previous version to it. + * Defaults to + * false: answers stay with the version they answered + */ + migrate_answers: /* @__PURE__ */ boolean(), + }, + ['id'], + ), + body: SurveyQuestion, + response: SurveyQuestion, + name: 'staff.surveysQuestions.update', +}); diff --git a/v2/src/generated/staff/operations/surveys.ts b/v2/src/generated/staff/operations/surveys.ts new file mode 100644 index 000000000..d3af6afdd --- /dev/null +++ b/v2/src/generated/staff/operations/surveys.ts @@ -0,0 +1,146 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Surveys` controller of the API. Import it as the `surveys` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { Survey } from '../schemas.ts'; + +/** + * Create a survey. + * + * `POST /api/staff/v1/surveys` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/surveys', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: Survey, + response: Survey, + name: 'staff.surveys.create', +}); + +/** + * Delete a survey. + * + * `DELETE /api/staff/v1/surveys/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/surveys/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.surveys.destroy', +}); + +/** + * List surveys. + * + * `GET /api/staff/v1/surveys` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys', + pathKeys: [], + params: /* @__PURE__ */ parameters({ + /** only return surveys whose zone_id matches this zone id exactly */ + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** only return surveys whose building_id matches this building zone id exactly */ + building_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }), + body: null, + response: /* @__PURE__ */ array(Survey), + name: 'staff.surveys.query', +}); + +/** + * Get a survey. + * + * `GET /api/staff/v1/surveys/{id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/surveys/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + /** the numeric id of the survey */ + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: Survey, + name: 'staff.surveys.show', +}); + +/** + * Update a survey with the fields in the request body and return the saved survey. + * + * `PATCH /api/staff/v1/surveys/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/surveys/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: Survey, + response: Survey, + name: 'staff.surveys.update', +}); diff --git a/v2/src/generated/staff/operations/teams.ts b/v2/src/generated/staff/operations/teams.ts new file mode 100644 index 000000000..008ece5ed --- /dev/null +++ b/v2/src/generated/staff/operations/teams.ts @@ -0,0 +1,111 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Teams` controller of the API. Import it as the `teams` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { integer, nullable, parameters, string } from '../../../core/schema.ts'; +import { Office365ChatMessage, Office365ChatMessageList } from '../schemas.ts'; + +/** + * List the messages in a Teams channel. + * + * `GET /api/staff/v1/teams/{teams_id}/{channel_id}` + */ +export function query( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/teams/{teams_id}/{channel_id}', + pathKeys: ['teams_id', 'channel_id'], + params: /* @__PURE__ */ parameters( + { + /** the Microsoft Teams team id */ + teams_id: /* @__PURE__ */ string(), + /** the channel id within the team */ + channel_id: /* @__PURE__ */ string(), + /** optional number of channel messages to return, graph defaults to 20 */ + top: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + }, + ['teams_id', 'channel_id'], + ), + body: null, + response: Office365ChatMessageList, + name: 'staff.teams.query', +}); + +/** + * Post a message to a Teams channel. + * + * `POST /api/staff/v1/teams/{teams_id}/{channel_id}` + */ +export function sendChannelMessage( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SEND_CHANNEL_MESSAGE, input, options); +} + +const SEND_CHANNEL_MESSAGE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/teams/{teams_id}/{channel_id}', + pathKeys: ['teams_id', 'channel_id'], + params: /* @__PURE__ */ parameters( + { + /** the Microsoft Teams team id */ + teams_id: /* @__PURE__ */ string(), + /** the channel id within the team */ + channel_id: /* @__PURE__ */ string(), + /** the message content type, TEXT (default) or HTML */ + type: /* @__PURE__ */ string(), + }, + ['teams_id', 'channel_id'], + ), + body: /* @__PURE__ */ string(), + response: null, + name: 'staff.teams.sendChannelMessage', +}); + +/** + * Get a message from a Teams channel. + * + * `GET /api/staff/v1/teams/{teams_id}/{channel_id}/{message_id}` + */ +export function show( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW, input, options); +} + +const SHOW = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/teams/{teams_id}/{channel_id}/{message_id}', + pathKeys: ['teams_id', 'channel_id', 'message_id'], + params: /* @__PURE__ */ parameters( + { + /** the Microsoft Teams team id */ + teams_id: /* @__PURE__ */ string(), + /** the channel id within the team */ + channel_id: /* @__PURE__ */ string(), + /** the id of the channel message */ + message_id: /* @__PURE__ */ string(), + }, + ['teams_id', 'channel_id', 'message_id'], + ), + body: null, + response: Office365ChatMessage, + name: 'staff.teams.show', +}); diff --git a/v2/src/generated/staff/operations/tenants.ts b/v2/src/generated/staff/operations/tenants.ts new file mode 100644 index 000000000..b237ea8ed --- /dev/null +++ b/v2/src/generated/staff/operations/tenants.ts @@ -0,0 +1,265 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Tenants` controller of the API. Import it as the `tenants` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { array, integer, parameters, record } from '../../../core/schema.ts'; +import { Int64, TenantResponder } from '../schemas.ts'; + +/** + * Create a tenant. + * + * `POST /api/staff/v1/tenants` + */ +export function create( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(CREATE, input, options); +} + +const CREATE = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/tenants', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: TenantResponder, + response: TenantResponder, + name: 'staff.tenants.create', +}); + +/** + * Get the early check-in window of the current tenant. + * + * `GET /api/staff/v1/tenants/current_early_checkin` + */ +export function currentEarlyCheckin( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CURRENT_EARLY_CHECKIN, input, options); +} + +const CURRENT_EARLY_CHECKIN = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/tenants/current_early_checkin', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: Int64, + name: 'staff.tenants.currentEarlyCheckin', +}); + +/** + * Get the booking limits of the current tenant. + * + * `GET /api/staff/v1/tenants/current_limits` + */ +export function currentLimits( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CURRENT_LIMITS, input, options); +} + +const CURRENT_LIMITS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/tenants/current_limits', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + name: 'staff.tenants.currentLimits', +}); + +/** + * Delete a tenant. + * + * `DELETE /api/staff/v1/tenants/{id}` + */ +export function destroy( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(DESTROY, input, options); +} + +const DESTROY = /* @__PURE__ */ operation({ + method: 'DELETE', + path: '/api/staff/v1/tenants/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: null, + name: 'staff.tenants.destroy', +}); + +/** + * List the tenants. + * + * `GET /api/staff/v1/tenants` + */ +export function query( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(QUERY, input, options); +} + +const QUERY = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/tenants', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: /* @__PURE__ */ array(TenantResponder), + name: 'staff.tenants.query', +}); + +/** + * Get the early check-in window of a tenant. + * + * `GET /api/staff/v1/tenants/{id}/early_checkin` + */ +export function showEarlyCheckin( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW_EARLY_CHECKIN, input, options); +} + +const SHOW_EARLY_CHECKIN = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/tenants/{id}/early_checkin', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: Int64, + name: 'staff.tenants.showEarlyCheckin', +}); + +/** + * Get the booking limits of a tenant. + * + * `GET /api/staff/v1/tenants/{id}/limits` + */ +export function showLimits( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(SHOW_LIMITS, input, options); +} + +const SHOW_LIMITS = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/tenants/{id}/limits', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: null, + response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + name: 'staff.tenants.showLimits', +}); + +/** + * Update a tenant with the fields in the request body and return the saved tenant. + * + * `PATCH /api/staff/v1/tenants/{id}` + */ +export function update( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE, input, options); +} + +const UPDATE = /* @__PURE__ */ operation({ + method: 'PATCH', + path: '/api/staff/v1/tenants/{id}', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: TenantResponder, + response: TenantResponder, + name: 'staff.tenants.update', +}); + +/** + * Set the early check-in window of a tenant. + * + * `POST /api/staff/v1/tenants/{id}/early_checkin` + */ +export function updateEarlyCheckin( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_EARLY_CHECKIN, input, options); +} + +const UPDATE_EARLY_CHECKIN = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/tenants/{id}/early_checkin', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: Int64, + response: Int64, + name: 'staff.tenants.updateEarlyCheckin', +}); + +/** + * Set the booking limits of a tenant. + * + * `POST /api/staff/v1/tenants/{id}/limits` + */ +export function updateLimits( + input: OperationInput, + options?: CallOptions, +): Promise> { + return call(UPDATE_LIMITS, input, options); +} + +const UPDATE_LIMITS = /* @__PURE__ */ operation({ + method: 'POST', + path: '/api/staff/v1/tenants/{id}/limits', + pathKeys: ['id'], + params: /* @__PURE__ */ parameters( + { + id: /* @__PURE__ */ integer(), + }, + ['id'], + ), + body: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), + name: 'staff.tenants.updateLimits', +}); diff --git a/v2/src/generated/staff/operations/users.ts b/v2/src/generated/staff/operations/users.ts new file mode 100644 index 000000000..7686877e6 --- /dev/null +++ b/v2/src/generated/staff/operations/users.ts @@ -0,0 +1,37 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +/** + * The `Users` controller of the API. Import it as the `users` namespace. + * + * @module + */ +import { + call, + operation, + type CallOptions, + type CallResult, + type OperationInput, +} from '../../../core/client.ts'; +import { parameters } from '../../../core/schema.ts'; +import { UserAdminResponse } from '../schemas.ts'; + +/** + * Get the signed in user's profile. + * + * `GET /api/staff/v1/users/current` + */ +export function current( + input: OperationInput = {}, + options?: CallOptions, +): Promise> { + return call(CURRENT, input, options); +} + +const CURRENT = /* @__PURE__ */ operation({ + method: 'GET', + path: '/api/staff/v1/users/current', + pathKeys: [], + params: /* @__PURE__ */ parameters({}), + body: null, + response: UserAdminResponse, + name: 'staff.users.current', +}); diff --git a/v2/src/generated/staff/schemas.ts b/v2/src/generated/staff/schemas.ts new file mode 100644 index 000000000..a55271b5d --- /dev/null +++ b/v2/src/generated/staff/schemas.ts @@ -0,0 +1,1660 @@ +// Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. +import { + type Input, + type Output, + type Schema, + array, + boolean, + integer, + json, + literal, + nullable, + number, + object, + record, + string, + union, +} from '../../core/schema.ts'; + +const AssetSchema = /* @__PURE__ */ object({ + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + identifier: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + serial_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + other_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + barcode: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + client_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + accessible: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + place_groups: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + assigned_to: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + assigned_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + features: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + notes: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + security_system_groups: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(/* @__PURE__ */ string()), + ), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + asset_type_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + purchase_order_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface Asset extends Output {} +export interface AssetInput extends Input {} +export const Asset: Schema = AssetSchema; + +const AssetCategorySchema = /* @__PURE__ */ object({ + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + hidden: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + parent_category_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface AssetCategory extends Output {} +export interface AssetCategoryInput extends Input {} +export const AssetCategory: Schema = AssetCategorySchema; + +const AssetPurchaseOrderSchema = /* @__PURE__ */ object({ + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + purchase_order_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + invoice_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + supplier_details: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + purchase_date: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + unit_price: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + expected_service_start_date: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + expected_service_end_date: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface AssetPurchaseOrder extends Output {} +export interface AssetPurchaseOrderInput extends Input {} +export const AssetPurchaseOrder: Schema = + AssetPurchaseOrderSchema; + +const AssetTypeSchema = /* @__PURE__ */ object({ + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + brand: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + model_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + category_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface AssetType extends Output {} +export interface AssetTypeInput extends Input {} +export const AssetType: Schema = AssetTypeSchema; + +const PlaylistOrientationSchema = /* @__PURE__ */ literal([ + 'unspecified', + 'landscape', + 'portrait', + 'square', +]); +export type PlaylistOrientation = Output; +export type PlaylistOrientationInput = Input; +export const PlaylistOrientation: Schema = + PlaylistOrientationSchema; + +const ControlSystemSchema = /* @__PURE__ */ object( + { + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + features: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + public: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + display_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + code: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + approval: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + security_groups: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + support_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + timetable_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + camera_snapshot_urls: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(/* @__PURE__ */ string()), + ), + camera_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + room_booking_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + version: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + installed_ui_devices: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + modules: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + orientation: /* @__PURE__ */ nullable(PlaylistOrientation), + sign_height: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + sign_width: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + playlists: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + signage: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + /** Unix time in seconds. */ + signage_last_seen: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + playlist_item_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + space_config: /* @__PURE__ */ nullable(/* @__PURE__ */ record(/* @__PURE__ */ json())), + remove_zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + add_zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + update_triggers: /* @__PURE__ */ boolean(), + }, + ['update_triggers'], +); +export interface ControlSystem extends Output {} +export interface ControlSystemInput extends Input {} +export const ControlSystem: Schema = ControlSystemSchema; + +const EventMetadataPermissionSchema = /* @__PURE__ */ literal(['private', 'open', 'public']); +export type EventMetadataPermission = Output; +export type EventMetadataPermissionInput = Input; +export const EventMetadataPermission: Schema< + EventMetadataPermission, + EventMetadataPermissionInput +> = EventMetadataPermissionSchema; + +const PlaceCalendarAttachmentSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + name: /* @__PURE__ */ string(), + content_type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + content_bytes: /* @__PURE__ */ string(), + size: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + }, + ['name', 'content_bytes'], +); +export interface PlaceCalendarAttachment extends Output {} +export interface PlaceCalendarAttachmentInput extends Input {} +export const PlaceCalendarAttachment: Schema< + PlaceCalendarAttachment, + PlaceCalendarAttachmentInput +> = PlaceCalendarAttachmentSchema; + +const PlaceCalendarEventAttendeeSchema = /* @__PURE__ */ object( + { + name: /* @__PURE__ */ string(), + email: /* @__PURE__ */ string(), + response_status: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + resource: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + organizer: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + visit_expected: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + preferred_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + organisation: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + photo: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + notes: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + banned: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + dangerous: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }, + ['name', 'email'], +); +export interface PlaceCalendarEventAttendee extends Output< + typeof PlaceCalendarEventAttendeeSchema +> {} +export interface PlaceCalendarEventAttendeeInput extends Input< + typeof PlaceCalendarEventAttendeeSchema +> {} +export const PlaceCalendarEventAttendee: Schema< + PlaceCalendarEventAttendee, + PlaceCalendarEventAttendeeInput +> = PlaceCalendarEventAttendeeSchema; + +const PlaceCalendarEventSystemSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + }, + ['id'], +); +export interface PlaceCalendarEventSystem extends Output {} +export interface PlaceCalendarEventSystemInput extends Input< + typeof PlaceCalendarEventSystemSchema +> {} +export const PlaceCalendarEventSystem: Schema< + PlaceCalendarEventSystem, + PlaceCalendarEventSystemInput +> = PlaceCalendarEventSystemSchema; + +const PlaceCalendarEventVisibilitySchema = /* @__PURE__ */ literal([ + 'normal', + 'personal', + 'public', + 'private', + 'confidential', +]); +export type PlaceCalendarEventVisibility = Output; +export type PlaceCalendarEventVisibilityInput = Input; +export const PlaceCalendarEventVisibility: Schema< + PlaceCalendarEventVisibility, + PlaceCalendarEventVisibilityInput +> = PlaceCalendarEventVisibilitySchema; + +const PlaceCalendarRecurrenceSchema = /* @__PURE__ */ object( + { + range_start: /* @__PURE__ */ integer(), + range_end: /* @__PURE__ */ integer(), + interval: /* @__PURE__ */ integer('Int32'), + pattern: /* @__PURE__ */ string(), + days_of_week: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + }, + ['range_start', 'range_end', 'interval', 'pattern'], +); +export interface PlaceCalendarRecurrence extends Output {} +export interface PlaceCalendarRecurrenceInput extends Input {} +export const PlaceCalendarRecurrence: Schema< + PlaceCalendarRecurrence, + PlaceCalendarRecurrenceInput +> = PlaceCalendarRecurrenceSchema; + +const PlaceCalendarEventSchema = /* @__PURE__ */ object( + { + event_start: /* @__PURE__ */ integer(), + /** Unix time in seconds. */ + event_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + recurring_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + host: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + body: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + attendees: /* @__PURE__ */ array(PlaceCalendarEventAttendee), + hide_attendees: /* @__PURE__ */ boolean(), + location: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + private: /* @__PURE__ */ boolean(), + all_day: /* @__PURE__ */ boolean(), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + recurring: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + created: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + updated: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + attachments: /* @__PURE__ */ array(PlaceCalendarAttachment), + recurrence: /* @__PURE__ */ nullable(PlaceCalendarRecurrence), + status: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + creator: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + online_meeting_provider: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + online_meeting_phones: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(/* @__PURE__ */ string()), + ), + online_meeting_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + online_meeting_sip: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + online_meeting_pin: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + online_meeting_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + extended_properties: /* @__PURE__ */ nullable( + /* @__PURE__ */ record(/* @__PURE__ */ nullable(/* @__PURE__ */ string())), + ), + visibility: /* @__PURE__ */ nullable(PlaceCalendarEventVisibility), + mailbox: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + system: /* @__PURE__ */ nullable( + /* @__PURE__ */ union([PlaceCalendarEventSystem, ControlSystem]), + ), + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + recurring_master_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + setup_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + breakdown_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + setup_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + breakdown_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + permission: /* @__PURE__ */ nullable(EventMetadataPermission), + }, + ['event_start', 'attendees', 'hide_attendees', 'private', 'all_day', 'attachments'], +); +export interface PlaceCalendarEvent extends Output {} +export interface PlaceCalendarEventInput extends Input {} +export const PlaceCalendarEvent: Schema = + PlaceCalendarEventSchema; + +const AttendeeSchema = /* @__PURE__ */ object({ + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + visit_expected: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + guest_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + tenant_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + booking_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + preferred_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + organisation: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + notes: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + photo: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + event: /* @__PURE__ */ nullable(PlaceCalendarEvent), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface Attendee extends Output {} +export interface AttendeeInput extends Input {} +export const Attendee: Schema = AttendeeSchema; + +const BookingStateSchema = /* @__PURE__ */ literal([ + 'reserved', + 'checked_in', + 'checked_out', + 'no_show', + 'rejected', + 'cancelled', + 'ended', + 'unknown', +]); +export type BookingState = Output; +export type BookingStateInput = Input; +export const BookingState: Schema = BookingStateSchema; + +const BookingHistorySchema = /* @__PURE__ */ object( + { + state: BookingState, + time: /* @__PURE__ */ integer(), + source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['state', 'time'], +); +export interface BookingHistory extends Output {} +export interface BookingHistoryInput extends Input {} +export const BookingHistory: Schema = BookingHistorySchema; + +const BookingInductionSchema = /* @__PURE__ */ literal(['tentative', 'accepted', 'declined']); +export type BookingInduction = Output; +export type BookingInductionInput = Input; +export const BookingInduction: Schema = + BookingInductionSchema; + +const BookingPermissionSchema = /* @__PURE__ */ literal(['private', 'open', 'public']); +export type BookingPermission = Output; +export type BookingPermissionInput = Input; +export const BookingPermission: Schema = + BookingPermissionSchema; + +const BookingRecurrenceSchema = /* @__PURE__ */ literal(['none', 'daily', 'weekly', 'monthly']); +export type BookingRecurrence = Output; +export type BookingRecurrenceInput = Input; +export const BookingRecurrence: Schema = + BookingRecurrenceSchema; + +const BookingSchema = /* @__PURE__ */ object({ + booking_type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + booking_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + booking_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + asset_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + user_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + user_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + zones: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + process_state: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + last_changed: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + approved: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + approved_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + rejected: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + rejected_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + approver_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + approver_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + approver_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + department: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + checked_in_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + checked_out_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + deleted: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + deleted_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + booked_by_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + booked_by_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + booked_from: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + history: /* @__PURE__ */ nullable(/* @__PURE__ */ array(BookingHistory)), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** provided if this booking is associated with a calendar event */ + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** provided when this booking is an instance of recurring booking */ + instance: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + attendees: /* @__PURE__ */ nullable(/* @__PURE__ */ array(PlaceCalendarEventAttendee)), + asset_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + /** The induction status of the booking. Defaults to TENTATIVE. */ + induction: /* @__PURE__ */ nullable(BookingInduction), + /** + * The permission level for the booking. Defaults to private. If set to private, attendees must + * be invited.If set to open, users in the same tenant can join. If set to public, the booking + * is open for everyone to join. + */ + permission: /* @__PURE__ */ nullable(BookingPermission), + /** Is this a recurring booking. This field defines the type of recurrence */ + recurrence_type: /* @__PURE__ */ nullable(BookingRecurrence), + /** + * a bitmap of valid days of the week for booking recurrences to land on, defaults to all days + * of the week + */ + recurrence_days: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** + * which day index should a monthly recurrence land on. 1st Monday, 2nd Monday (used in + * conjunction with the days bitmap). -1 == last Monday, -2 Second last Monday etc + */ + recurrence_nth_of_month: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** 1 == every occurrence, 2 == every second occurrence, etc */ + recurrence_interval: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + /** an optional end date for booking recurrences */ + recurrence_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + all_day: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + tenant_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface Booking extends Output {} +export interface BookingInput extends Input {} +export const Booking: Schema = BookingSchema; + +const PlaceCalendarAvailabilityStatusSchema = /* @__PURE__ */ literal(['busy', 'free']); +export type PlaceCalendarAvailabilityStatus = Output; +export type PlaceCalendarAvailabilityStatusInput = Input< + typeof PlaceCalendarAvailabilityStatusSchema +>; +export const PlaceCalendarAvailabilityStatus: Schema< + PlaceCalendarAvailabilityStatus, + PlaceCalendarAvailabilityStatusInput +> = PlaceCalendarAvailabilityStatusSchema; + +const PlaceCalendarAvailabilitySchema = /* @__PURE__ */ object( + { + status: PlaceCalendarAvailabilityStatus, + starts_at: /* @__PURE__ */ integer(), + ends_at: /* @__PURE__ */ integer(), + timezone: /* @__PURE__ */ string(), + }, + ['status', 'starts_at', 'ends_at', 'timezone'], +); +export interface PlaceCalendarAvailability extends Output {} +export interface PlaceCalendarAvailabilityInput extends Input< + typeof PlaceCalendarAvailabilitySchema +> {} +export const PlaceCalendarAvailability: Schema< + PlaceCalendarAvailability, + PlaceCalendarAvailabilityInput +> = PlaceCalendarAvailabilitySchema; + +const CalendarsAvailabilitySchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + system: /* @__PURE__ */ nullable(ControlSystem), + availability: /* @__PURE__ */ nullable(/* @__PURE__ */ array(PlaceCalendarAvailability)), + }, + ['id'], +); +export interface CalendarsAvailability extends Output {} +export interface CalendarsAvailabilityInput extends Input {} +export const CalendarsAvailability: Schema = + CalendarsAvailabilitySchema; + +const DesksDeskSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ string(), + map_id: /* @__PURE__ */ string(), + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + features: /* @__PURE__ */ array(/* @__PURE__ */ string()), + accessible: /* @__PURE__ */ boolean(), + assigned_to: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + distance: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), + }, + ['id', 'name', 'map_id', 'features', 'accessible'], +); +/** a desk asset */ +export interface DesksDesk extends Output {} +export interface DesksDeskInput extends Input {} +/** a desk asset */ +export const DesksDesk: Schema = DesksDeskSchema; + +const DesksColleagueSchema = /* @__PURE__ */ object( + { + email: /* @__PURE__ */ string(), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + desk: DesksDesk, + booking_start: /* @__PURE__ */ integer(), + booking_end: /* @__PURE__ */ integer(), + }, + ['email', 'desk', 'booking_start', 'booking_end'], +); +/** a colleague and the desk they've booked */ +export interface DesksColleague extends Output {} +export interface DesksColleagueInput extends Input {} +/** a colleague and the desk they've booked */ +export const DesksColleague: Schema = DesksColleagueSchema; + +const DesksLevelSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ string(), + display_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'name'], +); +/** the level the desks are on */ +export interface DesksLevel extends Output {} +export interface DesksLevelInput extends Input {} +/** the level the desks are on */ +export const DesksLevel: Schema = DesksLevelSchema; + +const DesksColleagueLevelSchema = /* @__PURE__ */ object( + { + level: DesksLevel, + timezone: /* @__PURE__ */ string(), + colleagues: /* @__PURE__ */ array(DesksColleague), + desks: /* @__PURE__ */ array(DesksDesk), + }, + ['level', 'timezone', 'colleagues', 'desks'], +); +/** the colleagues sitting on a level and the free desks near them */ +export interface DesksColleagueLevel extends Output {} +export interface DesksColleagueLevelInput extends Input {} +/** the colleagues sitting on a level and the free desks near them */ +export const DesksColleagueLevel: Schema = + DesksColleagueLevelSchema; + +const DesksYourBookingSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ integer(), + asset_id: /* @__PURE__ */ string(), + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + zones: /* @__PURE__ */ array(/* @__PURE__ */ string()), + booking_start: /* @__PURE__ */ integer(), + booking_end: /* @__PURE__ */ integer(), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'asset_id', 'zones', 'booking_start', 'booking_end'], +); +/** one of the signed in user's desk bookings */ +export interface DesksYourBooking extends Output {} +export interface DesksYourBookingInput extends Input {} +/** one of the signed in user's desk bookings */ +export const DesksYourBooking: Schema = + DesksYourBookingSchema; + +const DesksFreeDesksSchema = /* @__PURE__ */ object( + { + level: DesksLevel, + timezone: /* @__PURE__ */ string(), + period_start: /* @__PURE__ */ integer(), + period_end: /* @__PURE__ */ integer(), + features: /* @__PURE__ */ array(/* @__PURE__ */ string()), + total: /* @__PURE__ */ integer('Int32'), + desks: /* @__PURE__ */ array(DesksDesk), + your_bookings: /* @__PURE__ */ array(DesksYourBooking), + }, + [ + 'level', + 'timezone', + 'period_start', + 'period_end', + 'features', + 'total', + 'desks', + 'your_bookings', + ], +); +/** the free desks on a level */ +export interface DesksFreeDesks extends Output {} +export interface DesksFreeDesksInput extends Input {} +/** the free desks on a level */ +export const DesksFreeDesks: Schema = DesksFreeDesksSchema; + +const DesksNearColleaguesSchema = /* @__PURE__ */ object( + { + period_start: /* @__PURE__ */ integer(), + period_end: /* @__PURE__ */ integer(), + levels: /* @__PURE__ */ array(DesksColleagueLevel), + not_seated: /* @__PURE__ */ array(/* @__PURE__ */ string()), + unranked: /* @__PURE__ */ array(/* @__PURE__ */ string()), + }, + ['period_start', 'period_end', 'levels', 'not_seated', 'unranked'], +); +/** where colleagues are sitting and the free desks near them */ +export interface DesksNearColleagues extends Output {} +export interface DesksNearColleaguesInput extends Input {} +/** where colleagues are sitting and the free desks near them */ +export const DesksNearColleagues: Schema = + DesksNearColleaguesSchema; + +const DesksNearbyDesksSchema = /* @__PURE__ */ object( + { + origin: DesksDesk, + seated: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + level: DesksLevel, + timezone: /* @__PURE__ */ string(), + period_start: /* @__PURE__ */ integer(), + period_end: /* @__PURE__ */ integer(), + desks: /* @__PURE__ */ array(DesksDesk), + }, + ['origin', 'level', 'timezone', 'period_start', 'period_end', 'desks'], +); +/** the free desks closest to the origin desk */ +export interface DesksNearbyDesks extends Output {} +export interface DesksNearbyDesksInput extends Input {} +/** the free desks closest to the origin desk */ +export const DesksNearbyDesks: Schema = + DesksNearbyDesksSchema; + +const EventMetadataSchema = /* @__PURE__ */ object({ + system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + recurring_master_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + ical_uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + resource_master_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + host_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + resource_calendar: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + event_start: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + event_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + cancelled: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + ext_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + setup_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + breakdown_time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + setup_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + breakdown_event_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * The permission level for the event. Defaults to private. If set to private, attendees must be + * invited.If set to open, users in the same tenant can join. If set to public, the event is + * open for everyone to join. + */ + permission: /* @__PURE__ */ nullable(EventMetadataPermission), + tenant_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface EventMetadata extends Output {} +export interface EventMetadataInput extends Input {} +export const EventMetadata: Schema = EventMetadataSchema; + +const EventsChangeTypeSchema = /* @__PURE__ */ literal(['created', 'updated', 'deleted']); +export type EventsChangeType = Output; +export type EventsChangeTypeInput = Input; +export const EventsChangeType: Schema = + EventsChangeTypeSchema; + +const EventsStrictSchema = /* @__PURE__ */ literal(['notify', 'limit', 'all']); +export type EventsStrict = Output; +export type EventsStrictInput = Input; +export const EventsStrict: Schema = EventsStrictSchema; + +const GuestSchema = /* @__PURE__ */ object({ + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + preferred_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + organisation: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + notes: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + photo: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + banned: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + dangerous: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + searchable: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + extension_data: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + tenant_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface Guest extends Output {} +export interface GuestInput extends Input {} +export const Guest: Schema = GuestSchema; + +const MetadataInterfaceSchema = /* @__PURE__ */ object( + { + name: /* @__PURE__ */ string(), + description: /* @__PURE__ */ string(), + details: /* @__PURE__ */ json(), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + schema_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + editors: /* @__PURE__ */ array(/* @__PURE__ */ string()), + modified_by_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + updated_at: /* @__PURE__ */ integer(), + created_at: /* @__PURE__ */ integer(), + }, + ['name', 'description', 'details', 'editors', 'updated_at', 'created_at'], +); +export interface MetadataInterface extends Output {} +export interface MetadataInterfaceInput extends Input {} +export const MetadataInterface: Schema = + MetadataInterfaceSchema; + +const ZoneSchema = /* @__PURE__ */ object( + { + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + tags: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + location: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + display_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + code: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + triggers: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + playlists: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + place_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + remove_triggers: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + add_triggers: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + update_systems: /* @__PURE__ */ boolean(), + }, + ['update_systems'], +); +export interface Zone extends Output {} +export interface ZoneInput extends Input {} +export const Zone: Schema = ZoneSchema; + +const GuestsChildrenSchema = /* @__PURE__ */ object( + { + zone: Zone, + metadata: /* @__PURE__ */ record(MetadataInterface), + }, + ['zone', 'metadata'], +); +/** NOTE:: same as rest-api metadata Children */ +export interface GuestsChildren extends Output {} +export interface GuestsChildrenInput extends Input {} +/** NOTE:: same as rest-api metadata Children */ +export const GuestsChildren: Schema = GuestsChildrenSchema; + +const HealthCheckBuildInfoSchema = /* @__PURE__ */ object( + { + commit: /* @__PURE__ */ string(), + build_time: /* @__PURE__ */ string(), + }, + ['commit', 'build_time'], +); +export interface HealthCheckBuildInfo extends Output {} +export interface HealthCheckBuildInfoInput extends Input {} +export const HealthCheckBuildInfo: Schema = + HealthCheckBuildInfoSchema; + +const HistorySchema = /* @__PURE__ */ object({ + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + resource_type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + resource_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + correlation_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + action: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + changed_fields: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + diff: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + snapshot: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + user_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + context: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface History extends Output {} +export interface HistoryInput extends Input {} +export const History: Schema = HistorySchema; + +const Int64Schema = /* @__PURE__ */ integer(); +export type Int64 = Output; +export type Int64Input = Input; +export const Int64: Schema = Int64Schema; + +const Office365ChannelIdentitySchema = /* @__PURE__ */ object( + { + channelId: /* @__PURE__ */ string(), + teamId: /* @__PURE__ */ string(), + }, + ['channelId', 'teamId'], +); +export interface Office365ChannelIdentity extends Output {} +export interface Office365ChannelIdentityInput extends Input< + typeof Office365ChannelIdentitySchema +> {} +export const Office365ChannelIdentity: Schema< + Office365ChannelIdentity, + Office365ChannelIdentityInput +> = Office365ChannelIdentitySchema; + +const Office365ChatMessageAttachmentSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + content: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + contentType: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + contentUrl: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + teamsAppId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + thumbnailUrl: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], +); +export interface Office365ChatMessageAttachment extends Output< + typeof Office365ChatMessageAttachmentSchema +> {} +export interface Office365ChatMessageAttachmentInput extends Input< + typeof Office365ChatMessageAttachmentSchema +> {} +export const Office365ChatMessageAttachment: Schema< + Office365ChatMessageAttachment, + Office365ChatMessageAttachmentInput +> = Office365ChatMessageAttachmentSchema; + +const Office365ThumbnailSchema = /* @__PURE__ */ object({ + height: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + width: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + content: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + sourceItemId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface Office365Thumbnail extends Output {} +export interface Office365ThumbnailInput extends Input {} +export const Office365Thumbnail: Schema = + Office365ThumbnailSchema; + +const Office365ThumbnailSetSchema = /* @__PURE__ */ object({ + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + large: /* @__PURE__ */ nullable(Office365Thumbnail), + medium: /* @__PURE__ */ nullable(Office365Thumbnail), + small: /* @__PURE__ */ nullable(Office365Thumbnail), + source: /* @__PURE__ */ nullable(Office365Thumbnail), +}); +export interface Office365ThumbnailSet extends Output {} +export interface Office365ThumbnailSetInput extends Input {} +export const Office365ThumbnailSet: Schema = + Office365ThumbnailSetSchema; + +const Office365IdentitySchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + displayName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + tenantId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + thumbnails: /* @__PURE__ */ nullable(Office365ThumbnailSet), + }, + ['id'], +); +export interface Office365Identity extends Output {} +export interface Office365IdentityInput extends Input {} +export const Office365Identity: Schema = + Office365IdentitySchema; + +const Office365TeamworkUserIdentitySchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + displayName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + tenantId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + userIdentityType: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], +); +export interface Office365TeamworkUserIdentity extends Output< + typeof Office365TeamworkUserIdentitySchema +> {} +export interface Office365TeamworkUserIdentityInput extends Input< + typeof Office365TeamworkUserIdentitySchema +> {} +export const Office365TeamworkUserIdentity: Schema< + Office365TeamworkUserIdentity, + Office365TeamworkUserIdentityInput +> = Office365TeamworkUserIdentitySchema; + +const Office365ChatMessageFromIdentitySetSchema = /* @__PURE__ */ object({ + application: /* @__PURE__ */ nullable(Office365Identity), + device: /* @__PURE__ */ nullable(Office365Identity), + user: /* @__PURE__ */ nullable(Office365TeamworkUserIdentity), +}); +export interface Office365ChatMessageFromIdentitySet extends Output< + typeof Office365ChatMessageFromIdentitySetSchema +> {} +export interface Office365ChatMessageFromIdentitySetInput extends Input< + typeof Office365ChatMessageFromIdentitySetSchema +> {} +export const Office365ChatMessageFromIdentitySet: Schema< + Office365ChatMessageFromIdentitySet, + Office365ChatMessageFromIdentitySetInput +> = Office365ChatMessageFromIdentitySetSchema; + +const Office365ChatMessageActionsSchema = /* @__PURE__ */ literal([ + 'reaction_added', + 'reaction_removed', + 'action_undefined', + 'unknown_future_value', +]); +export type Office365ChatMessageActions = Output; +export type Office365ChatMessageActionsInput = Input; +export const Office365ChatMessageActions: Schema< + Office365ChatMessageActions, + Office365ChatMessageActionsInput +> = Office365ChatMessageActionsSchema; + +const Office365ChatMessageReactionIdentitySetSchema = /* @__PURE__ */ object({ + application: /* @__PURE__ */ nullable(Office365Identity), + device: /* @__PURE__ */ nullable(Office365Identity), + user: /* @__PURE__ */ nullable(Office365Identity), +}); +export interface Office365ChatMessageReactionIdentitySet extends Output< + typeof Office365ChatMessageReactionIdentitySetSchema +> {} +export interface Office365ChatMessageReactionIdentitySetInput extends Input< + typeof Office365ChatMessageReactionIdentitySetSchema +> {} +export const Office365ChatMessageReactionIdentitySet: Schema< + Office365ChatMessageReactionIdentitySet, + Office365ChatMessageReactionIdentitySetInput +> = Office365ChatMessageReactionIdentitySetSchema; + +const Office365ChatMessageReactionSchema = /* @__PURE__ */ object({ + createdDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + displayName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + reactionContentUrl: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + reactionType: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + user: /* @__PURE__ */ nullable(Office365ChatMessageReactionIdentitySet), +}); +export interface Office365ChatMessageReaction extends Output< + typeof Office365ChatMessageReactionSchema +> {} +export interface Office365ChatMessageReactionInput extends Input< + typeof Office365ChatMessageReactionSchema +> {} +export const Office365ChatMessageReaction: Schema< + Office365ChatMessageReaction, + Office365ChatMessageReactionInput +> = Office365ChatMessageReactionSchema; + +const Office365ChatMessageHistoryItemSchema = /* @__PURE__ */ object( + { + actions: Office365ChatMessageActions, + modifiedDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + reaction: /* @__PURE__ */ nullable(Office365ChatMessageReaction), + }, + ['actions'], +); +export interface Office365ChatMessageHistoryItem extends Output< + typeof Office365ChatMessageHistoryItemSchema +> {} +export interface Office365ChatMessageHistoryItemInput extends Input< + typeof Office365ChatMessageHistoryItemSchema +> {} +export const Office365ChatMessageHistoryItem: Schema< + Office365ChatMessageHistoryItem, + Office365ChatMessageHistoryItemInput +> = Office365ChatMessageHistoryItemSchema; + +const Office365TeamworkConversationIdentitySchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + displayName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + conversationIdentityType: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id'], +); +export interface Office365TeamworkConversationIdentity extends Output< + typeof Office365TeamworkConversationIdentitySchema +> {} +export interface Office365TeamworkConversationIdentityInput extends Input< + typeof Office365TeamworkConversationIdentitySchema +> {} +export const Office365TeamworkConversationIdentity: Schema< + Office365TeamworkConversationIdentity, + Office365TeamworkConversationIdentityInput +> = Office365TeamworkConversationIdentitySchema; + +const Office365ChatMessageMentionedIdentitySetSchema = /* @__PURE__ */ object({ + application: /* @__PURE__ */ nullable(Office365Identity), + conversation: /* @__PURE__ */ nullable(Office365TeamworkConversationIdentity), + device: /* @__PURE__ */ nullable(Office365Identity), + user: /* @__PURE__ */ nullable(Office365Identity), +}); +export interface Office365ChatMessageMentionedIdentitySet extends Output< + typeof Office365ChatMessageMentionedIdentitySetSchema +> {} +export interface Office365ChatMessageMentionedIdentitySetInput extends Input< + typeof Office365ChatMessageMentionedIdentitySetSchema +> {} +export const Office365ChatMessageMentionedIdentitySet: Schema< + Office365ChatMessageMentionedIdentitySet, + Office365ChatMessageMentionedIdentitySetInput +> = Office365ChatMessageMentionedIdentitySetSchema; + +const Office365ChatMessageMentionSchema = /* @__PURE__ */ object({ + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + mentioned: /* @__PURE__ */ nullable(Office365ChatMessageMentionedIdentitySet), + mentionText: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface Office365ChatMessageMention extends Output< + typeof Office365ChatMessageMentionSchema +> {} +export interface Office365ChatMessageMentionInput extends Input< + typeof Office365ChatMessageMentionSchema +> {} +export const Office365ChatMessageMention: Schema< + Office365ChatMessageMention, + Office365ChatMessageMentionInput +> = Office365ChatMessageMentionSchema; + +const Office365ChatMessagePolicyTipSchema = /* @__PURE__ */ object({ + complianceUrl: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + generalText: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + matchedConditionDescriptions: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(/* @__PURE__ */ string()), + ), +}); +export interface Office365ChatMessagePolicyTip extends Output< + typeof Office365ChatMessagePolicyTipSchema +> {} +export interface Office365ChatMessagePolicyTipInput extends Input< + typeof Office365ChatMessagePolicyTipSchema +> {} +export const Office365ChatMessagePolicyTip: Schema< + Office365ChatMessagePolicyTip, + Office365ChatMessagePolicyTipInput +> = Office365ChatMessagePolicyTipSchema; + +const Office365ChatMessagePolicyViolationDlpActionTypeSchema = /* @__PURE__ */ literal([ + 'none', + 'notify_sender', + 'block_access', + 'block_access_external', +]); +export type Office365ChatMessagePolicyViolationDlpActionType = Output< + typeof Office365ChatMessagePolicyViolationDlpActionTypeSchema +>; +export type Office365ChatMessagePolicyViolationDlpActionTypeInput = Input< + typeof Office365ChatMessagePolicyViolationDlpActionTypeSchema +>; +export const Office365ChatMessagePolicyViolationDlpActionType: Schema< + Office365ChatMessagePolicyViolationDlpActionType, + Office365ChatMessagePolicyViolationDlpActionTypeInput +> = Office365ChatMessagePolicyViolationDlpActionTypeSchema; + +const Office365ChatMessagePolicyViolationSchema = /* @__PURE__ */ object({ + dlpAction: /* @__PURE__ */ nullable(Office365ChatMessagePolicyViolationDlpActionType), + justificationText: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + policyTip: /* @__PURE__ */ nullable(Office365ChatMessagePolicyTip), + userAction: /* @__PURE__ */ nullable(Office365ChatMessagePolicyViolationDlpActionType), + verdictDetails: /* @__PURE__ */ nullable(Office365ChatMessagePolicyViolationDlpActionType), +}); +export interface Office365ChatMessagePolicyViolation extends Output< + typeof Office365ChatMessagePolicyViolationSchema +> {} +export interface Office365ChatMessagePolicyViolationInput extends Input< + typeof Office365ChatMessagePolicyViolationSchema +> {} +export const Office365ChatMessagePolicyViolation: Schema< + Office365ChatMessagePolicyViolation, + Office365ChatMessagePolicyViolationInput +> = Office365ChatMessagePolicyViolationSchema; + +const Office365ChatMessageTypeSchema = /* @__PURE__ */ literal([ + 'message', + 'chat_event', + 'typing', + 'unknown_future_value', + 'system_event_message', +]); +export type Office365ChatMessageType = Output; +export type Office365ChatMessageTypeInput = Input; +export const Office365ChatMessageType: Schema< + Office365ChatMessageType, + Office365ChatMessageTypeInput +> = Office365ChatMessageTypeSchema; + +const Office365ItemBodySchema = /* @__PURE__ */ object({ + content: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + contentType: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface Office365ItemBody extends Output {} +export interface Office365ItemBodyInput extends Input {} +export const Office365ItemBody: Schema = + Office365ItemBodySchema; + +const Office365ChatMessageSchema = /* @__PURE__ */ object( + { + attachments: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(Office365ChatMessageAttachment), + ), + body: Office365ItemBody, + chatId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + channelIdentity: /* @__PURE__ */ nullable(Office365ChannelIdentity), + createdDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + deletedDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + etag: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + from: /* @__PURE__ */ nullable(Office365ChatMessageFromIdentitySet), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + importance: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + lastModifiedDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + lastEditedDateTime: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + locale: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + mentions: /* @__PURE__ */ nullable(/* @__PURE__ */ array(Office365ChatMessageMention)), + messageHistory: /* @__PURE__ */ nullable( + /* @__PURE__ */ array(Office365ChatMessageHistoryItem), + ), + messageType: /* @__PURE__ */ nullable(Office365ChatMessageType), + policyViolation: /* @__PURE__ */ nullable(Office365ChatMessagePolicyViolation), + reactions: /* @__PURE__ */ nullable(/* @__PURE__ */ array(Office365ChatMessageReaction)), + replyToId: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + subject: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + summary: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + webUrl: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['body'], +); +export interface Office365ChatMessage extends Output {} +export interface Office365ChatMessageInput extends Input {} +export const Office365ChatMessage: Schema = + Office365ChatMessageSchema; + +const Office365ChatMessageListSchema = /* @__PURE__ */ object( + { + '@odata.context': /* @__PURE__ */ string(), + '@odata.count': /* @__PURE__ */ integer('Int32'), + '@odata.nextLink': /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + value: /* @__PURE__ */ array(Office365ChatMessage), + }, + ['@odata.context', '@odata.count', 'value'], +); +export interface Office365ChatMessageList extends Output {} +export interface Office365ChatMessageListInput extends Input< + typeof Office365ChatMessageListSchema +> {} +export const Office365ChatMessageList: Schema< + Office365ChatMessageList, + Office365ChatMessageListInput +> = Office365ChatMessageListSchema; + +const Office365OutlookGeoCoordinatesSchema = /* @__PURE__ */ object({ + altitudeAccuracy: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), + accuracy: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), + altitude: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), + latitude: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), + longitude: /* @__PURE__ */ nullable(/* @__PURE__ */ number()), +}); +export interface Office365OutlookGeoCoordinates extends Output< + typeof Office365OutlookGeoCoordinatesSchema +> {} +export interface Office365OutlookGeoCoordinatesInput extends Input< + typeof Office365OutlookGeoCoordinatesSchema +> {} +export const Office365OutlookGeoCoordinates: Schema< + Office365OutlookGeoCoordinates, + Office365OutlookGeoCoordinatesInput +> = Office365OutlookGeoCoordinatesSchema; + +const Office365PhysicalAddressSchema = /* @__PURE__ */ object({ + city: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + state: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + street: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + countryOrRegion: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + postalCode: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), +}); +export interface Office365PhysicalAddress extends Output {} +export interface Office365PhysicalAddressInput extends Input< + typeof Office365PhysicalAddressSchema +> {} +export const Office365PhysicalAddress: Schema< + Office365PhysicalAddress, + Office365PhysicalAddressInput +> = Office365PhysicalAddressSchema; + +const Office365RoomBookingTypeSchema = /* @__PURE__ */ literal(['reserved', 'standard']); +export type Office365RoomBookingType = Output; +export type Office365RoomBookingTypeInput = Input; +export const Office365RoomBookingType: Schema< + Office365RoomBookingType, + Office365RoomBookingTypeInput +> = Office365RoomBookingTypeSchema; + +const Office365RoomSchema = /* @__PURE__ */ object( + { + address: /* @__PURE__ */ nullable(Office365PhysicalAddress), + displayName: /* @__PURE__ */ string(), + geoCoordinates: /* @__PURE__ */ nullable(Office365OutlookGeoCoordinates), + id: /* @__PURE__ */ string(), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + audioDeviceName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + bookingType: /* @__PURE__ */ nullable(Office365RoomBookingType), + building: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + displayDeviceName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + emailAddress: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + floorLabel: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + floorNumber: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + isWheelChairAccessible: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + label: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + nickname: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + tags: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + videoDeviceName: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['displayName', 'id'], +); +export interface Office365Room extends Output {} +export interface Office365RoomInput extends Input {} +export const Office365Room: Schema = Office365RoomSchema; + +const PlaceCalendarCalendarSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + ref: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + summary: /* @__PURE__ */ string(), + primary: /* @__PURE__ */ boolean(), + can_edit: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + }, + ['summary', 'primary'], +); +export interface PlaceCalendarCalendar extends Output {} +export interface PlaceCalendarCalendarInput extends Input {} +export const PlaceCalendarCalendar: Schema = + PlaceCalendarCalendarSchema; + +const PlaceCalendarGroupSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ string(), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'name'], +); +export interface PlaceCalendarGroup extends Output {} +export interface PlaceCalendarGroupInput extends Input {} +export const PlaceCalendarGroup: Schema = + PlaceCalendarGroupSchema; + +const PlaceCalendarMemberSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email: /* @__PURE__ */ string(), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + username: /* @__PURE__ */ string(), + suspended: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + unmapped: /* @__PURE__ */ nullable(/* @__PURE__ */ record(/* @__PURE__ */ json())), + }, + ['id', 'email', 'username'], +); +export interface PlaceCalendarMember extends Output {} +export interface PlaceCalendarMemberInput extends Input {} +export const PlaceCalendarMember: Schema = + PlaceCalendarMemberSchema; + +const PlaceCalendarUserSchema = /* @__PURE__ */ object({ + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + department: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + photo: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + username: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + office_location: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + suspended: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + unmapped: /* @__PURE__ */ nullable(/* @__PURE__ */ record(/* @__PURE__ */ json())), +}); +export interface PlaceCalendarUser extends Output {} +export interface PlaceCalendarUserInput extends Input {} +export const PlaceCalendarUser: Schema = + PlaceCalendarUserSchema; + +const SpacesSpaceSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ string(), + display_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + capacity: /* @__PURE__ */ integer('Int32'), + features: /* @__PURE__ */ array(/* @__PURE__ */ string()), + images: /* @__PURE__ */ array(/* @__PURE__ */ string()), + map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + zones: /* @__PURE__ */ array(/* @__PURE__ */ string()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + approval: /* @__PURE__ */ boolean(), + }, + ['id', 'name', 'capacity', 'features', 'images', 'zones', 'approval'], +); +/** a bookable room, a PlaceOS system with a resource calendar */ +export interface SpacesSpace extends Output {} +export interface SpacesSpaceInput extends Input {} +/** a bookable room, a PlaceOS system with a resource calendar */ +export const SpacesSpace: Schema = SpacesSpaceSchema; + +const SpacesSpaceZoneSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ string(), + name: /* @__PURE__ */ string(), + display_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + tags: /* @__PURE__ */ array(/* @__PURE__ */ string()), + parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + location: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['id', 'name', 'tags'], +); +/** a campus, building, level or area */ +export interface SpacesSpaceZone extends Output {} +export interface SpacesSpaceZoneInput extends Input {} +/** a campus, building, level or area */ +export const SpacesSpaceZone: Schema = SpacesSpaceZoneSchema; + +const SpacesFreeSpacesSchema = /* @__PURE__ */ object( + { + buildings: /* @__PURE__ */ array(SpacesSpaceZone), + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + spaces: /* @__PURE__ */ array(SpacesSpace), + }, + ['buildings', 'spaces'], +); +/** the rooms free for a meeting, in a building or level */ +export interface SpacesFreeSpaces extends Output {} +export interface SpacesFreeSpacesInput extends Input {} +/** the rooms free for a meeting, in a building or level */ +export const SpacesFreeSpaces: Schema = + SpacesFreeSpacesSchema; + +const SpacesSpaceEventSchema = /* @__PURE__ */ object( + { + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + host: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + event_start: /* @__PURE__ */ integer(), + event_end: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + all_day: /* @__PURE__ */ boolean(), + private: /* @__PURE__ */ boolean(), + }, + ['event_start', 'all_day', 'private'], +); +/** a meeting in the space's calendar */ +export interface SpacesSpaceEvent extends Output {} +export interface SpacesSpaceEventInput extends Input {} +/** a meeting in the space's calendar */ +export const SpacesSpaceEvent: Schema = + SpacesSpaceEventSchema; + +const SpacesSpaceScheduleSchema = /* @__PURE__ */ object( + { + space: SpacesSpace, + zones: /* @__PURE__ */ array(SpacesSpaceZone), + timezone: /* @__PURE__ */ string(), + period_start: /* @__PURE__ */ integer(), + period_end: /* @__PURE__ */ integer(), + events: /* @__PURE__ */ nullable(/* @__PURE__ */ array(SpacesSpaceEvent)), + events_error: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['space', 'zones', 'timezone', 'period_start', 'period_end'], +); +/** a space with its meetings over a period */ +export interface SpacesSpaceSchedule extends Output {} +export interface SpacesSpaceScheduleInput extends Input {} +/** a space with its meetings over a period */ +export const SpacesSpaceSchedule: Schema = + SpacesSpaceScheduleSchema; + +const StaffBusySchema = /* @__PURE__ */ object( + { + email: /* @__PURE__ */ string(), + busy: /* @__PURE__ */ array( + /* @__PURE__ */ object( + { + start: /* @__PURE__ */ integer(), + end: /* @__PURE__ */ integer(), + }, + ['start', 'end'], + ), + ), + }, + ['email', 'busy'], +); +/** someone's busy times in a period, as unix epochs */ +export interface StaffBusy extends Output {} +export interface StaffBusyInput extends Input {} +/** someone's busy times in a period, as unix epochs */ +export const StaffBusy: Schema = StaffBusySchema; + +const SurveyPageSchema = /* @__PURE__ */ object( + { + title: /* @__PURE__ */ string(), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + question_order: /* @__PURE__ */ array(/* @__PURE__ */ integer()), + }, + ['title', 'question_order'], +); +export interface SurveyPage extends Output {} +export interface SurveyPageInput extends Input {} +export const SurveyPage: Schema = SurveyPageSchema; + +const SurveyTriggerTypeSchema = /* @__PURE__ */ literal([ + 'none', + 'reserved', + 'checkedin', + 'checkedout', + 'noshow', + 'rejected', + 'cancelled', + 'ended', + 'visitor_checkedin', + 'visitor_checkedout', +]); +export type SurveyTriggerType = Output; +export type SurveyTriggerTypeInput = Input; +export const SurveyTriggerType: Schema = + SurveyTriggerTypeSchema; + +const SurveySchema = /* @__PURE__ */ object({ + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** + * Triggers on booking states: RESERVED, CHECKEDIN, CHECKEDOUT, REJECTED, CANCELLED, + * VISITOR_CHECKEDIN, VISITOR_CHECKEDOUT + */ + trigger: /* @__PURE__ */ nullable(SurveyTriggerType), + zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + building_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + pages: /* @__PURE__ */ nullable(/* @__PURE__ */ array(SurveyPage)), + authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface Survey extends Output {} +export interface SurveyInput extends Input {} +export const Survey: Schema = SurveySchema; + +const SurveyAnswerSchema = /* @__PURE__ */ object({ + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + answer_json: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + question_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface SurveyAnswer extends Output {} +export interface SurveyAnswerInput extends Input {} +export const SurveyAnswer: Schema = SurveyAnswerSchema; + +const SurveyInvitationSchema = /* @__PURE__ */ object({ + token: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + sent: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface SurveyInvitation extends Output {} +export interface SurveyInvitationInput extends Input {} +export const SurveyInvitation: Schema = + SurveyInvitationSchema; + +const SurveyQuestionSchema = /* @__PURE__ */ object({ + title: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + type: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + options: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + required: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + choices: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + max_rating: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), + tags: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), + deleted_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + previous_question_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + /** Unix time in seconds. */ + updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface SurveyQuestion extends Output {} +export interface SurveyQuestionInput extends Input {} +export const SurveyQuestion: Schema = SurveyQuestionSchema; + +const TenantOutlookConfigSchema = /* @__PURE__ */ object( + { + app_id: /* @__PURE__ */ string(), + base_path: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + app_domain: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + app_resource: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + source_location: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + version: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + ['app_id'], +); +export interface TenantOutlookConfig extends Output {} +export interface TenantOutlookConfigInput extends Input {} +export const TenantOutlookConfig: Schema = + TenantOutlookConfigSchema; + +const TenantResponderSchema = /* @__PURE__ */ object({ + id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + domain: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email_domain: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + platform: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + delegated: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + service_account: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + credentials: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + booking_limits: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + booking_range: /* @__PURE__ */ nullable( + /* @__PURE__ */ record(/* @__PURE__ */ integer('UInt32')), + ), + booking_period: /* @__PURE__ */ nullable( + /* @__PURE__ */ record(/* @__PURE__ */ integer('UInt32')), + ), + outlook_config: /* @__PURE__ */ nullable(TenantOutlookConfig), + early_checkin: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), +}); +export interface TenantResponder extends Output {} +export interface TenantResponderInput extends Input {} +export const TenantResponder: Schema = TenantResponderSchema; + +const UserWorktimeBlockSchema = /* @__PURE__ */ object( + { + start_time: /* @__PURE__ */ number(), + end_time: /* @__PURE__ */ number(), + location: /* @__PURE__ */ string(), + }, + ['start_time', 'end_time', 'location'], +); +export interface UserWorktimeBlock extends Output {} +export interface UserWorktimeBlockInput extends Input {} +export const UserWorktimeBlock: Schema = + UserWorktimeBlockSchema; + +const UserWorktimePreferenceSchema = /* @__PURE__ */ object( + { + day_of_week: /* @__PURE__ */ integer('Int32'), + blocks: /* @__PURE__ */ array(UserWorktimeBlock), + }, + ['day_of_week', 'blocks'], +); +export interface UserWorktimePreference extends Output {} +export interface UserWorktimePreferenceInput extends Input {} +export const UserWorktimePreference: Schema = + UserWorktimePreferenceSchema; + +const UserAdminResponseSchema = /* @__PURE__ */ object( + { + /** Unix time in seconds. */ + created_at: /* @__PURE__ */ integer(), + name: /* @__PURE__ */ string(), + nickname: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email: /* @__PURE__ */ string(), + phone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + country: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + image: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + ui_theme: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + misc: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + login_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + staff_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + first_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + last_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + building: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + department: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + preferred_language: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + email_digest: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + card_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + deleted: /* @__PURE__ */ boolean(), + groups: /* @__PURE__ */ array(/* @__PURE__ */ string()), + sys_admin: /* @__PURE__ */ boolean(), + support: /* @__PURE__ */ boolean(), + locatable: /* @__PURE__ */ boolean(), + login_count: /* @__PURE__ */ integer(), + /** Unix time in seconds. */ + last_login: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + work_preferences: /* @__PURE__ */ array(UserWorktimePreference), + work_overrides: /* @__PURE__ */ record(UserWorktimePreference), + authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + photo_upload_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + }, + [ + 'created_at', + 'name', + 'email', + 'deleted', + 'groups', + 'sys_admin', + 'support', + 'locatable', + 'login_count', + 'work_preferences', + 'work_overrides', + ], +); +export interface UserAdminResponse extends Output {} +export interface UserAdminResponseInput extends Input {} +export const UserAdminResponse: Schema = + UserAdminResponseSchema; diff --git a/v2/src/migrate/map.ts b/v2/src/migrate/map.ts index 2e6db15af..2e876ad34 100644 --- a/v2/src/migrate/map.ts +++ b/v2/src/migrate/map.ts @@ -43,8 +43,16 @@ export interface V1Parameter { readonly use: 'mapped' | 'ignored' | 'unsupported'; } +/** The v2 type of a v1 class. `staff` is a type of `@placeos/ts-client/staff`. */ +export interface TypeMapping { + readonly name: string; + readonly module?: 'staff'; +} + /** The v2 call for one v1 function. */ export interface CallMapping { + /** `staff` for an operation of `@placeos/ts-client/staff`. */ + readonly module?: 'staff'; /** The namespace export of v2, such as `zones`. */ readonly namespace: string; /** The operation of the namespace, such as `show`. */ diff --git a/v2/src/migrate/migrate.ts b/v2/src/migrate/migrate.ts index 66c37f371..0682a72dd 100644 --- a/v2/src/migrate/migrate.ts +++ b/v2/src/migrate/migrate.ts @@ -21,10 +21,11 @@ */ import type * as TS from 'typescript-5'; import { assert } from '../core/assert.ts'; -import type { CallMap, CallMapping, ObjectEntry, Template } from './map.ts'; +import type { CallMap, CallMapping, ObjectEntry, Template, TypeMapping } from './map.ts'; export const V1_MODULE = '@placeos/ts-client'; export const COMPAT_MODULE = '@placeos/ts-client/compat'; +export const STAFF_MODULE = '@placeos/ts-client/staff'; /** The objects of the test frameworks: `vi` of Vitest and `jest` of Jest. */ const TEST_GLOBALS: ReadonlySet = new Set(['vi', 'jest']); /** The mock methods that set the value of a promise. The value becomes a v2 result. */ @@ -61,7 +62,7 @@ const ALIASES_MAX = 100; export interface MigrateTables { readonly calls: CallMap; - readonly types: Readonly>; + readonly types: Readonly>; /** The v1 names that `@placeos/ts-client/compat` has. Their imports move there. */ readonly compat: Readonly>; readonly unmapped: Readonly>; @@ -107,16 +108,25 @@ export function migrateSource( if (imports.declarations.length === 0) { return { text, changes: 0, findings: [], migrated: new Set() }; } - const taken = declaredNames(ts, source); + // A v1 class that the file uses only as a type loses its import, so a v2 type can take its + // name, such as `Survey` for the v1 `Survey`. + const typeOnly = (name: string) => { + const imported = imports.named.get(name); + return imported !== undefined && imported in tables.types; + }; + const taken = declaredNames(ts, source, typeOnly); const edits: Edit[] = []; const findings: Finding[] = []; const migrated = new Set(); /** The uses of each local name of a named import, and how many the tool changed. */ const uses = new Map(); - /** The local names of the v2 namespaces that the new import gives. */ - const namespaceNames = new Map(); - /** The v2 types that the new import gives, by local name. */ - const typeNames = new Map(); + /** The v2 namespaces that the new imports give, by module and name, with the local name. */ + const namespaceNames = new Map< + string, + { module: 'staff' | null; name: string; local: string } + >(); + /** The v2 types that the new imports give, by local name. */ + const typeNames = new Map(); const compatNames = new Set(); /** The local names of the v1 imports that move to the compat module. */ const moved = new Set(); @@ -149,12 +159,26 @@ export function migrateSource( assert(false, `a free local name for ${name}`); } - function namespaceLocal(namespace: string): string { - const known = namespaceNames.get(namespace); - if (known !== undefined) return known; - const name = localName(namespace); - namespaceNames.set(namespace, name); - return name; + function namespaceLocal(namespace: string, module: 'staff' | null = null): string { + const key = `${module ?? ''}|${namespace}`; + const known = namespaceNames.get(key); + if (known !== undefined) return known.local; + // A staff namespace, such as `assets`, can have the name of a REST API namespace. + const staffName = `staff${namespace.charAt(0).toUpperCase()}${namespace.slice(1)}`; + const local = + module === 'staff' && taken.has(namespace) && !taken.has(staffName) + ? localName(staffName) + : localName(namespace); + namespaceNames.set(key, { module, name: namespace, local }); + return local; + } + + /** The v2 namespace of a mapping. A namespace import of v1 has the REST API namespaces only. */ + function namespaceOf(mapping: CallMapping, prefix: string | null): string { + if (prefix === null || mapping.module === 'staff') { + return namespaceLocal(mapping.namespace, mapping.module ?? null); + } + return `${prefix}.${mapping.namespace}`; } /** The local name of a compat export that a namespace import used, such as `PlaceDriverRole`. */ @@ -169,10 +193,13 @@ export function migrateSource( return local; } - function typeLocal(v2Name: string): string { - for (const [local, name] of typeNames) if (name === v2Name) return local; - const local = localName(v2Name); - typeNames.set(local, v2Name); + function typeLocal(type: TypeMapping): string { + const module = type.module ?? null; + for (const [local, known] of typeNames) { + if (known.name === type.name && known.module === module) return local; + } + const local = localName(type.name); + typeNames.set(local, { module, name: type.name }); return local; } @@ -208,8 +235,7 @@ export function migrateSource( find(call, name, rendered); return false; } - const namespace = - prefix === null ? namespaceLocal(mapping.namespace) : `${prefix}.${mapping.namespace}`; + const namespace = namespaceOf(mapping, prefix); const helper = mapping.result === 'page' ? 'orThrowPage' : 'orThrow'; compatNames.add(helper); const pick = @@ -244,8 +270,7 @@ export function migrateSource( ): void { const mapping = tables.calls[name]; assert(mapping !== undefined, `${name} has a mapping`); - const namespace = - prefix === null ? namespaceLocal(mapping.namespace) : `${prefix}.${mapping.namespace}`; + const namespace = namespaceOf(mapping, prefix); replace(node, `${namespace}.${mapping.operation}`); doubles.set(wrapper, { name, mapping }); migrated.add(name); @@ -334,6 +359,20 @@ export function migrateSource( vitest: boolean, ): void { const objects = factoryObjects(ts, factory); + for (const object of objects) { + for (const property of object.properties) { + const name = property.name; + if (name === undefined || !(ts.isIdentifier(name) || ts.isStringLiteral(name))) + continue; + const mapping = tables.calls[name.text]; + if (mapping?.module !== 'staff') continue; + find( + property, + name.text, + `mock ${STAFF_MODULE} for ${mapping.namespace}.${mapping.operation}`, + ); + } + } const mapped = objects.some((object) => object.properties.some((property) => mappingOf(property) !== null), ); @@ -355,7 +394,9 @@ export function migrateSource( if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) { return null; } - return tables.calls[name.text] ?? null; + const mapping = tables.calls[name.text] ?? null; + // The staff functions are in another module, which this factory does not mock. + return mapping?.module === 'staff' ? null : mapping; } function rewriteFactoryObject(object: TS.ObjectLiteralExpression): void { @@ -442,7 +483,13 @@ export function migrateSource( ts.isStringLiteral(method) ) { const mapping = tables.calls[method.text]; - if (mapping !== undefined) { + if (mapping?.module === 'staff') { + find( + node, + method.text, + `spy on ${STAFF_MODULE} for ${mapping.namespace}.${mapping.operation}`, + ); + } else if (mapping !== undefined) { replace(method, `'${mapping.operation}'`); replace(target, `${target.text}.${mapping.namespace}`); doubles.set(node, { name: method.text, mapping }); @@ -504,10 +551,14 @@ export function migrateSource( } const left = typeName.left; const right = typeName.right.text; - const v2Name = tables.types[right]; + const type = tables.types[right]; if (!ts.isIdentifier(left) || !imports.namespaces.has(left.text)) return; - if (v2Name !== undefined) { - replace(typeName.right, v2Name); + if (type !== undefined && type.module === undefined) { + replace(typeName.right, type.name); + changes += 1; + } else if (type !== undefined) { + // A staff type is not in the namespace of v1. It gets its own import. + replace(typeName, typeLocal(type)); changes += 1; } else if (right in tables.compat) { replace(typeName, compatLocal(right)); @@ -596,15 +647,20 @@ export function migrateSource( // The hoisted `fromV1Mock` of a factory is also there for the tests. if (importsFromV1Mock && !usesFromV1Mock) compatNames.add('fromV1Mock'); - // The new import of the v2 namespaces and types, and of the helpers. - const added = [ - ...[...namespaceNames].map(([name, local]) => - name === local ? name : `${name} as ${local}`, - ), - ...[...typeNames].map(([local, name]) => - name === local ? `type ${name}` : `type ${name} as ${local}`, - ), - ].sort(compareSpecifiers); + // The new imports of the v2 namespaces and types, and of the helpers. + const specifiers = (module: 'staff' | null): string[] => + [ + ...[...namespaceNames.values()] + .filter((entry) => entry.module === module) + .map(({ name, local }) => (name === local ? name : `${name} as ${local}`)), + ...[...typeNames] + .filter(([, entry]) => entry.module === module) + .map(([local, { name }]) => + name === local ? `type ${name}` : `type ${name} as ${local}`, + ), + ].sort(compareSpecifiers); + const added = specifiers(null); + const staffAdded = specifiers('staff'); const changed = importEdits(ts, source, imports.declarations, uses, tables, added, moved); edits.push(...changed.edits); // The new imports go after the last v1 import, or in its place when the tool removes it. @@ -612,6 +668,9 @@ export function migrateSource( if (changed.pending.length > 0) { lines.push(`import { ${changed.pending.join(', ')} } from '${V1_MODULE}';`); } + if (staffAdded.length > 0) { + lines.push(`import { ${staffAdded.join(', ')} } from '${STAFF_MODULE}';`); + } if (compatNames.size > 0) { const names = [...compatNames].sort(compareSpecifiers).join(', '); lines.push(`import { ${names} } from '${COMPAT_MODULE}';`); @@ -674,10 +733,18 @@ function readImports(ts: typeof TS, source: TS.SourceFile): V1Imports { } /** The names that the file declares or uses, so that a new import does not hide one. */ -function declaredNames(ts: typeof TS, source: TS.SourceFile): Set { +function declaredNames( + ts: typeof TS, + source: TS.SourceFile, + replacedType: (name: string) => boolean, +): Set { const names = new Set(); function visit(node: TS.Node): void { - if (ts.isIdentifier(node) && isReference(ts, node)) names.add(node.text); + if (ts.isIdentifier(node) && isReference(ts, node)) { + const parent = node.parent; + const typeName = ts.isTypeReferenceNode(parent) && parent.typeName === node; + if (!typeName || !replacedType(node.text)) names.add(node.text); + } ts.forEachChild(node, visit); } visit(source); @@ -806,10 +873,11 @@ function isV1Name(tables: MigrateTables, name: string): boolean { /** The hint for a use that the tool did not change. */ function hint(tables: MigrateTables, name: string): string { const type = tables.types[name]; - if (type !== undefined) return `v2 has no classes: use an object of the type ${type}`; + if (type !== undefined) return `v2 has no classes: use an object of the type ${type.name}`; const mapping = tables.calls[name]; if (mapping !== undefined) { - return `a use that is not a call: use ${mapping.namespace}.${mapping.operation}`; + const from = mapping.module === 'staff' ? ` of ${STAFF_MODULE}` : ''; + return `a use that is not a call: use ${mapping.namespace}.${mapping.operation}${from}`; } return tables.unmapped[name] ?? 'v2 has no replacement'; } @@ -869,7 +937,7 @@ function renderCall( const initializer = mapping.parameters[index]?.initializer ?? null; return initializer === null ? null : { text: initializer, node: null }; }; - // An input that is only a spread of one argument is that argument: `zones.index(query)`. + // An input that is only a spread of one argument is that argument: `zones.query(query)`. const [only] = template.kind === 'object' ? template.entries : []; const whole = template.kind === 'object' && template.entries.length === 1 && only?.kind === 'spread' diff --git a/v2/src/migrate/v1-map.ts b/v2/src/migrate/v1-map.ts index 2c6c53207..7508fd477 100644 --- a/v2/src/migrate/v1-map.ts +++ b/v2/src/migrate/v1-map.ts @@ -1,5 +1,5 @@ // Generated by scripts/v1-map.ts from the v1 source and the v2 operations. Do not edit. -import type { CallMap } from './map.ts'; +import type { CallMap, TypeMapping } from './map.ts'; /** The v2 call for each v1 REST function. */ export const V1_CALLS: CallMap = { @@ -39,6 +39,19 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + addAnswer: { + module: 'staff', + namespace: 'surveysAnswers', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, addApiKey: { namespace: 'apiKeys', operation: 'create', @@ -219,6 +232,19 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + addInvitation: { + module: 'staff', + namespace: 'surveysInvitations', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, addLDAPSource: { namespace: 'ldapAuthentications', operation: 'create', @@ -255,6 +281,19 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + addQuestion: { + module: 'staff', + namespace: 'surveysQuestions', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, addRepository: { namespace: 'repositories', operation: 'create', @@ -411,6 +450,19 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + addSurvey: { + module: 'staff', + namespace: 'surveys', + operation: 'create', + parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], + input: { + kind: 'object', + entries: [{ kind: 'property', key: 'body', value: { kind: 'arg', index: 0 } }], + }, + result: 'data', + pick: null, + notes: [], + }, addSystem: { namespace: 'systems', operation: 'create', @@ -1039,7 +1091,7 @@ export const V1_CALLS: CallMap = { }, listPublicEvents: { namespace: 'publicEvents', - operation: 'index', + operation: 'query', parameters: [ { name: 'system_id', initializer: null, use: 'mapped' }, { name: 'query_params', initializer: '{}', use: 'mapped' }, @@ -1270,7 +1322,7 @@ export const V1_CALLS: CallMap = { }, listSystemTriggers: { namespace: 'systemTriggers', - operation: 'index', + operation: 'query', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, { name: 'query_params', initializer: '{}', use: 'mapped' }, @@ -1529,7 +1581,7 @@ export const V1_CALLS: CallMap = { }, queryAlertDashboards: { namespace: 'alertDashboards', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1538,16 +1590,26 @@ export const V1_CALLS: CallMap = { }, queryAlerts: { namespace: 'alerts', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', pick: null, notes: [], }, + queryAnswers: { + module: 'staff', + namespace: 'surveysAnswers', + operation: 'query', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, queryApiKeys: { namespace: 'apiKeys', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1556,7 +1618,7 @@ export const V1_CALLS: CallMap = { }, queryApplications: { namespace: 'oauthApplications', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1565,7 +1627,7 @@ export const V1_CALLS: CallMap = { }, queryAssetCategories: { namespace: 'assetCategories', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1574,7 +1636,7 @@ export const V1_CALLS: CallMap = { }, queryAssetPurchaseOrders: { namespace: 'assetPurchaseOrders', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1583,7 +1645,7 @@ export const V1_CALLS: CallMap = { }, queryAssets: { namespace: 'assets', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1592,7 +1654,7 @@ export const V1_CALLS: CallMap = { }, queryAssetTypes: { namespace: 'assetTypes', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1619,7 +1681,7 @@ export const V1_CALLS: CallMap = { }, queryDomains: { namespace: 'domains', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1628,7 +1690,7 @@ export const V1_CALLS: CallMap = { }, queryDrivers: { namespace: 'drivers', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1637,7 +1699,7 @@ export const V1_CALLS: CallMap = { }, queryEdges: { namespace: 'edges', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1646,7 +1708,7 @@ export const V1_CALLS: CallMap = { }, queryGroupHistory: { namespace: 'groupsHistory', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1655,7 +1717,7 @@ export const V1_CALLS: CallMap = { }, queryGroupInvitations: { namespace: 'groupsInvitations', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1664,7 +1726,7 @@ export const V1_CALLS: CallMap = { }, queryGroups: { namespace: 'groups', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1673,7 +1735,7 @@ export const V1_CALLS: CallMap = { }, queryGroupUsers: { namespace: 'groupsUsers', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1682,7 +1744,7 @@ export const V1_CALLS: CallMap = { }, queryGroupZones: { namespace: 'groupsZones', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1691,16 +1753,26 @@ export const V1_CALLS: CallMap = { }, queryHistory: { namespace: 'history', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', pick: null, notes: [], }, + queryInvitations: { + module: 'staff', + namespace: 'surveysInvitations', + operation: 'query', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, queryLDAPSources: { namespace: 'ldapAuthentications', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1709,7 +1781,7 @@ export const V1_CALLS: CallMap = { }, queryModules: { namespace: 'modules', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1718,7 +1790,7 @@ export const V1_CALLS: CallMap = { }, queryOAuthSources: { namespace: 'oauthAuthentications', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1743,9 +1815,19 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + queryQuestions: { + module: 'staff', + namespace: 'surveysQuestions', + operation: 'query', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, queryRepositories: { namespace: 'repositories', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1754,7 +1836,7 @@ export const V1_CALLS: CallMap = { }, querySAMLSources: { namespace: 'samlAuthentications', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1763,7 +1845,7 @@ export const V1_CALLS: CallMap = { }, querySettings: { namespace: 'settings', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1772,7 +1854,7 @@ export const V1_CALLS: CallMap = { }, queryShortUrls: { namespace: 'shortUrl', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1790,7 +1872,7 @@ export const V1_CALLS: CallMap = { }, querySignageAIProviders: { namespace: 'signageAiProviders', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1799,7 +1881,7 @@ export const V1_CALLS: CallMap = { }, querySignageMedia: { namespace: 'playlistMedia', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1808,7 +1890,7 @@ export const V1_CALLS: CallMap = { }, querySignagePlaylists: { namespace: 'playlist', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1817,7 +1899,7 @@ export const V1_CALLS: CallMap = { }, querySignagePlugins: { namespace: 'signagePlugins', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1826,7 +1908,7 @@ export const V1_CALLS: CallMap = { }, querySignageTemplateMappings: { namespace: 'signageTemplateMappings', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1835,7 +1917,7 @@ export const V1_CALLS: CallMap = { }, querySignageTemplates: { namespace: 'signageTemplates', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1844,16 +1926,26 @@ export const V1_CALLS: CallMap = { }, queryStorages: { namespace: 'storages', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', pick: null, notes: [], }, + querySurveys: { + module: 'staff', + namespace: 'surveys', + operation: 'query', + parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], + input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, + result: 'data', + pick: null, + notes: [], + }, querySystems: { namespace: 'systems', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1871,7 +1963,7 @@ export const V1_CALLS: CallMap = { }, queryTriggers: { namespace: 'triggers', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1889,7 +1981,7 @@ export const V1_CALLS: CallMap = { }, queryUsers: { namespace: 'users', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -1898,7 +1990,7 @@ export const V1_CALLS: CallMap = { }, queryWebrtcRooms: { namespace: 'webRtc', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'data', @@ -1907,7 +1999,7 @@ export const V1_CALLS: CallMap = { }, queryZones: { namespace: 'zones', - operation: 'index', + operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, result: 'page', @@ -2208,6 +2300,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + removeInvitation: { + module: 'staff', + namespace: 'surveysInvitations', + operation: 'destroy', + parameters: [ + { name: 'token', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'token', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, removeLDAPSource: { namespace: 'ldapAuthentications', operation: 'destroy', @@ -2262,6 +2373,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + removeQuestion: { + module: 'staff', + namespace: 'surveysQuestions', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, removeRepository: { namespace: 'repositories', operation: 'destroy', @@ -2451,6 +2581,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + removeSurvey: { + module: 'staff', + namespace: 'surveys', + operation: 'destroy', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, removeSystem: { namespace: 'systems', operation: 'destroy', @@ -3053,6 +3202,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + showInvitation: { + module: 'staff', + namespace: 'surveysInvitations', + operation: 'show', + parameters: [ + { name: 'token', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'token', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, showLDAPSource: { namespace: 'ldapAuthentications', operation: 'show', @@ -3113,6 +3281,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + showQuestion: { + module: 'staff', + namespace: 'surveysQuestions', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, showRepository: { namespace: 'repositories', operation: 'show', @@ -3319,6 +3506,25 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + showSurvey: { + module: 'staff', + namespace: 'surveys', + operation: 'show', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'query_params', initializer: '{}', use: 'mapped' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'spread', index: 1 }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, showSystem: { namespace: 'systems', operation: 'show', @@ -3954,6 +4160,26 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + updateInvitation: { + module: 'staff', + namespace: 'surveysInvitations', + operation: 'update', + parameters: [ + { name: 'token', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'token', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, updateLDAPSource: { namespace: 'ldapAuthentications', operation: 'update', @@ -4030,6 +4256,26 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + updateQuestion: { + module: 'staff', + namespace: 'surveysQuestions', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, updateRepository: { namespace: 'repositories', operation: 'update', @@ -4297,6 +4543,26 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, + updateSurvey: { + module: 'staff', + namespace: 'surveys', + operation: 'update', + parameters: [ + { name: 'id', initializer: null, use: 'mapped' }, + { name: 'form_data', initializer: null, use: 'mapped' }, + { name: 'method', initializer: "'patch'", use: 'ignored' }, + ], + input: { + kind: 'object', + entries: [ + { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, + { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, + ], + }, + result: 'data', + pick: null, + notes: [], + }, updateSystem: { namespace: 'systems', operation: 'update', @@ -4529,44 +4795,47 @@ export const V1_CALLS: CallMap = { }; /** The v2 type for each v1 class, such as `Zone` for `PlaceZone`. */ -export const V1_TYPES: Readonly> = { - PlaceAlert: 'Alert', - PlaceAlertDashboard: 'AlertDashboard', - PlaceApiKey: 'ApiKeysResponse', - PlaceApplication: 'Application', - PlaceAsset: 'Asset', - PlaceAssetCategory: 'AssetCategory', - PlaceAssetPurchaseOrder: 'AssetPurchaseOrder', - PlaceAssetType: 'AssetType', - PlaceDomain: 'Domain', - PlaceDriver: 'Driver', - PlaceEdge: 'Edge', - PlaceGroup: 'Group', - PlaceGroupInvitation: 'GroupInvitation', - PlaceGroupUser: 'GroupUser', - PlaceGroupZone: 'GroupZone', - PlaceHistory: 'History', - PlaceLDAPSource: 'LdapAuthentication', - PlaceMetadata: 'Metadata', - PlaceModule: 'Module', - PlaceMQTTBroker: 'Broker', - PlaceOAuthSource: 'OauthAuthentication', - PlaceRepository: 'Repository', - PlaceSAMLSource: 'SamlAuthentication', - PlaceSettings: 'Settings', - PlaceShortUrl: 'ShortUrl', - PlaceStorage: 'Storage', - PlaceSystem: 'System', - PlaceTrigger: 'Trigger', - PlaceUser: 'User', - PlaceZone: 'Zone', - SignageMedia: 'PlaylistItem', - SignagePlaylist: 'Playlist', - SignagePlaylistItemSchedule: 'PlaylistItemSchedule', - SignagePlaylistMedia: 'PlaylistRevision', - SignagePlugin: 'SignagePlugin', - SignageTemplate: 'SignageTemplate', - SignageTemplateMapping: 'SignageTemplateMapping', +export const V1_TYPES: Readonly> = { + PlaceAlert: { name: 'Alert' }, + PlaceAlertDashboard: { name: 'AlertDashboard' }, + PlaceApiKey: { name: 'ApiKeysResponse' }, + PlaceApplication: { name: 'Application' }, + PlaceAsset: { name: 'Asset' }, + PlaceAssetCategory: { name: 'AssetCategory' }, + PlaceAssetPurchaseOrder: { name: 'AssetPurchaseOrder' }, + PlaceAssetType: { name: 'AssetType' }, + PlaceDomain: { name: 'Domain' }, + PlaceDriver: { name: 'Driver' }, + PlaceEdge: { name: 'Edge' }, + PlaceGroup: { name: 'Group' }, + PlaceGroupInvitation: { name: 'GroupInvitation' }, + PlaceGroupUser: { name: 'GroupUser' }, + PlaceGroupZone: { name: 'GroupZone' }, + PlaceHistory: { name: 'History' }, + PlaceLDAPSource: { name: 'LdapAuthentication' }, + PlaceMetadata: { name: 'Metadata' }, + PlaceModule: { name: 'Module' }, + PlaceMQTTBroker: { name: 'Broker' }, + PlaceOAuthSource: { name: 'OauthAuthentication' }, + PlaceRepository: { name: 'Repository' }, + PlaceSAMLSource: { name: 'SamlAuthentication' }, + PlaceSettings: { name: 'Settings' }, + PlaceShortUrl: { name: 'ShortUrl' }, + PlaceStorage: { name: 'Storage' }, + PlaceSystem: { name: 'System' }, + PlaceTrigger: { name: 'Trigger' }, + PlaceUser: { name: 'User' }, + PlaceZone: { name: 'Zone' }, + SignageMedia: { name: 'PlaylistItem' }, + SignagePlaylist: { name: 'Playlist' }, + SignagePlaylistItemSchedule: { name: 'PlaylistItemSchedule' }, + SignagePlaylistMedia: { name: 'PlaylistRevision' }, + SignagePlugin: { name: 'SignagePlugin' }, + SignageTemplate: { name: 'SignageTemplate' }, + SignageTemplateMapping: { name: 'SignageTemplateMapping' }, + Survey: { name: 'Survey', module: 'staff' }, + SurveyInvitation: { name: 'SurveyInvitation', module: 'staff' }, + SurveyQuestion: { name: 'SurveyQuestion', module: 'staff' }, }; /** The v1 names that `@placeos/ts-client/compat` has. The tool moves their imports. */ @@ -4596,11 +4865,7 @@ export const V1_COMPAT: Readonly> = { /** The v1 exports that the tool does not change, with a hint. */ export const V1_UNMAPPED: Readonly> = { - addAnswer: 'no v2 operation for POST /api/staff/v1/surveys/answers', - addInvitation: 'no v2 operation for POST /api/staff/v1/surveys/invitations', addMetadata: 'no v2 operation for POST /api/engine/v2/metadata', - addQuestion: 'no v2 operation for POST /api/staff/v1/surveys/questions', - addSurvey: 'no v2 operation for POST /api/staff/v1/surveys', apiEndpoint: 'use createAuthSession and configure (README: Log in)', apiKey: 'use createAuthSession and configure (README: Log in)', appHeaders: 'use createAuthSession and configure (README: Log in)', @@ -4668,18 +4933,11 @@ export const V1_UNMAPPED: Readonly> = { put: 'use a generated operation, or fetch', qrCodeUrl: 'it sends 0 requests', query: 'a v1 request helper: use the generated operation', - queryAnswers: 'no v2 operation for GET /api/staff/v1/surveys/answers', - queryInvitations: 'no v2 operation for GET /api/staff/v1/surveys/invitations', - queryQuestions: 'no v2 operation for GET /api/staff/v1/surveys/questions', - querySurveys: 'no v2 operation for GET /api/staff/v1/surveys', redirectUri: 'use createAuthSession and configure (README: Log in)', refreshAuthority: 'use createAuthSession and configure (README: Log in)', refreshToken: 'use createAuthSession and configure (README: Log in)', remove: 'a v1 request helper: use the generated operation', removeFragment: 'v2 has no replacement', - removeInvitation: 'no v2 operation for DELETE /api/staff/v1/surveys/invitations/s0zq', - removeQuestion: 'no v2 operation for DELETE /api/staff/v1/surveys/questions/s0zq', - removeSurvey: 'no v2 operation for DELETE /api/staff/v1/surveys/s0zq', requestTotal: 'a v1 request helper: use the generated operation', responseHeaders: 'use a generated operation, or fetch', scoped_log: 'v2 has no replacement', @@ -4691,24 +4949,15 @@ export const V1_UNMAPPED: Readonly> = { shortUrlQrCodePngUrl: 'it sends 0 requests', shortUrlRedirectUrl: 'it sends 0 requests', show: 'a v1 request helper: use the generated operation', - showInvitation: 'no v2 operation for GET /api/staff/v1/surveys/invitations/s0zq', - showQuestion: 'no v2 operation for GET /api/staff/v1/surveys/questions/s0zq', - showSurvey: 'no v2 operation for GET /api/staff/v1/surveys/s0zq', simplifiedTime: 'v2 has no replacement', sleep: 'v2 has no replacement', status: 'use createRealtime (README: Realtime)', - Survey: 'v2 has no replacement', SurveyAnswer: 'v2 has no replacement', - SurveyInvitation: 'v2 has no replacement', - SurveyQuestion: 'v2 has no replacement', systemControlUrl: 'it sends 0 requests', token: 'use createAuthSession and configure (README: Log in)', unbind: 'use createRealtime (README: Realtime)', undeleteResource: 'v1 sends a body, and history.undelete has none', update: 'a v1 request helper: use the generated operation', - updateInvitation: 'no v2 operation for PATCH /api/staff/v1/surveys/invitations/s0zq', - updateQuestion: 'no v2 operation for PATCH /api/staff/v1/surveys/questions/s0zq', - updateSurvey: 'no v2 operation for PATCH /api/staff/v1/surveys/s0zq', value: 'use createRealtime (README: Realtime)', waitForSignal: 'v2 has no replacement', webrtcSignallerUrl: 'it sends 0 requests', diff --git a/v2/src/mock/index.ts b/v2/src/mock/index.ts index 4396e0418..a31e8cc52 100644 --- a/v2/src/mock/index.ts +++ b/v2/src/mock/index.ts @@ -9,7 +9,7 @@ * * configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); * mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); - * mockEndpoint('zones.index', (input) => respond([{ id: 'zone-1' }], { total: 1 })); + * mockEndpoint('zones.query', (input) => respond([{ id: 'zone-1' }], { total: 1 })); * * const result = await zones.show({ id: 'zone-1' }); // `ok`, with a `Zone` * ``` @@ -27,25 +27,35 @@ import { assert } from '../core/assert.ts'; import type { CallError, CallMock, MockAnswer, Reply } from '../core/client.ts'; import type { Result } from '../core/result.ts'; import type * as Operations from '../generated/operations/index.ts'; +import type * as StaffOperations from '../generated/staff/operations/index.ts'; type Namespaces = typeof Operations; +type StaffNamespaces = typeof StaffOperations; -/** The name of each endpoint, such as `zones.show`. */ -export type EndpointName = { - [N in keyof Namespaces]: { - [F in keyof Namespaces[N]]: `${N & string}.${F & string}`; - }[keyof Namespaces[N]]; -}[keyof Namespaces]; +/** `.` for each function of the namespaces. */ +type Names = { + [N in keyof T]: { [F in keyof T[N]]: `${N & string}.${F & string}` }[keyof T[N]]; +}[keyof T]; -/** The function of an endpoint, such as `zones.show` for `'zones.show'`. */ -type EndpointFunction = K extends `${infer N}.${infer F}` - ? N extends keyof Namespaces - ? F extends keyof Namespaces[N] - ? Namespaces[N][F] +/** + * The name of each endpoint, such as `zones.show`. The staff API endpoints start with `staff.`, + * such as `staff.bookings.query`. + */ +export type EndpointName = Names | `staff.${Names}`; + +type FunctionOf = K extends `${infer N}.${infer F}` + ? N extends keyof T + ? F extends keyof T[N] + ? T[N][F] : never : never : never; +/** The function of an endpoint, such as `zones.show` for `'zones.show'`. */ +type EndpointFunction = K extends `staff.${infer S}` + ? FunctionOf + : FunctionOf; + /** The input of an endpoint: its path and query parameters, and `body` if it has one. */ export type EndpointInput = EndpointFunction extends (...args: infer A) => unknown ? NonNullable : never; diff --git a/v2/src/staff.ts b/v2/src/staff.ts new file mode 100644 index 000000000..2cb1fe154 --- /dev/null +++ b/v2/src/staff.ts @@ -0,0 +1,19 @@ +/** + * The PlaceOS staff API client, at `@placeos/ts-client/staff`. It uses the client of `configure`, + * as the REST API functions do: + * + * ```ts + * import { configure } from '@placeos/ts-client'; + * import { bookings } from '@placeos/ts-client/staff'; + * + * configure({ baseUrl: '', auth: session.clientAuth }); + * const result = await bookings.query({ period_start, period_end, type: 'desk' }); + * ``` + * + * The staff API has its own schemas, such as `Booking`. A schema that both APIs have, such as + * `Zone`, is in both entries with the same shape. + * + * @module + */ +export * from './generated/staff/operations/index.ts'; +export * from './generated/staff/schemas.ts'; diff --git a/v2/test/compat.test.ts b/v2/test/compat.test.ts index ee94b252b..e18abe8df 100644 --- a/v2/test/compat.test.ts +++ b/v2/test/compat.test.ts @@ -55,7 +55,7 @@ test('a v2 call gets the response of a v1 mock endpoint', async () => { }); const [zone, page] = await Promise.all([ zones.show({ id: 'zone-1', complete: true }, options).then(orThrow), - zones.index({ tags: ['level'] }, options).then(orThrowPage), + zones.query({ tags: ['level'] }, options).then(orThrowPage), ]); expect(zone).toMatchObject({ id: 'zone-1', name: 'Level 1', tags: ['level'] }); // A required field that the mock leaves out gets its empty value. diff --git a/v2/test/loose/consumer.ts b/v2/test/loose/consumer.ts index da60123fe..f94b22977 100644 --- a/v2/test/loose/consumer.ts +++ b/v2/test/loose/consumer.ts @@ -10,7 +10,7 @@ import { mockEndpoint, respond } from '../../dist/mock/index.js'; export async function calls(): Promise { // An operation without a body does not ask for one. const zone: Zone = await zones.show({ id: 'zone-1' }).then(orThrow); - const page = await zones.index({ limit: 10 }).then(orThrowPage); + const page = await zones.query({ limit: 10 }).then(orThrowPage); await zones.update({ id: zone.id, body: { name: 'name' } }).then(orThrow); await metadata.show({ id: 'zone-1', name: 'settings' }).then(orThrow); // A v1 enum value fits the v2 field. @@ -21,7 +21,7 @@ export async function calls(): Promise { await zones.show({ id: 'zone-1', no_such_parameter: true }); // A typed mock: the input and the data have the types of the endpoint. mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); - mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 1 })); + mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 1 })); mockEndpoint('metadata.show', () => ({ settings: { details: { theme: 'dark' } } })); // @ts-expect-error there is no such endpoint mockEndpoint('zones.no_such_endpoint', () => ({})); diff --git a/v2/test/migrate.test.ts b/v2/test/migrate.test.ts index 30979d44c..6aef23688 100644 --- a/v2/test/migrate.test.ts +++ b/v2/test/migrate.test.ts @@ -34,7 +34,7 @@ test('rewrites calls, types and imports', () => { "import { type Zone, zones } from '@placeos/ts-client';", "import { orThrow, orThrowPage } from '@placeos/ts-client/compat';", 'async function load(id: string, query: object): Promise {', - ' const list = await zones.index(query).then(orThrowPage);', + ' const list = await zones.query(query).then(orThrowPage);', ' return zones.show({ id, complete: true }).then(orThrow);', '}', ].join('\n'), @@ -88,7 +88,7 @@ test('gives a new import another name when the file has the name', () => { [ "import { zones as zonesV2 } from '@placeos/ts-client';", "import { orThrowPage } from '@placeos/ts-client/compat';", - 'const zones = await zonesV2.index({}).then(orThrowPage);', + 'const zones = await zonesV2.query({}).then(orThrowPage);', ].join('\n'), ); }); @@ -181,7 +181,7 @@ test('rewrites test doubles: the function, the mock values and the argument chec "import { fromV1Mock, mockPage, mockReply } from '@placeos/ts-client/compat';", "vi.mock('@placeos/ts-client', { spy: true });", "vi.mocked(zones.show).mockResolvedValue(mockReply({ id: 'zone-1' } as any));", - 'vi.mocked(zones.index).mockResolvedValueOnce(mockPage({ data: [], total: 0 }));', + 'vi.mocked(zones.query).mockResolvedValueOnce(mockPage({ data: [], total: 0 }));', "vi.mocked(zones.show).mockRejectedValue(new Error('403'));", "expect(zones.show).toHaveBeenCalledWith({ id: 'zone-1' });", 'expect(zones.show).not.toHaveBeenCalled();', @@ -226,7 +226,7 @@ test('rewrites the v1 functions of a vi.mock factory to v2 namespaces', () => { "const { fromV1Mock } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", "vi.mock('@placeos/ts-client', () => ({ authority: vi.fn(() => null), " + "zones: { show: vi.fn(fromV1Mock((id: string) => Promise.resolve({ id }), ['id', '...'])), " + - "index: vi.fn(fromV1Mock(undefined, ['...'], 'page')) }, " + + "query: vi.fn(fromV1Mock(undefined, ['...'], 'page')) }, " + "metadata: { show: vi.fn(fromV1Mock(() => ({ details: {} }), ['id', 'name'], 'data', 'name')) } }));", ]); }); @@ -243,10 +243,45 @@ test('fromV1Mock gives the v1 arguments and a v2 result', async () => { await show({ id: 'zone-1', complete: true }); // An empty last argument is left out, as the v1 call left it out. expect(calls).toEqual([['zone-1'], ['zone-1', { complete: true }]]); - const index = fromV1Mock(() => ({ data: [1], total: 9 }), ['...'], 'page'); - expect(orThrowPage(await index({})).total).toBe(9); + const query = fromV1Mock(() => ({ data: [1], total: 9 }), ['...'], 'page'); + expect(orThrowPage(await query({})).total).toBe(9); const meta = fromV1Mock(() => ({ details: 1 }), ['id', 'name'], 'data', 'name'); expect(orThrow(await meta({ id: 'z', name: 'settings' }))).toEqual({ settings: { details: 1 }, }); }); + +test('a v2 type gets an alias when the v1 class stays for a value use', () => { + const result = migrate( + [ + "import { SignagePlugin } from '@placeos/ts-client';", + 'const plugin: SignagePlugin = new SignagePlugin();', + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import { SignagePlugin, type SignagePlugin as SignagePluginV2 } from '@placeos/ts-client';", + 'const plugin: SignagePluginV2 = new SignagePlugin();', + ]); +}); + +test('rewrites the v1 staff functions to @placeos/ts-client/staff', () => { + const result = migrate( + [ + "import { querySurveys, showSurvey, Survey, showZone } from '@placeos/ts-client';", + 'const assets = 1;', + 'const survey: Survey = await showSurvey(id);', + 'const list = await querySurveys({ zone_id: zone });', + 'await showZone(id);', + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import { zones } from '@placeos/ts-client';", + "import { type Survey, surveys } from '@placeos/ts-client/staff';", + "import { orThrow } from '@placeos/ts-client/compat';", + 'const assets = 1;', + 'const survey: Survey = await surveys.show({ id }).then(orThrow);', + // v1 `querySurveys` gave a list, not a page. + 'const list = await surveys.query({ zone_id: zone }).then(orThrow);', + 'await zones.show({ id }).then(orThrow);', + ]); +}); diff --git a/v2/test/mock.test.ts b/v2/test/mock.test.ts index 83866e5a2..54be60404 100644 --- a/v2/test/mock.test.ts +++ b/v2/test/mock.test.ts @@ -42,11 +42,11 @@ test('a mock gets the typed input and gives the parsed data', async () => { }); test('respond sets the status and the page total, and the body reaches the mock', async () => { - mockEndpoint('zones.index', () => respond([{ id: 'zone-1' }], { total: 25 })); + mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 25 })); mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 1, }); - const page = await zones.index({ limit: 1 }, options); + const page = await zones.query({ limit: 1 }, options); expect(page.ok && pageInfo(page.value.headers).total).toBe(25); const updated = await systems.update( { sys_id: 'sys-1', version: 2, body: { name: 'Room' } }, @@ -92,3 +92,15 @@ test('the compiler checks the name, the input and the data', () => { // An endpoint without a response schema gives bytes, text or nothing. mockEndpoint('zones.destroy', () => undefined); }); + +test('a staff API endpoint has a typed mock too', async () => { + const { bookings } = await import('../src/staff.ts'); + mockEndpoint('staff.bookings.show', (input) => ({ + id: Number(input.id), + booking_type: 'desk', + })); + const result = await bookings.show({ id: 7 }, options); + expect(result.ok && result.value.data).toMatchObject({ id: 7, booking_type: 'desk' }); + // @ts-expect-error the staff endpoints start with `staff.` + mockEndpoint('bookings.show', () => ({})); +}); From 2a18f14f61fd6b54b42eb3e9bde36396a26fd221 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 17 Nov 2026 20:56:48 +1100 Subject: [PATCH 09/29] ci(v2): regenerate the client each day, and close the stale regeneration PRs The generated client is in the repository, and nothing showed when the API documents on master moved ahead of it. - The `v2 regenerate` workflow runs `v2/scripts/regenerate-pr.sh` each day. When the output changes, it opens a PR on `bot/v2-regenerate-` with the diff and the check results. - A newer regeneration closes the older PRs and deletes their branches. When master matches the documents, it closes all of them. Each run also deletes the regeneration branches without an open PR, such as the branch of a merged PR. - The same change on a later day finds its open PR and does nothing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-regenerate.yml | 45 +++++++++ v2/README.md | 9 +- v2/scripts/regenerate-pr.sh | 143 ++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/v2-regenerate.yml create mode 100755 v2/scripts/regenerate-pr.sh diff --git a/.github/workflows/v2-regenerate.yml b/.github/workflows/v2-regenerate.yml new file mode 100644 index 000000000..ffffd1cc6 --- /dev/null +++ b/.github/workflows/v2-regenerate.yml @@ -0,0 +1,45 @@ +# Regenerates the v2 client from the API documents on master each day. A change opens a PR, and +# the older regeneration PRs close. See v2/scripts/regenerate-pr.sh. +# +# A PR that `GITHUB_TOKEN` opens does not start the `v2` checks, so the script runs the checks and +# puts the results in the PR. Set the secret `V2_REGENERATE_TOKEN` (a token with `contents` and +# `pull-requests` write access) to open the PRs as that token, and then the checks start too. +# With `GITHUB_TOKEN`, "Allow GitHub Actions to create and approve pull requests" must be on in the +# settings of the repository. +name: v2 regenerate + +on: + schedule: + - cron: '17 3 * * *' + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +concurrency: + group: v2-regenerate + cancel-in-progress: false + +jobs: + regenerate: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + ref: master + token: ${{ secrets.V2_REGENERATE_TOKEN || github.token }} + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.3 + + - run: bun install --frozen-lockfile + working-directory: v2 + # The v1 to v2 map loads the v1 source, which needs the v1 packages. + - run: npm ci --ignore-scripts + + - run: v2/scripts/regenerate-pr.sh + env: + GH_TOKEN: ${{ secrets.V2_REGENERATE_TOKEN || github.token }} diff --git a/v2/README.md b/v2/README.md index edda4aff7..e8fc9393d 100644 --- a/v2/README.md +++ b/v2/README.md @@ -394,7 +394,14 @@ bun run generate:check # Fails if the generated files do not match the current The generated files are in the repository, so a change to the API shows as a diff. Examine the diff before you commit it. `generate:check` can fail because the API changed, not because of your -change, so it is not part of `bun test`. +change, so it is not part of `bun test` or of the checks of a PR. + +Each day, the `v2 regenerate` workflow regenerates the client from the API documents on master +(`scripts/regenerate-pr.sh`). When the output changes, it opens a PR with the diff and the results +of the checks. It also closes the older regeneration PRs, because the new one has their changes. +When master matches the documents again, it closes all of them. Each run deletes the +regeneration branches that have no open PR, such as the branch of a merged PR. `DRY_RUN=1 +scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. The generator stops with an assertion on a part of the document that it does not support. Add the support to `scripts/generate.ts` and `src/core/schema.ts`. diff --git a/v2/scripts/regenerate-pr.sh b/v2/scripts/regenerate-pr.sh new file mode 100755 index 000000000..581f5c5c3 --- /dev/null +++ b/v2/scripts/regenerate-pr.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# Opens a pull request when the generated v2 client does not match the API documents on master, +# and closes the older regeneration pull requests. `.github/workflows/v2-regenerate.yml` runs it +# each day, from the root of the repository. +# +# v2/scripts/regenerate-pr.sh Regenerates, then pushes and opens or closes PRs. +# DRY_RUN=1 v2/scripts/regenerate-pr.sh Regenerates and shows what it would do on GitHub. +# +# The branch name has a hash of the change. A second run with the same change finds the open PR +# and does nothing. A run with another change opens a new PR and closes the old ones. Each run also +# deletes the regeneration branches that have no open PR, such as the branch of a merged PR. +set -euo pipefail + +readonly BRANCH_PREFIX='bot/v2-regenerate-' +readonly BASE="${BASE:-master}" +# More open regeneration PRs or branches than this is a bug in this script, not a normal state. +readonly PRS_MAX=50 +readonly BRANCHES_MAX=200 +readonly LOG_DIR="${RUNNER_TEMP:-$(mktemp -d)}" + +# Runs a command that changes GitHub. A dry run prints it. +remote() { + if [ "${DRY_RUN:-}" = 1 ]; then + echo "dry run: $*" + else + "$@" + fi +} + +# The open regeneration PRs: " " on each line. +open_prs() { + gh pr list --state open --base "$BASE" --limit "$PRS_MAX" --json number,headRefName \ + --jq ".[] | select(.headRefName | startswith(\"$BRANCH_PREFIX\")) | \"\(.number) \(.headRefName)\"" +} + +# Closes each open regeneration PR except the one on branch $1, with the comment $2. +close_others() { + local keep="$1" comment="$2" prs number head + # A failure of `gh` stops the script here, not in the loop. + prs="$(open_prs)" + while read -r number head; do + if [ -z "$number" ] || [ "$head" = "$keep" ]; then continue; fi + echo "Closing #$number ($head)." + remote gh pr close "$number" --delete-branch --comment "$comment" + done <<<"$prs" +} + +# Deletes each regeneration branch on the remote without an open PR, except the branch $1. The +# branch of a merged PR stays when the repository does not delete it, and a run can push a branch +# and then fail to open its PR. +delete_orphan_branches() { + local keep="$1" prs branches branch count=0 + prs="$(open_prs)" + branches="$(git ls-remote --heads origin "refs/heads/$BRANCH_PREFIX*" | sed 's#.*refs/heads/##')" + while read -r branch; do + if [ -z "$branch" ] || [ "$branch" = "$keep" ]; then continue; fi + if awk -v branch="$branch" '$2 == branch { found = 1 } END { exit !found }' <<<"$prs"; then + continue + fi + count=$((count + 1)) + if [ "$count" -gt "$BRANCHES_MAX" ]; then + echo "More than $BRANCHES_MAX regeneration branches. Delete them by hand." >&2 + exit 1 + fi + echo "Deleting the branch $branch. It has no open PR." + remote git push origin --delete "$branch" + done <<<"$branches" +} + +(cd v2 && bun run generate && bun run v1-map) + +if git diff --quiet -- v2; then + echo "The generated client matches the API documents." + close_others '' "Closed by the scheduled regeneration: \`$BASE\` matches the API documents now." + delete_orphan_branches '' + exit 0 +fi + +hash="$(git diff --binary -- v2 | sha256sum | cut -c1-12)" +branch="$BRANCH_PREFIX$hash" +prs="$(open_prs)" +existing="$(awk -v branch="$branch" '$2 == branch { print $1 }' <<<"$prs")" +if [ -n "$existing" ]; then + echo "#$existing has this change." + close_others "$branch" "Superseded by #$existing." + delete_orphan_branches "$branch" + exit 0 +fi + +# A PR that the workflow token opens does not start the PR checks, so the results go in the PR. +results='' +for check in v1-map:check check test build; do + if (cd v2 && bun run "$check") >"$LOG_DIR/$check.log" 2>&1; then + results+="- \`bun run $check\`: passes"$'\n' + else + results+="- \`bun run $check\`: **fails**. See the log of the workflow run."$'\n' + echo "bun run $check fails:" && tail -n 40 "$LOG_DIR/$check.log" + fi +done + +rest_api="$(gh api repos/PlaceOS/rest-api/commits/master --jq .sha)" +staff_api="$(gh api repos/PlaceOS/staff-api/commits/master --jq .sha)" +run_url="${GITHUB_SERVER_URL:-https://github.com}/${GITHUB_REPOSITORY:-PlaceOS/ts-client}/actions/runs/${GITHUB_RUN_ID:-local}" +body="$LOG_DIR/body.md" +cat >"$body" < Date: Tue, 17 Nov 2026 22:18:29 +1100 Subject: [PATCH 10/29] fix(v2): fixes from the sol-loop review of the migration tool, mocks and generator A review of the changes since the last sol loop found silent wrong rewrites in the migration tool, promises without a handler in the mock path, and data without limits. - Migration: a v1 list that maps to a v2 record (listMetadata) is unmapped; `version` keeps the v1 `|| 0` fallback; a test double whose v1 arguments cannot be rebuilt stays v1 with a finding; factory values stay mocks; helper imports are reused or get an alias; the `vi.hoisted` line goes with the new imports; files deeper than AST_DEPTH_MAX and folder walks over ENTRIES_MAX stop. - Client: a mock answer has the deadline, the signal and the size limit of a response, and starts inside `waitWithin`; `waitWithin` checks the signal again after `work()` starts. - Schema: zero-fill picks the union variant that knows the most given fields. - Compat: a string mock body is JSON; the realtime mock has one bounded outbox and named limits. - Regeneration: new generated files are in the change hash. Co-Authored-By: Claude Opus 5.5 --- v2/README.md | 6 + v2/scripts/regenerate-pr.sh | 9 +- v2/scripts/v1-map.ts | 47 ++++++- v2/src/compat/http-mock.ts | 8 +- v2/src/compat/realtime-mock.ts | 31 ++++- v2/src/core/client.ts | 31 ++++- v2/src/core/schema.ts | 34 ++++- v2/src/migrate/cli.ts | 11 +- v2/src/migrate/map.ts | 8 +- v2/src/migrate/migrate.ts | 232 +++++++++++++++++++++++++++------ v2/src/migrate/v1-map.ts | 51 +------- v2/test/compat.test.ts | 18 +++ v2/test/migrate.test.ts | 129 +++++++++++++++++- v2/test/mock.test.ts | 63 +++++++++ 14 files changed, 558 insertions(+), 120 deletions(-) diff --git a/v2/README.md b/v2/README.md index e8fc9393d..224b5e409 100644 --- a/v2/README.md +++ b/v2/README.md @@ -513,6 +513,12 @@ arguments, and it finds the v2 operation with the same method and path. that the parser output has the type of the schema. The tests check the parser. - `configure` keeps one client in module state, so a call does not need a client argument. A call before `configure` is a run-time assertion, not a compile error. +- The mocks keep their registries in module state, as v1 did: the endpoints of + `registerMockEndpoint` and the systems of `registerSystem` (`@placeos/ts-client/compat`), and + the mocks of `mockEndpoint` (`@placeos/ts-client/mock`). A test owns them. It removes them with + `clearMockEndpoints`, `deregisterSystem` and `clearEndpointMocks`. Each registry has a named + limit. The status variables of a mock module are properties with setters that notify the + bindings, as in v1. - `createAuthSession` keeps its state in a closure. The login is a state machine with I/O, and one object with one owner is the clearest model of it. - Records from the server are plain objects, not `Map`s. A `Map` does not go through diff --git a/v2/scripts/regenerate-pr.sh b/v2/scripts/regenerate-pr.sh index 581f5c5c3..f48715b7a 100755 --- a/v2/scripts/regenerate-pr.sh +++ b/v2/scripts/regenerate-pr.sh @@ -68,15 +68,17 @@ delete_orphan_branches() { } (cd v2 && bun run generate && bun run v1-map) +# Staged, so that a new generated file, such as one of a new controller, is in the diff and the hash. +git add -A -- v2 -if git diff --quiet -- v2; then +if git diff --cached --quiet -- v2; then echo "The generated client matches the API documents." close_others '' "Closed by the scheduled regeneration: \`$BASE\` matches the API documents now." delete_orphan_branches '' exit 0 fi -hash="$(git diff --binary -- v2 | sha256sum | cut -c1-12)" +hash="$(git diff --cached --binary -- v2 | sha256sum | cut -c1-12)" branch="$BRANCH_PREFIX$hash" prs="$(open_prs)" existing="$(awk -v branch="$branch" '$2 == branch { print $1 }' <<<"$prs")" @@ -115,7 +117,7 @@ operation. ${results} \`\`\` -$(git diff --stat -- v2 | tail -n 25) +$(git diff --cached --stat -- v2 | tail -n 25) \`\`\` The [scheduled regeneration]($run_url) opened this PR. It closes this PR when a newer @@ -125,7 +127,6 @@ EOF git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git switch -c "$branch" -git add -- v2 git commit -q -m 'chore(v2): regenerate the client from the API documents' # A branch of this name can be left from a failed run on an older base. Only this script writes to # the prefix, so the push replaces it. diff --git a/v2/scripts/v1-map.ts b/v2/scripts/v1-map.ts index 9c4fa92dc..e009f9ae6 100644 --- a/v2/scripts/v1-map.ts +++ b/v2/scripts/v1-map.ts @@ -53,6 +53,8 @@ interface V1Function { kind: ParameterKind; }[]; readonly page: boolean; + /** `true` when v1 gives an array (not a page). */ + readonly list: boolean; /** The v1 class of the data, such as `PlaceZone`, or `null`. */ readonly model: string | null; } @@ -66,6 +68,8 @@ interface V2Operation { readonly segments: readonly string[]; readonly params: ReadonlySet; readonly hasBody: boolean; + /** `true` when the response is an array. */ + readonly list: boolean; /** The named schema of the response data, or of its items, such as `Zone`. */ readonly model: string | null; } @@ -283,7 +287,8 @@ function readV1Functions(): V1Function[] { modelSymbol !== undefined && modelSymbol.flags & ts.SymbolFlags.Class ? modelSymbol.getName() : null; - functions.push({ name, file, parameters, page, model }); + const list = !page && data !== undefined && data !== null && checker.isArrayType(data); + functions.push({ name, file, parameters, page, list, model }); } return functions; } @@ -380,6 +385,8 @@ async function readV2Operations(dir: string, module: 'staff' | null): Promise { + if (template.kind !== 'member') return template; + const plain = await record( + fn, + fn.parameters.map((p, i) => marker(p.kind, i, true, { members: false })), + ); + const request = plain.requests[0]; + const value = request === undefined ? null : new URL(request.url, HOST).searchParams.get(key); + if (value === null) return template; + const fallback = literalQuery(stringTemplate(value)); + if (fallback.kind !== 'literal') return template; + return { ...template, fallback: fallback.value }; +} + async function mapFunction( fn: V1Function, operations: readonly V2Operation[], @@ -539,6 +574,10 @@ async function mapFunction( const segments = url.pathname.split('/').filter(Boolean).map(decodeURIComponent); const operation = findOperation(operations, request.method, segments); if (operation === null) return `no v2 operation for ${request.method} ${url.pathname}`; + // v1 can make the data into a list, such as the metadata of a zone, which v2 gives by name. + if (fn.list && !operation.list) { + return `v1 gives a list, and ${operation.namespace}.${operation.name} gives another shape`; + } const notes: string[] = []; const entries: ObjectEntry[] = []; @@ -556,7 +595,7 @@ async function mapFunction( spreads.add(index); continue; } - const template = stringTemplate(value); + const template = await withFallback(stringTemplate(value), key, fn, record); // v1 updates send the `version` of the data. Only some v2 updates have it. if (template.kind === 'member' && !operation.params.has(key)) continue; if (template.kind === 'literal' && !operation.params.has(key)) { diff --git a/v2/src/compat/http-mock.ts b/v2/src/compat/http-mock.ts index e83dd4910..c9d6691ce 100644 --- a/v2/src/compat/http-mock.ts +++ b/v2/src/compat/http-mock.ts @@ -143,10 +143,14 @@ export const mockFetch: FetchFunction = async (url, init) => { } await delay(handler, init.signal ?? null); if (body === undefined) return new Response(null, { status: 204, headers }); - const text = typeof body === 'string' ? body : JSON.stringify(body); + // v1 gave the value of the callback as it was, also a string. A JSON response has the string + // as JSON. A handler with another `content-type`, such as `text/plain`, sends its text. + const contentType = headers['content-type'] ?? 'application/json'; + const text = + typeof body === 'string' && !contentType.includes('json') ? body : JSON.stringify(body); return new Response(text, { status: 200, - headers: { 'content-type': 'application/json', ...headers }, + headers: { 'content-type': contentType, ...headers }, }); }; diff --git a/v2/src/compat/realtime-mock.ts b/v2/src/compat/realtime-mock.ts index 1563156ea..9dfbea55c 100644 --- a/v2/src/compat/realtime-mock.ts +++ b/v2/src/compat/realtime-mock.ts @@ -24,6 +24,10 @@ import { ERROR_CODE_NAMES } from '../realtime/realtime.ts'; /** More systems is a leak, such as a test that registers in a loop and never removes them. */ export const MOCK_SYSTEMS_MAX = 10_000; +/** More status variables on one mock module is a leak, such as a test that binds random names. */ +export const MOCK_VARIABLES_MAX = 1_000; +/** More messages waiting in one mock socket is a test that sends without letting it answer. */ +export const MOCK_MESSAGES_MAX = 10_000; /** A mock module: its status variables and its functions. As in v1, the values have no type. */ export type MockModule = Record; @@ -94,6 +98,7 @@ function mockModule(properties: object): ModuleState { } function addVariable(state: ModuleState, name: string, value: unknown): void { + assert(state.values.size < MOCK_VARIABLES_MAX, 'fewer variables on a mock module'); state.values.set(name, value); Object.defineProperty(state.module, name, { enumerable: true, @@ -135,11 +140,19 @@ function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket { let open = true; /** The listener of each binding, by the JSON of its target. */ const bound = new Map void>(); - // The socket answers later, as a real one does. - const later = (work: () => void) => - setTimeout(() => { - if (open) work(); - }, 0); + // The socket answers later, as a real one does: the answers wait here, and one timer sends + // them. A close drops the answers that wait. + const outbox: (() => void)[] = []; + let timer: ReturnType | null = null; + const flush = () => { + timer = null; + for (const work of outbox.splice(0, outbox.length)) if (open) work(); + }; + const later = (work: () => void) => { + assert(outbox.length < MOCK_MESSAGES_MAX, 'fewer messages wait in the mock socket'); + outbox.push(work); + timer ??= setTimeout(flush, 0); + }; const reply = (message: object) => later(() => handlers.message(JSON.stringify(message))); later(() => handlers.open()); @@ -172,7 +185,10 @@ function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket { const listeners = state.listeners.get(request.name) ?? new Set(); listeners.add(notify); state.listeners.set(request.name, listeners); - bound.set(key, () => listeners.delete(notify)); + bound.set(key, () => { + listeners.delete(notify); + if (listeners.size === 0) state.listeners.delete(request.name); + }); reply({ id: request.id, type: 'success' }); notify(state.values.get(request.name)); return; @@ -215,6 +231,9 @@ function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket { for (const release of bound.values()) release(); bound.clear(); open = false; + outbox.length = 0; + if (timer !== null) clearTimeout(timer); + timer = null; setTimeout(() => handlers.close(), 0); }, }; diff --git a/v2/src/core/client.ts b/v2/src/core/client.ts index 1d6a81702..9ae5aba18 100644 --- a/v2/src/core/client.ts +++ b/v2/src/core/client.ts @@ -229,8 +229,8 @@ export function createClient(config: ClientConfig): Client { } /** - * The client of `configure`. It is the one module state of the library, so that an application - * does not give its client to each call. + * The client of `configure`, so that an application does not give its client to each call. It is + * the one module state of the core. The mock registries of `compat` and `mock` are the others. */ let configuredClient: Client | null = null; @@ -310,16 +310,29 @@ async function send( bodyText = JSON.stringify(bodyChecked.value); } - // A mock gets the input after the checks, so a test finds the same errors as the server. - const answer = client.mock?.({ name: operation.name, input }) ?? null; - if (answer !== null) return mockResult(operation, await answer); - const timeoutMs = options.timeoutMs ?? client.timeoutMs; assertPositiveInteger(timeoutMs, 'timeoutMs'); // One deadline for the call. The credential, a renewal and each fetch share it, so a slow // login cannot make the call take longer than `timeoutMs`. const deadlineMs = Date.now() + timeoutMs; const signal = options.signal; + + // A mock gets the input after the checks, so a test finds the same errors as the server. Its + // answer has the same limits as a response: the deadline, the signal and the size. It starts + // in `waitWithin`, so that an aborted call does not leave its promise without a handler. + const mock = client.mock; + if (mock !== null) { + const answered = await waitWithin( + () => Promise.resolve(mock({ name: operation.name, input })), + deadlineMs, + signal, + ); + if (!answered.ok) return limitError(answered.error, timeoutMs); + // `null`: the mock does not answer this call, so the request goes to the server. + if (answered.value !== null) { + return mockResult(operation, answered.value, client.responseBytesMax); + } + } // Each attempt gets the credential again, because a `rejected` auth can renew it. let response: Fetched | null = null; for (let attempt = 0; attempt < AUTH_ATTEMPTS_MAX; attempt += 1) { @@ -397,6 +410,7 @@ async function send( function mockResult( operation: AnyOperation, answer: MockAnswer, + bytesMax: number, ): Result, CallError> { const reply = { status: answer.status, headers: answer.headers }; const bytes = @@ -407,6 +421,9 @@ function mockResult( ? answer.data : (JSON.stringify(answer.data) ?? 'null'), ); + if (bytes.length > bytesMax) { + return { ok: false, error: { kind: 'response_too_large', bytesMax } }; + } if (answer.status < 200 || answer.status > 299) { const parsed = decodeJson(bytes); const body = parsed.ok ? parseResponse(json(), parsed.value) : null; @@ -576,6 +593,8 @@ async function waitWithin( timer = setTimeout(() => resolve({ ok: false, error: 'timeout' }), remainingMs); onAbort = () => resolve({ ok: false, error: 'aborted' }); signal?.addEventListener('abort', onAbort, { once: true }); + // `work` can abort the signal before the listener exists, such as a mock of a test. + if (isAborted(signal)) resolve({ ok: false, error: 'aborted' }); }); const settled = promise.then((value): Result => ({ ok: true, diff --git a/v2/src/core/schema.ts b/v2/src/core/schema.ts index 53c3d9a51..cf2a97fb2 100644 --- a/v2/src/core/schema.ts +++ b/v2/src/core/schema.ts @@ -412,19 +412,46 @@ function walk( } return output; } - case 'union': + case 'union': { + if (direction !== 'response_zero') { + for (const variant of node.variants) { + const parsed = walk(variant, value, direction, failure, depth + 1); + if (parsed !== FAIL) return parsed; + failure.segments.length = 0; + } + return fail(failure, 'a match for one variant of the union'); + } + // Zero-fill can make each variant match. The variant that knows the most of the given + // fields wins, so that the fill does not drop them. In a tie, a variant that matches + // without the fill wins, then the first. + let best: unknown = FAIL; + let bestScore = -1; for (const variant of node.variants) { const parsed = walk(variant, value, direction, failure, depth + 1); - if (parsed !== FAIL) return parsed; failure.segments.length = 0; + if (parsed === FAIL) continue; + const strict = walk(variant, value, 'response', failure, depth + 1) !== FAIL; + failure.segments.length = 0; + const score = knownKeys(variant, value) * 2 + (strict ? 1 : 0); + if (score > bestScore) { + best = parsed; + bestScore = score; + } } + if (best !== FAIL) return best; return fail(failure, 'a match for one variant of the union'); + } default: return unreachable(node); } } -/** True if `JSON.stringify` writes `value` as it is. The walk has its own bounded stack. */ +/** The number of keys of `value` that an object schema has. Other schemas know none. */ +function knownKeys(node: SchemaNode, value: unknown): number { + if (node.kind !== 'object' || !isRecord(value)) return 0; + return Object.keys(value).filter((key) => node.keys.has(key)).length; +} + /** The empty value of a schema, for a missing required field of mock data. */ function zeroValue(node: SchemaNode, depth: number): unknown { assert(depth < SCHEMA_DEPTH_MAX, 'the schema depth is less than SCHEMA_DEPTH_MAX'); @@ -464,6 +491,7 @@ function zeroValue(node: SchemaNode, depth: number): unknown { } } +/** True if `JSON.stringify` writes `value` as it is. The walk has its own bounded stack. */ function isJsonValue(value: unknown): boolean { const stack: { readonly value: unknown; readonly depth: number }[] = [{ value, depth: 0 }]; for (let visited = 0; visited < JSON_NODES_MAX; visited += 1) { diff --git a/v2/src/migrate/cli.ts b/v2/src/migrate/cli.ts index 5df354d9d..d0948c951 100644 --- a/v2/src/migrate/cli.ts +++ b/v2/src/migrate/cli.ts @@ -18,6 +18,8 @@ import { V1_CALLS, V1_COMPAT, V1_TYPES, V1_UNMAPPED } from './v1-map.ts'; /** A project has fewer source files. The tool stops at this count. */ const FILES_MAX = 50_000; +/** The walk visits at most this many files and folders, of all kinds. */ +const ENTRIES_MAX = 500_000; /** A larger file is not hand-written source. The tool skips it. */ const FILE_BYTES_MAX = 5_000_000; const SKIPPED_FOLDERS: ReadonlySet = new Set([ @@ -156,7 +158,14 @@ async function sourceFiles(paths: readonly string[]): Promise { if (info.isDirectory()) { for (const entry of await readdir(path, { withFileTypes: true })) { if (entry.isDirectory() && SKIPPED_FOLDERS.has(entry.name)) continue; - if (entry.isDirectory() || entry.isFile()) queue.push(join(path, entry.name)); + if (!entry.isDirectory() && !entry.isFile()) continue; + if (queue.length >= ENTRIES_MAX) { + console.error( + `Stopped at ${ENTRIES_MAX} files and folders. Give a smaller folder.`, + ); + return files.sort(); + } + queue.push(join(path, entry.name)); } continue; } diff --git a/v2/src/migrate/map.ts b/v2/src/migrate/map.ts index 2e876ad34..04c27c319 100644 --- a/v2/src/migrate/map.ts +++ b/v2/src/migrate/map.ts @@ -17,7 +17,13 @@ */ export type Template = | { readonly kind: 'arg'; readonly index: number } - | { readonly kind: 'member'; readonly index: number; readonly key: string } + | { + readonly kind: 'member'; + readonly index: number; + readonly key: string; + /** The value that v1 sends when the argument does not have the member. */ + readonly fallback?: string | number | boolean | null; + } | { readonly kind: 'literal'; readonly value: string | number | boolean | null } | { readonly kind: 'concat'; readonly parts: readonly (string | number)[] } | { readonly kind: 'object'; readonly entries: readonly ObjectEntry[] } diff --git a/v2/src/migrate/migrate.ts b/v2/src/migrate/migrate.ts index 0682a72dd..a4773ec80 100644 --- a/v2/src/migrate/migrate.ts +++ b/v2/src/migrate/migrate.ts @@ -57,6 +57,11 @@ const VALUE_TO_IMPLEMENTATION: Readonly> = { }; /** A chain such as `vi.mocked(f).mockResolvedValueOnce(a).mockResolvedValueOnce(b)` is shorter. */ const CHAIN_DEPTH_MAX = 32; +/** + * The tool walks the syntax tree with recursion. A deeper file, such as one long chain of `+`, is + * left as it is, with a finding. Hand-written code is far less deep. + */ +const AST_DEPTH_MAX = 1_000; /** A name that collides gets a suffix. A file has fewer names with the same base. */ const ALIASES_MAX = 100; @@ -114,7 +119,10 @@ export function migrateSource( const imported = imports.named.get(name); return imported !== undefined && imported in tables.types; }; - const taken = declaredNames(ts, source, typeOnly); + const names = declaredNames(ts, source, typeOnly); + if (names === null) return tooDeep(text); + // A closure does not keep the narrowing of `names`, so this name has the narrow type. + const taken: Set = names; const edits: Edit[] = []; const findings: Finding[] = []; const migrated = new Set(); @@ -138,6 +146,58 @@ export function migrateSource( compatNames.add(kind === 'type' ? `type ${name}` : name); } let changes = 0; + let deep = false; + + // The helpers that a file already imports from the compat module, by name. + const compatImported = new Map(); + for (const statement of source.statements) { + if (!ts.isImportDeclaration(statement)) continue; + const specifier = statement.moduleSpecifier; + if (!ts.isStringLiteral(specifier) || specifier.text !== COMPAT_MODULE) continue; + // A type-only import has no value, so it cannot be a helper at run time. + if (statement.importClause?.isTypeOnly === true) continue; + const bindings = statement.importClause?.namedBindings; + if (bindings === undefined || !ts.isNamedImports(bindings)) continue; + for (const element of bindings.elements) { + if (element.isTypeOnly) continue; + compatImported.set((element.propertyName ?? element.name).text, element.name.text); + } + } + const helperLocals = new Map(); + + /** + * The local name of a compat helper, such as `orThrow`: the name of an import that the file + * has, or a new name that the file does not use. `register` adds it to the new compat import. + */ + function helperLocal( + name: string, + options: { readonly register: boolean } = { register: true }, + ): string { + const imported = compatImported.get(name); + if (imported !== undefined) return imported; + let local = helperLocals.get(name); + if (local === undefined) { + local = localName(name); + helperLocals.set(name, local); + } + if (options.register) compatNames.add(local === name ? name : `${name} as ${local}`); + return local; + } + + /** The name of `vi.hoisted` for `fromV1Mock`, when the file also imports `fromV1Mock`. */ + let hoistedLocal: string | null = null; + + /** + * The local name of `fromV1Mock`. A `vi.mock` factory runs before the imports, so it uses the + * name of `vi.hoisted`. That name is not the name of an import that the file has. + */ + function fromV1MockLocal(options: { readonly inFactory: boolean }): string { + if (options.inFactory && compatImported.has('fromV1Mock')) { + hoistedLocal ??= localName('fromV1Mock'); + return hoistedLocal; + } + return helperLocal('fromV1Mock', { register: false }); + } function find(node: TS.Node, name: string, message: string): void { const at = source.getLineAndCharacterOfPosition(node.getStart(source)); @@ -236,8 +296,7 @@ export function migrateSource( return false; } const namespace = namespaceOf(mapping, prefix); - const helper = mapping.result === 'page' ? 'orThrowPage' : 'orThrow'; - compatNames.add(helper); + const helper = helperLocal(mapping.result === 'page' ? 'orThrowPage' : 'orThrow'); const pick = rendered.pick === null ? '' @@ -311,8 +370,7 @@ export function migrateSource( const [value] = call.arguments; const callee = call.expression; if (RESOLVED_VALUE_METHODS.has(method) && value !== undefined && mapping.pick === null) { - const helper = mapping.result === 'page' ? 'mockPage' : 'mockReply'; - compatNames.add(helper); + const helper = helperLocal(mapping.result === 'page' ? 'mockPage' : 'mockReply'); replace(value, `${helper}(${textOf(value)})`); return; } @@ -324,13 +382,18 @@ export function migrateSource( ts.isPropertyAccessExpression(callee) && implementation !== undefined ) { + if (!invertible(mapping)) { + find(call, name, NOT_INVERTIBLE); + return; + } const v1 = method.startsWith('mockImplementation') ? textOf(value) : `() => (${textOf(value)})`; importsFromV1Mock = true; + const fromV1Mock = fromV1MockLocal({ inFactory: false }); replace( call, - `${textOf(callee.expression)}.${implementation}(fromV1Mock(${v1}, ${fromV1MockArgs(mapping)}))`, + `${textOf(callee.expression)}.${implementation}(${fromV1Mock}(${v1}, ${fromV1MockArgs(mapping)}))`, ); return; } @@ -365,7 +428,11 @@ export function migrateSource( if (name === undefined || !(ts.isIdentifier(name) || ts.isStringLiteral(name))) continue; const mapping = tables.calls[name.text]; - if (mapping?.module !== 'staff') continue; + if (mapping === undefined) continue; + if (mapping.module !== 'staff') { + if (!invertible(mapping)) find(property, name.text, NOT_INVERTIBLE); + continue; + } find( property, name.text, @@ -395,8 +462,10 @@ export function migrateSource( return null; } const mapping = tables.calls[name.text] ?? null; - // The staff functions are in another module, which this factory does not mock. - return mapping?.module === 'staff' ? null : mapping; + // The staff functions are in another module, which this factory does not mock. A function + // with an argument in a template cannot get its v1 arguments. `rewriteFactory` finds both. + if (mapping === null || mapping.module === 'staff' || !invertible(mapping)) return null; + return mapping; } function rewriteFactoryObject(object: TS.ObjectLiteralExpression): void { @@ -436,6 +505,7 @@ export function migrateSource( /** The v2 value of one v1 function of a factory. `null` is a shorthand property. */ function mockValue(value: TS.Expression | null, name: string, mapping: CallMapping): string { const extra = fromV1MockArgs(mapping); + const fromV1Mock = fromV1MockLocal({ inFactory: true }); if ( value !== null && ts.isCallExpression(value) && @@ -443,9 +513,11 @@ export function migrateSource( ) { const [implementation] = value.arguments; const text = implementation === undefined ? 'undefined' : textOf(implementation); - return `${textOf(value.expression)}(fromV1Mock(${text}, ${extra}))`; + return `${textOf(value.expression)}(${fromV1Mock}(${text}, ${extra}))`; } - return `fromV1Mock(${value === null ? name : textOf(value)}, ${extra})`; + // Another value, such as `vi.fn().mockResolvedValue(zone)` or a hoisted mock, is the v1 + // implementation of a new mock, so the v2 function is still a mock that tests can change. + return `vi.fn(${fromV1Mock}(${value === null ? name : textOf(value)}, ${extra}))`; } /** `vi.mocked(f)`, `jest.mocked(f)` or `expect(f)`, with `f` as the first argument. */ @@ -462,9 +534,13 @@ export function migrateSource( return isMocked ? parent : null; } - function visit(node: TS.Node): void { + function visit(node: TS.Node, depth: number): void { + if (depth > AST_DEPTH_MAX) { + deep = true; + return; + } // The children first, so that a call in an argument is changed before the outer call. - ts.forEachChild(node, visit); + ts.forEachChild(node, (child) => visit(child, depth + 1)); if (ts.isCallExpression(node)) { const callee = node.expression; @@ -489,6 +565,8 @@ export function migrateSource( method.text, `spy on ${STAFF_MODULE} for ${mapping.namespace}.${mapping.operation}`, ); + } else if (mapping !== undefined && !invertible(mapping)) { + find(node, method.text, NOT_INVERTIBLE); } else if (mapping !== undefined) { replace(method, `'${mapping.operation}'`); replace(target, `${target.text}.${mapping.namespace}`); @@ -575,6 +653,15 @@ export function migrateSource( if (!isV1Name(tables, imported)) return; if (isCountedAtParent(ts, node, imported, tables)) return; const wrapper = doubleWrapper(node); + const doubleMapping = tables.calls[imported]; + const isDouble = + wrapper !== null || (testFile && !ts.isShorthandPropertyAssignment(node.parent)); + // A test double of a function whose v1 arguments the tool cannot rebuild stays v1. + if (isDouble && doubleMapping !== undefined && !invertible(doubleMapping)) { + countUse(node.text, false); + find(node, imported, NOT_INVERTIBLE); + return; + } if (wrapper !== null && imported in tables.calls) { rewriteDouble(node, wrapper, imported, null); countUse(node.text, true); @@ -602,6 +689,15 @@ export function migrateSource( ) { const name = node.name.text; const wrapper = doubleWrapper(node); + const doubleMapping = tables.calls[name]; + if ( + (wrapper !== null || testFile) && + doubleMapping !== undefined && + !invertible(doubleMapping) + ) { + find(node, name, NOT_INVERTIBLE); + return; + } if (wrapper !== null && name in tables.calls) { rewriteDouble(node, wrapper, name, node.expression.text); return; @@ -642,10 +738,11 @@ export function migrateSource( find(node, node.text, `a test double of v1: make it for the v2 call${target}`); } } - visit(source); + visit(source, 0); + if (deep) return tooDeep(text); // The hoisted `fromV1Mock` of a factory is also there for the tests. - if (importsFromV1Mock && !usesFromV1Mock) compatNames.add('fromV1Mock'); + if (importsFromV1Mock && !usesFromV1Mock) helperLocal('fromV1Mock'); // The new imports of the v2 namespaces and types, and of the helpers. const specifiers = (module: 'staff' | null): string[] => @@ -675,6 +772,12 @@ export function migrateSource( const names = [...compatNames].sort(compareSpecifiers).join(', '); lines.push(`import { ${names} } from '${COMPAT_MODULE}';`); } + if (usesFromV1Mock) { + // `vi.mock` runs before the imports, so its factory gets the helper from `vi.hoisted`. + const local = hoistedLocal ?? fromV1MockLocal({ inFactory: true }); + const binding = local === 'fromV1Mock' ? local : `fromV1Mock: ${local}`; + lines.push(`const { ${binding} } = await vi.hoisted(() => import('${COMPAT_MODULE}'));`); + } const last = imports.declarations.at(-1); assert(last !== undefined, 'a v1 import exists'); if (lines.length > 0 && changed.removed.has(last)) { @@ -688,17 +791,6 @@ export function migrateSource( }); } - if (usesFromV1Mock) { - // `vi.mock` runs before the imports, so its factory gets the helper from `vi.hoisted`. - const lastImport = source.statements.filter(ts.isImportDeclaration).at(-1); - assert(lastImport !== undefined, 'the file has an import'); - edits.push({ - start: lastImport.end, - end: lastImport.end, - text: `\nconst { fromV1Mock } = await vi.hoisted(() => import('${COMPAT_MODULE}'));`, - }); - } - findings.sort((a, b) => a.line - b.line || a.column - b.column); return { text: applyEdits(text, edits, 0), changes, findings, migrated }; } @@ -733,22 +825,57 @@ function readImports(ts: typeof TS, source: TS.SourceFile): V1Imports { } /** The names that the file declares or uses, so that a new import does not hide one. */ +/** The result for a file deeper than `AST_DEPTH_MAX`: no change, and a finding. */ +function tooDeep(text: string): MigrateResult { + const message = `the file nests deeper than ${AST_DEPTH_MAX} levels: change it by hand`; + return { + text, + changes: 0, + findings: [{ line: 1, column: 1, name: V1_MODULE, message }], + migrated: new Set(), + }; +} + +/** + * The names that the file declares, uses or imports from other modules, so that a new import does + * not hide one. `null` for a file deeper than `AST_DEPTH_MAX`. + */ function declaredNames( ts: typeof TS, source: TS.SourceFile, replacedType: (name: string) => boolean, -): Set { +): Set | null { const names = new Set(); - function visit(node: TS.Node): void { + let deep = false; + function visit(node: TS.Node, depth: number): void { + if (depth > AST_DEPTH_MAX) { + deep = true; + return; + } if (ts.isIdentifier(node) && isReference(ts, node)) { const parent = node.parent; const typeName = ts.isTypeReferenceNode(parent) && parent.typeName === node; if (!typeName || !replacedType(node.text)) names.add(node.text); } - ts.forEachChild(node, visit); + // An import of another module, such as `import { orThrow } from './utils'`, has a name. + if (ts.isImportDeclaration(node)) { + const specifier = node.moduleSpecifier; + const v1 = ts.isStringLiteral(specifier) && specifier.text === V1_MODULE; + const clause = node.importClause; + if (!v1 && clause !== undefined) { + if (clause.name !== undefined) names.add(clause.name.text); + const bindings = clause.namedBindings; + if (bindings !== undefined && ts.isNamespaceImport(bindings)) + names.add(bindings.name.text); + if (bindings !== undefined && ts.isNamedImports(bindings)) { + for (const element of bindings.elements) names.add(element.name.text); + } + } + } + ts.forEachChild(node, (child) => visit(child, depth + 1)); } - visit(source); - return names; + visit(source, 0); + return deep ? null : names; } /** `vi.` or `jest.`, or only `.`. */ @@ -796,6 +923,21 @@ function factoryObjects( return objects; } +const NOT_INVERTIBLE = + 'the v2 input has an argument in a template, such as `${module}_${index}`, so a v1 ' + + 'implementation cannot get it: change the mock by hand'; + +/** `true` when each v1 argument that the v2 input has is a key of the input, or its spread. */ +function invertible(mapping: CallMapping): boolean { + const keyed = mapping.parameters.every( + (parameter, index) => parameter.use !== 'mapped' || inputKey(mapping, index) !== null, + ); + const pick = mapping.pick; + return ( + keyed && (pick === null || (pick.kind === 'arg' && inputKey(mapping, pick.index) !== null)) + ); +} + /** The arguments of `fromV1Mock` after the implementation: the input keys of the v1 arguments. */ function fromV1MockArgs(mapping: CallMapping): string { const keys = mapping.parameters.map((_parameter, index) => inputKey(mapping, index)); @@ -987,7 +1129,10 @@ function renderTemplate( if (given === null) return null; const base = given.node === null || isSimple(ts, given.node) ? given.text : `(${given.text})`; - return `${base}.${template.key}`; + const fallback = template.fallback; + if (fallback === undefined) return `${base}.${template.key}`; + const text = typeof fallback === 'string' ? quote(fallback) : String(fallback); + return `${base}.${template.key} ?? ${text}`; } case 'literal': return typeof template.value === 'string' @@ -1065,16 +1210,21 @@ function countArgs(template: Template, counts: Map): void { /** A name, a property path or a literal. It has no side effects, so it can be evaluated twice. */ function isSimple(ts: typeof TS, node: TS.Expression): boolean { - if (ts.isIdentifier(node) || node.kind === ts.SyntaxKind.ThisKeyword) return true; - if ( - ts.isStringLiteral(node) || - ts.isNumericLiteral(node) || - ts.isNoSubstitutionTemplateLiteral(node) - ) { - return true; + let current = node; + for (let depth = 0; depth < AST_DEPTH_MAX; depth += 1) { + if (ts.isIdentifier(current) || current.kind === ts.SyntaxKind.ThisKeyword) return true; + if ( + ts.isStringLiteral(current) || + ts.isNumericLiteral(current) || + ts.isNoSubstitutionTemplateLiteral(current) + ) { + return true; + } + if (!ts.isPropertyAccessExpression(current) && !ts.isParenthesizedExpression(current)) { + return false; + } + current = current.expression; } - if (ts.isPropertyAccessExpression(node)) return isSimple(ts, node.expression); - if (ts.isParenthesizedExpression(node)) return isSimple(ts, node.expression); return false; } diff --git a/v2/src/migrate/v1-map.ts b/v2/src/migrate/v1-map.ts index 7508fd477..6b0c0370c 100644 --- a/v2/src/migrate/v1-map.ts +++ b/v2/src/migrate/v1-map.ts @@ -1044,51 +1044,6 @@ export const V1_CALLS: CallMap = { pick: null, notes: [], }, - listInterfaceRepositories: { - namespace: 'repositories', - operation: 'loadedInterfaces', - parameters: [], - input: { kind: 'object', entries: [] }, - result: 'data', - pick: null, - notes: [], - }, - listMetadata: { - namespace: 'metadata', - operation: 'show', - parameters: [ - { name: 'id', initializer: null, use: 'mapped' }, - { name: 'query_params', initializer: '{}', use: 'mapped' }, - ], - input: { - kind: 'object', - entries: [ - { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, - { kind: 'spread', index: 1 }, - ], - }, - result: 'data', - pick: null, - notes: [], - }, - listMetadataHistory: { - namespace: 'metadata', - operation: 'history', - parameters: [ - { name: 'id', initializer: null, use: 'mapped' }, - { name: 'query_params', initializer: '{}', use: 'mapped' }, - ], - input: { - kind: 'object', - entries: [ - { kind: 'property', key: 'id', value: { kind: 'arg', index: 0 } }, - { kind: 'spread', index: 1 }, - ], - }, - result: 'data', - pick: null, - notes: [], - }, listPublicEvents: { namespace: 'publicEvents', operation: 'query', @@ -4578,7 +4533,7 @@ export const V1_CALLS: CallMap = { { kind: 'property', key: 'version', - value: { kind: 'member', index: 1, key: 'version' }, + value: { kind: 'member', index: 1, key: 'version', fallback: 0 }, }, { kind: 'property', key: 'body', value: { kind: 'arg', index: 1 } }, ], @@ -4913,6 +4868,10 @@ export const V1_UNMAPPED: Readonly> = { lastRequestTotal: 'a v1 request helper: use the generated operation', listen: 'use createRealtime (README: Realtime)', listenForToken: 'use createAuthSession and configure (README: Log in)', + listInterfaceRepositories: + 'v1 gives a list, and repositories.loadedInterfaces gives another shape', + listMetadata: 'v1 gives a list, and metadata.show gives another shape', + listMetadataHistory: 'v1 gives a list, and metadata.history gives another shape', log: 'v2 has no replacement', logout: 'use createAuthSession and configure (README: Log in)', mediaThumbnail: 'it sends 0 requests', diff --git a/v2/test/compat.test.ts b/v2/test/compat.test.ts index e18abe8df..602f5fe48 100644 --- a/v2/test/compat.test.ts +++ b/v2/test/compat.test.ts @@ -172,3 +172,21 @@ async function waitFor(done: () => boolean): Promise { } throw new Error('the condition did not become true'); } + +test('a mock endpoint that gives a string gives JSON, unless it sets another content type', async () => { + registerMockEndpoint({ + path: '/api/engine/v2/domains/lookup/:email', + method: 'GET', + callback: () => 'auth-1', + }); + const response = await mockFetch('http://mock.invalid/api/engine/v2/domains/lookup/a', {}); + expect(await response.json()).toBe('auth-1'); + registerMockEndpoint({ + path: '/api/engine/v2/drivers/:id/readme', + method: 'GET', + headers: { 'Content-Type': 'text/markdown' }, + callback: () => '# Readme', + }); + const text = await mockFetch('http://mock.invalid/api/engine/v2/drivers/d/readme', {}); + expect(await text.text()).toBe('# Readme'); +}); diff --git a/v2/test/migrate.test.ts b/v2/test/migrate.test.ts index 6aef23688..684f2d2f1 100644 --- a/v2/test/migrate.test.ts +++ b/v2/test/migrate.test.ts @@ -55,13 +55,16 @@ test('maps path templates, default values, members and picked keys', () => { expect(result.text.split('\n').slice(2)).toEqual([ "zones.zoneExecute({ id, module_slug: 'Display_1', method: 'power', body: [] }).then(orThrow);", 'metadata.show({ id: zone.id, name }).then(orThrow).then((data) => data[name]);', - 'systems.update({ sys_id: system.id, version: system.version, body: system }).then(orThrow);', + // v1 sent `form_data.version || 0`. + 'systems.update({ sys_id: system.id, version: system.version ?? 0, body: system }).then(orThrow);', ]); }); test('keeps the uses that it cannot rewrite, with a finding', () => { const text = [ - "import { addSystemModule, getModule, showMetadata, showZone } from '@placeos/ts-client';", + "import { addSystemModule, getModule, listMetadata, showMetadata, showZone } from '@placeos/ts-client';", + // v1 made a list of the metadata, which v2 gives by name. + 'listMetadata(zone.id);', "addSystemModule('sys-1', 'mod-1', { a: 1 });", 'showMetadata(id, names()[0]);', "getModule('sys-1', 'Bookings');", @@ -70,10 +73,11 @@ test('keeps the uses that it cannot rewrite, with a finding', () => { const result = migrate(text); expect(result.text).toBe(text); expect(result.findings.map((finding) => `${finding.line} ${finding.name}`)).toEqual([ - '2 addSystemModule', - '3 showMetadata', - '4 getModule', - '5 showZone', + '2 listMetadata', + '3 addSystemModule', + '4 showMetadata', + '5 getModule', + '6 showZone', ]); }); @@ -285,3 +289,116 @@ test('rewrites the v1 staff functions to @placeos/ts-client/staff', () => { 'await zones.show({ id }).then(orThrow);', ]); }); + +test('the hoisted helper goes with the new imports, also when the last v1 import goes', () => { + const result = migrate( + [ + "import { showZone } from '@placeos/ts-client';", + "import type { PlaceZone } from '@placeos/ts-client';", + "vi.mock('@placeos/ts-client', () => ({ showZone: vi.fn() }));", + 'let zone: PlaceZone;', + ].join('\n'), + ); + // `showZone` is only a key of the factory, so the file needs no `zones` import. + expect(result.text.split('\n').slice(0, 3)).toEqual([ + "import { type Zone } from '@placeos/ts-client';", + "const { fromV1Mock } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", + "vi.mock('@placeos/ts-client', () => ({ zones: { show: vi.fn(fromV1Mock(undefined, ['id', '...'])) } }));", + ]); +}); + +test('a helper reuses the compat import of the file, and gets an alias when the file has its name', () => { + const imported = migrate( + [ + "import { showZone } from '@placeos/ts-client';", + "import { orThrow } from '@placeos/ts-client/compat';", + 'await showZone(id);', + ].join('\n'), + ); + expect(imported.text.split('\n')).toEqual([ + "import { zones } from '@placeos/ts-client';", + "import { orThrow } from '@placeos/ts-client/compat';", + 'await zones.show({ id }).then(orThrow);', + ]); + // A type-only import has no value, so the call gets a value import. + const typeOnly = migrate( + [ + "import { showZone } from '@placeos/ts-client';", + "import type { orThrow } from '@placeos/ts-client/compat';", + 'await showZone(id);', + ].join('\n'), + ); + expect(typeOnly.text).toContain('.then(orThrowV2)'); + const local = migrate( + [ + "import { showZone } from '@placeos/ts-client';", + 'const orThrow = 1;', + 'await showZone(id);', + ].join('\n'), + ); + expect(local.text.split('\n').slice(1)).toEqual([ + "import { orThrow as orThrowV2 } from '@placeos/ts-client/compat';", + 'const orThrow = 1;', + 'await zones.show({ id }).then(orThrowV2);', + ]); +}); + +test('a factory keeps a mock as a mock, and finds a function whose arguments it cannot rebuild', () => { + const result = migrate( + [ + "import { executeOnZone, showZone } from '@placeos/ts-client';", + "vi.mock('@placeos/ts-client', () => ({", + ' showZone: vi.fn().mockResolvedValue(zone),', + ' executeOnZone: vi.fn(),', + '}));', + ].join('\n'), + 'zone.spec.ts', + ); + // `${module}_${index}` of `executeOnZone` has two v1 arguments in one input value. + expect(result.text).toContain( + "zones: { show: vi.fn(fromV1Mock(vi.fn().mockResolvedValue(zone), ['id', '...'])) }", + ); + expect(result.text).toContain('executeOnZone: vi.fn()'); + expect(result.findings.map((finding) => `${finding.line} ${finding.name}`)).toEqual([ + '4 executeOnZone', + ]); +}); + +test('a file deeper than the limit stays as it is, with a finding', () => { + const deep = `${'('.repeat(1_500)}1${')'.repeat(1_500)}`; + const text = ["import { showZone } from '@placeos/ts-client';", `showZone(${deep});`].join( + '\n', + ); + const result = migrate(text); + expect(result.text).toBe(text); + expect(result.findings[0]?.message).toContain('deeper than'); +}); + +test('a test double of a function whose arguments the tool cannot rebuild stays v1', () => { + const text = [ + "import { executeOnZone } from '@placeos/ts-client';", + 'vi.mocked(executeOnZone).mockImplementation((id, method, module, index) => Promise.resolve(index));', + 'expect(executeOnZone).toHaveBeenCalled();', + ].join('\n'); + const result = migrate(text, 'zone.spec.ts'); + expect(result.text).toBe(text); + expect(result.findings.map((finding) => `${finding.line} ${finding.name}`)).toEqual([ + '2 executeOnZone', + '3 executeOnZone', + ]); +}); + +test('the hoisted helper gets its own name when the file imports fromV1Mock', () => { + const result = migrate( + [ + "import { showZone } from '@placeos/ts-client';", + "import { fromV1Mock } from '@placeos/ts-client/compat';", + "vi.mock('@placeos/ts-client', () => ({ showZone: vi.fn() }));", + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "const { fromV1Mock: fromV1MockV2 } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", + "import { fromV1Mock } from '@placeos/ts-client/compat';", + "vi.mock('@placeos/ts-client', () => ({ zones: { show: vi.fn(fromV1MockV2(undefined, ['id', '...'])) } }));", + ]); +}); diff --git a/v2/test/mock.test.ts b/v2/test/mock.test.ts index 54be60404..e6452f2a5 100644 --- a/v2/test/mock.test.ts +++ b/v2/test/mock.test.ts @@ -104,3 +104,66 @@ test('a staff API endpoint has a typed mock too', async () => { // @ts-expect-error the staff endpoints start with `staff.` mockEndpoint('bookings.show', () => ({})); }); + +test('a mock answer has the deadline, the signal and the size limit of a response', async () => { + mockEndpoint('zones.show', () => new Promise(() => {})); + const late = await zones.show({ id: 'zone-1' }, { client, timeoutMs: 5 }); + expect(late.ok === false && late.error.kind).toBe('timeout'); + const controller = new AbortController(); + const pending = zones.show({ id: 'zone-1' }, { client, signal: controller.signal }); + controller.abort(); + const aborted = await pending; + expect(aborted.ok === false && aborted.error.kind).toBe('aborted'); + const small = createClient({ + baseUrl: 'http://mock.invalid', + auth: { kind: 'none' }, + mock: endpointMocks, + responseBytesMax: 16, + }); + mockEndpoint('zones.show', () => ({ id: 'zone-1', name: 'a name longer than the limit' })); + const large = await zones.show({ id: 'zone-1' }, { client: small }); + expect(large.ok === false && large.error.kind).toBe('response_too_large'); +}); + +test('zero-fill keeps the union variant that knows the given fields', async () => { + const { events } = await import('../src/staff.ts'); + const input = { id: 'event-1', body: { email: 'a@example.com' } } as never; + // `PlaceCalendarEventAttendee` is first, and has no `id`. + mockEndpoint('staff.events.addAttendee', () => ({ id: 7 }) as never); + const byId = await events.addAttendee(input, options); + expect(byId.ok && Reflect.get(Object(byId.value.data), 'id')).toBe(7); + // `Attendee` matches without the fill, and has no `resource`. + mockEndpoint('staff.events.addAttendee', () => ({ resource: true }) as never); + const byResource = await events.addAttendee(input, options); + expect(byResource.ok && Reflect.get(Object(byResource.value.data), 'resource')).toBe(true); +}); + +test('an aborted call does not leave the promise of a mock without a handler', async () => { + const rejections: unknown[] = []; + const onRejection = (reason: unknown) => rejections.push(reason); + process.on('unhandledRejection', onRejection); + try { + mockEndpoint('zones.show', () => Promise.reject(new Error('a bug in the test'))); + const controller = new AbortController(); + controller.abort(); + const result = await zones.show({ id: 'zone-1' }, { client, signal: controller.signal }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(result.ok === false && result.error.kind).toBe('aborted'); + expect(rejections).toEqual([]); + } finally { + process.off('unhandledRejection', onRejection); + } +}); + +test('a mock that aborts its own call gives aborted, not timeout', async () => { + const controller = new AbortController(); + mockEndpoint('zones.show', () => { + controller.abort(); + return new Promise(() => {}); + }); + const result = await zones.show( + { id: 'zone-1' }, + { client, signal: controller.signal, timeoutMs: 50 }, + ); + expect(result.ok === false && result.error.kind).toBe('aborted'); +}); From 9885612add733e527e5f94892c8513fe07b772f4 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 13:14:05 +1100 Subject: [PATCH 11/29] docs(v2): name list operations query in the README Co-Authored-By: Claude Opus 5.5 --- v2/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/v2/README.md b/v2/README.md index 224b5e409..e3b8ed2ca 100644 --- a/v2/README.md +++ b/v2/README.md @@ -28,9 +28,9 @@ if (result.ok) { ``` There is one namespace for each controller of the API, for example `zones`, `systems` and -`users`. Each function has the name of the server action: `index`, `show`, `create`, `update`, -`destroy`, or a custom action such as `systems.execute`. The comment of each function gives the -HTTP method and the path. +`users`. Each function has the name of the server action: `show`, `create`, `update`, `destroy`, +or a custom action such as `systems.execute`. The `index` action is `query`, because a list +operation queries the items. The comment of each function gives the HTTP method and the path. The first argument has the path parameters, the query parameters and, for an operation with a body, `body`. The second argument has the options of the request: @@ -88,7 +88,7 @@ await zones.query({}, { signal: controller.signal, timeoutMs: 60_000 }); ### Pages -An `index` operation returns one page. Use `pageInfo` to get the total and the next offset: +A `query` operation returns one page. Use `pageInfo` to get the total and the next offset: ```ts import { pageInfo, zones } from '@placeos/ts-client'; From cfbf25b976aa4ef16c400dcfd6894a0838f14e25 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 13:31:47 +1100 Subject: [PATCH 12/29] feat!: make the 7.x client the package at the repository root The 7.x client was in v2/, beside the 6.x client at the root. It is now the package: the 6.x source, tests and build config are gone from this branch, and the 6.x branch keeps them for fixes. - The 6.x to 7.x migration map reads the 6.x source from the 6.13.0 npm package. - The release workflow uses bun, publishes from master, next (prereleases) and the maintenance branches, and makes the API docs with deno doc. - The docs and comments name the versions 6.x and 7.x. BREAKING CHANGE: version 7 is a new client with a different API. `npx -p @placeos/ts-client@7 placeos-migrate` rewrites the 6.x calls of a project. See "Migrate from 6.x" in the README. Co-Authored-By: Claude Opus 5.5 --- .eslintrc.json | 5 - .github/workflows/{v2.yml => ci.yml} | 17 +- .../{v2-regenerate.yml => regenerate.yml} | 21 +- .github/workflows/releases.yml | 61 +- .prettierrc | 2 +- README.md | 905 +- bun.lock | 1044 ++ v2/oauth-resp.html => oauth-resp.html | 2 +- package-lock.json | 9379 ----------------- package.json | 99 +- scripts/copy-file.js | 7 - {v2/scripts => scripts}/generate.ts | 0 {v2/scripts => scripts}/regenerate-pr.sh | 34 +- {v2/scripts => scripts}/v1-map.ts | 125 +- {v2/scripts => scripts}/value-enums.ts | 4 +- src/alerts/alert.ts | 47 - src/alerts/dashboard.ts | 17 - src/alerts/functions.ts | 189 - src/alerts/interfaces.ts | 25 - src/api-keys/api-key.ts | 39 - src/api-keys/functions.ts | 52 - src/api-keys/interfaces.ts | 13 - src/api.ts | 801 -- src/applications/application.ts | 35 - src/applications/functions.ts | 70 - src/applications/interfaces.ts | 7 - src/assets/assets.class.ts | 126 - src/assets/functions.ts | 439 - src/assets/interfaces.ts | 41 - src/auth-sources/interfaces.ts | 9 - src/auth.ts | 39 - {v2/src => src}/auth/environment.ts | 0 src/auth/functions.ts | 1144 -- {v2/src => src}/auth/hash.ts | 0 src/auth/interfaces.ts | 107 - {v2/src => src}/auth/session.ts | 16 +- src/broker/broker.ts | 50 - src/broker/functions.ts | 70 - src/build-monitor/functions.ts | 25 - src/build-monitor/interfaces.ts | 26 - src/clusters/cluster.ts | 117 - src/clusters/functions.ts | 90 - src/clusters/interfaces.ts | 27 - src/clusters/process.ts | 85 - {v2/src => src}/compat/enums.ts | 20 +- {v2/src => src}/compat/http-mock.ts | 20 +- src/compat/index.ts | 16 + {v2/src => src}/compat/realtime-mock.ts | 12 +- {v2/src => src}/compat/result.ts | 30 +- {v2/src => src}/core/assert.ts | 0 {v2/src => src}/core/client.ts | 0 {v2/src => src}/core/pagination.ts | 0 {v2/src => src}/core/result.ts | 0 {v2/src => src}/core/schema.ts | 2 +- src/domains/domain.ts | 30 - src/domains/functions.ts | 79 - src/drivers/driver.ts | 74 - src/drivers/enums.ts | 8 - src/drivers/functions.ts | 108 - src/drivers/interfaces.ts | 35 - src/edge/edge.ts | 25 - src/edge/functions.ts | 209 - src/edge/interfaces.ts | 62 - .../generated/operations/alert-dashboards.ts | 0 .../generated/operations/alerts.ts | 0 .../generated/operations/api-keys.ts | 0 .../generated/operations/asset-categories.ts | 0 .../operations/asset-purchase-orders.ts | 0 .../generated/operations/asset-types.ts | 0 .../generated/operations/assets.ts | 0 .../generated/operations/brokers.ts | 0 .../generated/operations/build-monitor.ts | 0 .../generated/operations/chat-gpt-plugin.ts | 0 .../generated/operations/chat-gpt.ts | 0 .../generated/operations/cluster.ts | 0 .../generated/operations/domains.ts | 0 .../generated/operations/drivers.ts | 0 {v2/src => src}/generated/operations/edges.ts | 0 {v2/src => src}/generated/operations/flux.ts | 0 .../generated/operations/groups-history.ts | 0 .../operations/groups-invitations.ts | 0 .../generated/operations/groups-users.ts | 0 .../generated/operations/groups-zones.ts | 0 .../generated/operations/groups.ts | 0 .../generated/operations/history.ts | 0 {v2/src => src}/generated/operations/index.ts | 0 .../operations/ldap-authentications.ts | 0 .../generated/operations/map-ai.ts | 0 .../generated/operations/metadata.ts | 0 .../generated/operations/modules.ts | 0 {v2/src => src}/generated/operations/mqtt.ts | 0 .../operations/oauth-applications.ts | 0 .../operations/oauth-authentications.ts | 0 .../generated/operations/pending-mails.ts | 0 .../generated/operations/playlist-media.ts | 0 .../generated/operations/playlist.ts | 0 .../generated/operations/public-events.ts | 0 .../operations/push-notifications.ts | 0 .../generated/operations/repositories.ts | 0 {v2/src => src}/generated/operations/root.ts | 0 .../operations/saml-authentications.ts | 0 .../generated/operations/schema.ts | 0 .../generated/operations/settings.ts | 0 .../generated/operations/short-url.ts | 0 .../operations/signage-ai-providers.ts | 0 .../generated/operations/signage-ai.ts | 0 .../generated/operations/signage-plugins.ts | 0 .../operations/signage-template-mappings.ts | 0 .../generated/operations/signage-templates.ts | 0 .../generated/operations/signage.ts | 0 .../generated/operations/storages.ts | 0 .../generated/operations/system-triggers.ts | 0 .../generated/operations/systems.ts | 0 .../generated/operations/tenant-consent.ts | 0 .../generated/operations/triggers.ts | 0 .../generated/operations/uploads.ts | 0 .../generated/operations/url-proxy.ts | 0 {v2/src => src}/generated/operations/users.ts | 0 .../generated/operations/web-rtc.ts | 0 .../generated/operations/webhook.ts | 0 {v2/src => src}/generated/operations/zones.ts | 0 {v2/src => src}/generated/schemas.ts | 0 .../staff/operations/asset-categories.ts | 0 .../staff/operations/asset-purchase-orders.ts | 0 .../generated/staff/operations/asset-types.ts | 0 .../generated/staff/operations/assets.ts | 0 .../generated/staff/operations/bookings.ts | 0 .../generated/staff/operations/calendars.ts | 0 .../generated/staff/operations/desks.ts | 0 .../generated/staff/operations/events.ts | 0 .../generated/staff/operations/groups.ts | 0 .../generated/staff/operations/guests.ts | 0 .../staff/operations/health-check.ts | 0 .../generated/staff/operations/index.ts | 0 .../generated/staff/operations/place.ts | 0 .../generated/staff/operations/spaces.ts | 0 .../generated/staff/operations/staff.ts | 0 .../staff/operations/surveys-answers.ts | 0 .../staff/operations/surveys-invitations.ts | 0 .../staff/operations/surveys-questions.ts | 0 .../generated/staff/operations/surveys.ts | 0 .../generated/staff/operations/teams.ts | 0 .../generated/staff/operations/tenants.ts | 0 .../generated/staff/operations/users.ts | 0 {v2/src => src}/generated/staff/schemas.ts | 0 src/group-users/functions.ts | 61 - src/group-users/group-user.ts | 37 - src/group-users/interfaces.ts | 9 - src/group-zones/functions.ts | 61 - src/group-zones/group-zone.ts | 35 - src/group-zones/interfaces.ts | 9 - src/groups/functions.ts | 154 - src/groups/group-history.ts | 9 - src/groups/group-invitation.ts | 50 - src/groups/group.ts | 64 - src/groups/interfaces.ts | 38 - src/history/functions.ts | 41 - src/history/history.ts | 80 - src/history/interfaces.ts | 23 - src/http/functions.ts | 373 - src/http/interfaces.ts | 105 - src/http/mock.ts | 262 - src/index.ts | 98 +- src/ldap-sources/functions.ts | 70 - src/ldap-sources/ldap-source.ts | 40 - src/metadata/functions.ts | 190 - src/metadata/interfaces.ts | 41 - src/metadata/metadata.ts | 57 - src/metadata/zone-metadata.ts | 22 - {v2/src => src}/migrate/cli.ts | 8 +- {v2/src => src}/migrate/map.ts | 30 +- {v2/src => src}/migrate/migrate.ts | 110 +- {v2/src => src}/migrate/v1-map.ts | 106 +- {v2/src => src}/mock/index.ts | 2 +- src/modules/functions.ts | 182 - src/modules/interfaces.ts | 35 - src/modules/module.ts | 133 - src/mqtt/functions.ts | 19 - src/mqtt/interfaces.ts | 8 - src/oauth-resp.html | 105 - src/oauth-sources/functions.ts | 70 - src/oauth-sources/oauth-source.ts | 52 - src/public-events/functions.ts | 41 - src/public-events/interfaces.ts | 15 - src/push-notifications/functions.ts | 19 - src/push-notifications/interfaces.ts | 29 - src/realtime.ts | 37 - src/realtime/binding.ts | 35 - {v2/src => src}/realtime/environment.ts | 2 +- src/realtime/functions.ts | 829 -- src/realtime/interfaces.ts | 127 - src/realtime/mock-module.ts | 87 - src/realtime/mock-system.ts | 32 - src/realtime/mock.ts | 27 - src/realtime/module.ts | 82 - {v2/src => src}/realtime/realtime.ts | 2 +- src/realtime/status-variable.ts | 164 - src/realtime/system.ts | 49 - src/repositories/functions.ts | 322 - src/repositories/interfaces.ts | 94 - src/repositories/repository.ts | 40 - src/repositories/utilities.ts | 22 - src/resources/functions.ts | 238 - src/resources/interface.ts | 88 - src/resources/resource.ts | 35 - src/root/functions.ts | 57 - src/root/interfaces.ts | 30 - src/saml-sources/functions.ts | 70 - src/saml-sources/saml-source.ts | 64 - src/settings/functions.ts | 102 - src/settings/interfaces.ts | 27 - src/settings/settings.ts | 34 - src/settings/utilities.ts | 29 - src/short-url/functions.ts | 155 - src/short-url/interfaces.ts | 25 - src/short-url/short-url.class.ts | 33 - src/signage/ai/functions.ts | 242 - src/signage/ai/interfaces.ts | 322 - src/signage/functions.ts | 723 -- src/signage/interfaces.ts | 163 - src/signage/media.class.ts | 93 - src/signage/playlist.class.ts | 109 - src/signage/plugin.class.ts | 36 - src/signage/template.class.ts | 80 - src/staff.ts | 60 +- src/staff/answers/functions.ts | 31 - src/staff/answers/interfaces.ts | 1 - src/staff/answers/model.ts | 15 - src/staff/invitations/functions.ts | 74 - src/staff/invitations/interfaces.ts | 6 - src/staff/invitations/model.ts | 15 - src/staff/questions/functions.ts | 74 - src/staff/questions/interfaces.ts | 6 - src/staff/questions/model.ts | 25 - src/staff/surveys/functions.ts | 71 - src/staff/surveys/interfaces.ts | 3 - src/staff/surveys/model.ts | 25 - src/storages/functions.ts | 88 - src/storages/interfaces.ts | 7 - src/storages/storage.class.ts | 34 - src/systems/functions.ts | 450 - src/systems/interfaces.ts | 97 - src/systems/system.ts | 130 - src/systems/utilities.ts | 31 - src/triggers/functions.ts | 98 - src/triggers/interfaces.ts | 117 - src/triggers/trigger.ts | 110 - src/url-proxy/functions.ts | 28 - src/users/functions.ts | 190 - src/users/interfaces.ts | 63 - src/users/user.ts | 108 - src/utilities/abort-controller.ts | 8 - src/utilities/api.ts | 23 - src/utilities/async.ts | 140 - src/utilities/general.ts | 286 - src/utilities/nodejs.ts | 19 - src/utilities/signal.ts | 85 - src/utilities/types.ts | 3 - src/utilities/websocket.ts | 128 - src/webhook/functions.ts | 18 - src/webhook/interfaces.ts | 3 - src/webrtc/functions.ts | 118 - src/webrtc/interfaces.ts | 49 - src/zones/functions.ts | 155 - src/zones/interfaces.ts | 31 - src/zones/zone.ts | 93 - test/alerts/alert.spec.ts | 107 - test/alerts/dashboard.spec.ts | 40 - test/alerts/functions.spec.ts | 103 - test/applications/application.spec.ts | 48 - test/applications/functions.spec.ts | 47 - test/assets/assets.spec.ts | 388 - test/assets/functions.spec.ts | 229 - {v2/test => test}/auth.test.ts | 8 +- test/auth/functions.spec.ts | 598 -- test/broker/broker.spec.ts | 45 - test/broker/functions.spec.ts | 50 - {v2/test => test}/client.test.ts | 0 test/clusters/clusters.spec.ts | 63 - test/clusters/functions.spec.ts | 69 - test/clusters/process.spec.ts | 40 - {v2/test => test}/compat.test.ts | 12 +- test/domains/domain.spec.ts | 52 - test/domains/functions.spec.ts | 63 - test/drivers/driver.spec.ts | 54 - test/drivers/functions.spec.ts | 75 - test/edge/edge.spec.ts | 25 - test/edge/functions.spec.ts | 73 - test/groups/functions.spec.ts | 31 - test/groups/group.spec.ts | 29 - {v2/test => test}/hash.test.ts | 2 +- test/history/functions.spec.ts | 74 - test/history/history.spec.ts | 35 - test/http/expired-token.spec.ts | 123 - test/http/functions.spec.ts | 317 - test/http/mock.spec.ts | 178 - test/ldap-sources/functions.spec.ts | 45 - test/ldap-sources/ldap-source.spec.ts | 28 - {v2/test => test}/loose/consumer.ts | 2 +- {v2/test => test}/loose/tsconfig.json | 0 test/metadata/functions.spec.ts | 76 - test/metadata/metadata.spec.ts | 31 - test/metadata/zone-metadata.spec.ts | 28 - {v2/test => test}/migrate.test.ts | 42 +- {v2/test => test}/mock.test.ts | 0 test/modules/functions.spec.ts | 115 - test/modules/module.spec.ts | 80 - test/oauth-sources/functions.spec.ts | 47 - test/oauth-sources/oauth-source.spec.ts | 28 - {v2/test => test}/pagination.test.ts | 0 {v2/test => test}/realtime.test.ts | 0 test/realtime/binding.spec.ts | 28 - test/realtime/functions.spec.ts | 399 - test/realtime/mock-module.spec.ts | 109 - test/realtime/mock-system.spec.ts | 40 - test/realtime/mock.spec.ts | 141 - test/realtime/module.spec.ts | 65 - test/realtime/status-variable.spec.ts | 116 - test/realtime/system.spec.ts | 34 - test/repositories/functions.spec.ts | 179 - test/repositories/repository.spec.ts | 29 - test/resources/functions.spec.ts | 295 - test/resources/resource.spec.ts | 42 - test/root/functions.spec.ts | 45 - test/saml-sources/functions.spec.ts | 49 - test/saml-sources/saml-source.spec.ts | 29 - {v2/test => test}/schema.test.ts | 0 test/settings/functions.spec.ts | 58 - test/settings/settings.spec.ts | 41 - test/short-url/functions.spec.ts | 190 - test/short-url/short-url.class.spec.ts | 109 - test/signage/ai/functions.spec.ts | 306 - test/signage/functions.spec.ts | 389 - test/staff/answers/functions.spec.ts | 40 - test/staff/questions/functions.spec.ts | 59 - test/storages/functions.spec.ts | 66 - test/storages/storage.class.spec.ts | 113 - {v2/test => test}/style.test.ts | 2 +- test/systems/functions.spec.ts | 254 - test/systems/system.spec.ts | 80 - test/systems/utilities.spec.ts | 18 - test/triggers/functions.spec.ts | 56 - test/triggers/trigger.spec.ts | 77 - test/url-proxy/functions.spec.ts | 32 - test/users/functions.spec.ts | 167 - test/users/user.spec.ts | 68 - test/utilities/api.spec.ts | 20 - test/utilities/general.spec.ts | 104 - test/webrtc/functions.spec.ts | 227 - test/zones/functions.spec.ts | 71 - test/zones/zone.spec.ts | 49 - v2/tsconfig.build.json => tsconfig.build.json | 0 v2/tsconfig.cli.json => tsconfig.cli.json | 0 tsconfig.json | 31 +- v2/.gitignore | 2 - v2/.prettierrc | 6 - v2/README.md | 525 - v2/bun.lock | 72 - v2/package.json | 58 - v2/src/compat/index.ts | 16 - v2/src/index.ts | 86 - v2/src/staff.ts | 19 - v2/tsconfig.json | 30 - vite.config.ts | 37 - 364 files changed, 2052 insertions(+), 33382 deletions(-) delete mode 100644 .eslintrc.json rename .github/workflows/{v2.yml => ci.yml} (50%) rename .github/workflows/{v2-regenerate.yml => regenerate.yml} (50%) create mode 100644 bun.lock rename v2/oauth-resp.html => oauth-resp.html (94%) delete mode 100644 package-lock.json delete mode 100644 scripts/copy-file.js rename {v2/scripts => scripts}/generate.ts (100%) rename {v2/scripts => scripts}/regenerate-pr.sh (79%) rename {v2/scripts => scripts}/v1-map.ts (86%) rename {v2/scripts => scripts}/value-enums.ts (65%) delete mode 100644 src/alerts/alert.ts delete mode 100644 src/alerts/dashboard.ts delete mode 100644 src/alerts/functions.ts delete mode 100644 src/alerts/interfaces.ts delete mode 100644 src/api-keys/api-key.ts delete mode 100644 src/api-keys/functions.ts delete mode 100644 src/api-keys/interfaces.ts delete mode 100644 src/api.ts delete mode 100644 src/applications/application.ts delete mode 100644 src/applications/functions.ts delete mode 100644 src/applications/interfaces.ts delete mode 100644 src/assets/assets.class.ts delete mode 100644 src/assets/functions.ts delete mode 100644 src/assets/interfaces.ts delete mode 100644 src/auth-sources/interfaces.ts delete mode 100644 src/auth.ts rename {v2/src => src}/auth/environment.ts (100%) delete mode 100644 src/auth/functions.ts rename {v2/src => src}/auth/hash.ts (100%) delete mode 100644 src/auth/interfaces.ts rename {v2/src => src}/auth/session.ts (98%) delete mode 100644 src/broker/broker.ts delete mode 100644 src/broker/functions.ts delete mode 100644 src/build-monitor/functions.ts delete mode 100644 src/build-monitor/interfaces.ts delete mode 100644 src/clusters/cluster.ts delete mode 100644 src/clusters/functions.ts delete mode 100644 src/clusters/interfaces.ts delete mode 100644 src/clusters/process.ts rename {v2/src => src}/compat/enums.ts (75%) rename {v2/src => src}/compat/http-mock.ts (92%) create mode 100644 src/compat/index.ts rename {v2/src => src}/compat/realtime-mock.ts (96%) rename {v2/src => src}/compat/result.ts (80%) rename {v2/src => src}/core/assert.ts (100%) rename {v2/src => src}/core/client.ts (100%) rename {v2/src => src}/core/pagination.ts (100%) rename {v2/src => src}/core/result.ts (100%) rename {v2/src => src}/core/schema.ts (99%) delete mode 100644 src/domains/domain.ts delete mode 100644 src/domains/functions.ts delete mode 100644 src/drivers/driver.ts delete mode 100644 src/drivers/enums.ts delete mode 100644 src/drivers/functions.ts delete mode 100644 src/drivers/interfaces.ts delete mode 100644 src/edge/edge.ts delete mode 100644 src/edge/functions.ts delete mode 100644 src/edge/interfaces.ts rename {v2/src => src}/generated/operations/alert-dashboards.ts (100%) rename {v2/src => src}/generated/operations/alerts.ts (100%) rename {v2/src => src}/generated/operations/api-keys.ts (100%) rename {v2/src => src}/generated/operations/asset-categories.ts (100%) rename {v2/src => src}/generated/operations/asset-purchase-orders.ts (100%) rename {v2/src => src}/generated/operations/asset-types.ts (100%) rename {v2/src => src}/generated/operations/assets.ts (100%) rename {v2/src => src}/generated/operations/brokers.ts (100%) rename {v2/src => src}/generated/operations/build-monitor.ts (100%) rename {v2/src => src}/generated/operations/chat-gpt-plugin.ts (100%) rename {v2/src => src}/generated/operations/chat-gpt.ts (100%) rename {v2/src => src}/generated/operations/cluster.ts (100%) rename {v2/src => src}/generated/operations/domains.ts (100%) rename {v2/src => src}/generated/operations/drivers.ts (100%) rename {v2/src => src}/generated/operations/edges.ts (100%) rename {v2/src => src}/generated/operations/flux.ts (100%) rename {v2/src => src}/generated/operations/groups-history.ts (100%) rename {v2/src => src}/generated/operations/groups-invitations.ts (100%) rename {v2/src => src}/generated/operations/groups-users.ts (100%) rename {v2/src => src}/generated/operations/groups-zones.ts (100%) rename {v2/src => src}/generated/operations/groups.ts (100%) rename {v2/src => src}/generated/operations/history.ts (100%) rename {v2/src => src}/generated/operations/index.ts (100%) rename {v2/src => src}/generated/operations/ldap-authentications.ts (100%) rename {v2/src => src}/generated/operations/map-ai.ts (100%) rename {v2/src => src}/generated/operations/metadata.ts (100%) rename {v2/src => src}/generated/operations/modules.ts (100%) rename {v2/src => src}/generated/operations/mqtt.ts (100%) rename {v2/src => src}/generated/operations/oauth-applications.ts (100%) rename {v2/src => src}/generated/operations/oauth-authentications.ts (100%) rename {v2/src => src}/generated/operations/pending-mails.ts (100%) rename {v2/src => src}/generated/operations/playlist-media.ts (100%) rename {v2/src => src}/generated/operations/playlist.ts (100%) rename {v2/src => src}/generated/operations/public-events.ts (100%) rename {v2/src => src}/generated/operations/push-notifications.ts (100%) rename {v2/src => src}/generated/operations/repositories.ts (100%) rename {v2/src => src}/generated/operations/root.ts (100%) rename {v2/src => src}/generated/operations/saml-authentications.ts (100%) rename {v2/src => src}/generated/operations/schema.ts (100%) rename {v2/src => src}/generated/operations/settings.ts (100%) rename {v2/src => src}/generated/operations/short-url.ts (100%) rename {v2/src => src}/generated/operations/signage-ai-providers.ts (100%) rename {v2/src => src}/generated/operations/signage-ai.ts (100%) rename {v2/src => src}/generated/operations/signage-plugins.ts (100%) rename {v2/src => src}/generated/operations/signage-template-mappings.ts (100%) rename {v2/src => src}/generated/operations/signage-templates.ts (100%) rename {v2/src => src}/generated/operations/signage.ts (100%) rename {v2/src => src}/generated/operations/storages.ts (100%) rename {v2/src => src}/generated/operations/system-triggers.ts (100%) rename {v2/src => src}/generated/operations/systems.ts (100%) rename {v2/src => src}/generated/operations/tenant-consent.ts (100%) rename {v2/src => src}/generated/operations/triggers.ts (100%) rename {v2/src => src}/generated/operations/uploads.ts (100%) rename {v2/src => src}/generated/operations/url-proxy.ts (100%) rename {v2/src => src}/generated/operations/users.ts (100%) rename {v2/src => src}/generated/operations/web-rtc.ts (100%) rename {v2/src => src}/generated/operations/webhook.ts (100%) rename {v2/src => src}/generated/operations/zones.ts (100%) rename {v2/src => src}/generated/schemas.ts (100%) rename {v2/src => src}/generated/staff/operations/asset-categories.ts (100%) rename {v2/src => src}/generated/staff/operations/asset-purchase-orders.ts (100%) rename {v2/src => src}/generated/staff/operations/asset-types.ts (100%) rename {v2/src => src}/generated/staff/operations/assets.ts (100%) rename {v2/src => src}/generated/staff/operations/bookings.ts (100%) rename {v2/src => src}/generated/staff/operations/calendars.ts (100%) rename {v2/src => src}/generated/staff/operations/desks.ts (100%) rename {v2/src => src}/generated/staff/operations/events.ts (100%) rename {v2/src => src}/generated/staff/operations/groups.ts (100%) rename {v2/src => src}/generated/staff/operations/guests.ts (100%) rename {v2/src => src}/generated/staff/operations/health-check.ts (100%) rename {v2/src => src}/generated/staff/operations/index.ts (100%) rename {v2/src => src}/generated/staff/operations/place.ts (100%) rename {v2/src => src}/generated/staff/operations/spaces.ts (100%) rename {v2/src => src}/generated/staff/operations/staff.ts (100%) rename {v2/src => src}/generated/staff/operations/surveys-answers.ts (100%) rename {v2/src => src}/generated/staff/operations/surveys-invitations.ts (100%) rename {v2/src => src}/generated/staff/operations/surveys-questions.ts (100%) rename {v2/src => src}/generated/staff/operations/surveys.ts (100%) rename {v2/src => src}/generated/staff/operations/teams.ts (100%) rename {v2/src => src}/generated/staff/operations/tenants.ts (100%) rename {v2/src => src}/generated/staff/operations/users.ts (100%) rename {v2/src => src}/generated/staff/schemas.ts (100%) delete mode 100644 src/group-users/functions.ts delete mode 100644 src/group-users/group-user.ts delete mode 100644 src/group-users/interfaces.ts delete mode 100644 src/group-zones/functions.ts delete mode 100644 src/group-zones/group-zone.ts delete mode 100644 src/group-zones/interfaces.ts delete mode 100644 src/groups/functions.ts delete mode 100644 src/groups/group-history.ts delete mode 100644 src/groups/group-invitation.ts delete mode 100644 src/groups/group.ts delete mode 100644 src/groups/interfaces.ts delete mode 100644 src/history/functions.ts delete mode 100644 src/history/history.ts delete mode 100644 src/history/interfaces.ts delete mode 100644 src/http/functions.ts delete mode 100644 src/http/interfaces.ts delete mode 100644 src/http/mock.ts delete mode 100644 src/ldap-sources/functions.ts delete mode 100644 src/ldap-sources/ldap-source.ts delete mode 100644 src/metadata/functions.ts delete mode 100644 src/metadata/interfaces.ts delete mode 100644 src/metadata/metadata.ts delete mode 100644 src/metadata/zone-metadata.ts rename {v2/src => src}/migrate/cli.ts (95%) rename {v2/src => src}/migrate/map.ts (65%) rename {v2/src => src}/migrate/migrate.ts (92%) rename {v2/src => src}/migrate/v1-map.ts (98%) rename {v2/src => src}/mock/index.ts (99%) delete mode 100644 src/modules/functions.ts delete mode 100644 src/modules/interfaces.ts delete mode 100644 src/modules/module.ts delete mode 100644 src/mqtt/functions.ts delete mode 100644 src/mqtt/interfaces.ts delete mode 100644 src/oauth-resp.html delete mode 100644 src/oauth-sources/functions.ts delete mode 100644 src/oauth-sources/oauth-source.ts delete mode 100644 src/public-events/functions.ts delete mode 100644 src/public-events/interfaces.ts delete mode 100644 src/push-notifications/functions.ts delete mode 100644 src/push-notifications/interfaces.ts delete mode 100644 src/realtime.ts delete mode 100644 src/realtime/binding.ts rename {v2/src => src}/realtime/environment.ts (99%) delete mode 100644 src/realtime/functions.ts delete mode 100644 src/realtime/interfaces.ts delete mode 100644 src/realtime/mock-module.ts delete mode 100644 src/realtime/mock-system.ts delete mode 100644 src/realtime/mock.ts delete mode 100644 src/realtime/module.ts rename {v2/src => src}/realtime/realtime.ts (99%) delete mode 100644 src/realtime/status-variable.ts delete mode 100644 src/realtime/system.ts delete mode 100644 src/repositories/functions.ts delete mode 100644 src/repositories/interfaces.ts delete mode 100644 src/repositories/repository.ts delete mode 100644 src/repositories/utilities.ts delete mode 100644 src/resources/functions.ts delete mode 100644 src/resources/interface.ts delete mode 100644 src/resources/resource.ts delete mode 100644 src/root/functions.ts delete mode 100644 src/root/interfaces.ts delete mode 100644 src/saml-sources/functions.ts delete mode 100644 src/saml-sources/saml-source.ts delete mode 100644 src/settings/functions.ts delete mode 100644 src/settings/interfaces.ts delete mode 100644 src/settings/settings.ts delete mode 100644 src/settings/utilities.ts delete mode 100644 src/short-url/functions.ts delete mode 100644 src/short-url/interfaces.ts delete mode 100644 src/short-url/short-url.class.ts delete mode 100644 src/signage/ai/functions.ts delete mode 100644 src/signage/ai/interfaces.ts delete mode 100644 src/signage/functions.ts delete mode 100644 src/signage/interfaces.ts delete mode 100644 src/signage/media.class.ts delete mode 100644 src/signage/playlist.class.ts delete mode 100644 src/signage/plugin.class.ts delete mode 100644 src/signage/template.class.ts delete mode 100644 src/staff/answers/functions.ts delete mode 100644 src/staff/answers/interfaces.ts delete mode 100644 src/staff/answers/model.ts delete mode 100644 src/staff/invitations/functions.ts delete mode 100644 src/staff/invitations/interfaces.ts delete mode 100644 src/staff/invitations/model.ts delete mode 100644 src/staff/questions/functions.ts delete mode 100644 src/staff/questions/interfaces.ts delete mode 100644 src/staff/questions/model.ts delete mode 100644 src/staff/surveys/functions.ts delete mode 100644 src/staff/surveys/interfaces.ts delete mode 100644 src/staff/surveys/model.ts delete mode 100644 src/storages/functions.ts delete mode 100644 src/storages/interfaces.ts delete mode 100644 src/storages/storage.class.ts delete mode 100644 src/systems/functions.ts delete mode 100644 src/systems/interfaces.ts delete mode 100644 src/systems/system.ts delete mode 100644 src/systems/utilities.ts delete mode 100644 src/triggers/functions.ts delete mode 100644 src/triggers/interfaces.ts delete mode 100644 src/triggers/trigger.ts delete mode 100644 src/url-proxy/functions.ts delete mode 100644 src/users/functions.ts delete mode 100644 src/users/interfaces.ts delete mode 100644 src/users/user.ts delete mode 100644 src/utilities/abort-controller.ts delete mode 100644 src/utilities/api.ts delete mode 100644 src/utilities/async.ts delete mode 100644 src/utilities/general.ts delete mode 100644 src/utilities/nodejs.ts delete mode 100644 src/utilities/signal.ts delete mode 100644 src/utilities/types.ts delete mode 100644 src/utilities/websocket.ts delete mode 100644 src/webhook/functions.ts delete mode 100644 src/webhook/interfaces.ts delete mode 100644 src/webrtc/functions.ts delete mode 100644 src/webrtc/interfaces.ts delete mode 100644 src/zones/functions.ts delete mode 100644 src/zones/interfaces.ts delete mode 100644 src/zones/zone.ts delete mode 100644 test/alerts/alert.spec.ts delete mode 100644 test/alerts/dashboard.spec.ts delete mode 100644 test/alerts/functions.spec.ts delete mode 100644 test/applications/application.spec.ts delete mode 100644 test/applications/functions.spec.ts delete mode 100644 test/assets/assets.spec.ts delete mode 100644 test/assets/functions.spec.ts rename {v2/test => test}/auth.test.ts (98%) delete mode 100644 test/auth/functions.spec.ts delete mode 100644 test/broker/broker.spec.ts delete mode 100644 test/broker/functions.spec.ts rename {v2/test => test}/client.test.ts (100%) delete mode 100644 test/clusters/clusters.spec.ts delete mode 100644 test/clusters/functions.spec.ts delete mode 100644 test/clusters/process.spec.ts rename {v2/test => test}/compat.test.ts (94%) delete mode 100644 test/domains/domain.spec.ts delete mode 100644 test/domains/functions.spec.ts delete mode 100644 test/drivers/driver.spec.ts delete mode 100644 test/drivers/functions.spec.ts delete mode 100644 test/edge/edge.spec.ts delete mode 100644 test/edge/functions.spec.ts delete mode 100644 test/groups/functions.spec.ts delete mode 100644 test/groups/group.spec.ts rename {v2/test => test}/hash.test.ts (97%) delete mode 100644 test/history/functions.spec.ts delete mode 100644 test/history/history.spec.ts delete mode 100644 test/http/expired-token.spec.ts delete mode 100644 test/http/functions.spec.ts delete mode 100644 test/http/mock.spec.ts delete mode 100644 test/ldap-sources/functions.spec.ts delete mode 100644 test/ldap-sources/ldap-source.spec.ts rename {v2/test => test}/loose/consumer.ts (97%) rename {v2/test => test}/loose/tsconfig.json (100%) delete mode 100644 test/metadata/functions.spec.ts delete mode 100644 test/metadata/metadata.spec.ts delete mode 100644 test/metadata/zone-metadata.spec.ts rename {v2/test => test}/migrate.test.ts (91%) rename {v2/test => test}/mock.test.ts (100%) delete mode 100644 test/modules/functions.spec.ts delete mode 100644 test/modules/module.spec.ts delete mode 100644 test/oauth-sources/functions.spec.ts delete mode 100644 test/oauth-sources/oauth-source.spec.ts rename {v2/test => test}/pagination.test.ts (100%) rename {v2/test => test}/realtime.test.ts (100%) delete mode 100644 test/realtime/binding.spec.ts delete mode 100644 test/realtime/functions.spec.ts delete mode 100644 test/realtime/mock-module.spec.ts delete mode 100644 test/realtime/mock-system.spec.ts delete mode 100644 test/realtime/mock.spec.ts delete mode 100644 test/realtime/module.spec.ts delete mode 100644 test/realtime/status-variable.spec.ts delete mode 100644 test/realtime/system.spec.ts delete mode 100644 test/repositories/functions.spec.ts delete mode 100644 test/repositories/repository.spec.ts delete mode 100644 test/resources/functions.spec.ts delete mode 100644 test/resources/resource.spec.ts delete mode 100644 test/root/functions.spec.ts delete mode 100644 test/saml-sources/functions.spec.ts delete mode 100644 test/saml-sources/saml-source.spec.ts rename {v2/test => test}/schema.test.ts (100%) delete mode 100644 test/settings/functions.spec.ts delete mode 100644 test/settings/settings.spec.ts delete mode 100644 test/short-url/functions.spec.ts delete mode 100644 test/short-url/short-url.class.spec.ts delete mode 100644 test/signage/ai/functions.spec.ts delete mode 100644 test/signage/functions.spec.ts delete mode 100644 test/staff/answers/functions.spec.ts delete mode 100644 test/staff/questions/functions.spec.ts delete mode 100644 test/storages/functions.spec.ts delete mode 100644 test/storages/storage.class.spec.ts rename {v2/test => test}/style.test.ts (95%) delete mode 100644 test/systems/functions.spec.ts delete mode 100644 test/systems/system.spec.ts delete mode 100644 test/systems/utilities.spec.ts delete mode 100644 test/triggers/functions.spec.ts delete mode 100644 test/triggers/trigger.spec.ts delete mode 100644 test/url-proxy/functions.spec.ts delete mode 100644 test/users/functions.spec.ts delete mode 100644 test/users/user.spec.ts delete mode 100644 test/utilities/api.spec.ts delete mode 100644 test/utilities/general.spec.ts delete mode 100644 test/webrtc/functions.spec.ts delete mode 100644 test/zones/functions.spec.ts delete mode 100644 test/zones/zone.spec.ts rename v2/tsconfig.build.json => tsconfig.build.json (100%) rename v2/tsconfig.cli.json => tsconfig.cli.json (100%) delete mode 100644 v2/.gitignore delete mode 100644 v2/.prettierrc delete mode 100644 v2/README.md delete mode 100644 v2/bun.lock delete mode 100644 v2/package.json delete mode 100644 v2/src/compat/index.ts delete mode 100644 v2/src/index.ts delete mode 100644 v2/src/staff.ts delete mode 100644 v2/tsconfig.json delete mode 100644 vite.config.ts diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 68b3c9752..000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "no-restricted-globals": 0 - } -} diff --git a/.github/workflows/v2.yml b/.github/workflows/ci.yml similarity index 50% rename from .github/workflows/v2.yml rename to .github/workflows/ci.yml index 547df9119..4b6703c31 100644 --- a/.github/workflows/v2.yml +++ b/.github/workflows/ci.yml @@ -1,24 +1,16 @@ -# Checks the v2 package: types, tests and build. -name: v2 +# Checks the package: the migration map, types, tests and build. +name: CI on: pull_request: - paths: - - 'v2/**' - - '.github/workflows/v2.yml' push: branches: - master - paths: - - 'v2/**' - - '.github/workflows/v2.yml' + - next jobs: check: runs-on: ubuntu-latest - defaults: - run: - working-directory: v2 steps: - uses: actions/checkout@v4 @@ -27,9 +19,6 @@ jobs: bun-version: 1.4.3 - run: bun install --frozen-lockfile - # The v1 to v2 map loads the v1 source, which needs the v1 packages. - - run: npm ci --ignore-scripts - working-directory: . - run: bun run v1-map:check - run: bun run check - run: bun test diff --git a/.github/workflows/v2-regenerate.yml b/.github/workflows/regenerate.yml similarity index 50% rename from .github/workflows/v2-regenerate.yml rename to .github/workflows/regenerate.yml index ffffd1cc6..3bacdb017 100644 --- a/.github/workflows/v2-regenerate.yml +++ b/.github/workflows/regenerate.yml @@ -1,12 +1,12 @@ -# Regenerates the v2 client from the API documents on master each day. A change opens a PR, and -# the older regeneration PRs close. See v2/scripts/regenerate-pr.sh. +# Regenerates the client from the API documents on master each day. A change opens a PR, and the +# older regeneration PRs close. See scripts/regenerate-pr.sh. # -# A PR that `GITHUB_TOKEN` opens does not start the `v2` checks, so the script runs the checks and -# puts the results in the PR. Set the secret `V2_REGENERATE_TOKEN` (a token with `contents` and +# A PR that `GITHUB_TOKEN` opens does not start the CI checks, so the script runs the checks and +# puts the results in the PR. Set the secret `REGENERATE_TOKEN` (a token with `contents` and # `pull-requests` write access) to open the PRs as that token, and then the checks start too. # With `GITHUB_TOKEN`, "Allow GitHub Actions to create and approve pull requests" must be on in the # settings of the repository. -name: v2 regenerate +name: Regenerate on: schedule: @@ -18,7 +18,7 @@ permissions: pull-requests: write concurrency: - group: v2-regenerate + group: regenerate cancel-in-progress: false jobs: @@ -29,17 +29,14 @@ jobs: - uses: actions/checkout@v4 with: ref: master - token: ${{ secrets.V2_REGENERATE_TOKEN || github.token }} + token: ${{ secrets.REGENERATE_TOKEN || github.token }} - uses: oven-sh/setup-bun@v2 with: bun-version: 1.4.3 - run: bun install --frozen-lockfile - working-directory: v2 - # The v1 to v2 map loads the v1 source, which needs the v1 packages. - - run: npm ci --ignore-scripts - - run: v2/scripts/regenerate-pr.sh + - run: scripts/regenerate-pr.sh env: - GH_TOKEN: ${{ secrets.V2_REGENERATE_TOKEN || github.token }} + GH_TOKEN: ${{ secrets.REGENERATE_TOKEN || github.token }} diff --git a/.github/workflows/releases.yml b/.github/workflows/releases.yml index 8ccc21d8d..8f1bd3493 100644 --- a/.github/workflows/releases.yml +++ b/.github/workflows/releases.yml @@ -1,58 +1,65 @@ -# This is a basic workflow to help you get started with Actions - +# Releases the package with semantic-release, from the commit messages since the last release: +# +# - `master` publishes to the npm tag `latest`, and the API docs to GitHub Pages. +# - `next` publishes prereleases, such as 7.0.0-next.1, to the npm tag `next`. +# - A maintenance branch, such as `6.x`, publishes fixes of that major version. The workflow on +# that branch lists it in `on.push.branches`. +# +# The branches are in `release` of package.json. npm gets the package with trusted publishing +# (`id-token: write`), so the job has no npm token. name: Release -# Controls when the action will run. Triggers the workflow on push or pull request -# events but only for the master branch on: workflow_dispatch: push: branches: - master + - next -# A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: - # This workflow contains a single job called "build" - build: - # The type of runner that the job will run on + release: runs-on: ubuntu-latest permissions: contents: write issues: write pull-requests: write id-token: write - - # Steps represent a sequence of tasks that will be executed as part of the job steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Setup Node.js environment - uses: actions/setup-node@v4 + # semantic-release and `npm publish` run on Node. + - uses: actions/setup-node@v4 with: node-version: '24.10' - cache: npm - - - name: NPM install - run: npm ci - - - name: Test Library - run: npm run test - - name: Build Library - run: npm run build + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.3 - - name: Generate Documentation - run: npm run docs + - run: bun install --frozen-lockfile + - run: bun run check + - run: bun test + # Before the release, so that a failed build does not leave a tag without a package. + - run: bun run build - - name: Update application version + - name: Release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: npm run semantic-release + run: npx semantic-release + + - uses: denoland/setup-deno@v2 + if: github.ref == 'refs/heads/master' + with: + deno-version: 2.9.8 + + - name: Generate the API docs + if: github.ref == 'refs/heads/master' + run: bun run docs - - name: Publish generated content to GitHub Pages + - name: Publish the API docs to GitHub Pages + if: github.ref == 'refs/heads/master' uses: peaceiris/actions-gh-pages@v4.0.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.prettierrc b/.prettierrc index b6c9f77fb..969d4b941 100644 --- a/.prettierrc +++ b/.prettierrc @@ -2,5 +2,5 @@ "singleQuote": true, "tabWidth": 4, "semi": true, - "plugins": ["prettier-plugin-organize-imports"] + "printWidth": 100 } diff --git a/README.md b/README.md index fa8e99c4d..e9adbbded 100644 --- a/README.md +++ b/README.md @@ -1,517 +1,546 @@ -# TypeScript PlaceOS Library +# @placeos/ts-client -This library is a Typescript interface to PlaceOS +A typed client for the PlaceOS REST API and the staff API. A script generates the types and the +request functions from the OpenAPI documents of +[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) and +[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api/blob/master/OPENAPI_DOC.yml). The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) +where possible. -## Compilation +The library has no runtime dependencies. It runs in browsers, in Node 20.3 and later, and in Bun. -You can build the library from source after installing the dependencies with the command +Version 7 is a new client, with a different API from 6.x. To move an application from 6.x, see +[Migrate from 6.x](#migrate-from-6x). The 6.x source is on the +[`6.x` branch](https://github.com/PlaceOS/ts-client/tree/6.x), which gets the 6.x fixes. -`npm run build` - -## Usage - -API docs can be found [here](https://placeos.github.io/ts-client) - -You can install the PlaceOS Typescript client with the npm command +```sh +npm install @placeos/ts-client@7 +``` -`npm install --save-dev @placeos/ts-client` +## Use the client -Before using PlaceOS it will need to be initialised. +```ts +import { configure, zones } from '@placeos/ts-client'; -```typescript -import { setup } from '@placeos/ts-client'; +// Do this one time, when the application starts. +configure({ + baseUrl: 'https://placeos.example.com', // Use '' for the origin of the page. + auth: { kind: 'bearer', token: () => localStorage.getItem('token') }, +}); -setup(config).then(() => doAfterAuthInitialised()); +const result = await zones.show({ id: 'zone-1234', complete: true }); +if (result.ok) { + console.log(result.value.data.name); +} else { + console.error(result.error.kind); +} ``` -The setup method returns a promise that resolves after the auth flow has completed. -The setup method takes a `config` object with the following properties - -| Property | Description | Optional | Type | Example | -| ---------------- | ------------------------------------------------------- | -------- | -------------------------- | -------------------------- | -| `host` | Host name and port of the PlaceOS server | Yes | `string` | `"dev.placeos.com:8080"` | -| `mock` | Whether to initialise PlaceOS with mock services | Yes | `boolean` | `true` | -| `auth_uri` | URI for authorising users session | No | `string` | `"/auth/oauth/authorize"` | -| `token_uri` | URI for generating new auth tokens | No | `string` | `"/auth/token"` | -| `redirect_uri` | URI to redirect user to after authorising session | No | `string` | `"/oauth-resp.html"` | -| `scope` | Scope of the user permissions needed by the application | No | `string` | `"admin"` | -| `storage` | Browser storage to use for storing user credentials | Yes | `"local" \| "session"` | "session"` | -| `handle_login` | Whether PlaceOS should handle user login | Yes | `boolean` | `true` | -| `use_iframe` | Use iFrame for authorization of application | Yes | `boolean` | `false` | -| `secure` | Force requests to backend to be secure i.e. HTTPS/WSS | Yes | `boolean` | `false` | -| `ignore_api_key` | Ignore set API keys when authenticating requests | Yes | `boolean` | `false` | -| `token_header` | Force all requests to use headers for auth over cookies | Yes | `boolean` | `false` | -| `username` | Username to use for basic authentication | Yes | `string` | `"user@place.os"` | -| `password` | Password to use for basic authentication | Yes | `string` | `"hard-to-guest-password"` | -| `auth_type` | Type of authentication to perform | Yes | `"implicit" \| "password"` | `"implicit"` | -| `entra_token` | Get a Microsoft Entra access token to exchange | Yes | `() => Promise` | `getAccessToken` | - -#### Microsoft Entra token exchange - -Apps that are signed in to Microsoft (for example, an Outlook add-in) can exchange the Entra access token for PlaceOS tokens. The user does not have to sign in again. - -Set `entra_token` to a function that gets the Entra access token. When no other credentials are available, `authorise` sends the token to `token_uri` with the RFC 8693 token exchange grant. - -```typescript -import { setup } from '@placeos/ts-client'; - -await setup({ - auth_uri: '/auth/oauth/authorize', - token_uri: '/auth/oauth/token', - redirect_uri: `${location.origin}/addin/oauth-resp.html`, - scope: 'public', - entra_token: () => Office.auth.getAccessToken({ allowSignInPrompt: true }), +There is one namespace for each controller of the API, for example `zones`, `systems` and +`users`. Each function has the name of the server action: `show`, `create`, `update`, `destroy`, +or a custom action such as `systems.execute`. The `index` action is `query`, because a list +operation queries the items. The comment of each function gives the HTTP method and the path. + +The first argument has the path parameters, the query parameters and, for an operation with a +body, `body`. The second argument has the options of the request: + +```ts +await zones.update({ id: 'zone-1234', body: { name: 'Level 2' } }); +await systems.execute({ + sys_id: 'sys-1234', + module_slug: 'Display_1', + method: 'power', + body: [true], }); ``` -You can also call `exchangeEntraToken(token)` directly. +### Results and errors -The PlaceOS domain must have an Entra OAuth source for a single tenant. Refer to the [auth.cr documentation](https://github.com/PlaceOS/auth.cr/blob/master/README.md#microsoft-entra-token-exchange) for the server requirements. +A function does not throw for an expected failure. It returns a `Result`. Examine `ok` first: -#### Local Development with live environments +| `error.kind` | Meaning | +| -------------------- | -------------------------------------------------------------------------- | +| `http` | The server sent a status that is not 2xx. See `status`, `message`, `body`. | +| `network` | The request got no response. For example, the network is down. | +| `timeout` | The request took more than `timeoutMs`. | +| `aborted` | The `signal` of the caller cancelled the request. | +| `auth_missing` | The auth had no token or credential. | +| `response_too_large` | The body was more than `responseBytesMax`. | +| `response_invalid` | The body does not match the API document. See `path` and `expected`. | -You will not be able to use SSO for local development by default. -To solve this you will either need to: +A function throws only for a programmer error. For example, a parameter that the operation does +not have, an empty path parameter, or a call before `configure`. -- Reverse proxy the development UI through the live environment -- Reverse proxy the `/login` endpoint from the live environment to the local development environment then perform basic login instead -- Use an API key to authenticate with the backend +In a project without `strictNullChecks`, `if (!result.ok)` does not narrow the `Result`. Use +`if (result.ok === false)`. -If you're not proxying the local development UI through the live server it is recommended to reverse proxy all the API endpoints to prevent any possible CORS issues. +### More than one client -### Websocket API +`configure` makes the client that each call uses. To use a different client for one call, make it +with `createClient` and give it in the options. The configured client does not change: -`PlaceOS` exposes a websocket API through the `realtime` entrypoint. - -The `realtime` entrypoint provides methods for real-time interaction with modules running on PlaceOS. It provides an interface to build efficient, responsive user interfaces, monitoring systems and other extensions which require live, two-way or asynchronous interaction. - -Once PlaceOS has initialised you can listen to values on modules - -```typescript -import { getModule } from '@placeos/ts-client'; - -const my_mod = getModule('sys-death-star', 'TestModule', 3); -const my_variable = my_mod.variable('power'); -const unbind = my_variable.bind(); -const unsubscribe = my_variable.subscribe((value) => doSomething(value)); - -// Later, when the UI no longer needs the value: -unsubscribe(); -unbind(); +```ts +const other = createClient({ baseUrl: 'https://other.example.com', auth: { kind: 'none' } }); +await zones.query({}, { client: other }); ``` -This binds to the `power` status variable on the 3rd `TestModule` in the system `sys-death-star`. -Any changes to the value of `power` on PlaceOS will then be emitted to the function passed to `subscribe`. - -Realtime values are exposed as signals. A signal is a callable value holder with a `value` property and a `subscribe` method. +### Timeouts and cancel -```typescript -import { listen } from '@placeos/ts-client'; +Each request has a time limit. The default is 30 seconds. Set a different limit for the client or +for one request: -const power = listen({ - sys: 'sys-death-star', - mod: 'TestModule', - index: 3, - name: 'power', -}); - -console.log(power.value); // Current value -console.log(power()); // Same current value - -const unsubscribe = power.subscribe((value, previous) => { - console.log('Power changed from', previous, 'to', value); -}); -``` - -Other than listening to changes of values you can also remotely execute methods on modules. - -```typescript -const my_mod = getModule('sys-death-star', 'DemoModule', 2); - -try { - const resp = await my_mod.execute('power_off'); - handleSuccess(resp); -} catch (err) { - handleError(err); -} +```ts +configure({ baseUrl: '', auth: { kind: 'none' }, timeoutMs: 10_000 }); +const controller = new AbortController(); +await zones.query({}, { signal: controller.signal, timeoutMs: 60_000 }); ``` -This will execute the method `power_off` on the 2nd `DemoModule` in the system `sys-death-star`. -If the method doesn't exist or the system is turned off it will return an error. -The response from PlaceOS can be handled using the promise returned by the `execute` method. - -### HTTP API - -For the HTTP API, `PlaceOS` provides various methods for each of the root endpoints available on PlaceOS's RESTful API. - -Docs for the API can be found here https://docs.placeos.com/api/control +### Pages -Methods are provided for `brokers`, `drivers`, `metadata`, `modules`, `repositories`, `settings`, `systems`, `triggers`, `users`, and `zones`. +A `query` operation returns one page. Use `pageInfo` to get the total and the next offset: -```typescript -// Drivers CRUD -const new_driver = await addDriver(driver_data); -const driver = await showDriver(driver_id); -const updated_driver = await updateDriver(driver_id, driver_data); -await removeDriver(driver_id); +```ts +import { pageInfo, zones } from '@placeos/ts-client'; -// Modules CRUD -const new_module = await addModule(module_data); -const mod = await showModule(module_id); -const updated_module = await updateModule(module_id, module_data); -await removeModule(module_id); - -// Systems CRUD -const new_system = await addSystem(system_data); -const system = await showSystem(system_id); -const updated_system = await updateSystem(system_id, system_data); -await removeSystem(system_id); - -// Users CRUD -const new_user = await addUser(user_data); -const user = await showUser(user_id); -const updated_user = await updateUser(user_id, user_data); -await removeUser(user_id); - -// Zones CRUD -const new_zone = await addZone(zone_data); -const zone = await showZone(zone_id); -const updated_zone = await updateZone(zone_id, zone_data); -await removeZone(zone_id); -``` - -The lower-level HTTP helpers are promise-based too. - -```typescript -import { get, post, del } from '@placeos/ts-client'; - -const system = await get(`/api/engine/v2/systems/${system_id}`); -const created = await post('/api/engine/v2/zones', zone_data); -await del(`/api/engine/v2/zones/${zone_id}`); +const result = await zones.query({ limit: 100 }); +if (result.ok) { + const { total, nextOffset } = pageInfo(result.value.headers); +} ``` -Every HTTP request sends the OAuth client ID as `X-App-Id` after `setup` runs. -To identify your application, set app headers. Every HTTP request then also sends `X-App-Name`, `X-App-Date` and `X-App-Build`. -Headers given in the request options override them. - -```typescript -import { setAppHeaders } from '@placeos/ts-client'; +### Tests and mocks -setAppHeaders('workplace', '2026-10-08', 'abcd1234'); -``` - -The modules also provide methods for the various item action endpoints - -```typescript -// Driver Actions -await reloadDriver(driver_id); - -// Module Actions -await startModule(module_id); -await stopModule(module_id); -await pingModule(module_id); -await lookupModuleState(module_id, lookup); -await moduleState(module_id); - -// System Actions -await addSystemModule(system_id, module_name); -await removeSystemModule(system_id, module_name); -await startSystem(system_id); -await stopSystem(system_id); -await executeOnSystem(system_id, module_name, index, args); -await lookupSystemModuleState(system_id, module_name, index, lookup); -await functionList(system_id, module_name, index); -await moduleTypes(system_id, module_name); -await moduleCount(system_id); -await listSystemZones(system_id); - -// User Actions -await currentUser(); -``` +Give the client a `fetch` function. The client sends each request through it. A test can give +its own client in the options, so it does not change the configured client: -Objects returned by `show` and `query` methods are immutable. -Therefore to change items you'll need to create a new object to store the changes. - -```typescript -showZone(zone_id).then((zone) => { - console.log(zone.description); // Some Description - const zone_edited = new PlaceZone({ - ...zone, - description: 'New description', - }); - updateZone(zone_edited.id, zone_edited).then((updated_zone) => { - console.log(updated_zone.description); // New description - }); +```ts +const client = createClient({ + baseUrl: '', + auth: { kind: 'none' }, + fetch: async (url, init) => new Response(JSON.stringify({ id: 'zone-1' })), }); +const result = await zones.show({ id: 'zone-1' }, { client }); ``` -You can find more details about endpoint action on the API docs +### Typed mocks -https://placeos.docs.apiary.io/ +`@placeos/ts-client/mock` answers the calls of an endpoint without a request. The compiler checks +the name of the endpoint, the input that the handler gets, and the data that it gives: -## Migrating from RxJS +```ts +import { endpointMocks, httpError, mockEndpoint, respond } from '@placeos/ts-client/mock'; -The client no longer depends on RxJS. HTTP and resource methods now return promises, while realtime and authentication state methods return signals. +configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); -### HTTP and resource requests - -Replace observable subscriptions with `await` or promise handlers. - -```typescript -// Before -showDriver(driver_id).subscribe((driver) => doSomething(driver)); - -// After -const driver = await showDriver(driver_id); -doSomething(driver); -``` - -```typescript -// Before -querySystems({ limit: 20 }).subscribe(({ data }) => render(data)); - -// After -const { data } = await querySystems({ limit: 20 }); -render(data); +mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); +mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 1 })); +mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 300 }); +mockEndpoint('zones.destroy', () => { + throw httpError(403); +}); ``` -For error handling, use `try`/`catch` or `.catch`. - -```typescript -try { - await updateZone(zone_id, zone_data); -} catch (error) { - handleError(error); -} +- The client checks the input first, as for a request. Then it parses the data of the handler with + the response schema of the endpoint, as it parses a response. The data can leave out fields: a + missing required field gets its empty value, such as `''`, `0` or `[]`. A field with the wrong + type is a `response_invalid` error. +- `respond(data, { status, headers, total })` sets the status and the headers. `total` is the + `X-Total-Count` that `pageInfo` and `orThrowPage` read. +- `mockEndpoint` returns the function that removes the mock. `clearEndpointMocks()` removes all. +- A call to an endpoint without a mock goes to the `fetch` of the client. Give `mockFetch` of + `@placeos/ts-client/compat` to answer it from the 6.x mock endpoints. +- `mock` of the client is a function. A test can give its own, which gets the name of the endpoint + (such as `zones.show`) and the input, and returns an answer or `null`. + +A test double of a 7.x call gives a `Result`. `mockReply` and `mockPage` of +`@placeos/ts-client/compat` make one: + +```ts +vi.mock('@placeos/ts-client', { spy: true }); +vi.mocked(zones.show).mockResolvedValue(mockReply(zone)); +vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); ``` -### Realtime values - -Realtime listeners now return signals instead of observables. A signal: - -- can be called to read its current value: `signal()` -- exposes the same current value as `signal.value` -- emits changes with `signal.subscribe((value, previous) => {})` -- returns an unsubscribe function from `subscribe` -- emits the current value immediately by default - -```typescript -// Before -const sub = listen(binding).subscribe((value) => render(value)); -sub.unsubscribe(); +### Mock mode -// After -const signal = listen(binding); -render(signal.value); +For new mocks, use [typed mocks](#typed-mocks). The 6.x mock endpoints and mock systems are in +`@placeos/ts-client/compat`, with the same names. +Give `mockFetch` to the client, and `mockRealtimeEnvironment()` to the realtime client: -const unsubscribe = signal.subscribe((value, previous) => { - render(value); +```ts +registerMockEndpoint({ + path: '/api/engine/v2/zones/:id', + method: 'GET', + callback: (request) => ({ id: request.route_params['id'], name: 'Level 1' }), }); -unsubscribe(); -``` +registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); -If you do not want the initial value to emit on subscription, pass `{ emitCurrent: false }`. - -```typescript -const unsubscribe = signal.subscribe((value) => render(value), { - emitCurrent: false, +configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch, missingFields: 'zero' }); +const realtime = createRealtime({ + baseUrl: '', + auth: { kind: 'none' }, + environment: mockRealtimeEnvironment(), }); ``` -The same pattern applies to realtime status helpers. +- 7.x parses each mock response with the schema of the operation. Mock data often has only some + fields. `missingFields: 'zero'` gives each missing required field its empty value, such as `''`, + `0` or `[]`, as the 6.x classes did. A field with the wrong type is still an error, because the + real server does not send it. +- A mock endpoint that throws an error with a `status`, such as `404`, gives that HTTP status. +- A change to a variable of a mock module, such as `mockSystem('sys-1')['Display'][0]['power'] += true`, notifies its bindings. -```typescript -const unsubscribe = status().subscribe((connected) => { - renderConnectionState(connected); -}); -``` +## Staff API -### Auth state +The staff API (bookings, events, guests, desks, surveys and more) is at +`@placeos/ts-client/staff`. It uses the client of `configure`, as the REST API functions do: -`listenForToken()` and `onlineState()` now return signals. +```ts +import { bookings } from '@placeos/ts-client/staff'; -```typescript -const stopListening = onlineState().subscribe((online) => { - renderOnlineState(online); -}); +const now = Math.floor(Date.now() / 1000); +const result = await bookings.query({ period_start: now, period_end: now + 86_400, type: 'desk' }); ``` -### Common replacements - -| Old RxJS pattern | New API | -| ------------------------------------ | --------------------------------------------------------------------- | -| `await firstValueFrom(showZone(id))` | `await showZone(id)` | -| `showZone(id).toPromise()` | `showZone(id)` | -| `showZone(id).subscribe(fn)` | `showZone(id).then(fn)` or `const zone = await showZone(id)` | -| `listen(binding).pipe(...)` | `listen(binding).subscribe(...)` and handle filtering in the callback | -| `subscription.unsubscribe()` | `unsubscribe()` | - -## Writing mocks - -If you don't have access to a PlaceOS server you can also write mocks so that you can still develop interfaces for PlaceOS. - -To use the mock services you can pass `mock: true` into the initialisation object. - -### Websockets +- The staff API has its own schemas, such as `Booking` and `Guest`. A schema that both APIs have, + such as `Zone`, is in both entries with the same shape. +- The typed mocks of the staff API start with `staff.`: `mockEndpoint('staff.bookings.show', ...)`. +- Some routes of the staff API have an occurrence of a recurring booking: `bookings.showInstance` + is `GET /bookings/{id}/instance/{instance}`, the occurrence of `bookings.show`. -To write mocks for the the realtime(websocket) API you'll need to register your systems with the `registerSystem` before attempting to bind to the modules it contains. +## Log in -```typescript -import { registerSystem } from '@placeos/ts-client'; +`createAuthSession` does the OAuth login of PlaceOS and gives the client its credential: -registerSystem('my-system', { - MyModule: [ - { - power: true, - $power_on: function () { - this.power = true; - }, - $power_off: function () { - this.power = false; - }, - }, - ], -}); -``` - -Note that executable methods on mock systems are namespaced with `$` as real systems in PlaceOS allow for methods to have the same name as variables. - -Once initialised interactions with a system are performed in the same manner as the live system. - -```typescript -const my_mod = getModule('my-system', 'MyModule', 1); -const my_variable = my_mod.variable('power'); -const unbind = my_variable.bind(); -const unsubscribe = my_variable.subscribe((value) => doSomething(value)); // Emits true -await my_mod.execute('power_off'); // The listen callback will now emit false -``` +```ts +import { configure, createAuthSession } from '@placeos/ts-client'; -Some methods may need access to other modules within the system, for this a property is appended on runtime called `_system` which allows for access to the parent system - -```typescript -registerSystem('my-system', { - "MyModule": [ - { - $lights_off: function () { this._system.MyOtherModule[0].lights = false; } - } - ] - "MyOtherModule": [ - { - lights: true, - } - ] +const session = createAuthSession({ + baseUrl: '', + redirectUri: `${location.origin}/oauth-resp.html`, + scope: 'public', + grant: { kind: 'code' }, }); -``` - -### HTTP Requests +configure({ baseUrl: '', auth: session.clientAuth, headers: { 'X-App-Id': session.clientId } }); -HTTP API Requests can be mocked in a similar way to the realtime API by registering handlers with `registerMockEndpoint` - -```typescript -import { registerMockEndpoint } from '@placeos/ts-client'; - -registerMockEndpoint({ - path: '/api/engine/v2/systems', - metadata: {}, - method: 'GET', - callback: (request) => my_mock_systems, -}); +const result = await session.start(); +if (!result.ok && result.error.kind === 'redirecting') { + // The page goes to the login page now. +} ``` -Paths allow for route parameters and will pass the value in the callback input. - -```typescript -registerMockEndpoint({ - path: '/api/engine/v2/systems/:system_id', - ... - callback: (request) => - my_mock_systems.find(sys => sys.id === request.route_params.system_id) +Copy `oauth-resp.html` from the package to your application, and use its URL as `redirectUri`. The +client ID is the MD5 of `redirectUri`, as in 6.x. + +`session.start()` loads `/auth/authority`, and gets a credential in this order: + +1. An API key from the URL or the storage (a fixed device), or an access token that is valid. +2. A code or a token from the redirect. The `state` must be the nonce of this client. +3. The refresh token. +4. The `password` or `entra` grant. +5. If the user has a session: the authorize page, with a redirect or, with `useFrame`, in a + hidden frame. +6. Else the login page of the authority. With `handleLogin: false`, the result is a + `login_required` error, and the application shows its own login. + +The grants are `code` (with PKCE), `implicit`, `password` and `entra`. PlaceOS auth.cr refuses +the `password` grant; only older auth services accept it. A trusted application (`?trust=true`) +keeps its tokens in the storage. Other applications keep them in memory only. + +After a 401, the client asks the session for a new token and sends the request again, one time. +Parallel requests share one renewal. After a 511, the session sends the user to the login page. + +Other parts of the session: + +- `session.status()` and `session.subscribe(listener)` give the state: `loading`, `signed_in`, + `redirecting` or `signed_out` with the error. +- `session.handleRedirect(url)` completes a login from a deep link, in a native wrapper. +- When the application comes back to the foreground without a session, the session loads the + authority again. The user can have logged in from a different tab. +- `session.useToken`, `session.useApiKey`, `session.invalidateToken` and `session.logout`. +- `createAuthSession({ ..., environment })` replaces the browser parts, for tests or a native + wrapper. See `AuthEnvironment`. + +### Changes from 6.x + +- The session keeps the storage keys of 6.x, so a user stays logged in after the change. +- The default token path is `/auth/oauth/token`. PlaceOS auth.cr and the older Ruby auth service + both serve it. The Ruby auth service does not serve `/auth/token`. +- A relative login or logout URL of the authority is on `baseUrl`. 6.x used the `domain` of the + authority, which has no port. +- A refused code stops the login with `token_rejected`. A new redirect could loop. +- The token requests send their parameters in the body, not in the URL. A password is not in the + URL. +- A trusted application with the `implicit` grant uses the code with PKCE. +- The frame login checks the `state`. It needs the `oauth-resp.html` of 7.x. +- The session removes `x-api-key` from the URL after it reads it. +- After a refused refresh token, the login continues immediately. +- A refusal on the consent page (`error=access_denied` with the state of this client) stops the + login with `authorization_denied`. 6.x sent the user to the authorize page again. +- `/auth/authority` gets `AUTHORITY_ATTEMPTS_MAX` attempts, not an unlimited number. Then + `start` gives `authority_unavailable`. Call `start` again to try again. +- Not ported: `revokeToken`, the state of the application in `authorise(state)`, and the ACA + Engine API path. The mock mode is in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). + It does not need a login: give `auth: { kind: 'none' }`. + +## Realtime + +`createRealtime` opens one WebSocket to `systems/control`. It binds to the status variables of +modules, calls their functions and gets their logs: + +```ts +import { createRealtime } from '@placeos/ts-client'; + +const realtime = createRealtime({ baseUrl: '', auth: session.clientAuth }); + +const power = { sys: 'sys-1234', mod: 'Display', index: 1, name: 'power' }; +const release = realtime.bind(power, (state) => { + if (state.kind === 'value') console.log('power', state.value); }); +const result = await realtime.exec(power, [true]); +release(); ``` -Handlers may also throw errors - -```typescript -registerMockEndpoint({ - path: `/api/engin/v2/systems/:id`, - method: 'GET', - callback: (request) => { - if (request.route_params.id) { - ... - } - throw { status: 404, message: 'Invalid system ID' }; - } -}); +- The client connects when the first binding or call needs it. `start` connects now. +- A binding has a count. The first `bind` sends `bind`. The last release sends `unbind`. +- After a new connection, the client binds each variable again. +- The client handles the messages of the server in batches. In one batch, many notifications for + one variable give one call to its listeners, with the last value. +- `exec` gives a `Result` with the return value of the function, or a `RealtimeError`: + `timeout`, `disconnected` (the socket closed after the server got the call), `stopped`, + `unavailable`, `too_many_requests` or `server` (with the error code and the status). +- The client sends `ping` each 15 seconds. A socket without a message for 60 seconds closes, and + the client connects again. It waits longer after each failure, to 5 seconds. After 40 attempts, + the status is `failed`. Call `start` to try again. +- `realtime.debug({ sys, moduleId }, listener)` gets the logs of a module. +- `splitModuleId('Display_2')` gives `{ mod: 'Display', index: 2 }`. +- In a browser, the token goes in a cookie on the socket path. In a frame and on mobile Safari it + goes in the query, as in 6.x. `createRealtime({ ..., environment })` replaces the socket, the + timers and the cookie, for tests. + +### Changes from 6.x + +- A call that the server got fails with `disconnected` when the socket closes. 6.x did not settle + these calls. +- Two calls with the same arguments are two calls. 6.x merged them for one minute. +- Server errors have the correct code name. 6.x read the HTTP style status as the error code. +- `iface: true` addresses an interface, such as `Interface::Sensor`. +- After 40 failed attempts, the status is `failed`. 6.x reloaded the page. +- Not ported: the `connectionState` signal and the `/control/websocket` path of ACA Engine. The + mock systems are in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). + +## Types + +Each schema of the API document has a value and two types with the same base name: + +- `Zone` is the type of a zone from the server. Each field is present. A field that the server can + leave out is `null`. +- `ZoneInput` is the type of a zone that you send. Each field is optional. +- The `Zone` value is the schema. `parseResponse(Zone, value)` parses data from other sources. + +The parser removes the fields that the schema does not have. A request that has a field that the +schema does not have stops with an error, because a typing error in a field name is a bug. + +Some schemas have a name from the server code that does not say what they are. These have a +short name too. The short name is the same value and type: + +| Short name | Name in the API document | +| ------------------------ | ------------------------------- | +| `User` | `UserAdminMetadataResponse` | +| `System` | `ControlSystem` | +| `Application` | `DoorkeeperApplication` | +| `Domain` | `Authority` | +| `Metadata` | `MetadataInterface` | +| `ShortUrl` | `Shortener` | +| `SignageTemplateMapping` | `SignageTemplateSystemTemplate` | + +`TYPE_ALIASES` in `scripts/generate.ts` has the list. + +## Differences from the API document + +The generator changes some parts of the document. Each change has a comment in +`scripts/generate.ts`. + +- **Time fields.** The document says `date-time` for some fields that the server sends as Unix time + in seconds, for example `created_at` on most models. The generator changes these fields to + integers. The list comes from the source of PlaceOS/models. The generator stops if it finds a + `date-time` field that is not in a list, so each new field gets a decision. +- **Enum numbers.** The server sends some enums as numbers, for example `Driver.role` (`99` is + `logic`). The document gives their names. The generator changes these fields to the numbers. +- **Required fields in a request.** The document marks a field as required when the server always + sends it. The server can have a default for the same field in a request. Thus each field of a + request body is optional, and the server checks the body. Path and query parameters keep the + `required` of the document. +- **Arrays in a query.** The server reads an array parameter as one value with commas, for example + `zone_id=a,b`. The items of an array parameter must not contain commas. +- **PATCH and PUT.** The server sends PATCH and PUT of `update` to the same method. The client has + only `update`, which sends PATCH. +- **Numbered routes.** The document numbers the routes of one action: `show` and `show_2`. A second + path with the same signature is an alias, such as `checkin` for `check_in` in the staff API. The + client has only the first path. A path with more segments gets a name from them, such as + `showInstance` for `bookings/{id}/instance/{instance}`. +- **A query parameter named `body`.** `body` of the input is the request body, so the `body` query + parameter of `staff.events.book` (the description of the meeting) is `body_text` in the input. + The query keeps the name `body`. +- **Responses without a schema.** The data is a `Uint8Array` with the raw body. `systems.execute`, + `modules.execute` and `modules.stateValue` are exceptions: they return a `JsonValue`. +- **WebSocket endpoints** (`systems/control`, `webrtc/signaller` and others) are not in the + client. + +## Change the generated code + +Do not edit `src/generated`. The generator downloads the API documents from the master branches of +[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api) and +[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api) on each run. It does not keep a copy in +this repository. `APIS` in `scripts/generate.ts` has the list: the repository, the output folder +and the prefix of the operation IDs and names. + +```sh +bun run generate # Downloads the documents and writes src/generated and src/generated/staff. +bun run generate:check # Fails if the generated files do not match the current documents. ``` -Query parameters are also available on the callback input. - -Handlers can return response headers, e.g. `Link` and `X-Total-Count` for paginated results. -Use a static map, or a function to make headers from the request. -Header keys are lowercase in `responseHeaders(url)`, the same as live requests. - -```typescript -registerMockEndpoint({ - path: '/api/engine/v2/systems', - method: 'GET', - callback: (request) => { - const offset = +(request.query_params.offset || 0); - return my_mock_systems.slice(offset, offset + 20); - }, - headers: (request) => { - const next = +(request.query_params.offset || 0) + 20; - return { - 'X-Total-Count': `${my_mock_systems.length}`, - ...(next < my_mock_systems.length - ? { - Link: `; rel="next"`, - } - : {}), - }; - }, -}); +The generated files are in the repository, so a change to the API shows as a diff. Examine the +diff before you commit it. `generate:check` can fail because the API changed, not because of your +change, so it is not part of `bun test` or of the checks of a PR. + +Each day, the `Regenerate` workflow regenerates the client from the API documents on master +(`scripts/regenerate-pr.sh`). When the output changes, it opens a PR with the diff and the results +of the checks. It also closes the older regeneration PRs, because the new one has their changes. +When master matches the documents again, it closes all of them. Each run deletes the +regeneration branches that have no open PR, such as the branch of a merged PR. `DRY_RUN=1 +scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. + +The generator stops with an assertion on a part of the document that it does not support. Add the +support to `scripts/generate.ts` and `src/core/schema.ts`. + +## Development + +```sh +bun install +bun run check # Type checks the library, the tests and the scripts. +bun test +bun run build # Writes dist/. Then it type checks test/loose without `strict`. +bun run v1-map # Writes the 6.x to 7.x map, from the source of the placeos-ts-client-6 package. +bun run docs # Writes the API docs to docs/. It needs Deno. ``` -`GET`, `POST`, `PUT`, `PATCH` and `DELETE` requests can be mocked out. - -Mock HTTP handlers return promises. If a request is made and there are no handlers it will attempt to make the live request. - -### Authentication - -Authentication is handled automatically by the library but can be configured with the `setup` configuration. - -If you wish to handle login within your application you can set `handle_login` to `false` to prevent redirecting to the login URL set in the `authority`. -If you wish to prevent redirecting the application to handle application authentication you can set `use_iframe` to `true` to have that handled in the background. +### Releases -![Authentication Flowchart](https://aca.im/cdn/images/auth-flowchart.png) +semantic-release publishes the package from the commit messages, with the `Release` workflow. A +`fix` commit gives a patch release, a `feat` commit gives a minor release, and a commit with a +`BREAKING CHANGE:` footer gives a major release. `release` in `package.json` has the branches: -## Usage with Node JS +| Branch | Releases | +| -------- | ------------------------------------------------------------------------ | +| `master` | To the npm tag `latest`. The API docs go to GitHub Pages. | +| `next` | Prereleases, such as `7.0.0-next.1`, to the npm tag `next`. | +| `6.x` | The fixes of 6.x, such as `6.13.1`. The workflow of that branch runs it. | -It is possible to use `ts-client` with Node JS. -It requires an addition setup step before the library can be used loading the library. +## Migrate from 6.x -### Javascript: +The migration tool rewrites the 6.x calls of a project to 7.x. Commit your work first, so that you +can examine and undo the changes. Run it in the folder of the project, because it uses the +`typescript` package of the project: -```javascript -const ts_client = require('@placeos/ts-client'); - -async function setupPlaceOS() { - await ts_client.preSetupNode(); - await ts_client.setup({ - ... - }) -} +```sh +npx -p @placeos/ts-client@7 placeos-migrate src # Shows the changes. Writes no file. +npx -p @placeos/ts-client@7 placeos-migrate --write src # Writes the changes. ``` -### Typescript: - -```typescript -import { preSetupNode, setup } from '@placeos/ts-client'; - -async function setupPlaceOS() { - await preSetupNode(); - await setup({ - ... - }) -} -``` +The tool makes these changes: + +- A call of a 6.x REST function becomes the 7.x operation. `.then(orThrow)` gives the data, and an + error rejects the promise, as in 6.x. A 6.x query function gets `.then(orThrowPage)`, which gives + `{ data, total, nextOffset }`. + + ```ts + // 6.x + const zone = await showZone(id, { complete: true }); + const list = await queryZones({ limit: 10 }); + // 7.x, after the tool + const zone = await zones.show({ id, complete: true }).then(orThrow); + const list = await zones.query({ limit: 10 }).then(orThrowPage); + ``` + +- A type reference to a 6.x class becomes the 7.x type. For example, `PlaceZone` becomes `Zone`. +- The imports of the 6.x enums, such as `PlaceDriverRole`, and of `QueryResponse` move to + `@placeos/ts-client/compat`. The enums have the 7.x values, so they fit the 7.x fields of the + data. A query parameter takes the name: the `role` of `drivers.query` is `'logic'`, not `99`. +- A new import gets another name when the file has the name. For example, a file with a + `zones` variable gets `zones as zonesV2`. + +The tool also changes the test doubles, so that the tests of the app still work: + +- `vi.mocked(showZone)`, `expect(showZone)`, `vi.spyOn(client, 'showZone')` and, in a spec file, + each other use of `showZone` become `zones.show`. +- A value of `mockResolvedValue` gets `mockReply` or `mockPage`. The arguments of + `toHaveBeenCalledWith` become the 7.x input. +- A 6.x implementation, such as the value of `mockImplementation`, gets `fromV1Mock`. It gives the + implementation the 6.x arguments, and makes a 7.x result of its value. +- The 6.x functions of a `vi.mock('@placeos/ts-client', () => ({ ... }))` factory become 7.x + namespaces: `showZone: vi.fn(impl)` becomes `zones: { show: vi.fn(fromV1Mock(impl, ['id', +'...'])) }`. The factory runs before the imports, so the tool adds `fromV1Mock` with + `vi.hoisted`. +- The 6.x staff functions, such as `querySurveys`, become the operations of + `@placeos/ts-client/staff`, with their own import. +- The imports of the mock endpoints and mock systems move to `@placeos/ts-client/compat`. See + [Mock mode](#mock-mode). + +The tool does not change a use that it cannot rewrite safely. It shows each one with a hint, and +it keeps its 6.x import, so the compiler also shows it. These uses are: + +- the login and the realtime functions, such as `setup`, `token` and `getModule`; +- `get`, `post` and the other HTTP functions; +- `new` and `instanceof` on a 6.x class, because 7.x has plain objects; +- the `next` function of a 6.x page. 7.x gives `nextOffset`; +- a function that is not called, out of a test; +- a `vi.mock` without a factory or `{ spy: true }`: its 7.x functions give `undefined`, and + `.then(orThrow)` fails; +- a `jest.mock` factory with 6.x functions; +- an argument that has no place in 7.x, and an argument with side effects that 7.x uses two times. + +On a copy of backoffice, 329 of the 399 tests pass after the tool. 6.x passes 394. The other tests +use 6.x classes, the 6.x `next` function or the 6.x `createSignal`, or wait for one microtask only. +These are the uses that the tool shows. + +After the tool: + +1. Run Prettier, or your formatter. The tool writes long imports on one line. +2. Install 7.x, and call `configure` once before the first call (see [Log in](#log-in)). For a + mock mode, give `fetch: mockFetch` (see [Mock mode](#mock-mode)). +3. Run the compiler. It shows the differences of the data. For example, a field that can be + `null`, an array that is `readonly`, or a query parameter that has a different type in 7.x. +4. Change the uses that the tool showed. + +`orThrow` and `orThrowPage` keep the 6.x behavior. In new code, examine the `Result`. + +The tool parses each file. It does not type check it. The map from 6.x to 7.x is +`src/migrate/v1-map.ts`. `scripts/v1-map.ts` makes it: it calls each 6.x REST function with marker +arguments, and it finds the 7.x operation with the same method and path. + +## What 6.x has that 7.x does not have + +- Classes with methods for each model. 7.x has plain data and functions. + +## Where 7.x does not follow TigerStyle + +- `orThrow` and `orThrowPage` of `@placeos/ts-client/compat` throw. They are for code that moves + from 6.x. +- The 6.x mock types of `@placeos/ts-client/compat` (`MockHttpRequest.body`, `metadata` and + `MockModule`) keep `any`, so that the mocks of an app still compile. +- `missingFields: 'zero'` accepts data without its required fields. It is for mock data only. +- `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove + that the parser output has the type of the schema. The tests check the parser. +- `configure` keeps one client in module state, so a call does not need a client argument. A + call before `configure` is a run-time assertion, not a compile error. +- The mocks keep their registries in module state, as 6.x did: the endpoints of + `registerMockEndpoint` and the systems of `registerSystem` (`@placeos/ts-client/compat`), and + the mocks of `mockEndpoint` (`@placeos/ts-client/mock`). A test owns them. It removes them with + `clearMockEndpoints`, `deregisterSystem` and `clearEndpointMocks`. Each registry has a named + limit. The status variables of a mock module are properties with setters that notify the + bindings, as in 6.x. +- `createAuthSession` keeps its state in a closure. The login is a state machine with I/O, and + one object with one owner is the clearest model of it. +- Records from the server are plain objects, not `Map`s. A `Map` does not go through + `JSON.stringify`, and the API sends these objects back and forth. diff --git a/bun.lock b/bun.lock new file mode 100644 index 000000000..ab000a834 --- /dev/null +++ b/bun.lock @@ -0,0 +1,1044 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "@placeos/ts-client", + "devDependencies": { + "@types/bun": "1.4.3", + "placeos-ts-client-6": "npm:@placeos/ts-client@6.13.0", + "prettier": "3.9.10", + "semantic-release": "25.0.9", + "typescript": "7.0.2", + "typescript-5": "npm:typescript@5.8.3", + }, + }, + }, + "packages": { + "@actions/core": ["@actions/core@3.0.1", "", { "dependencies": { "@actions/exec": "^3.0.0", "@actions/http-client": "^4.0.0" } }, "sha512-a6d/Nwahm9fliVGRhdhofo40HjHQasUPusmc7vBfyky+7Z+P2A1J68zyFVaNcEclc/Se+eO595oAr5nwEIoIUA=="], + + "@actions/exec": ["@actions/exec@3.0.0", "", { "dependencies": { "@actions/io": "^3.0.2" } }, "sha512-6xH/puSoNBXb72VPlZVm7vQ+svQpFyA96qdDBvhB8eNZOE8LtPf9L4oAsfzK/crCL8YZ+19fKYVnM63Sl+Xzlw=="], + + "@actions/http-client": ["@actions/http-client@4.0.1", "", { "dependencies": { "tunnel": "^0.0.6", "undici": "^6.23.0" } }, "sha512-+Nvd1ImaOZBSoPbsUtEhv+1z99H12xzncCkz0a3RuehINE81FZSe2QTj3uvAPTcJX/SCzUQHQ0D1GrPMbrPitg=="], + + "@actions/io": ["@actions/io@3.0.2", "", {}, "sha512-nRBchcMM+QK1pdjO7/idu86rbJI5YHUKCvKs0KxnSYbVe3F51UfGxuZX4Qy/fWlp6l7gWFwIkrOzN+oUK03kfw=="], + + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@colors/colors": ["@colors/colors@1.5.0", "", {}, "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ=="], + + "@octokit/auth-token": ["@octokit/auth-token@6.0.0", "", {}, "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w=="], + + "@octokit/core": ["@octokit/core@7.0.8", "", { "dependencies": { "@octokit/auth-token": "^6.0.0", "@octokit/graphql": "^9.0.5", "@octokit/request": "^10.0.16", "@octokit/request-error": "^7.1.2", "@octokit/types": "^18.0.0", "before-after-hook": "^4.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-L7y8eYc+AwxGr2PWI4WFt1VG4TiJ66c26BD16mXpYIlXxG0SMigM1+m4aTSlYyBr5BlQsGAlz8uDCoZN4SEMcg=="], + + "@octokit/endpoint": ["@octokit/endpoint@11.0.5", "", { "dependencies": { "@octokit/types": "^18.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-iXa654H3yFafF/ieHkukfbgWo2rmXD2ceD0ZOtrPhw1bc3FDch1d9N/TNs0FQ1/cIbwb7kspUX8jzIs8nzb9DQ=="], + + "@octokit/graphql": ["@octokit/graphql@9.0.5", "", { "dependencies": { "@octokit/request": "^10.0.16", "@octokit/types": "^18.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-bt/hm03LeU6Vy7FwTrkkC9p3XGT/lBwClglMqxBSe5/q0E5CdJTXeAqEI0vlw89/LF/G6tryTIH8HirZ3prMVg=="], + + "@octokit/openapi-types": ["@octokit/openapi-types@29.0.1", "", {}, "sha512-9qWOMFNxxLokERcms42rU0PTLqQmVs7g5E41TI4mCOxmpFayD1rfC7XxOL55cG9MBZLFlC31BrR37myMKardwg=="], + + "@octokit/plugin-paginate-rest": ["@octokit/plugin-paginate-rest@15.0.0", "", { "dependencies": { "@octokit/types": "^17.0.0" }, "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-lw9A9YL5s4VPj+VEx8uMxaxQm2YTgrPDkrLEuZuu18R8TK3oPcXF4K6t52nx6xn1RcogZC9i188sAr/4XYJaQQ=="], + + "@octokit/plugin-retry": ["@octokit/plugin-retry@8.1.1", "", { "dependencies": { "@octokit/request-error": "^7.1.1", "@octokit/types": "^17.0.0", "bottleneck": "^2.15.3" }, "peerDependencies": { "@octokit/core": ">=7" } }, "sha512-VCVvZ/R1+u3WuiBWpNavZ0mY4aaJNAsENrpBP9aLSR2QyOpQgd7DhM5j4AW7z4MQpnJYgwBPf0XqPQoNBRdQwg=="], + + "@octokit/plugin-throttling": ["@octokit/plugin-throttling@11.0.5", "", { "dependencies": { "@octokit/types": "^17.0.0", "bottleneck": "^2.15.3" }, "peerDependencies": { "@octokit/core": "^7.0.0" } }, "sha512-LIdrkrUv+DWbKeg/49rGuFJ3SU0d3hUS+B4MhNZLepBoNUFXms8Ic9edJjrlx+zycqJHjrMRudVpVb/bAXM2Lw=="], + + "@octokit/request": ["@octokit/request@10.0.16", "", { "dependencies": { "@octokit/endpoint": "^11.0.5", "@octokit/request-error": "^7.1.2", "@octokit/types": "^18.0.0", "content-type": "^3.0.0", "json-with-bigint": "^3.5.12", "universal-user-agent": "^7.0.2" } }, "sha512-A0zWGjHzISIb+9ccG8s0dq7LKO5zVpJLRICjgUb+sJxEWqn8RUHB1rD3AE51+PECvXHIxqZ1VVvs4fHTSD9nUQ=="], + + "@octokit/request-error": ["@octokit/request-error@7.1.2", "", { "dependencies": { "@octokit/types": "^18.0.0" } }, "sha512-XZRuT3xZ84D3gYErI1DZvhJ33dCWVV6uzBtWkaBB4TvA/L6eOeTZodxLFVB44bBEEo3vEx7y00UfX1tBLrtLRg=="], + + "@octokit/types": ["@octokit/types@18.0.0", "", { "dependencies": { "@octokit/openapi-types": "^29.0.1" } }, "sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA=="], + + "@pnpm/config.env-replace": ["@pnpm/config.env-replace@1.1.0", "", {}, "sha512-htyl8TWnKL7K/ESFa1oW2UB5lVDxuF5DpM7tBi6Hu2LNL3mWkIzNLG6N4zoCUP1lCKNxWy/3iu8mS8MvToGd6w=="], + + "@pnpm/network.ca-file": ["@pnpm/network.ca-file@1.0.2", "", { "dependencies": { "graceful-fs": "4.2.10" } }, "sha512-YcPQ8a0jwYU9bTdJDpXjMi7Brhkr1mXsXrUJvjqM2mQDgkRiz8jFaQGOdaLxgjtUfQgZhKy/O3cG/YwmgKaxLA=="], + + "@pnpm/npm-conf": ["@pnpm/npm-conf@3.0.3", "", { "dependencies": { "@pnpm/config.env-replace": "^1.1.0", "@pnpm/network.ca-file": "^1.0.1", "config-chain": "^1.1.11" } }, "sha512-//0sR/cow/s4ICQaYoAobOl4aU8cjU6x/V24V7XkKotb9+O+3zySIYp146vpaobYHnxa4pZX8NkV54Z5AwbDKA=="], + + "@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="], + + "@semantic-release/commit-analyzer": ["@semantic-release/commit-analyzer@13.0.1", "", { "dependencies": { "conventional-changelog-angular": "^8.0.0", "conventional-changelog-writer": "^8.0.0", "conventional-commits-filter": "^5.0.0", "conventional-commits-parser": "^6.0.0", "debug": "^4.0.0", "import-from-esm": "^2.0.0", "lodash-es": "^4.17.21", "micromatch": "^4.0.2" }, "peerDependencies": { "semantic-release": ">=20.1.0" } }, "sha512-wdnBPHKkr9HhNhXOhZD5a2LNl91+hs8CC2vsAVYxtZH3y0dV3wKn+uZSN61rdJQZ8EGxzWB3inWocBHV9+u/CQ=="], + + "@semantic-release/error": ["@semantic-release/error@4.0.0", "", {}, "sha512-mgdxrHTLOjOddRVYIYDo0fR3/v61GNN1YGkfbrjuIKg/uMgCd+Qzo3UAXJ+woLQQpos4pl5Esuw5A7AoNlzjUQ=="], + + "@semantic-release/github": ["@semantic-release/github@12.0.11", "", { "dependencies": { "@octokit/core": "^7.0.0", "@octokit/plugin-paginate-rest": "^15.0.0", "@octokit/plugin-retry": "^8.0.0", "@octokit/plugin-throttling": "^11.0.0", "@semantic-release/error": "^4.0.0", "aggregate-error": "^5.0.0", "debug": "^4.3.4", "dir-glob": "^3.0.1", "http-proxy-agent": "^9.0.0", "https-proxy-agent": "^9.0.0", "issue-parser": "^7.0.0", "lodash-es": "^4.17.21", "mime": "^4.0.0", "p-filter": "^4.0.0", "tinyglobby": "^0.2.14", "undici": "^7.0.0", "url-join": "^5.0.0" }, "peerDependencies": { "semantic-release": ">=24.1.0" } }, "sha512-/8JPlFOV8he+gs+kS8Gx0tNWBboCRBd1q3y7pQhYwtrBL0CzDe9yzguZZAfnjGM2duWYB3rEYn9BdYLu9x00cg=="], + + "@semantic-release/npm": ["@semantic-release/npm@13.2.0", "", { "dependencies": { "@actions/core": "^3.0.0", "@semantic-release/error": "^4.0.0", "aggregate-error": "^5.0.0", "env-ci": "^11.2.0", "execa": "^9.0.0", "fs-extra": "^11.0.0", "lodash-es": "^4.17.21", "nerf-dart": "^1.0.0", "normalize-url": "^9.0.0", "npm": "^11.6.2", "rc": "^1.2.8", "read-pkg": "^10.0.0", "registry-auth-token": "^5.0.0", "semver": "^7.1.2", "tempy": "^3.0.0" }, "peerDependencies": { "semantic-release": ">=20.1.0" } }, "sha512-Uz4JGafLoEGiheLKEs1orockCWP6liY9D2YnvKHYbqo9hCHAw9fuAHcU53q29SXVCtkvDhs/QVUg7Vvuyfp4Jg=="], + + "@semantic-release/release-notes-generator": ["@semantic-release/release-notes-generator@14.1.1", "", { "dependencies": { "conventional-changelog-angular": "^8.0.0", "conventional-changelog-writer": "^8.0.0", "conventional-commits-filter": "^5.0.0", "conventional-commits-parser": "^6.0.0", "debug": "^4.0.0", "import-from-esm": "^2.0.0", "lodash-es": "^4.17.21", "read-package-up": "^11.0.0" }, "peerDependencies": { "semantic-release": ">=20.1.0" } }, "sha512-Pbd2e2XRMUD0OxehHpgd5/YghsE76cddkRHSoDvKLK+OCy4Ewxn49rWR631MEUU01lgwF/uyVXvbnVuu6+Z6VA=="], + + "@simple-libs/stream-utils": ["@simple-libs/stream-utils@1.2.0", "", {}, "sha512-KxXvfapcixpz6rVEB6HPjOUZT22yN6v0vI0urQSk1L8MlEWPDFCZkhw2xmkyoTGYeFw7tWTZd7e3lVzRZRN/EA=="], + + "@sindresorhus/is": ["@sindresorhus/is@4.6.0", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="], + + "@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="], + + "@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="], + + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@types/normalize-package-data": ["@types/normalize-package-data@2.4.4", "", {}, "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA=="], + + "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], + + "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], + + "@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="], + + "@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="], + + "@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="], + + "@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="], + + "@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="], + + "@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="], + + "@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="], + + "@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="], + + "@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="], + + "@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="], + + "@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="], + + "@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="], + + "@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="], + + "@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="], + + "@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="], + + "@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="], + + "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="], + + "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], + + "agent-base": ["agent-base@9.0.0", "", {}, "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA=="], + + "aggregate-error": ["aggregate-error@5.1.0", "", { "dependencies": { "clean-stack": "^5.2.0", "indent-string": "^5.0.0" } }, "sha512-1m4/ydbOGBbHTtBYa4/ISQcqfPdZAxQLzj71wM71T8lP4ktez8lcsVolvscrujQW4CJr/LJSzoZ6mcfnqzYQ3A=="], + + "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], + + "ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="], + + "ansi-styles": ["ansi-styles@3.2.1", "", { "dependencies": { "color-convert": "^1.9.0" } }, "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA=="], + + "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], + + "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "argv-formatter": ["argv-formatter@1.0.0", "", {}, "sha512-F2+Hkm9xFaRg+GkaNnbwXNDV5O6pnCFEmqyhvfC/Ic5LbgOWjJh3L+mN/s91rxVL3znE7DYVpW0GJFT+4YBgWw=="], + + "array-ify": ["array-ify@1.0.0", "", {}, "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng=="], + + "before-after-hook": ["before-after-hook@4.0.0", "", {}, "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ=="], + + "bottleneck": ["bottleneck@2.19.5", "", {}, "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw=="], + + "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], + + "bufferutil": ["bufferutil@4.2.0", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-gyy58jET9kst2IGyBKb96a4Y2bPGTHXGyCd0/1eqIV3hr1Sz3VxtA8n7bXh8fLIuE2K6Z0Upax5a5Msx+HU1IQ=="], + + "bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="], + + "byte-base64": ["byte-base64@1.1.0", "", {}, "sha512-56cXelkJrVMdCY9V/3RfDxTh4VfMFCQ5km7B7GkIGfo4bcPL9aACyJLB0Ms3Ezu5rsHmLB2suis96z4fLM03DA=="], + + "callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="], + + "chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "char-regex": ["char-regex@1.0.2", "", {}, "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw=="], + + "clean-stack": ["clean-stack@5.3.0", "", { "dependencies": { "escape-string-regexp": "5.0.0" } }, "sha512-9ngPTOhYGQqNVSfeJkYXHmF7AGWp4/nN5D/QqNQs3Dvxd1Kk/WpjHfNujKHYUQ/5CoGyOyFNoWSPk5afzP0QVg=="], + + "cli-highlight": ["cli-highlight@2.1.11", "", { "dependencies": { "chalk": "^4.0.0", "highlight.js": "^10.7.1", "mz": "^2.4.0", "parse5": "^5.1.1", "parse5-htmlparser2-tree-adapter": "^6.0.0", "yargs": "^16.0.0" }, "bin": { "highlight": "bin/highlight" } }, "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg=="], + + "cli-table3": ["cli-table3@0.6.5", "", { "dependencies": { "string-width": "^4.2.0" }, "optionalDependencies": { "@colors/colors": "1.5.0" } }, "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ=="], + + "cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], + + "color-convert": ["color-convert@1.9.3", "", { "dependencies": { "color-name": "1.1.3" } }, "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg=="], + + "color-name": ["color-name@1.1.3", "", {}, "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="], + + "compare-func": ["compare-func@2.0.0", "", { "dependencies": { "array-ify": "^1.0.0", "dot-prop": "^5.1.0" } }, "sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA=="], + + "config-chain": ["config-chain@1.1.13", "", { "dependencies": { "ini": "^1.3.4", "proto-list": "~1.2.1" } }, "sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ=="], + + "content-type": ["content-type@3.1.1", "", {}, "sha512-GW4qUsfFo59d0HbUibDlWv5wPz+vAAcaTWbKIuKCf0JkC7wWkSyf8f13IpXn5JkeMlB2P8iTSSIjwXljorg2vA=="], + + "conventional-changelog-angular": ["conventional-changelog-angular@8.3.1", "", { "dependencies": { "compare-func": "^2.0.0" } }, "sha512-6gfI3otXK5Ph5DfCOI1dblr+kN3FAm5a97hYoQkqNZxOaYa5WKfXH+AnpsmS+iUH2mgVC2Cg2Qw9m5OKcmNrIg=="], + + "conventional-changelog-writer": ["conventional-changelog-writer@8.4.0", "", { "dependencies": { "@simple-libs/stream-utils": "^1.2.0", "conventional-commits-filter": "^5.0.0", "handlebars": "^4.7.7", "meow": "^13.0.0", "semver": "^7.5.2" }, "bin": { "conventional-changelog-writer": "dist/cli/index.js" } }, "sha512-HHBFkk1EECxxmCi4CTu091iuDpQv5/OavuCUAuZmrkWpmYfyD816nom1CvtfXJ/uYfAAjavgHvXHX291tSLK8g=="], + + "conventional-commits-filter": ["conventional-commits-filter@5.0.0", "", {}, "sha512-tQMagCOC59EVgNZcC5zl7XqO30Wki9i9J3acbUvkaosCT6JX3EeFwJD7Qqp4MCikRnzS18WXV3BLIQ66ytu6+Q=="], + + "conventional-commits-parser": ["conventional-commits-parser@6.4.0", "", { "dependencies": { "@simple-libs/stream-utils": "^1.2.0", "meow": "^13.0.0" }, "bin": { "conventional-commits-parser": "dist/cli/index.js" } }, "sha512-tvRg7FIBNlyPzjdG8wWRlPHQJJHI7DylhtRGeU9Lq+JuoPh5BKpPRX83ZdLrvXuOSu5Eo/e7SzOQhU4Hd2Miuw=="], + + "convert-hrtime": ["convert-hrtime@5.0.0", "", {}, "sha512-lOETlkIeYSJWcbbcvjRKGxVMXJR+8+OQb/mTPbA4ObPMytYIsUbuOE0Jzy60hjARYszq1id0j8KgVhC+WGZVTg=="], + + "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], + + "cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "crypto-random-string": ["crypto-random-string@4.0.0", "", { "dependencies": { "type-fest": "^1.0.1" } }, "sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA=="], + + "d": ["d@1.0.2", "", { "dependencies": { "es5-ext": "^0.10.64", "type": "^2.7.2" } }, "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw=="], + + "data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], + + "date-fns": ["date-fns@4.4.0", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "deep-extend": ["deep-extend@0.6.0", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="], + + "dir-glob": ["dir-glob@3.0.1", "", { "dependencies": { "path-type": "^4.0.0" } }, "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA=="], + + "dot-prop": ["dot-prop@5.3.0", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q=="], + + "duplexer2": ["duplexer2@0.1.4", "", { "dependencies": { "readable-stream": "^2.0.2" } }, "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA=="], + + "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "emojilib": ["emojilib@2.4.0", "", {}, "sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw=="], + + "env-ci": ["env-ci@11.2.0", "", { "dependencies": { "execa": "^8.0.0", "java-properties": "^1.0.2" } }, "sha512-D5kWfzkmaOQDioPmiviWAVtKmpPT4/iJmMVQxWxMPJTFyTkdc5JQUfc5iXEeWxcOdsYTKSAiA/Age4NUOqKsRA=="], + + "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], + + "environment": ["environment@1.1.0", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="], + + "error-ex": ["error-ex@1.3.4", "", { "dependencies": { "is-arrayish": "^0.2.1" } }, "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ=="], + + "es5-ext": ["es5-ext@0.10.64", "", { "dependencies": { "es6-iterator": "^2.0.3", "es6-symbol": "^3.1.3", "esniff": "^2.0.1", "next-tick": "^1.1.0" } }, "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg=="], + + "es6-iterator": ["es6-iterator@2.0.3", "", { "dependencies": { "d": "1", "es5-ext": "^0.10.35", "es6-symbol": "^3.1.1" } }, "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g=="], + + "es6-symbol": ["es6-symbol@3.1.4", "", { "dependencies": { "d": "^1.0.2", "ext": "^1.7.0" } }, "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg=="], + + "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + + "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + + "esniff": ["esniff@2.0.1", "", { "dependencies": { "d": "^1.0.1", "es5-ext": "^0.10.62", "event-emitter": "^0.3.5", "type": "^2.7.2" } }, "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg=="], + + "event-emitter": ["event-emitter@0.3.7", "", { "dependencies": { "d": "^1.0.2", "es5-ext": "^0.10.64", "type": "^2.7.3" } }, "sha512-R9h/VgWniW4ZRqx3Pd2/n3aGGbPmWilvHwzgrc6YQcFd2HzwPsIFLbrtfoU0hWorKUowd5Iqr5x3ZNv5H6bP+w=="], + + "execa": ["execa@9.6.1", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="], + + "ext": ["ext@1.7.0", "", { "dependencies": { "type": "^2.7.2" } }, "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw=="], + + "fast-sha256": ["fast-sha256@1.3.0", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="], + + "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], + + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], + + "find-up": ["find-up@2.1.0", "", { "dependencies": { "locate-path": "^2.0.0" } }, "sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ=="], + + "find-up-simple": ["find-up-simple@1.0.1", "", {}, "sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ=="], + + "find-versions": ["find-versions@6.0.0", "", { "dependencies": { "semver-regex": "^4.0.5", "super-regex": "^1.0.0" } }, "sha512-2kCCtc+JvcZ86IGAz3Z2Y0A1baIz9fL31pH/0S1IqZr9Iwnjq8izfPtrCyQKO6TLMPELLsQMre7VDqeIKCsHkA=="], + + "formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="], + + "fs-extra": ["fs-extra@11.4.1", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA=="], + + "function-timeout": ["function-timeout@1.0.2", "", {}, "sha512-939eZS4gJ3htTHAldmyyuzlrD58P03fHG49v2JfFXbV6OhvZKRC9j2yAtdHw/zrp2zXHuv05zMIy40F0ge7spA=="], + + "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], + + "get-east-asian-width": ["get-east-asian-width@1.7.0", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="], + + "get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], + + "git-log-parser": ["git-log-parser@1.2.1", "", { "dependencies": { "argv-formatter": "~1.0.0", "spawn-error-forwarder": "~1.0.0", "split2": "~1.0.0", "stream-combiner2": "~1.1.1", "through2": "~2.0.0", "traverse": "0.6.8" } }, "sha512-PI+sPDvHXNPl5WNOErAK05s3j0lgwUzMN6o8cyQrDaKfT3qd7TmNJKeXX+SknI5I0QhG5fVPAEwSY4tRGDtYoQ=="], + + "graceful-fs": ["graceful-fs@4.2.12", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], + + "handlebars": ["handlebars@4.7.10", "", { "dependencies": { "minimist": "^1.2.8", "neo-async": "^2.6.2", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "optionalDependencies": { "uglify-js": "^3.1.4" }, "bin": { "handlebars": "bin/handlebars" } }, "sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg=="], + + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + + "highlight.js": ["highlight.js@10.7.3", "", {}, "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A=="], + + "hook-std": ["hook-std@4.0.0", "", {}, "sha512-IHI4bEVOt3vRUDJ+bFA9VUJlo7SzvFARPNLw75pqSmAOP2HmTWfFJtPvLBrDrlgjEYXY9zs7SFdHPQaJShkSCQ=="], + + "hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], + + "http-proxy-agent": ["http-proxy-agent@9.1.0", "", { "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "proxy-agent-negotiate": "1.1.0" } }, "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig=="], + + "https-proxy-agent": ["https-proxy-agent@9.1.0", "", { "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "proxy-agent-negotiate": "1.1.0" } }, "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA=="], + + "human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="], + + "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], + + "import-from-esm": ["import-from-esm@2.0.0", "", { "dependencies": { "debug": "^4.3.4", "import-meta-resolve": "^4.0.0" } }, "sha512-YVt14UZCgsX1vZQ3gKjkWVdBdHQ6eu3MPU1TBgL1H5orXe2+jWD006WCPPtOuwlQm10NuzOW5WawiF1Q9veW8g=="], + + "import-meta-resolve": ["import-meta-resolve@4.2.0", "", {}, "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg=="], + + "indent-string": ["indent-string@5.0.0", "", {}, "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg=="], + + "index-to-position": ["index-to-position@1.2.0", "", {}, "sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], + + "is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="], + + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + + "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + + "is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], + + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + + "is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="], + + "is-typedarray": ["is-typedarray@1.0.0", "", {}, "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA=="], + + "is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="], + + "isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "issue-parser": ["issue-parser@7.0.2", "", { "dependencies": { "lodash.capitalize": "^4.2.1", "lodash.escaperegexp": "^4.1.2", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.uniqby": "^4.7.0" } }, "sha512-7atWPjhGEIX3JEtMrOYd8TKzboYlq+5sNbdl9POiLYOI14G5HZiQbZP0Xj5EZdrufQVXfJlpTV0hys0CuxwxZw=="], + + "java-properties": ["java-properties@1.0.2", "", {}, "sha512-qjdpeo2yKlYTH7nFdK0vbZWuTCesk4o63v5iVOlhMQPfuIZQfW/HI35SjfhA+4qpg36rnFSvUK5b1m+ckIblQQ=="], + + "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], + + "js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], + + "json-parse-better-errors": ["json-parse-better-errors@1.0.2", "", {}, "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw=="], + + "json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="], + + "json-with-bigint": ["json-with-bigint@3.5.12", "", {}, "sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w=="], + + "jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], + + "lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="], + + "load-json-file": ["load-json-file@4.0.0", "", { "dependencies": { "graceful-fs": "^4.1.2", "parse-json": "^4.0.0", "pify": "^3.0.0", "strip-bom": "^3.0.0" } }, "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw=="], + + "locate-path": ["locate-path@2.0.0", "", { "dependencies": { "p-locate": "^2.0.0", "path-exists": "^3.0.0" } }, "sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA=="], + + "lodash-es": ["lodash-es@4.18.1", "", {}, "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="], + + "lodash.capitalize": ["lodash.capitalize@4.2.1", "", {}, "sha512-kZzYOKspf8XVX5AvmQF94gQW0lejFVgb80G85bU4ZWzoJ6C03PQg3coYAUpSTpQWelrZELd3XWgHzw4Ck5kaIw=="], + + "lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="], + + "lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="], + + "lodash.isstring": ["lodash.isstring@4.0.1", "", {}, "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="], + + "lodash.uniqby": ["lodash.uniqby@4.7.0", "", {}, "sha512-e/zcLx6CSbmaEgFHCA7BnoQKyCtKMxnuWrJygbwPs/AIn+IMKl66L8/s+wBUn5LRw2pZx3bUHibiV1b6aTWIww=="], + + "lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], + + "make-asynchronous": ["make-asynchronous@1.1.0", "", { "dependencies": { "p-event": "^6.0.0", "type-fest": "^4.6.0", "web-worker": "^1.5.0" } }, "sha512-ayF7iT+44LXdxJLTrTd3TLQpFDDvPCBxXxbv+pMUSuHA5Q8zyAfwkRP6aHHwNVFBUFWtxAHqwNJxF8vMZLAbVg=="], + + "marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="], + + "marked-terminal": ["marked-terminal@7.3.1", "", { "dependencies": { "ansi-escapes": "^7.3.0", "ansi-regex": "^6.4.0", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", "cli-table3": "^0.6.5", "node-emoji": "^2.2.0", "supports-hyperlinks": "^3.2.0" }, "peerDependencies": { "marked": ">=1 <19" } }, "sha512-B1eKs5mRiacjHHMlex1zn0zkVomz2/KWjD/dyA8WRQTXk2d15OzVjiK/iuPfvDFB27Gvr8p/u6MYgU0NY/O45w=="], + + "meow": ["meow@13.2.0", "", {}, "sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA=="], + + "merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="], + + "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], + + "mime": ["mime@4.1.2", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-ikRzZ2RwbUVDyL9SsU0f2Phcmav4yq5r8faH5ZZKHtOZrMBLnrQOrj0uvqZ5R1uQnj+RO7Wcklw/lAf81mP9LQ=="], + + "mimic-fn": ["mimic-fn@4.0.0", "", {}, "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], + + "neo-async": ["neo-async@2.6.2", "", {}, "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw=="], + + "nerf-dart": ["nerf-dart@1.0.0", "", {}, "sha512-EZSPZB70jiVsivaBLYDCyntd5eH8NTSMOn3rB+HxwdmKThGELLdYv8qVIMWvZEFy9w8ZZpW9h9OB32l1rGtj7g=="], + + "next-tick": ["next-tick@1.1.0", "", {}, "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ=="], + + "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], + + "node-emoji": ["node-emoji@2.2.0", "", { "dependencies": { "@sindresorhus/is": "^4.6.0", "char-regex": "^1.0.2", "emojilib": "^2.4.0", "skin-tone": "^2.0.0" } }, "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw=="], + + "node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], + + "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], + + "normalize-package-data": ["normalize-package-data@8.0.0", "", { "dependencies": { "hosted-git-info": "^9.0.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4" } }, "sha512-RWk+PI433eESQ7ounYxIp67CYuVsS1uYSonX3kA6ps/3LWfjVQa/ptEg6Y3T6uAMq1mWpX9PQ+qx+QaHpsc7gQ=="], + + "normalize-url": ["normalize-url@9.0.1", "", {}, "sha512-ARftfC5HdUNu9jJeL8pHj8debUIHA2b91FizCoMzY4lG6dDX13jdvTK0TBe24IBDRf2HvJSzzwEPvmbkQWHRSg=="], + + "npm": ["npm@11.21.3", "", { "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/arborist": "^9.9.4", "@npmcli/config": "^10.14.1", "@npmcli/fs": "^5.0.0", "@npmcli/map-workspaces": "^5.0.3", "@npmcli/metavuln-calculator": "^9.0.3", "@npmcli/package-json": "^7.0.5", "@npmcli/promise-spawn": "^9.0.2", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.4", "@sigstore/tuf": "^4.0.2", "abbrev": "^4.0.0", "archy": "~1.0.0", "cacache": "^20.0.4", "chalk": "^5.6.2", "ci-info": "^4.4.0", "fastest-levenshtein": "^1.0.16", "fs-minipass": "^3.0.3", "glob": "^13.0.6", "graceful-fs": "^4.2.11", "hosted-git-info": "^9.0.3", "ini": "^6.0.0", "init-package-json": "^8.2.5", "is-cidr": "^6.0.4", "json-parse-even-better-errors": "^5.0.0", "libnpmaccess": "^10.0.3", "libnpmdiff": "^8.1.15", "libnpmexec": "^10.3.6", "libnpmfund": "^7.0.29", "libnpmorg": "^8.0.1", "libnpmpack": "^9.1.16", "libnpmpublish": "^11.2.1", "libnpmsearch": "^9.0.1", "libnpmteam": "^8.0.2", "libnpmversion": "^8.0.4", "make-fetch-happen": "^15.0.6", "minimatch": "^10.2.5", "minipass": "^7.1.3", "minipass-pipeline": "^1.2.4", "ms": "^2.1.2", "node-gyp": "^12.4.0", "nopt": "^9.0.0", "npm-audit-report": "^7.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.2", "npm-pick-manifest": "^11.0.3", "npm-profile": "^12.0.2", "npm-registry-fetch": "^19.1.1", "npm-user-validate": "^4.0.0", "p-map": "^7.0.4", "pacote": "^21.5.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.1.0", "qrcode-terminal": "^0.12.0", "read": "^5.0.1", "semver": "^7.8.6", "spdx-expression-parse": "^4.0.0", "ssri": "^13.0.1", "supports-color": "^10.2.2", "tar": "^7.5.22", "text-table": "~0.2.0", "tiny-relative-date": "^2.0.2", "treeverse": "^3.0.0", "validate-npm-package-name": "^7.0.2", "which": "^6.0.1" }, "bin": { "npm": "bin/npm-cli.js", "npx": "bin/npx-cli.js" } }, "sha512-5Cf+jE+XctbhH/zjOOqXC+ity7eec/Tkk4Ql38tf6w+1htp2wYPHmE4c1R1Es3DY227Ac14+SLrlYJwkBicbTg=="], + + "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "onetime": ["onetime@6.0.0", "", { "dependencies": { "mimic-fn": "^4.0.0" } }, "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ=="], + + "p-each-series": ["p-each-series@3.0.0", "", {}, "sha512-lastgtAdoH9YaLyDa5i5z64q+kzOcQHsQ5SsZJD3q0VEyI8mq872S3geuNbRUQLVAE9siMfgKrpj7MloKFHruw=="], + + "p-event": ["p-event@6.0.1", "", { "dependencies": { "p-timeout": "^6.1.2" } }, "sha512-Q6Bekk5wpzW5qIyUP4gdMEujObYstZl6DMMOSenwBvV0BlE5LkDwkjs5yHbZmdCEq2o4RJx4tE1vwxFVf2FG1w=="], + + "p-filter": ["p-filter@4.1.0", "", { "dependencies": { "p-map": "^7.0.1" } }, "sha512-37/tPdZ3oJwHaS3gNJdenCDB3Tz26i9sjhnguBtvN0vYlRIiDNnvTWkuh+0hETV9rLPdJ3rlL3yVOYPIAnM8rw=="], + + "p-limit": ["p-limit@1.3.0", "", { "dependencies": { "p-try": "^1.0.0" } }, "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q=="], + + "p-locate": ["p-locate@2.0.0", "", { "dependencies": { "p-limit": "^1.1.0" } }, "sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg=="], + + "p-map": ["p-map@7.1.1", "", {}, "sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g=="], + + "p-reduce": ["p-reduce@3.0.0", "", {}, "sha512-xsrIUgI0Kn6iyDYm9StOpOeK29XM1aboGji26+QEortiFST1hGZaUQOLhtEbqHErPpGW/aSz6allwK2qcptp0Q=="], + + "p-timeout": ["p-timeout@6.1.4", "", {}, "sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg=="], + + "p-try": ["p-try@1.0.0", "", {}, "sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww=="], + + "parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="], + + "parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="], + + "parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="], + + "parse5": ["parse5@5.1.1", "", {}, "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug=="], + + "parse5-htmlparser2-tree-adapter": ["parse5-htmlparser2-tree-adapter@6.0.1", "", { "dependencies": { "parse5": "^6.0.1" } }, "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA=="], + + "path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-type": ["path-type@4.0.0", "", {}, "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + + "pify": ["pify@3.0.0", "", {}, "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg=="], + + "pkg-conf": ["pkg-conf@2.1.0", "", { "dependencies": { "find-up": "^2.0.0", "load-json-file": "^4.0.0" } }, "sha512-C+VUP+8jis7EsQZIhDYmS5qlNtjv2yP4SNtjXK9AP1ZcTRlnSfuumaTnRfYZnYgUUYVIKqL0fRvmUGDV2fmp6g=="], + + "placeos-ts-client-6": ["@placeos/ts-client@6.13.0", "", { "dependencies": { "byte-base64": "^1.1.0", "fast-sha256": "^1.3.0" }, "peerDependencies": { "date-fns": "^4.1.0", "node-fetch": "^3.2.0", "ts-md5": "^2.0.1", "websocket": "^1.0.34" } }, "sha512-SloxE6XH9z96jl26Xr8RLM3PCFj3jIIyRRomcqSJGkQKdleCw7T5KgcVsJxgikIB34iM7l6K+CpiczO4JW3vkA=="], + + "prettier": ["prettier@3.9.10", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA=="], + + "pretty-ms": ["pretty-ms@9.3.1", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA=="], + + "process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="], + + "proto-list": ["proto-list@1.2.4", "", {}, "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA=="], + + "proxy-agent-negotiate": ["proxy-agent-negotiate@1.1.0", "", { "peerDependencies": { "kerberos": "^2.0.0" }, "optionalPeers": ["kerberos"] }, "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ=="], + + "rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="], + + "read-package-up": ["read-package-up@12.0.0", "", { "dependencies": { "find-up-simple": "^1.0.1", "read-pkg": "^10.0.0", "type-fest": "^5.2.0" } }, "sha512-Q5hMVBYur/eQNWDdbF4/Wqqr9Bjvtrw2kjGxxBbKLbx8bVCL8gcArjTy8zDUuLGQicftpMuU0riQNcAsbtOVsw=="], + + "read-pkg": ["read-pkg@10.1.0", "", { "dependencies": { "@types/normalize-package-data": "^2.4.4", "normalize-package-data": "^8.0.0", "parse-json": "^8.3.0", "type-fest": "^5.4.4", "unicorn-magic": "^0.4.0" } }, "sha512-I8g2lArQiP78ll51UeMZojewtYgIRCKCWqZEgOO8c/uefTI+XDXvCSXu3+YNUaTNvZzobrL5+SqHjBrByRRTdg=="], + + "readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], + + "registry-auth-token": ["registry-auth-token@5.1.1", "", { "dependencies": { "@pnpm/npm-conf": "^3.0.2" } }, "sha512-P7B4+jq8DeD2nMsAcdfaqHbssgHtZ7Z5+++a5ask90fvmJ8p5je4mOa+wzu+DB4vQ5tdJV/xywY+UnVFeQLV5Q=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + + "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], + + "safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], + + "semantic-release": ["semantic-release@25.0.9", "", { "dependencies": { "@semantic-release/commit-analyzer": "^13.0.1", "@semantic-release/error": "^4.0.0", "@semantic-release/github": "^12.0.0", "@semantic-release/npm": "^13.1.1", "@semantic-release/release-notes-generator": "^14.1.0", "aggregate-error": "^5.0.0", "cosmiconfig": "^9.0.0", "debug": "^4.0.0", "env-ci": "^11.0.0", "execa": "^9.0.0", "figures": "^6.0.0", "find-versions": "^6.0.0", "get-stream": "^6.0.0", "git-log-parser": "^1.2.0", "hook-std": "^4.0.0", "hosted-git-info": "^9.0.0", "import-from-esm": "^2.0.0", "lodash-es": "^4.17.21", "marked": "^15.0.0", "marked-terminal": "^7.3.0", "micromatch": "^4.0.2", "p-each-series": "^3.0.0", "p-reduce": "^3.0.0", "read-package-up": "^12.0.0", "resolve-from": "^5.0.0", "semver": "^7.3.2", "signale": "^1.2.1", "yargs": "^18.0.0" }, "bin": { "semantic-release": "bin/semantic-release.js" } }, "sha512-bxve7csK0/Txr++CkfrmV+X1r4jqiSOw2WsSad9E2S68R+ZfLBwDn8IceM8WfiOmKQIHgsQc1cNA8Dzg7U75pg=="], + + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "semver-regex": ["semver-regex@4.0.5", "", {}, "sha512-hunMQrEy1T6Jr2uEVjrAIqjwWcQTgOAcIM52C8MY1EZSD3DDNft04XzvYKPqjED65bNVVko0YI38nYeEHCX3yw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + + "signale": ["signale@1.4.0", "", { "dependencies": { "chalk": "^2.3.2", "figures": "^2.0.0", "pkg-conf": "^2.1.0" } }, "sha512-iuh+gPf28RkltuJC7W5MRi6XAjTDCAPC/prJUpQoG4vIP3MJZ+GTydVnodXA7pwvTKb2cA0m9OFZW/cdWy/I/w=="], + + "skin-tone": ["skin-tone@2.0.0", "", { "dependencies": { "unicode-emoji-modifier-base": "^1.0.0" } }, "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA=="], + + "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + + "spawn-error-forwarder": ["spawn-error-forwarder@1.0.0", "", {}, "sha512-gRjMgK5uFjbCvdibeGJuy3I5OYz6VLoVdsOJdA6wV0WlfQVLFueoqMxwwYD9RODdgb6oUIvlRlsyFSiQkMKu0g=="], + + "spdx-correct": ["spdx-correct@3.2.0", "", { "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" } }, "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA=="], + + "spdx-exceptions": ["spdx-exceptions@2.5.0", "", {}, "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w=="], + + "spdx-expression-parse": ["spdx-expression-parse@3.0.1", "", { "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q=="], + + "spdx-license-ids": ["spdx-license-ids@3.0.24", "", {}, "sha512-cLS9TtWkIQFyLkJ3/5aFQAOHOSKTlOs/7WDut/XPSdjom1fJhUdkepeJAKXa9Y05+FabHd0sti+Et559vDtkpQ=="], + + "split2": ["split2@1.0.0", "", { "dependencies": { "through2": "~2.0.0" } }, "sha512-NKywug4u4pX/AZBB1FCPzZ6/7O+Xhz1qMVbzTvvKvikjO99oPN87SkK08mEY9P63/5lWjK+wgOOgApnTg5r6qg=="], + + "stream-combiner2": ["stream-combiner2@1.1.1", "", { "dependencies": { "duplexer2": "~0.1.0", "readable-stream": "^2.0.2" } }, "sha512-3PnJbYgS56AeWgtKF5jtJRT6uFJe56Z0Hc5Ngg/6sI6rIt8iiMBTa9cvdyFfpMQjaVHr8dusbNeFGIIonxOvKw=="], + + "string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], + + "string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], + + "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "strip-bom": ["strip-bom@3.0.0", "", {}, "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA=="], + + "strip-final-newline": ["strip-final-newline@4.0.0", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="], + + "strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="], + + "super-regex": ["super-regex@1.1.0", "", { "dependencies": { "function-timeout": "^1.0.1", "make-asynchronous": "^1.0.1", "time-span": "^5.1.0" } }, "sha512-WHkws2ZflZe41zj6AolvvmaTrWds/VuyeYr9iPVv/oQeaIoVxMKaushfFWpOGDT+GuBrM/sVqF8KUCYQlSSTdQ=="], + + "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "supports-hyperlinks": ["supports-hyperlinks@3.2.0", "", { "dependencies": { "has-flag": "^4.0.0", "supports-color": "^7.0.0" } }, "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig=="], + + "tagged-tag": ["tagged-tag@1.0.0", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="], + + "temp-dir": ["temp-dir@3.0.0", "", {}, "sha512-nHc6S/bwIilKHNRgK/3jlhDoIHcp45YgyiwcAk46Tr0LfEqGBVpmiAyuiuxeVE44m3mXnEeVhaipLOEWmH+Njw=="], + + "tempy": ["tempy@3.2.0", "", { "dependencies": { "is-stream": "^3.0.0", "temp-dir": "^3.0.0", "type-fest": "^2.12.2", "unique-string": "^3.0.0" } }, "sha512-d79HhZya5Djd7am0q+W4RTsSU+D/aJzM+4Y4AGJGuGlgM2L6sx5ZvOYTmZjqPhrDrV6xJTtRSm1JCLj6V6LHLQ=="], + + "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], + + "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], + + "through2": ["through2@2.0.5", "", { "dependencies": { "readable-stream": "~2.3.6", "xtend": "~4.0.1" } }, "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ=="], + + "time-span": ["time-span@5.1.0", "", { "dependencies": { "convert-hrtime": "^5.0.0" } }, "sha512-75voc/9G4rDIJleOo4jPvN4/YC4GRZrY8yy1uU4lwrB3XEQbWve8zXoO5No4eFrGcTAMYyoY67p8jRQdtA1HbA=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], + + "traverse": ["traverse@0.6.8", "", {}, "sha512-aXJDbk6SnumuaZSANd21XAo15ucCDE38H4fkqiGsc3MhCK+wOlZvLP9cB/TvpHT0mOyWgC4Z8EwRlzqYSUzdsA=="], + + "ts-md5": ["ts-md5@2.0.1", "", {}, "sha512-yF35FCoEOFBzOclSkMNEUbFQZuv89KEQ+5Xz03HrMSGUGB1+r+El+JiGOFwsP4p9RFNzwlrydYoTLvPOuICl9w=="], + + "tunnel": ["tunnel@0.0.6", "", {}, "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg=="], + + "type": ["type@2.7.3", "", {}, "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ=="], + + "type-fest": ["type-fest@5.10.0", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA=="], + + "typedarray-to-buffer": ["typedarray-to-buffer@3.1.5", "", { "dependencies": { "is-typedarray": "^1.0.0" } }, "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q=="], + + "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], + + "typescript-5": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], + + "uglify-js": ["uglify-js@3.19.3", "", { "bin": { "uglifyjs": "bin/uglifyjs" } }, "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ=="], + + "undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], + + "undici-types": ["undici-types@8.12.4", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="], + + "unicode-emoji-modifier-base": ["unicode-emoji-modifier-base@1.0.0", "", {}, "sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g=="], + + "unicorn-magic": ["unicorn-magic@0.4.1", "", {}, "sha512-lzlXPoVB0Uy/FvTaUgX39RbixYiSKoc3JSoSf01+0c2B6FR3qdYIPN7Qjo/AV7n6sqLCk0509cT3LRj1oSZ1+A=="], + + "unique-string": ["unique-string@3.0.0", "", { "dependencies": { "crypto-random-string": "^4.0.0" } }, "sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ=="], + + "universal-user-agent": ["universal-user-agent@7.0.3", "", {}, "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A=="], + + "universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], + + "url-join": ["url-join@5.2.0", "", {}, "sha512-/tMVQdp/2eE90fGb6npbd2nLHH8jamzLLeZhLEKTz4Rc38wO5AeEuIhoWroWWfQJS50ZzL4Xod9JER/pJWTTEQ=="], + + "utf-8-validate": ["utf-8-validate@5.0.10", "", { "dependencies": { "node-gyp-build": "^4.3.0" } }, "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ=="], + + "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + + "validate-npm-package-license": ["validate-npm-package-license@3.0.4", "", { "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" } }, "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew=="], + + "web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="], + + "web-worker": ["web-worker@1.5.0", "", {}, "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw=="], + + "websocket": ["websocket@1.0.35", "", { "dependencies": { "bufferutil": "^4.0.1", "debug": "^2.2.0", "es5-ext": "^0.10.63", "typedarray-to-buffer": "^3.1.5", "utf-8-validate": "^5.0.2", "yaeti": "^0.0.6" } }, "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "wordwrap": ["wordwrap@1.0.0", "", {}, "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q=="], + + "wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], + + "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], + + "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], + + "yaeti": ["yaeti@0.0.6", "", {}, "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug=="], + + "yargs": ["yargs@18.2.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w=="], + + "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], + + "yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="], + + "@actions/http-client/undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], + + "@octokit/plugin-paginate-rest/@octokit/types": ["@octokit/types@17.0.0", "", { "dependencies": { "@octokit/openapi-types": "^28.0.0" } }, "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q=="], + + "@octokit/plugin-retry/@octokit/types": ["@octokit/types@17.0.0", "", { "dependencies": { "@octokit/openapi-types": "^28.0.0" } }, "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q=="], + + "@octokit/plugin-throttling/@octokit/types": ["@octokit/types@17.0.0", "", { "dependencies": { "@octokit/openapi-types": "^28.0.0" } }, "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q=="], + + "@pnpm/network.ca-file/graceful-fs": ["graceful-fs@4.2.10", "", {}, "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA=="], + + "@semantic-release/release-notes-generator/read-package-up": ["read-package-up@11.0.0", "", { "dependencies": { "find-up-simple": "^1.0.0", "read-pkg": "^9.0.0", "type-fest": "^4.6.0" } }, "sha512-MbgfoNPANMdb4oRBNg5eqLbB2t2r+o5Ua1pNt8BqGp4I0FJZhuVSOj3PaBPni4azWuSzEdNn2evevzVmEk1ohQ=="], + + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "cli-highlight/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "cli-highlight/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], + + "cli-table3/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + + "crypto-random-string/type-fest": ["type-fest@1.4.0", "", {}, "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA=="], + + "env-ci/execa": ["execa@8.0.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^8.0.1", "human-signals": "^5.0.0", "is-stream": "^3.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^5.1.0", "onetime": "^6.0.0", "signal-exit": "^4.1.0", "strip-final-newline": "^3.0.0" } }, "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg=="], + + "execa/get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="], + + "fdir/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "import-fresh/resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], + + "load-json-file/parse-json": ["parse-json@4.0.0", "", { "dependencies": { "error-ex": "^1.3.1", "json-parse-better-errors": "^1.0.1" } }, "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw=="], + + "make-asynchronous/type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="], + + "npm/@gar/promise-retry": ["@gar/promise-retry@1.0.3", "", {}, "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA=="], + + "npm/@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], + + "npm/@isaacs/string-locale-compare": ["@isaacs/string-locale-compare@1.1.0", "", { "bundled": true }, "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ=="], + + "npm/@npmcli/agent": ["@npmcli/agent@4.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg=="], + + "npm/@npmcli/arborist": ["@npmcli/arborist@9.9.4", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^5.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/map-workspaces": "^5.0.0", "@npmcli/metavuln-calculator": "^9.0.2", "@npmcli/name-from-folder": "^4.0.0", "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.0", "bin-links": "^6.0.0", "cacache": "^20.0.1", "common-ancestor-path": "^2.0.0", "hosted-git-info": "^9.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^9.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.0", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "pacote": "^21.0.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^13.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "bundled": true, "bin": { "arborist": "bin/index.js" } }, "sha512-tEIsWWsjOQ9To1SRDgY5DzPW71argHTiVsvxuFH8QG5aJoD8TbpYql2uoUpr1B3v12lKL6iULxUKrRCNQvXKQQ=="], + + "npm/@npmcli/config": ["@npmcli/config@10.14.1", "", { "dependencies": { "@npmcli/map-workspaces": "^5.0.0", "@npmcli/package-json": "^7.0.0", "ci-info": "^4.0.0", "ini": "^6.0.0", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "walk-up-path": "^4.0.0" }, "bundled": true }, "sha512-mYGWg0D3cWoFL+LHjOwXq4K8tgk+jO1G5+7y6Mq8MGIwtdh5VNzalRNLTgzjGnuMQ+GWwk1JGa5LV5RkjSRDLw=="], + + "npm/@npmcli/fs": ["@npmcli/fs@5.0.0", "", { "dependencies": { "semver": "^7.3.5" }, "bundled": true }, "sha512-7OsC1gNORBEawOa5+j2pXN9vsicaIOH5cPXxoR6fJOmH6/EXpJB2CajXOu1fPRFun2m1lktEFX11+P89hqO/og=="], + + "npm/@npmcli/git": ["@npmcli/git@7.0.2", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/promise-spawn": "^9.0.0", "ini": "^6.0.0", "lru-cache": "^11.2.1", "npm-pick-manifest": "^11.0.1", "proc-log": "^6.0.0", "semver": "^7.3.5", "which": "^6.0.0" } }, "sha512-oeolHDjExNAJAnlYP2qzNjMX/Xi9bmu78C9dIGr4xjobrSKbuMYCph8lTzn4vnW3NjIqVmw/f8BCfouqyJXlRg=="], + + "npm/@npmcli/installed-package-contents": ["@npmcli/installed-package-contents@4.0.0", "", { "dependencies": { "npm-bundled": "^5.0.0", "npm-normalize-package-bin": "^5.0.0" }, "bin": { "installed-package-contents": "bin/index.js" } }, "sha512-yNyAdkBxB72gtZ4GrwXCM0ZUedo9nIbOMKfGjt6Cu6DXf0p8y1PViZAKDC8q8kv/fufx0WTjRBdSlyrvnP7hmA=="], + + "npm/@npmcli/map-workspaces": ["@npmcli/map-workspaces@5.0.3", "", { "dependencies": { "@npmcli/name-from-folder": "^4.0.0", "@npmcli/package-json": "^7.0.0", "glob": "^13.0.0", "minimatch": "^10.0.3" }, "bundled": true }, "sha512-o2grssXo1e774E5OtEwwrgoszYRh0lqkJH+Pb9r78UcqdGJRDRfhpM8DvZPjzNLLNYeD/rNbjOKM3Ss5UABROw=="], + + "npm/@npmcli/metavuln-calculator": ["@npmcli/metavuln-calculator@9.0.3", "", { "dependencies": { "cacache": "^20.0.0", "json-parse-even-better-errors": "^5.0.0", "pacote": "^21.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5" }, "bundled": true }, "sha512-94GLSYhLXF2t2LAC7pDwLaM4uCARzxShyAQKsirmlNcpidH89VA4/+K1LbJmRMgz5gy65E/QBBWQdUvGLe2Frg=="], + + "npm/@npmcli/name-from-folder": ["@npmcli/name-from-folder@4.0.0", "", {}, "sha512-qfrhVlOSqmKM8i6rkNdZzABj8MKEITGFAY+4teqBziksCQAOLutiAxM1wY2BKEd8KjUSpWmWCYxvXr0y4VTlPg=="], + + "npm/@npmcli/node-gyp": ["@npmcli/node-gyp@5.0.0", "", {}, "sha512-uuG5HZFXLfyFKqg8QypsmgLQW7smiRjVc45bqD/ofZZcR/uxEjgQU8qDPv0s9TEeMUiAAU/GC5bR6++UdTirIQ=="], + + "npm/@npmcli/package-json": ["@npmcli/package-json@7.0.5", "", { "dependencies": { "@npmcli/git": "^7.0.0", "glob": "^13.0.0", "hosted-git-info": "^9.0.0", "json-parse-even-better-errors": "^5.0.0", "proc-log": "^6.0.0", "semver": "^7.5.3", "spdx-expression-parse": "^4.0.0" }, "bundled": true }, "sha512-iVuTlG3ORq2iaVa1IWUxAO/jIp77tUKBhoMjuzYW2kL4MLN1bi/ofqkZ7D7OOwh8coAx1/S2ge0rMdGv8sLSOQ=="], + + "npm/@npmcli/promise-spawn": ["@npmcli/promise-spawn@9.0.2", "", { "dependencies": { "which": "^6.0.0" }, "bundled": true }, "sha512-h7b1j0egrruBm/32eVA6/zMw5VJxxaB3vT+uVGGQ4SAAMrQVFHNuzL4+EAXn66j+huj0jApINc1fW3fC+kVoeA=="], + + "npm/@npmcli/query": ["@npmcli/query@5.0.0", "", { "dependencies": { "postcss-selector-parser": "^7.0.0" } }, "sha512-8TZWfTQOsODpLqo9SVhVjHovmKXNpevHU0gO9e+y4V4fRIOneiXy0u0sMP9LmS71XivrEWfZWg50ReH4WRT4aQ=="], + + "npm/@npmcli/redact": ["@npmcli/redact@4.0.0", "", { "bundled": true }, "sha512-gOBg5YHMfZy+TfHArfVogwgfBeQnKbbGo3pSUyK/gSI0AVu+pEiDVcKlQb0D8Mg1LNRZILZ6XG8I5dJ4KuAd9Q=="], + + "npm/@npmcli/run-script": ["@npmcli/run-script@10.0.4", "", { "dependencies": { "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "node-gyp": "^12.1.0", "proc-log": "^6.0.0" }, "bundled": true }, "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg=="], + + "npm/@sigstore/bundle": ["@sigstore/bundle@4.0.0", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A=="], + + "npm/@sigstore/core": ["@sigstore/core@3.2.1", "", {}, "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g=="], + + "npm/@sigstore/protobuf-specs": ["@sigstore/protobuf-specs@0.5.2", "", {}, "sha512-SQqvFMt4V78fdjcDdYX6HbiVSOR4QK3ZgwCa2KOsopAgPIHy1rU5UDUmzLl02r5oyyaYcYHR1hpwDRk/yUe+Mw=="], + + "npm/@sigstore/sign": ["@sigstore/sign@4.1.1", "", { "dependencies": { "@gar/promise-retry": "^1.0.2", "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.0", "@sigstore/protobuf-specs": "^0.5.0", "make-fetch-happen": "^15.0.4", "proc-log": "^6.1.0" } }, "sha512-Hf4xglukg0XXQ2RiD5vSoLjdPe8OBUPA8XeVjUObheuDcWdYWrnH/BNmxZCzkAy68MzmNCxXLeurJvs6hcP2OQ=="], + + "npm/@sigstore/tuf": ["@sigstore/tuf@4.0.2", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0", "tuf-js": "^4.1.0" }, "bundled": true }, "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ=="], + + "npm/@sigstore/verify": ["@sigstore/verify@3.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA=="], + + "npm/@tufjs/canonical-json": ["@tufjs/canonical-json@2.0.0", "", {}, "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA=="], + + "npm/@tufjs/models": ["@tufjs/models@4.1.0", "", { "dependencies": { "@tufjs/canonical-json": "2.0.0", "minimatch": "^10.1.1" } }, "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww=="], + + "npm/abbrev": ["abbrev@4.0.0", "", { "bundled": true }, "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA=="], + + "npm/agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + + "npm/aproba": ["aproba@2.1.0", "", {}, "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew=="], + + "npm/archy": ["archy@1.0.0", "", { "bundled": true }, "sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw=="], + + "npm/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + + "npm/bin-links": ["bin-links@6.0.3", "", { "dependencies": { "cmd-shim": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "proc-log": "^6.0.0", "read-cmd-shim": "^6.0.0", "write-file-atomic": "^7.0.0" } }, "sha512-Qg5FD7/YSReWJB1zaM8VIi1l4O637JKK/WPaF/JzJGy/9FcMDWtSklF0dOX5S9X2OMrPGhifIHIKuwtHG0IGFg=="], + + "npm/binary-extensions": ["binary-extensions@3.2.0", "", {}, "sha512-DjR9rgAOMQn9TrUHzijJUtvoKviDRvFxuIyqZrubxHqRpQN9OzfXrrLivm7xb3q8oJSKsiuBor4bAS2wafLnVQ=="], + + "npm/brace-expansion": ["brace-expansion@5.0.13", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ=="], + + "npm/cacache": ["cacache@20.0.4", "", { "dependencies": { "@npmcli/fs": "^5.0.0", "fs-minipass": "^3.0.0", "glob": "^13.0.0", "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^13.0.0" }, "bundled": true }, "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA=="], + + "npm/chalk": ["chalk@5.6.2", "", { "bundled": true }, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "npm/chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], + + "npm/ci-info": ["ci-info@4.5.0", "", { "bundled": true }, "sha512-d1uM8k5UZEyPza1n/MG3ko8nKupKN0KJpFsipgPcgaCCvV+IqIfJ+NzTjetlLM+UcXZx3+cLrNr76+eAO7G1Mw=="], + + "npm/cidr-regex": ["cidr-regex@5.0.5", "", {}, "sha512-59tdLZcC+BJXa4C5rOmVSuJTy/UneqfJJtCraqwdx5BDHTkGrBtKCUl3u2uiCFvXu+wk0kVuX8axX7yHCZOI9w=="], + + "npm/cmd-shim": ["cmd-shim@8.0.0", "", {}, "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA=="], + + "npm/common-ancestor-path": ["common-ancestor-path@2.0.0", "", {}, "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng=="], + + "npm/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "npm/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "npm/diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + + "npm/env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], + + "npm/exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], + + "npm/fastest-levenshtein": ["fastest-levenshtein@1.0.16", "", { "bundled": true }, "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg=="], + + "npm/fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "npm/fs-minipass": ["fs-minipass@3.0.3", "", { "dependencies": { "minipass": "^7.0.3" }, "bundled": true }, "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw=="], + + "npm/glob": ["glob@13.0.7", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" }, "bundled": true }, "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g=="], + + "npm/graceful-fs": ["graceful-fs@4.2.12", "", { "bundled": true }, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], + + "npm/hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" }, "bundled": true }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], + + "npm/http-cache-semantics": ["http-cache-semantics@4.3.0", "", {}, "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA=="], + + "npm/http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], + + "npm/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + + "npm/iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "npm/ignore-walk": ["ignore-walk@8.0.0", "", { "dependencies": { "minimatch": "^10.0.3" } }, "sha512-FCeMZT4NiRQGh+YkeKMtWrOmBgWjHjMJ26WQWrRQyoyzqevdaGSakUaJW5xQYmjLlUVk2qUnCjYVBax9EKKg8A=="], + + "npm/ini": ["ini@6.0.0", "", { "bundled": true }, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], + + "npm/init-package-json": ["init-package-json@8.2.5", "", { "dependencies": { "@npmcli/package-json": "^7.0.0", "npm-package-arg": "^13.0.0", "promzard": "^3.0.1", "read": "^5.0.1", "semver": "^7.7.2", "validate-npm-package-name": "^7.0.0" }, "bundled": true }, "sha512-IknQ+upLuJU6t3p0uo9wS3GjFD/1GtxIwcIGYOWR8zL2HxQeJwvxYTgZr9brJ8pyZ4kvpkebM8ZKcyqOeLOHSg=="], + + "npm/ip-address": ["ip-address@10.7.6", "", {}, "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg=="], + + "npm/is-cidr": ["is-cidr@6.0.4", "", { "dependencies": { "cidr-regex": "^5.0.4" }, "bundled": true }, "sha512-tOIBU3QiXy0W4LvHbcKWAWSuQfGwDiEILphFCAZtDqj7C57uv3ClO6K8aNEGV4VTA7bWJlpQ0suKQkUe6Rd6ag=="], + + "npm/isexe": ["isexe@4.0.0", "", {}, "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw=="], + + "npm/json-parse-even-better-errors": ["json-parse-even-better-errors@5.0.0", "", { "bundled": true }, "sha512-ZF1nxZ28VhQouRWhUcVlUIN3qwSgPuswK05s/HIaoetAoE/9tngVmCHjSxmSQPav1nd+lPtTL0YZ/2AFdR/iYQ=="], + + "npm/json-stringify-nice": ["json-stringify-nice@1.1.4", "", {}, "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw=="], + + "npm/jsonparse": ["jsonparse@1.3.1", "", {}, "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg=="], + + "npm/just-diff": ["just-diff@6.0.2", "", {}, "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA=="], + + "npm/just-diff-apply": ["just-diff-apply@5.5.0", "", {}, "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw=="], + + "npm/libnpmaccess": ["libnpmaccess@10.0.3", "", { "dependencies": { "npm-package-arg": "^13.0.0", "npm-registry-fetch": "^19.0.0" }, "bundled": true }, "sha512-JPHTfWJxIK+NVPdNMNGnkz4XGX56iijPbe0qFWbdt68HL+kIvSzh+euBL8npLZvl2fpaxo+1eZSdoG15f5YdIQ=="], + + "npm/libnpmdiff": ["libnpmdiff@8.1.15", "", { "dependencies": { "@npmcli/arborist": "^9.9.4", "@npmcli/installed-package-contents": "^4.0.0", "binary-extensions": "^3.0.0", "diff": "^8.0.2", "minimatch": "^10.0.3", "npm-package-arg": "^13.0.0", "pacote": "^21.0.2", "tar": "^7.5.1" }, "bundled": true }, "sha512-zQVsS5ijfnWad0CM1Btts8auGPXsNz7sziL8Q/Lv5HcGA+w4reGJlELVsdGP7G4FEptHEjSGQo0cZncche6txw=="], + + "npm/libnpmexec": ["libnpmexec@10.3.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/arborist": "^9.9.4", "@npmcli/package-json": "^7.0.0", "@npmcli/run-script": "^10.0.0", "ci-info": "^4.0.0", "npm-package-arg": "^13.0.0", "pacote": "^21.0.2", "proc-log": "^6.0.0", "read": "^5.0.1", "semver": "^7.3.7", "signal-exit": "^4.1.0", "walk-up-path": "^4.0.0" }, "bundled": true }, "sha512-wmCEEf22wjHs+VCAsAkotklgX5K1mwlewamkpOP8xaX2VvUqDlPPWl+rsb1NvE78+faruxSnMqsydc5INgiSfw=="], + + "npm/libnpmfund": ["libnpmfund@7.0.29", "", { "dependencies": { "@npmcli/arborist": "^9.9.4" }, "bundled": true }, "sha512-k5D1He2dQV25PINeQstDrPoisTAP1zUrme9WOiX0Vk2AbfMexDS1TOrKpjg1GqP7lW/IY7gmNQzWQedr53CdhQ=="], + + "npm/libnpmorg": ["libnpmorg@8.0.1", "", { "dependencies": { "aproba": "^2.0.0", "npm-registry-fetch": "^19.0.0" }, "bundled": true }, "sha512-/QeyXXg4hqMw0ESM7pERjIT2wbR29qtFOWIOug/xO4fRjS3jJJhoAPQNsnHtdwnCqgBdFpGQ45aIdFFZx2YhTA=="], + + "npm/libnpmpack": ["libnpmpack@9.1.16", "", { "dependencies": { "@npmcli/arborist": "^9.9.4", "@npmcli/run-script": "^10.0.0", "npm-package-arg": "^13.0.0", "pacote": "^21.0.2" }, "bundled": true }, "sha512-adTj/bSkS+jirPA5fP1zjj7MZMoISLrmABwyoOc0y7HNFg3Ew+VXf6lkZ5ptn4FqMfLj30Ay7lqggKVAJ3Idiw=="], + + "npm/libnpmpublish": ["libnpmpublish@11.2.1", "", { "dependencies": { "@npmcli/package-json": "^7.0.0", "ci-info": "^4.0.0", "npm-package-arg": "^13.0.0", "npm-registry-fetch": "^19.0.0", "proc-log": "^6.0.0", "semver": "^7.3.7", "sigstore": "^4.0.0", "ssri": "^13.0.0" }, "bundled": true }, "sha512-eZTRbsvZnG7tV0b9Hxug9feQt9Z29GyijcWpEKpLrgaJjxuVCkUNPW+w6OcXmlvSaopkyrGN65hgtk+Z0YP3Hg=="], + + "npm/libnpmsearch": ["libnpmsearch@9.0.1", "", { "dependencies": { "npm-registry-fetch": "^19.0.0" }, "bundled": true }, "sha512-oKw58X415ERY/BOGV3jQPVMcep8YeMRWMzuuqB0BAIM5VxicOU1tQt19ExCu4SV77SiTOEoziHxGEgJGw3FBYQ=="], + + "npm/libnpmteam": ["libnpmteam@8.0.2", "", { "dependencies": { "aproba": "^2.0.0", "npm-registry-fetch": "^19.0.0" }, "bundled": true }, "sha512-ypLrDUQoi8EhG+gzx5ENMcYq23YjPV17Mfvx4nOnQiHOi8vp47+4GvZBrMsEM4yeHPwxguF/HZoXH4rJfHdH/w=="], + + "npm/libnpmversion": ["libnpmversion@8.0.4", "", { "dependencies": { "@npmcli/git": "^7.0.0", "@npmcli/run-script": "^10.0.0", "json-parse-even-better-errors": "^5.0.0", "proc-log": "^6.0.0", "semver": "^7.3.7" }, "bundled": true }, "sha512-5NiNpLxXkNeLHCYVTLxX/qRgdAoRAjiR0arFdVpQ5kZOJ2b0pHdXS9G3qC7uiqVsLa/gfQQIbQIEPdmSMKXF2A=="], + + "npm/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], + + "npm/make-fetch-happen": ["make-fetch-happen@15.0.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" }, "bundled": true }, "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw=="], + + "npm/minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" }, "bundled": true }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="], + + "npm/minipass": ["minipass@7.1.3", "", { "bundled": true }, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], + + "npm/minipass-collect": ["minipass-collect@2.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw=="], + + "npm/minipass-fetch": ["minipass-fetch@5.0.2", "", { "dependencies": { "minipass": "^7.0.3", "minipass-sized": "^2.0.0", "minizlib": "^3.0.1" }, "optionalDependencies": { "iconv-lite": "^0.7.2" } }, "sha512-2d0q2a8eCi2IRg/IGubCNRJoYbA1+YPXAzQVRFmB45gdGZafyivnZ5YSEfo3JikbjGxOdntGFvBQGqaSMXlAFQ=="], + + "npm/minipass-flush": ["minipass-flush@1.0.7", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA=="], + + "npm/minipass-pipeline": ["minipass-pipeline@1.2.4", "", { "dependencies": { "minipass": "^3.0.0" }, "bundled": true }, "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A=="], + + "npm/minipass-sized": ["minipass-sized@2.0.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-zSsHhto5BcUVM2m1LurnXY6M//cGhVaegT71OfOXoprxT6o780GZd792ea6FfrQkuU4usHZIUczAQMRUE2plzA=="], + + "npm/minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], + + "npm/ms": ["ms@2.1.3", "", { "bundled": true }, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "npm/mute-stream": ["mute-stream@3.0.0", "", {}, "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw=="], + + "npm/negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + + "npm/node-gyp": ["node-gyp@12.4.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bundled": true, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw=="], + + "npm/nopt": ["nopt@9.0.0", "", { "dependencies": { "abbrev": "^4.0.0" }, "bundled": true, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw=="], + + "npm/npm-audit-report": ["npm-audit-report@7.0.0", "", { "bundled": true }, "sha512-bluLL4xwGr/3PERYz50h2Upco0TJMDcLcymuFnfDWeGO99NqH724MNzhWi5sXXuXf2jbytFF0LyR8W+w1jTI6A=="], + + "npm/npm-bundled": ["npm-bundled@5.0.0", "", { "dependencies": { "npm-normalize-package-bin": "^5.0.0" } }, "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw=="], + + "npm/npm-install-checks": ["npm-install-checks@8.0.0", "", { "dependencies": { "semver": "^7.1.1" }, "bundled": true }, "sha512-ScAUdMpyzkbpxoNekQ3tNRdFI8SJ86wgKZSQZdUxT+bj0wVFpsEMWnkXP0twVe1gJyNF5apBWDJhhIbgrIViRA=="], + + "npm/npm-normalize-package-bin": ["npm-normalize-package-bin@5.0.0", "", {}, "sha512-CJi3OS4JLsNMmr2u07OJlhcrPxCeOeP/4xq67aWNai6TNWWbTrlNDgl8NcFKVlcBKp18GPj+EzbNIgrBfZhsag=="], + + "npm/npm-package-arg": ["npm-package-arg@13.0.2", "", { "dependencies": { "hosted-git-info": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^7.0.0" }, "bundled": true }, "sha512-IciCE3SY3uE84Ld8WZU23gAPPV9rIYod4F+rc+vJ7h7cwAJt9Vk6TVsK60ry7Uj3SRS3bqRRIGuTp9YVlk6WNA=="], + + "npm/npm-packlist": ["npm-packlist@10.0.4", "", { "dependencies": { "ignore-walk": "^8.0.0", "proc-log": "^6.0.0" } }, "sha512-uMW73iajD8hiH4ZBxEV3HC+eTnppIqwakjOYuvgddnalIw2lJguKviK1pcUJDlIWm1wSJkchpDZDSVVsZEYRng=="], + + "npm/npm-pick-manifest": ["npm-pick-manifest@11.0.3", "", { "dependencies": { "npm-install-checks": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "npm-package-arg": "^13.0.0", "semver": "^7.3.5" }, "bundled": true }, "sha512-buzyCfeoGY/PxKqmBqn1IUJrZnUi1VVJTdSSRPGI60tJdUhUoSQFhs0zycJokDdOznQentgrpf8LayEHyyYlqQ=="], + + "npm/npm-profile": ["npm-profile@12.0.2", "", { "dependencies": { "npm-registry-fetch": "^19.0.0", "proc-log": "^6.1.0" }, "bundled": true }, "sha512-+OKkPvqvx83vRG8aIetzABI99e5uzZZ6HIS5zCr+oRPSuDL0Buk1KJh/LqyR0BuiWmLeDWGI77igNYipztLm1w=="], + + "npm/npm-registry-fetch": ["npm-registry-fetch@19.1.1", "", { "dependencies": { "@npmcli/redact": "^4.0.0", "jsonparse": "^1.3.1", "make-fetch-happen": "^15.0.0", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minizlib": "^3.0.1", "npm-package-arg": "^13.0.0", "proc-log": "^6.0.0" }, "bundled": true }, "sha512-TakBap6OM1w0H73VZVDf44iFXsOS3h+L4wVMXmbWOQroZgFhMch0juN6XSzBNlD965yIKvWg2dfu7NSiaYLxtw=="], + + "npm/npm-user-validate": ["npm-user-validate@4.0.0", "", { "bundled": true }, "sha512-TP+Ziq/qPi/JRdhaEhnaiMkqfMGjhDLoh/oRfW+t5aCuIfJxIUxvwk6Sg/6ZJ069N/Be6gs00r+aZeJTfS9uHQ=="], + + "npm/p-map": ["p-map@7.1.1", "", { "bundled": true }, "sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g=="], + + "npm/pacote": ["pacote@21.5.3", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/git": "^7.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "@npmcli/run-script": "^10.0.0", "cacache": "^20.0.0", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", "npm-package-arg": "^13.0.0", "npm-packlist": "^10.0.1", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "proc-log": "^6.0.0", "sigstore": "^4.0.0", "ssri": "^13.0.0", "tar": "^7.4.3" }, "bundled": true, "bin": { "pacote": "bin/index.js" } }, "sha512-XAHnxRzERPW/Y3sLaCgfUVdfP5Di1K0wiUWsDaK4reodu20Kl0pVZcw8Mdd2LaLsUpot6YLVOEgmIqMEL9Tjog=="], + + "npm/parse-conflict-json": ["parse-conflict-json@5.0.1", "", { "dependencies": { "json-parse-even-better-errors": "^5.0.0", "just-diff": "^6.0.0", "just-diff-apply": "^5.2.0" }, "bundled": true }, "sha512-ZHEmNKMq1wyJXNwLxyHnluPfRAFSIliBvbK/UiOceROt4Xh9Pz0fq49NytIaeaCUf5VR86hwQ/34FCcNU5/LKQ=="], + + "npm/path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="], + + "npm/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "npm/postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="], + + "npm/proc-log": ["proc-log@6.1.0", "", { "bundled": true }, "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ=="], + + "npm/proggy": ["proggy@4.0.0", "", {}, "sha512-MbA4R+WQT76ZBm/5JUpV9yqcJt92175+Y0Bodg3HgiXzrmKu7Ggq+bpn6y6wHH+gN9NcyKn3yg1+d47VaKwNAQ=="], + + "npm/promise-all-reject-late": ["promise-all-reject-late@1.0.1", "", {}, "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw=="], + + "npm/promise-call-limit": ["promise-call-limit@3.0.2", "", {}, "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw=="], + + "npm/promzard": ["promzard@3.0.1", "", { "dependencies": { "read": "^5.0.0" } }, "sha512-M5mHhWh+Adz0BIxgSrqcc6GTCSconR7zWQV9vnOSptNtr6cSFlApLc28GbQhuN6oOWBQeV2C0bNE47JCY/zu3Q=="], + + "npm/qrcode-terminal": ["qrcode-terminal@0.12.0", "", { "bundled": true, "bin": { "qrcode-terminal": "./bin/qrcode-terminal.js" } }, "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="], + + "npm/read": ["read@5.0.1", "", { "dependencies": { "mute-stream": "^3.0.0" }, "bundled": true }, "sha512-+nsqpqYkkpet2UVPG8ZiuE8d113DK4vHYEoEhcrXBAlPiq6di7QRTuNiKQAbaRYegobuX2BpZ6QjanKOXnJdTA=="], + + "npm/read-cmd-shim": ["read-cmd-shim@6.0.0", "", {}, "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A=="], + + "npm/safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "npm/semver": ["semver@7.8.6", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "npm/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + + "npm/sigstore": ["sigstore@4.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0", "@sigstore/sign": "^4.1.1", "@sigstore/tuf": "^4.0.2", "@sigstore/verify": "^3.1.1" } }, "sha512-endqECJkfhozrXMK5ngu/UAA0xVcVEFdnHJCElGaExypjW+HK5i6zu3NteLoaX/iFbRUbC3+DjttQs0GARr+5w=="], + + "npm/smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + + "npm/socks": ["socks@2.8.10", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ=="], + + "npm/socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="], + + "npm/spdx-exceptions": ["spdx-exceptions@2.5.0", "", {}, "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w=="], + + "npm/spdx-expression-parse": ["spdx-expression-parse@4.0.0", "", { "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" }, "bundled": true }, "sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ=="], + + "npm/spdx-license-ids": ["spdx-license-ids@3.0.24", "", {}, "sha512-cLS9TtWkIQFyLkJ3/5aFQAOHOSKTlOs/7WDut/XPSdjom1fJhUdkepeJAKXa9Y05+FabHd0sti+Et559vDtkpQ=="], + + "npm/ssri": ["ssri@13.0.1", "", { "dependencies": { "minipass": "^7.0.3" }, "bundled": true }, "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ=="], + + "npm/supports-color": ["supports-color@10.2.2", "", { "bundled": true }, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "npm/tar": ["tar@7.5.23", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" }, "bundled": true }, "sha512-lkukzdoGngZHJZXxW4S/E4Fp9ghTDlyZXrQGRNoJ/LXvDKcXUTq2sg5yQe74po7Voea6n/IN09+wE/QvJMiifA=="], + + "npm/text-table": ["text-table@0.2.0", "", { "bundled": true }, "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw=="], + + "npm/tiny-relative-date": ["tiny-relative-date@2.0.2", "", { "bundled": true }, "sha512-rGxAbeL9z3J4pI2GtBEoFaavHdO4RKAU54hEuOef5kfx5aPqiQtbhYktMOTL5OA33db8BjsDcLXuNp+/v19PHw=="], + + "npm/tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "npm/treeverse": ["treeverse@3.0.0", "", { "bundled": true }, "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ=="], + + "npm/tuf-js": ["tuf-js@4.1.0", "", { "dependencies": { "@tufjs/models": "4.1.0", "debug": "^4.4.3", "make-fetch-happen": "^15.0.1" } }, "sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ=="], + + "npm/undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], + + "npm/util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + + "npm/validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", { "bundled": true }, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], + + "npm/walk-up-path": ["walk-up-path@4.0.0", "", {}, "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A=="], + + "npm/which": ["which@6.0.1", "", { "dependencies": { "isexe": "^4.0.0" }, "bundled": true, "bin": { "node-which": "bin/which.js" } }, "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg=="], + + "npm/write-file-atomic": ["write-file-atomic@7.0.1", "", { "dependencies": { "signal-exit": "^4.0.1" } }, "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg=="], + + "npm/yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="], + + "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], + + "npm-run-path/unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="], + + "parse5-htmlparser2-tree-adapter/parse5": ["parse5@6.0.1", "", {}, "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw=="], + + "read-pkg/parse-json": ["parse-json@8.3.0", "", { "dependencies": { "@babel/code-frame": "^7.26.2", "index-to-position": "^1.1.0", "type-fest": "^4.39.1" } }, "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ=="], + + "signale/chalk": ["chalk@2.4.2", "", { "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ=="], + + "signale/figures": ["figures@2.0.0", "", { "dependencies": { "escape-string-regexp": "^1.0.5" } }, "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA=="], + + "supports-hyperlinks/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "tempy/is-stream": ["is-stream@3.0.0", "", {}, "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA=="], + + "tempy/type-fest": ["type-fest@2.19.0", "", {}, "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA=="], + + "tinyglobby/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "websocket/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], + + "wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], + + "wrap-ansi/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + + "@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@28.0.0", "", {}, "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ=="], + + "@octokit/plugin-retry/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@28.0.0", "", {}, "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ=="], + + "@octokit/plugin-throttling/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@28.0.0", "", {}, "sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg": ["read-pkg@9.0.1", "", { "dependencies": { "@types/normalize-package-data": "^2.4.3", "normalize-package-data": "^6.0.0", "parse-json": "^8.0.0", "type-fest": "^4.6.0", "unicorn-magic": "^0.1.0" } }, "sha512-9viLL4/n1BJUCT1NXVTdS1jtm80yDEgR5T4yCelII49Mbj0v1rZdKqj7zCiYdbB0CuCgdrvHcNogAKTFPBocFA=="], + + "@semantic-release/release-notes-generator/read-package-up/type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="], + + "cli-highlight/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "cli-highlight/chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "cli-highlight/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], + + "cli-highlight/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "cli-highlight/yargs/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], + + "cli-table3/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "cliui/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + + "env-ci/execa/get-stream": ["get-stream@8.0.1", "", {}, "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA=="], + + "env-ci/execa/human-signals": ["human-signals@5.0.0", "", {}, "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ=="], + + "env-ci/execa/is-stream": ["is-stream@3.0.0", "", {}, "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA=="], + + "env-ci/execa/npm-run-path": ["npm-run-path@5.3.0", "", { "dependencies": { "path-key": "^4.0.0" } }, "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ=="], + + "env-ci/execa/strip-final-newline": ["strip-final-newline@3.0.0", "", {}, "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw=="], + + "npm/minipass-flush/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + + "npm/minipass-pipeline/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + + "read-pkg/parse-json/type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="], + + "signale/chalk/escape-string-regexp": ["escape-string-regexp@1.0.5", "", {}, "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg=="], + + "signale/chalk/supports-color": ["supports-color@5.5.0", "", { "dependencies": { "has-flag": "^3.0.0" } }, "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow=="], + + "signale/figures/escape-string-regexp": ["escape-string-regexp@1.0.5", "", {}, "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg=="], + + "websocket/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], + + "wrap-ansi/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg/normalize-package-data": ["normalize-package-data@6.0.2", "", { "dependencies": { "hosted-git-info": "^7.0.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4" } }, "sha512-V6gygoYb/5EmNI+MEGrWkC+e6+Rr7mTmfHrxDbLzxQogBkgzo76rkok0Am6thgSF7Mv2nLOajAJj5vDJZEFn7g=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg/parse-json": ["parse-json@8.3.0", "", { "dependencies": { "@babel/code-frame": "^7.26.2", "index-to-position": "^1.1.0", "type-fest": "^4.39.1" } }, "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg/unicorn-magic": ["unicorn-magic@0.1.0", "", {}, "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ=="], + + "cli-highlight/chalk/ansi-styles/color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "cli-highlight/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "cli-highlight/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "cli-highlight/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "cli-table3/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "env-ci/execa/npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], + + "npm/minipass-flush/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + + "npm/minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + + "signale/chalk/supports-color/has-flag": ["has-flag@3.0.0", "", {}, "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg/normalize-package-data/hosted-git-info": ["hosted-git-info@7.0.2", "", { "dependencies": { "lru-cache": "^10.0.1" } }, "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w=="], + + "cli-highlight/chalk/ansi-styles/color-convert/color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "cli-highlight/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "cli-highlight/yargs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "cli-highlight/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "@semantic-release/release-notes-generator/read-package-up/read-pkg/normalize-package-data/hosted-git-info/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], + + "cli-highlight/yargs/cliui/wrap-ansi/ansi-styles/color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "cli-highlight/yargs/cliui/wrap-ansi/ansi-styles/color-convert/color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + } +} diff --git a/v2/oauth-resp.html b/oauth-resp.html similarity index 94% rename from v2/oauth-resp.html rename to oauth-resp.html index 5785cb219..34a891131 100644 --- a/v2/oauth-resp.html +++ b/oauth-resp.html @@ -6,7 +6,7 @@ - - diff --git a/src/oauth-sources/functions.ts b/src/oauth-sources/functions.ts deleted file mode 100644 index 58ded0e8d..000000000 --- a/src/oauth-sources/functions.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { PlaceAuthSourceQueryOptions } from '../auth-sources/interfaces'; -import { create, query, remove, show, update } from '../resources/functions'; -import { PlaceOAuthSource } from './oauth-source'; - -/** - * @private - */ -const PATH = 'oauth_auths'; - -/** Convert raw server data to an OAuth source object */ -function process(item: Partial) { - return new PlaceOAuthSource(item); -} - -/** - * Query the available OAuth sources - * @param query_params Query parameters to add the to request URL - */ -export function queryOAuthSources( - query_params: PlaceAuthSourceQueryOptions = {}, -) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for an OAuth source - * @param id ID of the OAuth source to retrieve - */ -export function showOAuthSource(id: string) { - return show({ id, query_params: {}, fn: process, path: PATH }); -} - -/** - * Update the OAuth source in the database - * @param id ID of the OAuth source - * @param form_data New values for the OAuth source - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateOAuthSource( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new OAuth source to the database - * @param form_data OAuth source data - * @param query_params Query parameters to add the to request URL - */ -export function addOAuthSource(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove an OAuth source from the database - * @param id ID of the OAuth source - */ -export function removeOAuthSource(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} diff --git a/src/oauth-sources/oauth-source.ts b/src/oauth-sources/oauth-source.ts deleted file mode 100644 index 36a77efd6..000000000 --- a/src/oauth-sources/oauth-source.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { PlaceResource } from '../resources/resource'; -import { HashMap } from '../utilities/types'; - -export class PlaceOAuthSource extends PlaceResource { - /** Type of auth source */ - public readonly type = 'oauth'; - /** ID of the authority associted with the auth method */ - public readonly authority_id: string; - /** Application ID from the SSO provider providing the OAuth services */ - public readonly client_id: string; - /** Application secret from the SSO provider providing the OAuth services */ - public readonly client_secret: string; - /** Mapping of engine values to SSO provider values */ - public readonly info_mappings: HashMap; - /** HTTP URL of the SSO provider */ - public readonly site: string; - /** URL from the SSO provider for authorisation */ - public readonly authorize_url: string; - /** HTTP Method used to generating tokens */ - public readonly token_method: 'get' | 'post' | 'put'; - /** URL for generating user tokens */ - public readonly token_url: string; - /** Scheme used to authenticate the user */ - public readonly auth_scheme: 'request_body' | 'basic_auth'; - /** Space seperated access scopes for the user */ - public readonly scope: string; - /** URL to grab user's profile details with a valid token */ - public readonly raw_info_url: string; - /** Additional params to be sent as part of the authorization reqest */ - public readonly authorize_params: HashMap; - /** Security checks to be made on the returned data */ - public readonly ensure_matching: HashMap; - - constructor(raw_data: Partial = {}) { - super(raw_data); - this.authority_id = raw_data.authority_id || ''; - this.client_id = raw_data.client_id || ''; - this.client_secret = raw_data.client_secret || ''; - this.info_mappings = raw_data.info_mappings || {}; - this.authorize_params = raw_data.authorize_params || {}; - this.ensure_matching = raw_data.ensure_matching || {}; - this.site = raw_data.site || ''; - this.authorize_url = raw_data.authorize_url || 'oauth/authorize'; - this.token_method = raw_data.token_method || 'post'; - this.token_url = raw_data.token_url || 'oauth/token'; - this.auth_scheme = raw_data.auth_scheme || 'request_body'; - this.scope = raw_data.scope || ''; - this.raw_info_url = raw_data.raw_info_url || ''; - this.authorize_params = raw_data.authorize_params || {}; - this.ensure_matching = raw_data.ensure_matching || {}; - } -} diff --git a/src/public-events/functions.ts b/src/public-events/functions.ts deleted file mode 100644 index ef30678db..000000000 --- a/src/public-events/functions.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { get, post } from '../http/functions'; -import { toQueryString } from '../utilities/api'; -import { HashMap } from '../utilities/types'; -import { - PublicEventQueryOptions, - PublicEventRegistrationRequest, - PublicEventTokenRequest, -} from './interfaces'; - -const PATH = 'public_events'; - -/** Issue a short-lived guest JWT for public event registration */ -export function publicEventGuestToken( - system_id: string, - body: PublicEventTokenRequest, -): Promise { - const url = `${apiEndpoint()}/${PATH}/guest_token/${encodeURIComponent(system_id)}`; - return post(url, body, { skip_auth: true }) as any; -} - -/** List cached public events for a system */ -export function listPublicEvents( - system_id: string, - query_params: PublicEventQueryOptions = {}, -): Promise { - const q = toQueryString(query_params); - const url = `${apiEndpoint()}/${PATH}/${encodeURIComponent(system_id)}/events${q ? '?' + q : ''}`; - return get(url, { skip_auth_flow: true }).then( - (resp: HashMap) => (resp || []) as HashMap[], - ); -} - -/** Register an external attendee for a public calendar event */ -export function registerPublicEvent( - system_id: string, - body: PublicEventRegistrationRequest, -): Promise { - const url = `${apiEndpoint()}/${PATH}/${encodeURIComponent(system_id)}/register`; - return post(url, body, { skip_auth_flow: true }) as any; -} diff --git a/src/public-events/interfaces.ts b/src/public-events/interfaces.ts deleted file mode 100644 index 66afc2b72..000000000 --- a/src/public-events/interfaces.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -export interface PublicEventTokenRequest { - captcha: string; - name: string; - email: string; -} - -export interface PublicEventRegistrationRequest { - event_id: string; - name: string; - email: string; -} - -export interface PublicEventQueryOptions extends PlaceResourceQueryOptions {} diff --git a/src/push-notifications/functions.ts b/src/push-notifications/functions.ts deleted file mode 100644 index 960b298ed..000000000 --- a/src/push-notifications/functions.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { post } from '../http/functions'; -import { MicrosoftNotification } from './interfaces'; - -const PATH = 'notifications'; - -/** Receive a Google push notification */ -export function googleNotification(body: unknown = {}): Promise { - return post(`${apiEndpoint()}/${PATH}/google`, body).then(() => undefined); -} - -/** Receive a Microsoft Graph push notification */ -export function office365Notification( - body: MicrosoftNotification, -): Promise { - return post(`${apiEndpoint()}/${PATH}/office365`, body).then( - () => undefined, - ); -} diff --git a/src/push-notifications/interfaces.ts b/src/push-notifications/interfaces.ts deleted file mode 100644 index 67e5625e0..000000000 --- a/src/push-notifications/interfaces.ts +++ /dev/null @@ -1,29 +0,0 @@ -export interface MicrosoftNotification { - validationTokens?: string[]; - value: MicrosoftNotificationValue[]; -} - -export interface MicrosoftNotificationValue { - changeType?: 'created' | 'updated' | 'deleted'; - clientState?: string; - encryptedContent?: MicrosoftNotificationEncryptedContent; - id?: string; - lifecycleEvent?: - | 'missed' - | 'subscription_removed' - | 'reauthorization_required' - | 'unexpected_value'; - resource?: string; - resourceData?: { id?: string }; - subscriptionExpirationDateTime: string; - subscriptionId: string; - tenantId: string; -} - -export interface MicrosoftNotificationEncryptedContent { - data?: string; - dataKey?: string; - dataSignature?: string; - encryptionCertificateId?: string; - encryptionCertificateThumbprint?: string; -} diff --git a/src/realtime.ts b/src/realtime.ts deleted file mode 100644 index dedbf8e24..000000000 --- a/src/realtime.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* istanbul ignore file */ - -export { getModule, getSystem } from './realtime/binding'; -export { - bind, - connectionState, - debug, - debug_events, - execute, - ignore, - isConnected as is_connected, - listen, - status, - unbind, - value, - websocketRoute, -} from './realtime/functions'; -export { PlaceErrorCodes, PlaceLogLevel } from './realtime/interfaces'; -export type { - PlaceCommand, - PlaceCommandRequest, - PlaceCommandRequestMetadata, - PlaceDebugEvent, - PlaceExecRequestOptions, - PlaceRequestOptions, - PlaceResponse, - PlaceWebsocketOptions, - SimpleNetworkError, -} from './realtime/interfaces'; - -export { PlaceModuleBinding } from './realtime/module'; -export { PlaceVariableBinding } from './realtime/status-variable'; -export { PlaceSystemBinding } from './realtime/system'; - -export { deregisterSystem, mockSystem, registerSystem } from './realtime/mock'; -export { MockPlaceWebsocketModule } from './realtime/mock-module'; -export { MockPlaceWebsocketSystem } from './realtime/mock-system'; diff --git a/src/realtime/binding.ts b/src/realtime/binding.ts deleted file mode 100644 index ada71f1ed..000000000 --- a/src/realtime/binding.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { HashMap } from '../utilities/types'; -import { PlaceModuleBinding } from './module'; -import { PlaceSystemBinding } from './system'; - -/** - * @private - * Mapping of system IDs to binding interfaces - */ -const _system_list: HashMap = {}; - -/** - * Get binding interface for an engine system - * @param system_id ID of the system - */ -export function getSystem(system_id: string): PlaceSystemBinding { - if (!_system_list[system_id]) { - _system_list[system_id] = new PlaceSystemBinding(system_id); - } - return _system_list[system_id]; -} - -/** - * Get binding interface for an engine module - * @param system_id ID of the system - * @param module_id ID of the module withing the system - * @param index Index of the module within the system - */ -export function getModule( - system_id: string, - module_id: string, - index: number = 1, -): PlaceModuleBinding { - const system = getSystem(system_id); - return system.module(module_id, index); -} diff --git a/v2/src/realtime/environment.ts b/src/realtime/environment.ts similarity index 99% rename from v2/src/realtime/environment.ts rename to src/realtime/environment.ts index faab2c947..1d4a5c128 100644 --- a/v2/src/realtime/environment.ts +++ b/src/realtime/environment.ts @@ -41,7 +41,7 @@ export interface RealtimeEnvironment { /** * The real browser parts. The token goes in a cookie, except in a frame and on mobile Safari, - * where the cookie does not reach the socket. There it goes in the query, as in v1. + * where the cookie does not reach the socket. There it goes in the query, as in 6.x. */ export function browserRealtimeEnvironment(): RealtimeEnvironment { assert(typeof window !== 'undefined', 'browserRealtimeEnvironment runs in a browser'); diff --git a/src/realtime/functions.ts b/src/realtime/functions.ts deleted file mode 100644 index 9c75b7bee..000000000 --- a/src/realtime/functions.ts +++ /dev/null @@ -1,829 +0,0 @@ -import { - apiEndpoint, - apiKey, - authority, - host, - httpRoute, - invalidateToken, - isFixedDevice, - isMock, - isSecure, - needsTokenHeader, - refreshAuthority, - token, -} from '../auth/functions'; -import { - clearAsyncTimeout, - destroyWaitingAsync, - timeout, -} from '../utilities/async'; -import { - isMobileSafari, - scoped_log, - simplifiedTime, -} from '../utilities/general'; -import { - Signal, - Unsubscribe, - WritableSignal, - createSignal, -} from '../utilities/signal'; -import { HashMap } from '../utilities/types'; -import { - MemoryWebSocket, - WebSocketConnection, - webSocket, -} from '../utilities/websocket'; -import { - PlaceCommandRequest, - PlaceCommandRequestMetadata, - PlaceDebugEvent, - PlaceErrorCodes, - PlaceExecRequestOptions, - PlaceLogLevel, - PlaceRequestOptions, - PlaceResponse, - SimpleNetworkError, -} from './interfaces'; -import { mockSystem } from './mock'; -import { MockPlaceWebsocketModule } from './mock-module'; -import { MockPlaceWebsocketSystem } from './mock-system'; - -const log = scoped_log('WS'); - -/** - * @private - * Time in seconds to ping the server to keep the websocket connection alive - */ -const KEEP_ALIVE = 15; -/** - * @private - * Global counter for websocket request IDs - */ -let REQUEST_COUNT = 0; -/** - * @private - * Websocket for connecting to engine - */ -let _websocket: WebSocketConnection | undefined; -let _websocket_id = 0; -/** - * @private - * Request promises - */ -const _requests: { [id: string]: PlaceCommandRequestMetadata } = {}; -/** - * @private - * Signals for listening to values of bindings - */ -const _binding: { [id: string]: WritableSignal } = {}; -/** - * @private - * Unsubscribe callbacks for active mock listeners - */ -const _listeners: { [id: string]: Unsubscribe } = {}; -/** - * @private - * Signal holding the connection status of the websocket - */ -const _status = createSignal(false); -/** - * @private - * Signal holding the connection past websocket - */ -const _sync = createSignal<[number, number]>([0, 0]); -let _connect_time = Date.now(); -/** - * @private - * Interval ID for the server ping callback - */ -let _keep_alive: number | undefined; -/** - * @private - * Number of connection attempts made before the session is established - */ -let _connection_attempts: number = 0; -/** - * @private - * Promise to handle connections to the websocket API - */ -let _connection_promise: Promise | null = null; -/** - * @private - * Timer to check the initial health of the websocket connection - */ -let _health_check: number | undefined; -let _last_pong = 0; -/** - * @private - * Delay in milliseconds to cancel a request - */ -export const REQUEST_TIMEOUT = 10 * 1000; - -/** Listener for debugging events */ -export const debug_events = createSignal(null); - -/* istanbul ignore next */ -/** - * @private - * Cleanup websocket connection in tests - */ -export function cleanupRealtime() { - _websocket?.complete(); - _websocket = undefined; - REQUEST_COUNT = 0; - for (const key in _binding) { - if (_binding[key]) { - delete _binding[key]; - } - } - for (const key in _listeners) { - if (_listeners[key]) { - _listeners[key](); - delete _listeners[key]; - } - } - for (const key in _requests) { - if (_requests[key]) { - delete _requests[key]; - } - } - _status.set(false); - clearInterval(_keep_alive); - clearTimeout(_health_check); - destroyWaitingAsync(); -} - -export function websocketRoute() { - return apiEndpoint().indexOf('/control/') >= 0 - ? '/control/websocket' - : `${httpRoute()}/systems/control`; -} - -/** Whether the websocket is connected */ -export function isConnected(): boolean { - return _status.value; -} - -/** - * Listen to websocket status changes - */ -export function status(): Signal { - return _status.asReadonly(); -} - -/** - * Listen to details about the connection status. - * First value is the number of the current websocket connection. - * Second value is the time the successful websocket connection was alive. - * @returns - */ -export function connectionState(): Signal<[number, number]> { - return _sync.asReadonly(); -} - -/** - * Listen to binding changes on the given status variable. DOES NOT BIND TO VARIABLE - * @param binding_details Binding details - */ -export function listen( - binding_details: PlaceRequestOptions, -): Signal; -export function listen( - binding_details: PlaceRequestOptions, - bindings: HashMap> = _binding, -): Signal { - const key = `${binding_details.sys}|${binding_details.mod}_${binding_details.index}|${binding_details.name}`; - /* istanbul ignore else */ - if (!bindings[key]) { - bindings[key] = createSignal(undefined as any); - } - return bindings[key].asReadonly(); -} - -/** - * Get current binding value - * @param options Binding details - */ -export function value(options: PlaceRequestOptions): T | undefined; -export function value( - options: PlaceRequestOptions, - bindings: HashMap> = _binding, -): T | void { - const key = `${options.sys}|${options.mod}_${options.index}|${options.name}`; - if (bindings[key]) { - return bindings[key].value as T; - } - return; -} - -/** - * Bind to status variable on the given system module - * @param options Binding request options - */ -export function bind( - options: PlaceRequestOptions, - timeout_delay?: number, -): Promise; -export function bind( - options: PlaceRequestOptions, - timeout_delay: number = 0, - post: (_: PlaceCommandRequest, t?: number) => Promise = send, -): Promise { - const request: PlaceCommandRequest = { - id: ++REQUEST_COUNT, - cmd: 'bind', - ...options, - }; - return post(request, timeout_delay); -} - -/** - * Unbind from a status variable on the given system module - * @param options Unbind request options - */ -export function unbind( - options: PlaceRequestOptions, - timeout_delay?: number, -): Promise; -export function unbind( - options: PlaceRequestOptions, - timeout_delay: number = 0, - post: (_: PlaceCommandRequest, t?: number) => Promise = send, -): Promise { - const request: PlaceCommandRequest = { - id: ++REQUEST_COUNT, - cmd: 'unbind', - ...options, - }; - return post(request, timeout_delay); -} - -/** - * Execute method on the given system module - * @param options Exec request options - */ -export function execute( - options: PlaceExecRequestOptions, - timeout_delay: number = REQUEST_TIMEOUT, - post: (_: PlaceCommandRequest, t?: number) => Promise = send, -): Promise { - const request: PlaceCommandRequest = { - id: ++REQUEST_COUNT, - cmd: 'exec', - ...options, - }; - return post(request, timeout_delay); -} - -/** - * Listen to debug logging for on the given system module binding - * @param options Debug request options - */ -export function debug( - options: PlaceRequestOptions, - timeout_delay?: number, -): Promise; -export function debug( - options: PlaceRequestOptions, - timeout_delay: number = REQUEST_TIMEOUT, - post: (_: PlaceCommandRequest, t?: number) => Promise = send, -): Promise { - const request: PlaceCommandRequest = { - id: ++REQUEST_COUNT, - cmd: 'debug', - ...options, - }; - return post(request, timeout_delay); -} - -/** - * Stop debug logging on the given system module binding - * @param options Debug request options - */ -export function ignore( - options: PlaceRequestOptions, - timeout_delay?: number, -): Promise; -export function ignore( - options: PlaceRequestOptions, - timeout_delay: number = REQUEST_TIMEOUT, - post: (_: PlaceCommandRequest, t?: number) => Promise = send, -): Promise { - const request: PlaceCommandRequest = { - id: ++REQUEST_COUNT, - cmd: 'ignore', - ...options, - }; - return post(request, timeout_delay); -} - -/** - * @private - * Send request to engine through the websocket connection - * @param request New request to post to the server - */ -export function send( - request: PlaceCommandRequest, - timeout_delay: number = REQUEST_TIMEOUT, - tries: number = 0, -): Promise { - const key = `${request.cmd}|${request.sys}|${request.mod}${request.index}|${ - request.name - }|${request.args}|${simplifiedTime()}`; - /* istanbul ignore else */ - if (!_requests[key]) { - const req: PlaceCommandRequestMetadata = { ...request, key }; - req.promise = new Promise((resolve, reject) => { - const retry = () => { - delete _requests[key]; - (_requests[key] as any) = null; - send(request, timeout_delay, tries).then( - (_) => resolve(_), - (_) => reject(_), - ); - }; - if (_websocket && isConnected()) { - if (isMock()) handleMockSend(request, _websocket, _listeners); - req.resolve = resolve; - req.reject = reject; - const binding = `${request.sys}, ${request.mod}_${request.index}, ${request.name}`; - log( - `[${request.cmd.toUpperCase()}](${request.id}) ${binding}`, - request.args, - ); - _websocket.next(request); - if (timeout_delay > 0) { - timeout( - `${key}`, - () => { - reject('Request timed out.'); - delete _requests[key]; - (_requests[key] as any) = null; - }, - timeout_delay, - ); - } - } else if (!_connection_promise) { - connect().then(() => retry()); - } else { - setTimeout(() => retry(), 1000); - } - }); - _requests[key] = req; - } else { - log(`Request already in progress. Waiting...`, request); - } - return _requests[key].promise as Promise; -} - -/** - * @private - * Callback for messages from the server - * @param message Message from the engine server - */ -export function onMessage(message: PlaceResponse | 'pong'): void { - if (message !== 'pong' && message instanceof Object) { - if (message.type === 'notify' && message.meta) { - handleNotify(message.meta, message.value); - } else if (message.type === 'success') { - handleSuccess(message); - } else if (message.type === 'debug') { - log(`[DEBUG] ${message.mod}${message.klass || ''} →`, message.msg); - const meta = message.meta || { mod: '', index: '' }; - debug_events.set({ - mod_id: message.mod || '', - module: `${meta.mod}_${meta.index}`, - class_name: message.klass || '', - message: message.msg || '', - level: message.level || PlaceLogLevel.Debug, - time: Math.floor(new Date().getTime() / 1000), - }); - } else if (message.type === 'error') { - handleError(message); - } else if (!(message as any).cmd) { - // Not mock message - log.error('Invalid websocket message', message); - } - clearAsyncTimeout(`${message.id}`); - } else if (message === 'pong') { - _last_pong = Date.now(); - log(`Pong!`); - } -} - -/** - * @private - * Handle websocket success response - * @param message Success message - */ -export function handleSuccess(message: PlaceResponse) { - const request = Object.keys(_requests) - .map((i) => _requests[i]) - .find((item) => item?.id === message.id); - log(`[SUCCESS](${message.id})`); - /* istanbul ignore else */ - if (request && request.resolve) { - request.resolve(message.value); - delete _requests[request.key]; - } -} - -/** - * @private - * Handle websocket request error - * @param message Error response - */ -export function handleError(message: PlaceResponse) { - let type = 'UNEXPECTED FAILURE'; - switch (message.code) { - case PlaceErrorCodes.ACCESS_DENIED: - type = 'ACCESS DENIED'; - break; - case PlaceErrorCodes.BAD_REQUEST: - type = 'BAD REQUEST'; - break; - case PlaceErrorCodes.MOD_NOT_FOUND: - type = 'MODULE NOT FOUND'; - break; - case PlaceErrorCodes.SYS_NOT_FOUND: - type = 'SYSTEM NOT FOUND'; - break; - case PlaceErrorCodes.PARSE_ERROR: - type = 'PARSE ERROR'; - break; - case PlaceErrorCodes.REQUEST_FAILED: - type = 'REQUEST FAILED'; - break; - case PlaceErrorCodes.UNKNOWN_CMD: - type = 'UNKNOWN COMMAND'; - break; - } - log.error(`[ERROR] ${type}(${message.id}): ${message.msg}`); - const request = Object.keys(_requests) - .map((key) => _requests[key]) - .filter((_) => _) - .find((request) => request.id === message.id); - if (request && request.reject) { - request.reject(message); - clearAsyncTimeout(`${request.key}`); - delete _requests[request.key]; - } -} - -/** - * @private - * Update the current value of the binding - * @param options Binding details - * @param updated_value New binding value - */ -export function handleNotify( - options: PlaceRequestOptions, - updated_value: T, - bindings: HashMap> = _binding, -): void { - const key = `${options.sys}|${options.mod}_${options.index}|${options.name}`; - if (!bindings[key]) { - bindings[key] = createSignal(null as any); - } - const binding = `${options.sys}, ${options.mod}_${options.index}, ${options.name}`; - log(`[NOTIFY] ${binding} changed`, [ - bindings[key].value, - '→', - updated_value, - ]); - bindings[key].set(updated_value); -} - -/** - * @private - * Connect to engine websocket - */ -export function connect(tries: number = 0): Promise { - if (_connection_promise == null) { - _connection_promise = new Promise((resolve) => { - if (tries > 40) { - return location.reload(); - } - _connection_attempts++; - _connect_time = Date.now(); - _websocket = ( - isMock() ? createMockWebSocket() : createWebsocket() - ) as any; - if (_websocket) { - log.debug(`Authority:`, authority()); - log(`Connecting to websocket...`); - _websocket.subscribe( - (resp: PlaceResponse) => { - if (!_status.value) { - log(`Connection established.`); - resolve(); - } - _status.set(true); - _connection_attempts = 0; - clearHealthCheck(); - onMessage(resp); - }, - (err: SimpleNetworkError) => { - _websocket = undefined; - _connection_promise = null; - _clearRequests(); - clearHealthCheck(); - onWebSocketError(err); - }, - () => { - _websocket = undefined; - _connection_promise = null; - _clearRequests(); - log(`Connection closed by browser.`); - _status.set(false); - // Try reconnecting after 1 second - reconnect(); - }, - ); - if (_keep_alive) clearInterval(_keep_alive); - _last_pong = Date.now(); - ping(); - _keep_alive = setInterval( - () => ping(), - KEEP_ALIVE * 1000, - ) as any; - clearHealthCheck(); - _websocket_id += 1; - _health_check = setTimeout(() => { - log('Unhealthy connection. Reconnecting...'); - _status.set(false); - _connection_promise = null; - reconnect(); - }, 30 * 1000) as any; - } else { - /* istanbul ignore else */ - if (!_websocket) { - log.error( - `Failed to create websocket(${tries}). Retrying in ${ - 1000 * Math.min(10, tries + 1) - }ms...`, - ); - } else { - log( - `Waiting on auth(${tries}). Retrying in ${ - 1000 * Math.min(10, tries + 1) - }ms...`, - [!!token(), !!authority()], - 'info', - ); - } - setTimeout( - () => { - _connection_promise = null; - connect(tries).then((_) => resolve(_)); - }, - 1000 * Math.min(10, ++tries), - ); - } - }); - } - return _connection_promise; -} - -/** - * @private - * Create websocket connection - */ -export function createWebsocket() { - /* istanbul ignore if */ - if (!authority() || !token()) return null; - const secure = isSecure() || location.protocol.indexOf('https') >= 0; - let url = `ws${secure ? 's' : ''}://${host()}${websocketRoute()}${ - isFixedDevice() ? '?fixed_device=true' : '' - }`; - const tkn = token(); - let query = - tkn === 'x-api-key' ? `api-key=${apiKey()}` : `bearer_token=${tkn}`; - if (!needsTokenHeader() && !isMobileSafari()) { - log(`Authenticating through cookie...`); - query += `;max-age=120;path=${websocketRoute()};`; - query += `${secure ? 'secure;' : ''}samesite=strict`; - document.cookie = query; - log(`Cookies:`, [document.cookie, query]); - } else { - log(`Authenticating through URL query parameter...`); - url += `${url.indexOf('?') >= 0 ? '&' : '?'}${query}`; - } - log( - `Creating websocket connection to ws${ - secure ? 's' : '' - }://${host()}${websocketRoute()}`, - ); - /* istanbul ignore next */ - return webSocket({ - url, - serializer: (data) => - typeof data === 'object' ? JSON.stringify(data) : data, - deserializer: (data) => { - let return_value = data.data; - if (return_value === 'pong') return return_value; - try { - return JSON.parse(data.data); - } catch (e) { - return return_value; - } - }, - }); -} - -/** - * @private - * Close old websocket connect and open a new one - */ -export function reconnect() { - _sync.set([_websocket_id, Date.now() - _connect_time]); - /* istanbul ignore else */ - if (_websocket && isConnected()) { - _websocket.complete(); - /* istanbul ignore else */ - if (_keep_alive) { - clearInterval(_keep_alive); - _keep_alive = undefined; - } - } - log( - `Reconnecting in ${Math.min( - 5000, - _connection_attempts * 300 || 1000, - )}ms...`, - ); - timeout( - 'reconnect', - () => connect(), - Math.min(5000, (_connection_attempts + 1) * 300 || 1000), - ); -} - -/** - * @private - * Send ping through the websocket - */ -export function ping() { - if (Date.now() - _last_pong > 4 * KEEP_ALIVE * 1000) { - return reconnect(); - } - _websocket?.next('ping'); -} - -/** - * @private - * Handle errors on the websocket - * @param err Network error response - */ -export function onWebSocketError(err: SimpleNetworkError) { - _status.set(false); - log.error('Websocket error:', err); - /* istanbul ignore else */ - if (err.status === 401) { - invalidateToken(); - } - refreshAuthority(); - // Try reconnecting after 1 second - reconnect(); -} - -/** - * @private - * Clear health check timer - */ -export function clearHealthCheck() { - if (_health_check) { - clearTimeout(_health_check); - _health_check = undefined; - } -} - -/** - * @private - * Connect to engine websocket - */ -export function createMockWebSocket() { - const websocket = new MemoryWebSocket< - PlaceResponse | PlaceCommandRequest - >(); - websocket.subscribe((resp: PlaceResponse | PlaceCommandRequest) => - onMessage(resp as PlaceResponse), - ); - return websocket; -} - -function mockRealtimeError( - request: PlaceCommandRequest, - error: any, -): PlaceResponse { - const message = - typeof error === 'string' - ? error - : error?.message || error?.msg || 'Mock realtime callback failed'; - return { - id: request.id, - type: 'error', - code: error?.code || PlaceErrorCodes.UNEXPECTED_FAILURE, - msg: message, - } as PlaceResponse; -} - -/** - * @private - * Send request to engine through the websocket connection - * @param request New request to post to the server - */ -export function handleMockSend( - request: PlaceCommandRequest, - websocket: WebSocketConnection, - listeners: HashMap, -) { - const key = `${request.sys}|${request.mod}_${request.index}|${request.name}`; - const system: MockPlaceWebsocketSystem = mockSystem(request.sys); - const module: MockPlaceWebsocketModule = - system && system[request.mod] - ? system[request.mod][request.index - 1 || 0] - : null; - if (module) { - try { - switch (request.cmd) { - case 'bind': - listeners[key] = module - .listen(request.name) - .subscribe((new_value) => { - setTimeout( - () => { - websocket.next({ - type: 'notify', - value: new_value, - meta: request, - }); - }, - Math.floor(Math.random() * 100 + 50), // Add natural delay before response - ); - }); - break; - case 'unbind': - /* istanbul ignore else */ - if (listeners[key]) { - listeners[key](); - delete listeners[key]; - clearAsyncTimeout(`${key}`); - } - break; - } - } catch (error) { - log.error(`[MOCK ERROR](${request.id}) request failed`, error); - timeout( - `${request.id}-error`, - () => websocket.next(mockRealtimeError(request, error)), - 10, - ); - return; - } - timeout( - `${request.id}-response`, - () => { - try { - const resp = { - id: request.id, - type: 'success', - value: - request.cmd === 'exec' - ? module.call(request.name, request.args) - : null, - } as PlaceResponse; - websocket.next(resp); - } catch (error) { - log.error( - `[MOCK ERROR](${request.id}) execute failed`, - error, - ); - websocket.next(mockRealtimeError(request, error)); - } - }, - 10, - ); - } else { - // Error determining system or module - timeout( - `${request.id}-error`, - () => - websocket.next({ - id: request.id, - type: 'error', - code: system - ? PlaceErrorCodes.SYS_NOT_FOUND - : PlaceErrorCodes.MOD_NOT_FOUND, - } as PlaceResponse), - 10, - ); - } -} - -function _clearRequests() { - for (const key in _requests) { - if (_requests[key]) delete _requests[key]; - } -} diff --git a/src/realtime/interfaces.ts b/src/realtime/interfaces.ts deleted file mode 100644 index aba33a5a8..000000000 --- a/src/realtime/interfaces.ts +++ /dev/null @@ -1,127 +0,0 @@ -/** Commands allowed by Place */ -export type PlaceCommand = 'bind' | 'unbind' | 'debug' | 'ignore' | 'exec'; - -/** General Place websocket request metadata */ -export interface PlaceCommandRequest { - /** Unique request identifier */ - id: string | number; - /** Type of the command to send to engine */ - cmd: PlaceCommand; - /** System ID to perform the command */ - sys: string; - /** Module on the given system to perform the command */ - mod: string; - /** Index of the module in the system */ - index: number; - /** Name of variable to `bind` or method to `exec` on the given module */ - name: string; - /** Aruguments to pass to the method executed on the module */ - args?: any[]; -} - -/** Additional management metadata for a Place request */ -export interface PlaceCommandRequestMetadata extends PlaceCommandRequest { - /** Request and binding identifier */ - key: string; - /** Request promise */ - promise?: Promise; - /** Resolve function for the request promise */ - resolve?: (_?: any) => void; - /** Reject function for the request promise */ - reject?: (_?: any) => void; -} - -/** Metadata describing the actor the request should be performed on */ -export interface PlaceRequestOptions { - /** System ID to perform the command */ - sys: string; - /** Module on the given system to perform the command */ - mod: string; - /** Index of the module in the system */ - index: number; - /** Name of variable to `bind` or method to `exec` on the given module */ - name: string; -} - -/** Place websocket exec request metadata */ -export interface PlaceExecRequestOptions extends PlaceRequestOptions { - args?: any[]; -} - -/** Websocket initialisation options */ -export interface PlaceWebsocketOptions { - /** Domain and port of the engine server */ - host?: string; - /** Whether this endpoint is a fixed device */ - fixed?: boolean; - /** Whether to use the secure communcations protocol */ - secure?: boolean; -} - -/** Place webscoket API response */ -export interface PlaceResponse { - /** ID of the associated request */ - id: string | number; - /** Response type */ - type: 'success' | 'error' | 'notify' | 'debug'; - /** Error code */ - code?: number; - /** New value of binding if `notify` or return value from an `exec */ - value?: any; - /** Request metadata */ - meta?: PlaceRequestOptions; - /** Debug module */ - mod?: string; - /** Debug module */ - klass?: string; - /** Log message level */ - level?: PlaceLogLevel; - /** Debug message */ - msg?: string; -} - -/** Possible error codes returned by Place */ -export enum PlaceErrorCodes { - PARSE_ERROR = 0, - BAD_REQUEST = 1, - ACCESS_DENIED = 2, - REQUEST_FAILED = 3, - UNKNOWN_CMD = 4, - SYS_NOT_FOUND = 5, - MOD_NOT_FOUND = 6, - UNEXPECTED_FAILURE = 7, -} - -/** Simple interface for a network error response */ -export interface SimpleNetworkError { - /** Status code of the error */ - status: number; - /** Details aboun the error */ - message: string; -} - -/** Logging levels of debug messages */ -export enum PlaceLogLevel { - Info = 'info', - Debug = 'debug', - Warning = 'warn', - Error = 'error', - Fatal = 'fatal', - Trace = 'trace', -} - -/** Metadata associated with Place Debug events */ -export interface PlaceDebugEvent { - /** ID of the module associated with the event */ - mod_id: string; - /** Module associated with the event */ - module: string; - /** Logically class name of the module driver */ - class_name: string; - /** Logging level of the message */ - level: PlaceLogLevel; - /** Contents of the debug event */ - message: string; - /** Unix epoch of the message arrival in seconds */ - time: number; -} diff --git a/src/realtime/mock-module.ts b/src/realtime/mock-module.ts deleted file mode 100644 index b846da6d2..000000000 --- a/src/realtime/mock-module.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Signal, WritableSignal, createSignal } from '../utilities/signal'; -import { HashMap } from '../utilities/types'; -import { MockPlaceWebsocketSystem } from './mock-system'; - -export class MockPlaceWebsocketModule { - [name: string]: any; - - constructor( - protected _system: MockPlaceWebsocketSystem, - properties: HashMap, - ) { - const proto_fn = Object.getOwnPropertyNames( - Object.getPrototypeOf(properties), - ).filter((_) => _.startsWith('$')); - for (const key in properties) { - /* istanbul ignore else */ - if ( - properties.hasOwnProperty(key) && - properties[key] !== undefined - ) { - if (properties[key] instanceof Function) { - this.addMethod(key, properties[key]); - } else { - this.addProperty(key, properties[key]); - } - } - } - for (const fn of proto_fn) { - if (properties[fn] instanceof Function) { - this.addMethod(fn, properties[fn]); - } - } - } - - /** - * Call method on the module - * @param command Name of the method to call on the module - * @param args Array of arguments to pass to the method being called - */ - public call(command: string, args: any[] = []): T | null { - if (this[`$${command}`] instanceof Function) { - return this[`$${command}`](...args) as T; - } - return null; - } - - /** - * Subscribe to value changes on the given property - * @param prop_name Name of the property - * @param next Callback for changes to the property - */ - public listen(prop_name: string): Signal { - if (!this[`_${prop_name}`] && !this[prop_name]) { - this.addProperty(prop_name, null); - } - const observer = this[`_${prop_name}`] as WritableSignal; - return observer.asReadonly(); - } - - /** - * Add method to module - * @param prop_name Name of the method - * @param fn Method logic - */ - private addMethod(prop_name: string, fn: (...args: any[]) => any) { - if (prop_name[0] !== '$') { - prop_name = `$${prop_name}`; - } - this[prop_name] = fn; - } - - /** - * Add signal property to module - * @param prop_name Name of the property - * @param value Initial value of the property - */ - private addProperty(prop_name: string, value: any) { - if (prop_name[0] === '$') { - prop_name = prop_name.replace('$', ''); - } - this[`_${prop_name}`] = createSignal(value); - Object.defineProperty(this, prop_name, { - get: () => this[`_${prop_name}`].value, - set: (v) => this[`_${prop_name}`].set(v), - }); - } -} diff --git a/src/realtime/mock-system.ts b/src/realtime/mock-system.ts deleted file mode 100644 index 4cad30434..000000000 --- a/src/realtime/mock-system.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { HashMap } from '../utilities/types'; -import { MockPlaceWebsocketModule } from './mock-module'; - -export class MockPlaceWebsocketSystem { - [name: string]: any; - - constructor(properties: HashMap) { - for (const key in properties) { - /* istanbul ignore else */ - if (properties.hasOwnProperty(key) && properties[key]) { - /* istanbul ignore else */ - if (properties[key] instanceof Array) { - properties[key].forEach((i: HashMap) => { - this.addModule(key, i); - }); - } - } - } - } - - /** - * Add new module to the system - * @param mod_name Module class - * @param properties Properties of the new module - */ - private addModule(mod_name: string, properties: HashMap) { - if (!this[mod_name]) { - this[mod_name] = []; - } - this[mod_name].push(new MockPlaceWebsocketModule(this, properties)); - } -} diff --git a/src/realtime/mock.ts b/src/realtime/mock.ts deleted file mode 100644 index f52e90bc4..000000000 --- a/src/realtime/mock.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { HashMap } from '../utilities/types'; -import { MockPlaceWebsocketSystem } from './mock-system'; - -/** - * @private - * List of registered mock systems for websocket bindings - */ -const _mock_systems: HashMap = {}; - -/** Register a mock system for websocket bindings */ -export function registerSystem( - id: string, - details: HashMap, -): MockPlaceWebsocketSystem { - _mock_systems[id] = new MockPlaceWebsocketSystem(details); - return _mock_systems[id]; -} - -/** Retrieve a mock system for websocket bindings */ -export function mockSystem(id: string): MockPlaceWebsocketSystem { - return _mock_systems[id]; -} - -/** Remove a mock system for websocket bindings */ -export function deregisterSystem(id: string): void { - delete _mock_systems[id]; -} diff --git a/src/realtime/module.ts b/src/realtime/module.ts deleted file mode 100644 index 51c2c156f..000000000 --- a/src/realtime/module.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { HashMap } from '../utilities/types'; -import { execute, REQUEST_TIMEOUT } from './functions'; -import { PlaceVariableBinding } from './status-variable'; -import { PlaceSystemBinding } from './system'; - -export class PlaceModuleBinding { - /** Mapping of module bindings */ - private _bindings: HashMap = {}; - - constructor( - private _system: PlaceSystemBinding, - private _id: string, - ) {} - - public get id(): string { - return `${this.name}_${this.index}`; - } - - /** Parent system of the module */ - public get system(): PlaceSystemBinding { - return this._system; - } - - /** Module index */ - public get index(): number { - const parts = this._id.split('_'); - const index = parts.pop(); - return parseInt(index || '', 10) || 1; - } - - /** Module name */ - public get name(): string { - const parts = this._id.split('_'); - parts.pop(); - return parts.join('_'); - } - - /** - * Get binding with the given name - * @param name Name of the binding - * @deprecated Use `variable` instead - */ - public binding(name: string) { - if (!this._bindings[name]) { - this._bindings[name] = new PlaceVariableBinding(this, name); - } - return this._bindings[name] as PlaceVariableBinding; - } - - /** - * Get binding with the given name - * @param name Name of the binding - */ - public variable(name: string) { - if (!this._bindings[name]) { - this._bindings[name] = new PlaceVariableBinding(this, name); - } - return this._bindings[name] as PlaceVariableBinding; - } - - /** - * Execute method on the engine module - * @param method Name of the method - * @param args Array of arguments to pass to the method - */ - public execute( - method: string, - args?: any[], - timeout_delay: number = REQUEST_TIMEOUT, - ): Promise { - return execute( - { - sys: this._system.id, - mod: this.name, - index: this.index, - name: method, - args, - }, - timeout_delay, - ); - } -} diff --git a/v2/src/realtime/realtime.ts b/src/realtime/realtime.ts similarity index 99% rename from v2/src/realtime/realtime.ts rename to src/realtime/realtime.ts index b0f25dbc2..87a1731b5 100644 --- a/v2/src/realtime/realtime.ts +++ b/src/realtime/realtime.ts @@ -38,7 +38,7 @@ import { export const CONTROL_PATH = '/api/engine/v2/systems/control'; export const REQUEST_TIMEOUT_MS = 10_000; export const KEEP_ALIVE_MS = 15_000; -/** A socket without a message for this long is dead: four keep-alives, as in v1. */ +/** A socket without a message for this long is dead: four keep-alives, as in 6.x. */ export const STALE_MS = 4 * KEEP_ALIVE_MS; /** The time limit for a new socket to open. */ export const CONNECT_TIMEOUT_MS = 30_000; diff --git a/src/realtime/status-variable.ts b/src/realtime/status-variable.ts deleted file mode 100644 index 648be3402..000000000 --- a/src/realtime/status-variable.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { clearAsyncTimeout, timeout } from '../utilities/async'; -import { log } from '../utilities/general'; -import { Signal, Unsubscribe } from '../utilities/signal'; - -import { bind, listen, status, unbind, value } from './functions'; -import { PlaceRequestOptions } from './interfaces'; -import { PlaceModuleBinding } from './module'; - -enum PENDING { - NONE, - BIND, - UNBIND, -} - -export class PlaceVariableBinding { - /** Status variable name */ - public readonly name: string; - /** Active pending state of the variable binding */ - private _pending = PENDING.NONE; - /** Number of active bindings to this variable */ - private _binding_count: number = 0; - /** Number of bindings to restore on reconnection */ - private _stale_bindings: number = 0; - - constructor( - private _module: PlaceModuleBinding, - _name: string, - ) { - this.name = _name; - // Listen for state changes in the websocket connection - status().subscribe((connected: boolean, previous: boolean) => { - if (connected === previous) return; - if ( - connected && - (this._stale_bindings || this._pending === PENDING.BIND) - ) { - log('VAR', 'Re-binding to status variable', this.binding()); - this.rebind(); - } else if (!connected) { - clearAsyncTimeout(`rebind:${JSON.stringify(this.binding())}`); - log( - 'VAR', - 'Binding dropped due to disconnection, re-binding when possible.', - this.binding(), - ); - this._stale_bindings = - this._binding_count || this._stale_bindings; - this._binding_count = 0; - } - }); - } - - /** Number of bindings to this status variable */ - public get count(): number { - return this._binding_count; - } - - /** Current value of the binding */ - public get value(): T | undefined { - return value(this.binding()); - } - - /** - * Get a signal that emits the current value of the binding - */ - public listen(): Signal { - return listen(this.binding()); - } - - /** - * Subscribe to changes of the variable's binding value. - * Note: Initial value emitted may be `undefined` - * @param next Callback for changes to the bindings value - */ - public subscribe(next: (value: T) => void): Unsubscribe { - return this.listen().subscribe(next); - } - - public bindThenSubscribe(next: (value: T) => void): Unsubscribe { - const unbind = this.bind(); - const unsubscribe = this.listen().subscribe((v) => { - try { - next(v); - } catch (e) { - console.error(e); - } - }); - return () => { - try { - unsubscribe(); - } finally { - try { - unbind(); - } catch { - // Ignore unbind errors during cleanup. - } - } - }; - } - - /** - * Bind to the status variable's value - */ - public bind(): () => void { - /* istanbul ignore else */ - if ( - (this._binding_count <= 0 && this._stale_bindings <= 0) || - this._pending === PENDING.UNBIND - ) { - this._pending = PENDING.BIND; - bind(this.binding()) - .then(() => { - this._binding_count++; - this._pending = PENDING.NONE; - }) - .catch(() => null); - } - return () => this.unbind(); - } - - /** - * Unbind from status variable - */ - public unbind() { - if (this._binding_count === 1 && this._pending === PENDING.NONE) { - this._pending = PENDING.UNBIND; - unbind(this.binding()).then(() => { - if (this._pending === PENDING.UNBIND) - this._pending = PENDING.NONE; - this._binding_count--; - }); - } else { - this._binding_count = Math.max(this._binding_count - 1, 0); - } - } - - /** - * Rebind to the status variable - */ - private async rebind() { - if (!this._stale_bindings && this._pending !== PENDING.BIND) return; - timeout( - `rebind:${JSON.stringify(this.binding())}`, - async () => { - await bind(this.binding()); - this._binding_count = this._stale_bindings || 1; - this._stale_bindings = 0; - }, - 100, - ); - } - - /** - * Generate binding details for the status variable - */ - private binding(): PlaceRequestOptions { - return { - sys: this._module.system.id, - mod: this._module.name, - index: this._module.index, - name: this.name, - }; - } -} diff --git a/src/realtime/system.ts b/src/realtime/system.ts deleted file mode 100644 index 16a9ed5d8..000000000 --- a/src/realtime/system.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { HashMap } from '../utilities/types'; -import { PlaceModuleBinding } from './module'; - -export class PlaceSystemBinding { - /** Unique idetifier of the system */ - public readonly id: string; - /** Mapping of engine modules within the system */ - private _module_list: HashMap = {}; - - constructor(_id: string) { - this.id = _id; - } - - /** - * Get binding interface for the given module - * @param module_id ID of the module - * @param index Index of the module within the system - */ - public module(module_id: string, index: number = 1) { - if (!module_id) { - throw new Error('Invalid module ID'); - } - const parts = module_id.split('_'); - // Check if module index is part of given ID - if (parts.length > 1 && Number.isInteger(+parts[parts.length - 1])) { - index = +parts[parts.length - 1]; - parts.pop(); - } - // Make sure index is not invalid - if (index < 1) { - index = 1; - } - const module = parts.join('_'); - // Initialise module list for type - if (!this._module_list[module]) { - this._module_list[module] = []; - } - // Initialise module if it does not exist - while (this._module_list[module].length < index) { - this._module_list[module].push( - new PlaceModuleBinding( - this, - `${module}_${this._module_list[module].length + 1}`, - ), - ); - } - return this._module_list[module][index - 1]; - } -} diff --git a/src/repositories/functions.ts b/src/repositories/functions.ts deleted file mode 100644 index adc9a44b3..000000000 --- a/src/repositories/functions.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { PlaceDriverDetails } from '../drivers/interfaces'; -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { HashMap } from '../utilities/types'; -import { - GitCommitDetails, - PlaceRemoteRepositoryCommitsQuery, - PlaceRemoteRepositoryQuery, - PlaceRepositoryCommitQuery, - PlaceRepositoryDetailsQuery, - PlaceRepositoryFilesQuery, - PlaceRepositoryFoldersQuery, - PlaceRepositoryPullQuery, - PlaceRepositoryQueryOptions, -} from './interfaces'; -import { PlaceRepository } from './repository'; - -/** - * @private - */ -const PATH = 'repositories'; - -/** Convert raw server data to a repository object */ -function process(item: Partial) { - return new PlaceRepository(item); -} - -/** - * Query the available repositories - * @param query_params Query parameters to add the to request URL - */ -export function queryRepositories( - query_params: PlaceRepositoryQueryOptions = {}, -) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for a repository - * @param id ID of the repository to retrieve - */ -export function showRepository(id: string) { - return show({ id, query_params: {}, fn: process, path: PATH }); -} - -/** - * Update the repository in the database - * @param id ID of the repository - * @param form_data New values for the repository - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateRepository( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new repository to the database - * @param form_data Repository data - * @param query_params Query parameters to add the to request URL - */ -export function addRepository(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a repository from the database - * @param id ID of the repository - */ -export function removeRepository(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} - -/** - * Get a list of all the interfaces - */ -export function listInterfaceRepositories(): Promise { - return show({ - id: 'interfaces', - query_params: {}, - path: PATH, - }); -} - -/** - * Get name of the default branch for a new repository - * @param query_params Details about the repository - */ -export function listRemoteRepositoryDefaultBranch( - query_params: PlaceRemoteRepositoryQuery, -): Promise { - return show({ - id: 'remote_default_branch', - query_params, - path: PATH, - }); -} - -/** - * Get a list of branches for a new repository - * @param query_params Details about the repository - */ -export function listRemoteRepositoryBranches( - query_params: PlaceRemoteRepositoryQuery, -): Promise { - return show({ - id: 'remote_branches', - query_params, - path: PATH, - }); -} - -/** - * Get a list of branch commits for a new repository - * @param query_params Details about the repository - */ -export function listRemoteRepositoryCommits( - query_params: PlaceRemoteRepositoryCommitsQuery, -): Promise { - return show({ - id: 'remote_commits', - query_params, - path: PATH, - }); -} - -/** - * Get a list of tags for a new repository - * @param query_params Details about the repository - */ -export function listRemoteRepositoryTags( - query_params: PlaceRemoteRepositoryQuery, -): Promise { - return show({ - id: 'remote_tags', - query_params, - path: PATH, - }); -} - -/** - * Get a list of all the drivers for a repository - * @param id ID of the repository - * @param query Addition query parameters to pass to the request - */ -export function listRepositoryDrivers( - id: string, - query_params?: HashMap, -): Promise { - return task({ - id, - task_name: 'drivers', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Get a list of all the releases for a repository - * @param id ID of the repository - * @param query Addition query parameters to pass to the request - */ -export function listRepositoryReleases( - id: string, - query_params?: HashMap, -): Promise { - return task({ - id, - task_name: 'releases', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Get a list of all the commits for a repository - * @param id ID of the repository - * @param query Addition query parameters to pass to the request - */ -export function listRepositoryCommits( - id: string, - query_params?: PlaceRepositoryCommitQuery, -): Promise { - return task({ - id, - task_name: 'commits', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Get a list of all the branches for a repository - * @param id ID of the repository - */ -export function listRepositoryBranches(id: string): Promise { - return task({ - id, - task_name: 'branches', - method: 'get', - path: PATH, - }); -} - -/** - * Get a list of all the branches for a repository - * @param id ID of the repository - */ -export function listRepositoryDefaultBranch(id: string): Promise { - return task({ - id, - task_name: 'default_branch', - method: 'get', - path: PATH, - }); -} - -/** - * Get a list of all the tags for a repository - * @param id ID of the repository - */ -export function listRepositoryTags(id: string): Promise { - return task({ - id, - task_name: 'tags', - method: 'get', - path: PATH, - }); -} - -/** - * Get the details for a given driver - * @param id ID of the repository - * @param query Addition query parameters to pass to the request - */ -export function listRepositoryDriverDetails( - id: string, - query_params: PlaceRepositoryDetailsQuery, -): Promise { - return task({ - id, - task_name: 'details', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Pull remote changes to tshe repository - * @param id ID of the repository - * @param query Addition query parameters to pass to the request - */ -export function pullRepositoryChanges( - id: string, - query_params?: PlaceRepositoryPullQuery, -): Promise { - return task({ - id, - task_name: 'pull', - form_data: query_params, - method: 'post', - path: PATH, - }); -} - -/** - * Get the folder tree structure of a repository - * @param id ID of the repository - * @param query_params Query parameters to add to the request - */ -export function listRepositoryFolders( - id: string, - query_params?: PlaceRepositoryFoldersQuery, -): Promise { - return task({ - id, - task_name: 'folders', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * List the files in an interface repository that match a glob pattern. - * Paths are relative to where they are served, i.e. `//path/to/file.html` - * @param id ID of the repository - * @param query_params Glob pattern to match files against - */ -export function listRepositoryFiles( - id: string, - query_params: PlaceRepositoryFilesQuery, -): Promise { - return task({ - id, - task_name: 'files', - form_data: query_params, - method: 'get', - path: PATH, - }); -} diff --git a/src/repositories/interfaces.ts b/src/repositories/interfaces.ts deleted file mode 100644 index f0a217bc5..000000000 --- a/src/repositories/interfaces.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Type of repository */ -export enum PlaceRepositoryType { - /** Repository is a collection of Driver logic */ - Driver = 'driver', - /** Repository is a collection of interfaces */ - Interface = 'interface', -} - -/** Mapping of available query parameters for the repositories index endpoint */ -export interface PlaceRepositoryQueryOptions - extends PlaceResourceQueryOptions {} - -/** Query parameters for repository commit listing */ -export interface PlaceRepositoryCommitQuery { - /** URL encoded name of the branch being requested */ - branch?: string; - /** URL encoded name of the driver being requested */ - driver?: string; - /** Number of commits to return */ - limit?: number; -} - -export interface GitCommitDetails { - /** Name of the commit author */ - author: string; - /** Short hash of the commit */ - commit: string; - /** ISO datetime string for commit */ - date: string; - /** Commit summary */ - subject: string; -} - -/** Query parameters for repository driver details */ -export interface PlaceRepositoryDetailsQuery { - /** URL encoded name of the driver being requested (required) */ - driver: string; - /** Hash of the commit being requested for the driver (required) */ - commit: string; -} - -/** Query parameters for repository pull */ -export interface PlaceRepositoryPullQuery { - /** Hash of the commit being requested */ - commit: string; -} - -/** Query parameters for remote repository operations */ -export interface PlaceRemoteRepositoryQuery { - /** The git URL that represents the repository (required) */ - repository_url: string; - /** A username for access if required */ - username?: string; - /** The password or access token as required */ - password?: string; -} - -/** Query parameters for remote repository commits */ -export interface PlaceRemoteRepositoryCommitsQuery - extends PlaceRemoteRepositoryQuery { - /** The branch to grab commits from */ - branch?: string; - /** The number of commits to return */ - depth?: number; -} - -/** Query parameters for repository folders listing */ -export interface PlaceRepositoryFoldersQuery { - /** Include dot files and folders */ - include_dots?: boolean; -} - -/** Query parameters for repository files listing */ -export interface PlaceRepositoryFilesQuery { - /** - * Glob pattern. Without a `/` it matches file names at any depth, - * otherwise the full path (use `**` to recurse) - */ - pattern: string; -} - -/** Metadata for a repository commit */ -export interface PlaceRepositoryCommit { - /** Hash associated with the commit */ - commit: string; - /** UTC epoch in seconds of the time the commit was made */ - date: number; - /** Author of the commit */ - author: string; - /** Commit subject line */ - subject: string; -} diff --git a/src/repositories/repository.ts b/src/repositories/repository.ts deleted file mode 100644 index 4dde9a3f4..000000000 --- a/src/repositories/repository.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { PlaceResource } from '../resources/resource'; -import { PlaceRepositoryType } from './interfaces'; - -export class PlaceRepository extends PlaceResource { - /** Name of the folder on the server to pull the repository */ - public readonly folder_name: string; - /** Description of the contents of the repository */ - public readonly description: string; - /** URI that the repository can be pulled from */ - public readonly uri: string; - /** Working branch for the repository */ - public readonly branch: string; - /** Hash of the commit at the head of the repository */ - public readonly commit_hash: string; - /** Repository type */ - public readonly repo_type: PlaceRepositoryType; - /** Username to connect to repository with */ - public readonly username: string; - /** Password to connect to repository with */ - public readonly password: string; - /** Root path of the repository to serve at the `folder_name` path */ - public readonly root_path: string; - /** Repository type */ - public get type() { - return this.repo_type; - } - - constructor(raw_data: Partial = {}) { - super(raw_data); - this.folder_name = raw_data.folder_name || ''; - this.description = raw_data.description || ''; - this.uri = raw_data.uri || ''; - this.branch = raw_data.branch || ''; - this.commit_hash = raw_data.commit_hash || ''; - this.repo_type = raw_data.repo_type || PlaceRepositoryType.Driver; - this.username = raw_data.username || ''; - this.password = raw_data.password || ''; - this.root_path = raw_data.root_path || ''; - } -} diff --git a/src/repositories/utilities.ts b/src/repositories/utilities.ts deleted file mode 100644 index ad53610c0..000000000 --- a/src/repositories/utilities.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* istanbul ignore next */ -/** - * Generate mocked out repository object metadata - * @param overrides Map of overrides for top level keys - */ -export function generateMockRepository(overrides: any = {}) { - if (typeof overrides !== 'object' || !overrides) { - overrides = {}; - } - const company = `company${Math.floor(Math.random() * 123)}`; - const product = `product${Math.floor(Math.random() * 123)}`; - return { - id: `repository-${Math.floor(Math.random() * 999_999_999)}`, - name: `${product}`, - folder_name: `${company}/${product}`, - description: `There is a description yes`, - uri: `https://github.com/placeos/${company}-drivers`, - commit_hash: 'HEAD', - repo_type: Math.floor(Math.random() * 999_999_999) % 2, - ...overrides, - }; -} diff --git a/src/resources/functions.ts b/src/resources/functions.ts deleted file mode 100644 index eeee0b52d..000000000 --- a/src/resources/functions.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { del, get, patch, post, put, responseHeaders } from '../http/functions'; -import { toQueryString } from '../utilities/api'; -import { convertPairStringToMap, parseLinkHeader } from '../utilities/general'; -import { HashMap } from '../utilities/types'; -import { - CreateParameters, - QueryParameters, - RemoveParameters, - ShowParameters, - TaskParameters, - UpdateParameters, -} from './interface'; - -/** Total number of items returned by the last basic index query */ -export function requestTotal(name: string): number { - return _total[name] || 0; -} - -/** Total number of items returned by the last basic index query */ -export function lastRequestTotal(name: string): number { - return _last_total[name] || 0; -} - -/** URL for the next query page */ -export function next(): string { - return _next; -} -/** - * @private - * Total number of items returned by the last basic index query - */ -let _total: HashMap = {}; -/** - * @private - * Total number of items returned by the last index query - */ -let _last_total: HashMap = {}; -/** - * @private - * URL to get the next page - */ -let _next: string = ''; - -const pass_fn = (_: any) => _; -const query_cache_delay = 300; -const _query_cache: HashMap<{ - promise: QueryResponse; - timeout: ReturnType; -}> = {}; - -/** - * @private - */ -export function cleanupAPI() { - _total = {}; - _last_total = {}; - _next = ''; - for (const key in _query_cache) { - clearTimeout(_query_cache[key].timeout); - delete _query_cache[key]; - } -} - -export type QueryResponse = Promise<{ - total: number; - next: () => QueryResponse | null; - data: T[]; -}>; - -/** - * @hidden - * Query the index of the API route associated with this service - * @param query_params Map of query paramaters to add to the request URL - */ -export function query(q: QueryParameters): QueryResponse { - const { query_params, fn, path, endpoint } = q; - const query_str = toQueryString(query_params); - const url = `${endpoint || apiEndpoint()}${path ? '/' + path : ''}${ - query_str ? '?' + query_str : '' - }`; - if (_query_cache[url]) return _query_cache[url].promise; - const promise = get(url).then((resp: HashMap) => { - const details = handleHeaders(url, query_str, path); - return { - total: details.total || 0, - next: details.next - ? () => - query({ - query_params: details.next as HashMap, - fn, - endpoint, - path, - }) - : null, - data: - resp && resp instanceof Array - ? resp.map((i) => (fn || pass_fn)(i)) - : resp && !(resp instanceof Array) && resp.results - ? (resp.results as HashMap[]).map((i) => process(i)) - : [], - } as any; - }); - _query_cache[url] = { - promise, - timeout: setTimeout(() => delete _query_cache[url], query_cache_delay), - }; - promise.catch(() => { - clearTimeout(_query_cache[url]?.timeout); - delete _query_cache[url]; - }); - return promise; -} - -/** - * @hidden - * Query the API route for a sepecific item - * @param id ID of the item - * @param query_params Map of query paramaters to add to the request URL - */ -export function show(details: ShowParameters): Promise { - const { query_params, id, path, fn, options } = details; - const query_str = toQueryString(query_params); - const url = `${apiEndpoint()}/${path}/${id}${ - query_str ? '?' + query_str : '' - }`; - return get(url, options).then((resp: any) => (fn || pass_fn)(resp)); -} - -/** - * @hidden - * Make post request for a new item to the service - * @param form_data Data to post to the server - * @param query_params Map of query paramaters to add to the request URL - */ -export function create(details: CreateParameters): Promise { - const { query_params, form_data, path, fn } = details; - const query_str = toQueryString(query_params); - const url = `${apiEndpoint()}/${path}${query_str ? '?' + query_str : ''}`; - return post(url, form_data).then((resp: any) => (fn || pass_fn)(resp)); -} - -/** - * @hidden - * Perform API task for the given item ID - * @param id ID of the item - * @param task_name Name of the task - * @param form_data Map of data to pass to the API - * @param method Verb to use for request - */ -export function task(details: TaskParameters): Promise { - const { id, task_name, form_data, method, path, callback } = details; - const query_str = toQueryString(form_data); - const url = `${apiEndpoint()}/${path}/${id}/${task_name}`; - const request = - method === 'post' || method === 'put' || !method - ? (method === 'put' ? put : post)(url, form_data) - : (method === 'del' ? del : get)( - `${url}${query_str ? '?' + query_str : ''}`, - { - response_type: 'json', - }, - ); - return request.then((resp: HashMap) => (callback || ((_: any) => _))(resp)); -} - -/** - * @hidden - * Make put request for changes to the item with the given id - * @param id ID of the item being updated - * @param form_data New values for the item - * @param query_params Map of query paramaters to add to the request URL - */ -export function update(details: UpdateParameters): Promise { - const { id, query_params, form_data, method, path, fn } = details; - const query_str = toQueryString({ - ...query_params, - version: form_data.version || 0, - }); - const url = `${apiEndpoint()}/${path}/${id}${ - query_str ? '?' + query_str : '' - }`; - return (method === 'put' ? put : patch)(url, form_data).then((resp: any) => - (fn || pass_fn)(resp), - ); -} - -/** - * @hidden - * Make delete request for the given item - * @param id ID of item - */ -export function remove(details: RemoveParameters): Promise { - const { id, query_params, path } = details; - const query_str = toQueryString(query_params); - const url = `${apiEndpoint()}/${path}/${id}${ - query_str ? '?' + query_str : '' - }`; - return del(url); -} - -/** - * @private - * @param url - * @param query_str - * @param name - */ -export function handleHeaders(url: string, query_str: string, name: string) { - const headers = responseHeaders( - url[0] === '/' ? `${location.origin}${url}` : url, - ); - const details: { total: number; next: HashMap | null } = { - total: 0, - next: null, - }; - - if (headers && headers['x-total-count']) { - const total_value = +(headers['x-total-count'] || 0); - if ( - query_str.length < 2 || - (query_str.length < 12 && query_str.indexOf('offset=') >= 0) - ) { - _total[name] = total_value; - } - _last_total[name] = total_value; - details.total = total_value; - } - if (headers && headers.link) { - const link_map = parseLinkHeader(headers.link || ''); - _next = link_map.next; - details.next = convertPairStringToMap(_next.split('?')[1]); - } - return details; -} - -function process(data: HashMap) { - return data as any; -} diff --git a/src/resources/interface.ts b/src/resources/interface.ts deleted file mode 100644 index e6c1eed24..000000000 --- a/src/resources/interface.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { HttpJsonOptions } from '../api'; -import { HashMap } from '../utilities/types'; - -/* tslint:disable */ - -/** Allowable query parameters for basic index endpoints */ -export interface PlaceResourceQueryOptions { - /** - * Free-text search filter. Words match as prefixes against the resource's - * searchable fields (PostgreSQL full-text search); all words must match. - */ - q?: string; - /** @deprecated Ignored by the server since PlaceOS moved search to PostgreSQL (PPT-2644) */ - fields?: string; - /** Number of results to return. Defaults to `20`. Max `10000` */ - limit?: number; - /** Offset of the results to return. Max `1000000` */ - offset?: number; - /** @deprecated Ignored by the server; pagination follows the `Link` header's offset */ - ref?: string; - /** Number of milliseconds to cache the query response */ - cache?: number; - /** Whether the request is a API poll request */ - _poll?: boolean; -} - -export interface ResourceService { - query: (fields?: HashMap) => Promise; - show: (id: string, fields?: HashMap) => Promise; - add: (data: HashMap) => Promise; - update: ( - id: string, - data: HashMap, - fields?: HashMap, - type?: 'put' | 'patch', - ) => Promise; - delete: (id: string) => Promise; -} - -export type PlaceDataEventType = - | 'value_change' - | 'item_saved' - | 'reset' - | 'other'; - -export interface PlaceDataClassEvent { - /** Type of event that has occurred on the object */ - type: PlaceDataEventType; - /** Associated metadata with the event */ - metadata: HashMap; -} - -export interface QueryParameters { - query_params: HashMap; - fn?: (data: Partial) => T; - path: string; - endpoint?: string; - options?: HttpJsonOptions; -} - -export interface ShowParameters extends QueryParameters { - id: string; -} - -export interface CreateParameters extends QueryParameters { - form_data: Partial; -} - -export interface UpdateParameters extends QueryParameters { - id: string; - form_data: HashMap; - method: 'put' | 'patch'; -} - -export interface RemoveParameters { - id: string; - query_params: HashMap; - path: string; -} - -export interface TaskParameters { - id: string; - task_name: string; - form_data?: any; - method?: 'post' | 'get' | 'del' | 'put' | 'patch'; - callback?: (_: any) => T; - path: string; -} diff --git a/src/resources/resource.ts b/src/resources/resource.ts deleted file mode 100644 index 12379a1ef..000000000 --- a/src/resources/resource.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { cleanObject } from '../utilities/general'; -import { HashMap } from '../utilities/types'; - -export abstract class PlaceResource { - /** Unique Identifier of the object */ - public readonly id: string; - /** Human readable name of the object */ - public readonly name: string; - /** Unix epoch in seconds of the creation time of the object */ - public readonly created_at: number; - /** Unix epoch in seconds of the creation time of the object */ - public readonly updated_at: number; - /** Version of the data */ - public readonly version: number; - - constructor(raw_data: Partial = {}) { - this.id = raw_data.id || ''; - this.name = raw_data.name || ''; - this.created_at = raw_data.created_at || 0; - this.updated_at = raw_data.updated_at || 0; - - this.version = raw_data.version || 0; - } - - /** - * Convert object into plain object - */ - public toJSON(): HashMap { - const obj: any = { ...this }; - obj.version = this.version; - /** Remove unneeded public members */ - delete obj.created_at; - return cleanObject(obj, [undefined, null, '']); - } -} diff --git a/src/root/functions.ts b/src/root/functions.ts deleted file mode 100644 index 71441c11b..000000000 --- a/src/root/functions.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { get, post } from '../http/functions'; -import { toQueryString } from '../utilities/api'; -import { HashMap } from '../utilities/types'; -import { - PlacePlatformInfo, - PlaceSourceResyncStatus, - PlaceVersion, - SignalOptions, -} from './interfaces'; - -/** Check API health */ -export function healthCheck(): Promise { - return get(apiEndpoint()).then(() => undefined); -} - -/** Get platform release details */ -export function platformInfo(): Promise { - return get(`${apiEndpoint()}/platform`) as any; -} - -/** Get this service version */ -export function serviceVersion(): Promise { - return get(`${apiEndpoint()}/version`) as any; -} - -/** Get core node versions */ -export function coreVersions(): Promise { - return get(`${apiEndpoint()}/cluster/versions`) as any; -} - -/** List available API scopes */ -export function apiScopes(): Promise { - return get(`${apiEndpoint()}/scopes`) as any; -} - -/** - * Publish every module's state and every model's metadata to the MQTT brokers - * again. With `clear`, everything PlaceOS publishes is removed from the brokers - * first, for when what they hold has drifted. Runs in the background; follow - * it with `sourceResyncStatus`. Rejects with a 409 while one is running. - * Needs a system admin. - */ -export function sourceResync(clear = false): Promise { - return post(`${apiEndpoint()}/source/resync?clear=${clear}`, {}) as any; -} - -/** Where the last resync of the MQTT brokers got to. Needs a system admin */ -export function sourceResyncStatus(): Promise { - return get(`${apiEndpoint()}/source/resync`) as any; -} - -/** Signal a channel in a similar manner to a webhook for drivers */ -export function signal(channel: string, body: HashMap = {}): Promise { - const q = toQueryString({ channel } as SignalOptions); - return post(`${apiEndpoint()}/signal?${q}`, body).then(() => undefined); -} diff --git a/src/root/interfaces.ts b/src/root/interfaces.ts deleted file mode 100644 index f030a2614..000000000 --- a/src/root/interfaces.ts +++ /dev/null @@ -1,30 +0,0 @@ -export interface PlacePlatformInfo { - version: string; - changelog: string; -} - -export interface PlaceVersion { - service: string; - commit: string; - version: string; - build_time: string; - platform_version: string; -} - -export interface SignalOptions { - channel: string; -} - -/** Where a resync of the MQTT brokers got to */ -export interface PlaceSourceResyncStatus { - state: 'idle' | 'clearing' | 'resyncing' | 'complete' | 'failed'; - /** Whether everything source publishes was removed from the brokers first */ - clear: boolean; - started_at?: string; - finished_at?: string; - /** Retained topics removed, when clearing */ - cleared: number; - /** Models whose metadata was published again */ - metadata: number; - error?: string; -} diff --git a/src/saml-sources/functions.ts b/src/saml-sources/functions.ts deleted file mode 100644 index 6120797c2..000000000 --- a/src/saml-sources/functions.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { PlaceAuthSourceQueryOptions } from '../auth-sources/interfaces'; -import { create, query, remove, show, update } from '../resources/functions'; -import { PlaceSAMLSource } from './saml-source'; - -/** - * @private - */ -const PATH = 'saml_auths'; - -/** Convert raw server data to an SAML source object */ -function process(item: Partial) { - return new PlaceSAMLSource(item); -} - -/** - * Query the available SAML sources - * @param query_params Query parameters to add the to request URL - */ -export function querySAMLSources( - query_params: PlaceAuthSourceQueryOptions = {}, -) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for a SAML source - * @param id ID of the SAML source to retrieve - */ -export function showSAMLSource(id: string) { - return show({ id, query_params: {}, fn: process, path: PATH }); -} - -/** - * Update the SAML source in the database - * @param id ID of the SAML source - * @param form_data New values for the SAML source - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSAMLSource( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new SAML source to the database - * @param form_data SAML source data - * @param query_params Query parameters to add the to request URL - */ -export function addSAMLSource(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a SAML source from the database - * @param id ID of the SAML source - */ -export function removeSAMLSource(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} diff --git a/src/saml-sources/saml-source.ts b/src/saml-sources/saml-source.ts deleted file mode 100644 index d00c51589..000000000 --- a/src/saml-sources/saml-source.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { PlaceResource } from '../resources/resource'; -import { HashMap } from '../utilities/types'; - -export interface PlaceSamlRequestAttribute { - name: string; - name_format: string; - friendly_name: string; -} - -export class PlaceSAMLSource extends PlaceResource { - /** Type of auth source */ - public readonly type = 'saml'; - /** ID of the authority associted with the auth method */ - public readonly authority_id: string; - /** Name of the application requesting auth */ - public readonly issuer: string; - /** - * Mapping of request params that exist during the request - * phase of OmniAuth that should to be sent to the IdP - */ - public readonly idp_sso_target_url_runtime_params: HashMap; - /** Describes the format of the username required by this application */ - public readonly name_identifier_format: string; - /** Attribute that uniquely identifies the user */ - public readonly uid_attribute: string; - /** URL at which the SAML assertion should be received (SSO Service => Place URL) */ - public readonly assertion_consumer_service_url: string; - /** URL to which the authentication request should be sent (Place => SSO Service) */ - public readonly idp_sso_target_url: string; - /** Identity provider's certificate in PEM format (this or fingerprint is required) */ - public readonly idp_cert: string; - /** SHA1 fingerprint of the certificate */ - public readonly idp_cert_fingerprint: string; - /** Name for the attribute service */ - public readonly attribute_service_name: string; - /** Mapping of Attribute Names in a SAMLResponse to entries in the OmniAuth info hash */ - public readonly attribute_statements: HashMap; - /** Mapping of Attribute Names in a SAMLResponse to entries in the OmniAuth info hash */ - public readonly request_attributes: PlaceSamlRequestAttribute[]; - /** URL to which the single logout request and response should be sent */ - public readonly idp_slo_target_url: string; - /** Value to use as default RelayState for single log outs */ - public readonly slo_default_relay_state: string; - - constructor(raw_data: Partial = {}) { - super(raw_data); - this.authority_id = raw_data.authority_id || ''; - this.issuer = raw_data.issuer || ''; - this.idp_sso_target_url_runtime_params = - raw_data.idp_sso_target_url_runtime_params || {}; - this.name_identifier_format = raw_data.name_identifier_format || ''; - this.uid_attribute = raw_data.uid_attribute || ''; - this.assertion_consumer_service_url = - raw_data.assertion_consumer_service_url || ''; - this.idp_sso_target_url = raw_data.idp_sso_target_url || ''; - this.idp_cert = raw_data.idp_cert || ''; - this.idp_cert_fingerprint = raw_data.idp_cert_fingerprint || ''; - this.attribute_service_name = raw_data.attribute_service_name || ''; - this.attribute_statements = raw_data.attribute_statements || {}; - this.request_attributes = raw_data.request_attributes || []; - this.idp_slo_target_url = raw_data.idp_slo_target_url || ''; - this.slo_default_relay_state = raw_data.slo_default_relay_state || ''; - } -} diff --git a/src/settings/functions.ts b/src/settings/functions.ts deleted file mode 100644 index 9e08648b4..000000000 --- a/src/settings/functions.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { HashMap } from '../utilities/types'; -import { - PlaceSettingsHistoryOptions, - PlaceSettingsQueryOptions, -} from './interfaces'; -import { PlaceSettings } from './settings'; - -/** - * @private - */ -const PATH = 'settings'; - -/** Convert raw server data to an settings object */ -function process(item: Partial) { - return new PlaceSettings(item); -} - -/** - * Query the available settings - * @param query_params Query parameters to add the to request URL - */ -export function querySettings(query_params: PlaceSettingsQueryOptions = {}) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for settings - * @param id ID of the settings to retrieve - */ -export function showSettings(id: string) { - return show({ id, query_params: {}, fn: process, path: PATH }); -} - -/** - * Update the settings in the database - * @param id ID of the settings - * @param form_data New values for the settings - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSettings( - id: string, - form_data: Partial, - query_params: HashMap = {}, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new settings to the database - * @param form_data Settings data - * @param query_params Query parameters to add the to request URL - */ -export function addSettings( - form_data: Partial, - query_params: HashMap = {}, -) { - return create({ form_data, query_params, fn: process, path: PATH }); -} - -/** - * Remove settings from the database - * @param id ID of the settings - */ -export function removeSettings(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} - -/** - * Get historical versions of settings - * @param id ID of the settings to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function settingsHistory( - id: string, - query_params: PlaceSettingsHistoryOptions = {}, -) { - return task({ - id, - task_name: 'history', - form_data: query_params, - method: 'get', - callback: (resp: HashMap[]) => resp.map((i) => process(i)), - path: PATH, - }); -} diff --git a/src/settings/interfaces.ts b/src/settings/interfaces.ts deleted file mode 100644 index c8d19e633..000000000 --- a/src/settings/interfaces.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Access level for the settings string */ -export enum EncryptionLevel { - /** Full access to the settings string */ - None = 0, - /** Only support users are allowed to view the settings contents */ - Support = 1, - /** Only admin users are allowed to view the settings contents */ - Admin = 2, - /** Never show the settings contents */ - NeverDisplay = 3, -} - -/** Allowable query parameters for settings index endpoint */ -export interface PlaceSettingsQueryOptions extends PlaceResourceQueryOptions { - /** ID of the parent zone, system, module or driver to grab settings for */ - parent_id?: string; -} - -/** Allowable query parameters for settings history endpoint */ -export interface PlaceSettingsHistoryOptions { - /** Maximum number of results to return */ - limit?: number; - /** Starting offset of the result set for pagination */ - offset?: number; -} diff --git a/src/settings/settings.ts b/src/settings/settings.ts deleted file mode 100644 index 6d75c63af..000000000 --- a/src/settings/settings.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { PlaceResource } from '../resources/resource'; -import { EncryptionLevel } from './interfaces'; - -export class PlaceSettings extends PlaceResource { - /** ID of the parent zone/system/module/driver */ - public readonly parent_id: string; - /** Unix timestamp in seconds of when the settings where last updated */ - public readonly updated_at: number; - /** Access level for the settings data */ - public readonly encryption_level: EncryptionLevel; - /** Contents of the settings */ - public readonly settings_string: string; - /** Top level keys for the parsed settings */ - public readonly keys: string[]; - /** ID of the user that last modified the metadata */ - public readonly modified_by_id: string; - - /** Contents of the settings */ - public get value(): string { - return this.settings_string; - } - - constructor(raw_data: Partial = {}) { - super(raw_data); - this.parent_id = raw_data.parent_id || ''; - this.updated_at = - raw_data.updated_at || Math.floor(new Date().getTime() / 1000); - this.settings_string = raw_data.settings_string || ''; - this.encryption_level = - raw_data.encryption_level || EncryptionLevel.None; - this.keys = raw_data.keys || []; - this.modified_by_id = raw_data.modified_by_id || ''; - } -} diff --git a/src/settings/utilities.ts b/src/settings/utilities.ts deleted file mode 100644 index f42f6c9d7..000000000 --- a/src/settings/utilities.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { startOfMinute, sub } from 'date-fns'; - -/** - * Generate mocked out settings object metadata - * @param overrides Map of overrides for top level keys - */ -export function generateMockSettings(overrides: any = {}) { - if (typeof overrides !== 'object' || !overrides) { - overrides = {}; - } - const parent_types = ['zone', 'sys', 'mod', 'driver']; - const created = sub(startOfMinute(new Date()), { - minutes: Math.floor(Math.random() * 99) * 15, - }).getTime(); - return { - id: `setting-${Math.floor(Math.random() * 999_999_999)}`, - parent_id: `${ - parent_types[Math.floor(Math.random() * parent_types.length)] - }-${Math.floor(Math.random() * 999_999_999)}`, - created_at: Math.floor(created / 1000), - updated_at: Math.floor( - created / 1000 + Math.floor(Math.random() * 20) * 15 * 60, - ), - encryption_level: Math.floor(Math.random() * 4), - settings_string: '', - keys: [], - ...overrides, - }; -} diff --git a/src/short-url/functions.ts b/src/short-url/functions.ts deleted file mode 100644 index 27db769cc..000000000 --- a/src/short-url/functions.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { create, query, remove, show, update } from '../api'; -import { apiEndpoint } from '../auth'; -import { get } from '../http/functions'; -import { toQueryString } from '../utilities/api'; -import { PlaceShortUrl } from './short-url.class'; -import { - PlaceQrCodeOptions, - PlaceShortUrlPngQrOptions, - PlaceShortUrlQueryOptions, -} from './interfaces'; - -/** - * @private - */ -const PATH = 'short_url'; - -/** Convert raw server data to a short URL object */ -function processShortUrl(item: Partial) { - return new PlaceShortUrl(item); -} - -/** - * Query the available short URLs - * @param query_params Query parameters to add to the request URL - */ -export function queryShortUrls(query_params: PlaceShortUrlQueryOptions = {}) { - return query({ - query_params, - fn: processShortUrl, - path: PATH, - }); -} - -/** - * Get the data for a short URL - * @param id ID of the short URL to retrieve - * @param query_params Query parameters to add to the request URL - */ -export function showShortUrl( - id: string, - query_params: Record = {}, -) { - return show({ - id, - query_params, - fn: processShortUrl, - path: PATH, - }); -} - -/** - * Update a short URL in the database - * @param id ID of the short URL - * @param form_data New values for the short URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateShortUrl( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processShortUrl, - path: PATH, - }); -} - -/** - * Add a new short URL to the database - * @param form_data Short URL data - */ -export function addShortUrl(form_data: Partial) { - return create({ - form_data, - query_params: {}, - fn: processShortUrl, - path: PATH, - }); -} - -/** - * Remove a short URL from the database - * @param id ID of the short URL - * @param query_params Query parameters to add to the request URL - */ -export function removeShortUrl( - id: string, - query_params: Record = {}, -) { - return remove({ id, query_params, path: PATH }); -} - -/** - * Get the redirect URL for a short URL. - * Returns the full redirect URL that can be used to navigate to the short URL destination. - * @param id ID of the short URL - */ -export function shortUrlRedirectUrl( - id: string, -): string { - return `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}/redirect`; -} - -/** - * Get an SVG QR code for a short URL - * @param id ID of the short URL - */ -export function getShortUrlQrCodeSvg(id: string) { - return get( - `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}/qr_code.svg`, - { response_type: 'text' }, - ); -} - -/** - * Get the URL for a PNG QR code for a short URL. - * Use this URL directly in an img tag or fetch it separately. - * @param id ID of the short URL - * @param options Options including size (between 72px and 512px) - */ -export function shortUrlQrCodePngUrl( - id: string, - options: PlaceShortUrlPngQrOptions = {}, -): string { - const q = toQueryString(options); - return `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}/qr_code.png${q ? '?' + q : ''}`; -} - -/** - * Get the URL for generating a QR code with user-defined content. - * @param options Options for QR code generation including content, format, and size - */ -export function qrCodeUrl(options: PlaceQrCodeOptions): string { - const { format = 'svg', ...params } = options; - const query_params = { ...params, format }; - const q = toQueryString(query_params); - return `${apiEndpoint()}/${PATH}/qr_code${q ? '?' + q : ''}`; -} - -/** - * Generate an SVG QR code with user-defined content. - * For PNG format, use qrCodeUrl() and fetch the URL directly. - * @param options Options for QR code generation including content and size - */ -export function generateQrCode(options: Omit) { - const query_params = { ...options, format: 'svg' }; - const q = toQueryString(query_params); - return get(`${apiEndpoint()}/${PATH}/qr_code${q ? '?' + q : ''}`, { - response_type: 'text', - }); -} diff --git a/src/short-url/interfaces.ts b/src/short-url/interfaces.ts deleted file mode 100644 index af2a98bad..000000000 --- a/src/short-url/interfaces.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Mapping of available query parameters for the short_url index endpoint */ -export interface PlaceShortUrlQueryOptions extends PlaceResourceQueryOptions {} - -/** Format options for QR code generation */ -export type QrCodeFormat = 'svg' | 'png'; - -/** Options for generating a QR code with custom content */ -export interface PlaceQrCodeOptions { - /** The contents of the QR code (required) */ - content: string; - /** Identifier for the QR code (required) */ - id: string; - /** File format of the response */ - format?: QrCodeFormat; - /** Size of the QR code in pixels (between 72px and 512px) */ - size?: number; -} - -/** Options for generating a PNG QR code for a short URL */ -export interface PlaceShortUrlPngQrOptions { - /** Size of the QR code in pixels (between 72px and 512px) */ - size?: number; -} diff --git a/src/short-url/short-url.class.ts b/src/short-url/short-url.class.ts deleted file mode 100644 index aa6c49ed9..000000000 --- a/src/short-url/short-url.class.ts +++ /dev/null @@ -1,33 +0,0 @@ -export class PlaceShortUrl { - readonly id: string; - readonly name: string; - readonly uri: string; - readonly description: string; - readonly user_id: string; - readonly user_email: string; - readonly user_name: string; - readonly redirect_count: number; - readonly enabled: boolean; - readonly valid_from: string; - readonly valid_until: string; - readonly authority_id: string; - readonly created_at: number; - readonly updated_at: number; - - constructor(data: Partial) { - this.id = data.id || ''; - this.name = data.name || ''; - this.uri = data.uri || ''; - this.description = data.description || ''; - this.user_id = data.user_id || ''; - this.user_email = data.user_email || ''; - this.user_name = data.user_name || ''; - this.redirect_count = data.redirect_count || 0; - this.enabled = data.enabled ?? true; - this.valid_from = data.valid_from || ''; - this.valid_until = data.valid_until || ''; - this.authority_id = data.authority_id || ''; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - } -} diff --git a/src/signage/ai/functions.ts b/src/signage/ai/functions.ts deleted file mode 100644 index 7d7c38cb0..000000000 --- a/src/signage/ai/functions.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { query, remove, show } from '../../api'; -import { apiEndpoint } from '../../auth'; -import { patch, post, put } from '../../http/functions'; -import { HttpJsonOptions } from '../../http/interfaces'; -import { task } from '../../resources/functions'; -import { HashMap } from '../../utilities/types'; -import { - SignageAICapabilities, - SignageAIClaimRequest, - SignageAIEditRequest, - SignageAIGenerateRequest, - SignageAIJob, - SignageAIJobQueryOptions, - SignageAIJobShowOptions, - SignageAIProvider, - SignageAIProviderQueryOptions, - SignageAIProviderRequest, - SignageAIProviderTestResult, - SignageAIUsageOptions, - SignageAIUsageRow, -} from './interfaces'; - -/** - * @private - */ -const PATH = 'signage/ai'; - -/** - * @private - */ -const JOBS_PATH = 'signage/ai/jobs'; - -/** - * @private - */ -const PROVIDERS_PATH = 'signage/ai/providers'; - -/** - * Get what image generation can do on the current domain, and what the caller - * has left of their image allowance - */ -export function signageAICapabilities() { - return show({ - id: 'capabilities', - query_params: {}, - fn: (response) => response as SignageAICapabilities, - path: PATH, - }); -} - -/** - * Start generating an image from a brief. Answers as soon as the job is - * accepted, long poll `showSignageAIJob` for the candidates - * @param request Brief and generation settings - */ -export function generateSignageImage(request: SignageAIGenerateRequest) { - return post(`${apiEndpoint()}/${PATH}/generate`, request).then( - (response) => response as unknown as SignageAIJob, - ); -} - -/** - * Start editing an existing image, or refining an earlier job. Answers as soon - * as the job is accepted, long poll `showSignageAIJob` for the candidates - * @param request Instruction, source image and generation settings - */ -export function editSignageImage(request: SignageAIEditRequest) { - return post(`${apiEndpoint()}/${PATH}/edit`, request).then( - (response) => response as unknown as SignageAIJob, - ); -} - -/** - * Get an image generation job, optionally holding the request open until the - * job changes. - * - * Pass `{ skip_auth_flow: true }` as `options` to stop a failed poll being - * retried four times before it rejects - * @param id ID of the job - * @param query_params Query parameters to add the to request URL - * @param options Options to add to the request - */ -export function showSignageAIJob( - id: string, - query_params: SignageAIJobShowOptions = {}, - options?: HttpJsonOptions, -) { - return show({ - id, - query_params, - fn: (response) => response as SignageAIJob, - path: JOBS_PATH, - options, - }); -} - -/** - * List recent image generation jobs, for the recent generations list. - * @param query_params Query parameters to add the to request URL - */ -export function querySignageAIJobs( - query_params: SignageAIJobQueryOptions = {}, -) { - return show({ - id: 'jobs', - query_params, - fn: (response) => response as SignageAIJob[], - path: PATH, - }); -} - -/** - * Ask a running job to stop. Candidates already with the vendor run to - * completion, so the returned job may still gain images - * @param id ID of the job - */ -export function cancelSignageAIJob(id: string) { - return task({ - id, - task_name: 'cancel', - method: 'post', - path: JOBS_PATH, - callback: (response) => response as SignageAIJob, - }); -} - -/** - * Record that a candidate was kept as a media item, so the sweep that clears - * unused candidates leaves it alone - * @param id ID of the job the candidate belongs to - * @param request The candidate's upload and the media item now using it - */ -export function claimSignageAIImage( - id: string, - request: SignageAIClaimRequest, -) { - return task({ - id, - task_name: 'claim', - form_data: request, - method: 'post', - path: JOBS_PATH, - callback: (response) => response as SignageAIJob, - }); -} - -/** - * Get image generation spend for the current domain, broken down by provider - * and model - * @param query_params Query parameters to add the to request URL - */ -export function signageAIUsage(query_params: SignageAIUsageOptions = {}) { - return show({ - id: 'usage', - query_params, - fn: (response) => response as SignageAIUsageRow[], - path: PATH, - }); -} - -/** Convert raw server data to an AI provider object */ -function processProvider(item: Partial) { - return item as SignageAIProvider; -} - -/** - * Query the configured AI providers - * @param query_params Query parameters to add the to request URL - */ -export function querySignageAIProviders( - query_params: SignageAIProviderQueryOptions = {}, -) { - return query({ - query_params, - fn: processProvider, - path: PROVIDERS_PATH, - }); -} - -/** - * Get the details of an AI provider - * @param id ID of the provider - */ -export function showSignageAIProvider(id: string) { - return show({ - id, - query_params: {}, - fn: processProvider, - path: PROVIDERS_PATH, - }); -} - -/** - * Add a new AI provider - * @param form_data Provider details, including the vendor credentials - */ -export function addSignageAIProvider(form_data: SignageAIProviderRequest) { - return post(`${apiEndpoint()}/${PROVIDERS_PATH}`, form_data).then( - (response) => response as unknown as SignageAIProvider, - ); -} - -/** - * Update an AI provider. Leaving `credentials` out keeps the stored value. - * @param id ID of the provider - * @param form_data New values for the provider - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSignageAIProvider( - id: string, - form_data: SignageAIProviderRequest, - method: 'put' | 'patch' = 'patch', -) { - return (method === 'put' ? put : patch)( - `${apiEndpoint()}/${PROVIDERS_PATH}/${id}`, - form_data, - ).then((response: HashMap) => response as unknown as SignageAIProvider); -} - -/** - * Remove an AI provider. Jobs it produced keep the vendor and model they - * recorded - * @param id ID of the provider - */ -export function removeSignageAIProvider(id: string) { - return remove({ id, query_params: {}, path: PROVIDERS_PATH }); -} - -/** - * Prove an AI provider's credentials work by generating one small image and - * discarding it - * @param id ID of the provider - */ -export function testSignageAIProvider(id: string) { - return task({ - id, - task_name: 'test', - method: 'post', - path: PROVIDERS_PATH, - callback: (response) => response as SignageAIProviderTestResult, - }); -} diff --git a/src/signage/ai/interfaces.ts b/src/signage/ai/interfaces.ts deleted file mode 100644 index 1ce0ab7a2..000000000 --- a/src/signage/ai/interfaces.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { PlaceResourceQueryOptions } from '../../resources/interface'; - -/** Vendors an AI provider row can be pointed at */ -export type SignageAIProviderType = 'OPENAI' | 'AZURE_OPENAI' | 'GOOGLE_VERTEX'; - -/** Lifecycle of an image generation job */ -export type SignageAIJobState = - | 'queued' - | 'running' - | 'done' - | 'failed' - | 'cancelled'; - -/** Whether a job started from a prompt alone or from an existing image */ -export type SignageAIJobKind = 'generate' | 'edit'; - -/** What a single model on a provider is able to do */ -export interface SignageAIModelCapabilities { - /** Vendor identifier for the model, sent back as `model` on a request */ - id: string; - /** Display name for the model */ - name: string; - /** Model can create an image from a prompt alone */ - generate: boolean; - /** Model can edit a supplied source image */ - edit: boolean; - /** Model can enhance an image without a new brief */ - enhance: boolean; - /** Maximum number of reference images accepted in one request */ - max_references: number; - /** Maximum number of candidates the model will return in one request */ - max_candidates: number; - /** Quality levels the model accepts */ - qualities: string[]; - /** Aspect ratios the model accepts */ - aspect_ratios: string[]; -} - -/** A configured provider as seen by a user, without its credentials */ -export interface SignageAIProviderCapabilities { - /** ID of the provider row */ - id: string; - /** Display name for the provider */ - name: string; - /** Vendor the provider talks to */ - provider: SignageAIProviderType; - /** Vendor region the provider is deployed in, when it has one */ - region?: string; - /** Model used when a request does not name one */ - default_model?: string; - /** Models available on this provider */ - models: SignageAIModelCapabilities[]; -} - -/** Images the caller has left of their allowance. `null` when the feature is off */ -export interface SignageAIQuota { - /** Candidates the current user may still request today */ - user_remaining_today: number | null; - /** Candidates the current domain may still request this month */ - domain_remaining_month: number | null; -} - -/** What image generation can do on the current domain, and for the current user */ -export interface SignageAICapabilities { - /** Whether image generation can be used at all */ - enabled: boolean; - /** Why the feature is unavailable. Only set when `enabled` is false */ - reason?: string; - /** Providers configured for this domain */ - providers: SignageAIProviderCapabilities[]; - /** ID of the provider used when a request does not name one */ - default_provider_id?: string; - /** Aspect ratios accepted across the platform */ - aspect_ratios: string[]; - /** Quality levels accepted across the platform */ - qualities: string[]; - /** Most candidates that may be asked for in one request */ - max_candidates: number; - /** Whether the domain has a logo that can be composited over a generated image */ - logo_layer: boolean; - /** Remaining allowance for the caller and their domain */ - quota: SignageAIQuota; -} - -/** - * One candidate produced by a job. Slots are `null` in `SignageAIJob.images` - * until the candidate for that slot lands - */ -export interface SignageAIImage { - /** State of the candidate */ - state: string; - /** Position of the candidate in the job's image list */ - index: number; - /** ID of the upload holding the image */ - upload_id: string; - /** Endpoint returning a signed URL for the image */ - url: string; - /** Width of the image in pixels, when it could be read */ - width: number | null; - /** Height of the image in pixels, when it could be read */ - height: number | null; - /** Content type of the stored image */ - mime: string; - /** Size of the stored image in bytes */ - bytes: number; - /** ID of the media item the candidate was kept as. Set by claiming the image */ - item_id?: string; -} - -/** An image generation or edit job */ -export interface SignageAIJob { - /** ID of the job */ - id: string; - /** Lifecycle state of the job */ - state: SignageAIJobState; - /** Whether the job generates or edits */ - kind: SignageAIJobKind; - /** Vendor the job was sent to */ - provider?: SignageAIProviderType; - /** Model the job was sent to */ - model?: string; - /** Number of candidates asked for */ - candidates: number; - /** Number of candidates that have landed so far */ - images_produced: number; - /** ID of the job this one refines, when it is a refine */ - parent_job_id?: string; - /** - * Bumped on every change to the job. Pass it back as `since` when long - * polling so the request only returns once something new has landed - */ - version: number; - /** Brief the user asked for */ - prompt?: string; - /** Candidate slots in order, `null` until that candidate lands */ - images: (SignageAIImage | null)[]; - /** Class of failure, when the job failed */ - error_kind?: string; - /** Description of the failure, when the job failed */ - error_message?: string; - /** Vendor spend attributed to the job */ - cost_units?: number; - /** Time the job took, in milliseconds */ - latency_ms?: number; - /** Unix epoch in seconds at which the job was accepted */ - created_at?: number; - /** Unix epoch in seconds at which the job stopped */ - finished_at?: number; -} - -/** Body of a request to generate an image from a brief */ -export interface SignageAIGenerateRequest { - /** What the image should show. Required */ - prompt: string; - /** Shape of the image. Defaults to `16:9` */ - aspect_ratio?: string; - /** Quality level to ask the vendor for. Defaults to `standard` */ - quality?: string; - /** Number of candidates to produce. Clamped to the platform maximum */ - candidates?: number; - /** IDs of uploads to hand the vendor as visual references */ - references?: string[]; - /** Composite the domain logo over the result. Defaults to `true` */ - include_logo?: boolean; - /** Keep wording out of the image so it can be laid over. Defaults to `true` */ - add_text_with_layer?: boolean; - /** Apply the organisation's colours, face and tone. Defaults to `true` */ - use_branding?: boolean; - /** Wording the image is being made for, used to leave room for it */ - words?: string; - /** Provider to use. Defaults to the domain's default provider */ - provider_id?: string; - /** Model to use. Defaults to the provider's default model */ - model?: string; - /** Signage group the caller is acting in. Required unless the caller is support */ - group_id?: string; - /** Repeating a key returns the job it first created rather than spending again */ - idempotency_key?: string; -} - -/** Body of a request to edit an existing image, or refine an earlier job */ -export interface SignageAIEditRequest extends SignageAIGenerateRequest { - /** ID of the upload to edit. Required */ - source_upload_id: string; - /** Media item proving the caller may read a source they do not own */ - source_item_id?: string; - /** ID of the job being refined, so its brief carries into the new prompt */ - parent_job_id?: string; -} - -/** Body of a request recording that a candidate became a media item */ -export interface SignageAIClaimRequest { - /** ID of the candidate's upload */ - upload_id: string; - /** ID of the media item now using the upload */ - item_id: string; -} - -/** Allowable query parameters for the AI job show endpoint */ -export interface SignageAIJobShowOptions { - /** - * Seconds to hold the request open until the job changes, up to `25`. - * Defaults to `0`, which answers immediately - */ - wait?: number; - /** Version the caller already holds. Defaults to the job's current version */ - since?: number; -} - -/** Allowable query parameters for the AI jobs index endpoint */ -export interface SignageAIJobQueryOptions { - /** Only return the caller's own jobs. Defaults to `true` */ - mine?: boolean; - /** Number of jobs to return. Clamped to `100`. Defaults to `20` */ - limit?: number; -} - -/** Allowable query parameters for the AI usage endpoint */ -export interface SignageAIUsageOptions { - /** Unix epoch in seconds to report from. Defaults to 30 days ago */ - from?: number; - /** Unix epoch in seconds to report to. Defaults to now */ - to?: number; -} - -/** Spend on one provider and model over the reported period */ -export interface SignageAIUsageRow { - /** Vendor the jobs were sent to */ - provider: string; - /** Model the jobs were sent to */ - model: string; - /** Number of jobs */ - jobs: number; - /** Candidates asked for across those jobs */ - candidates: number; - /** Candidates that landed across those jobs */ - images_produced: number; - /** Vendor spend attributed to those jobs */ - cost_units: number; -} - -/** A stored provider row. Credentials are never returned */ -export interface SignageAIProvider { - /** ID of the provider row */ - id: string; - /** Display name for the provider */ - name: string; - /** Vendor the provider talks to */ - provider: SignageAIProviderType; - /** Domain the row belongs to, set by the server. `null` on the shared row */ - authority_id: string | null; - /** Vendor endpoint, for deployments that have their own */ - endpoint: string | null; - /** Vendor region, for deployments that have one */ - location: string | null; - /** Model used when a request does not name one */ - default_model: string | null; - /** Models this row may be asked for. Empty allows every model the vendor offers */ - allowed_models: string[]; - /** Whether the row may be used */ - enabled: boolean; - /** Whether the row is the default for its domain */ - is_default: boolean; - /** Per user and per domain image allowances */ - quotas: Record; - /** Unix epoch in seconds at which the row was created */ - created_at: number; - /** Unix epoch in seconds at which the row was last changed */ - updated_at: number; -} - -/** - * Body of a request creating or updating a provider row. `credentials` is - * required on create; left out of an update the stored value is kept - */ -export interface SignageAIProviderRequest { - /** Display name for the provider */ - name?: string; - /** Vendor the provider talks to */ - provider?: SignageAIProviderType; - /** Domain for the provider. The server uses the current authority on create */ - authority_id?: string; - /** Vendor credentials, in the shape that vendor expects */ - credentials?: Record; - /** Vendor endpoint, for deployments that have their own */ - endpoint?: string; - /** Vendor region, for deployments that have one */ - location?: string; - /** Model used when a request does not name one */ - default_model?: string; - /** Models this row may be asked for */ - allowed_models?: string[]; - /** Whether the row may be used */ - enabled?: boolean; - /** Whether the row is the default for its domain */ - is_default?: boolean; - /** Per user and per domain image allowances */ - quotas?: Record; -} - -/** - * Allowable query parameters for the AI providers index endpoint. - */ -export interface SignageAIProviderQueryOptions - extends PlaceResourceQueryOptions { - /** Include the shared fallback row. Defaults to `true` */ - include_shared?: boolean; -} - -/** Outcome of proving a provider row's credentials work */ -export interface SignageAIProviderTestResult { - /** Whether the vendor answered with an image */ - ok: boolean; - /** Time the vendor took, in milliseconds */ - latency_ms: number; - /** Model the test was run against */ - model?: string; - /** Description of the failure, when the test failed */ - error?: string; - /** Class of failure, when the test failed */ - kind?: string; -} diff --git a/src/signage/functions.ts b/src/signage/functions.ts deleted file mode 100644 index 2d413b552..000000000 --- a/src/signage/functions.ts +++ /dev/null @@ -1,723 +0,0 @@ -import { create, query, remove, show, update } from '../api'; -import { apiEndpoint } from '../auth'; -import { del, patch, post } from '../http/functions'; -import { HttpJsonOptions } from '../http/interfaces'; -import { task } from '../resources/functions'; -import { toQueryString } from '../utilities/api'; -import { - SignageCreateOptions, - SignageDisplayOptions, - SignageMediaQueryOptions, - SignageMediaTagRemoveOptions, - SignageMediaTagRenameOptions, - SignageMediaTagsOptions, - SignageMetrics, - SignagePlaylistApprover, - SignagePlaylistQueryOptions, - SignagePlaylistRevisionsOptions, - SignagePluginQueryOptions, - SignageRemoveOptions, - SignageShareOptions, - SignageShareResult, - SignageTemplateApprover, - SignageTemplateMappingQueryOptions, - SignageTemplateQueryOptions, - SignageTemplateShowOptions, -} from './interfaces'; -import { SignageMedia } from './media.class'; -import { - SignagePlaylist, - SignagePlaylistItemSchedule, - SignagePlaylistMedia, -} from './playlist.class'; -import { SignagePlugin } from './plugin.class'; -import { SignageTemplate, SignageTemplateMapping } from './template.class'; - -/** - * @private - */ -const PATH = 'signage'; - -/** - * Get all the details needed to display signage on a system - * @param id ID of the system to display signage for - * @param query_params Query parameters to add the to request URL - */ -export function showSignage( - id: string, - query_params: SignageDisplayOptions = {}, - options?: HttpJsonOptions, -) { - return show({ id, query_params, fn: (r) => r, path: `${PATH}`, options }); -} - -/** - * Post the playback metrics collected by a production player - * @param id ID of the system the player is running on - * @param metrics Playback counts collected since the last update - */ -export function updateSignageMetrics(id: string, metrics: SignageMetrics) { - return task({ - id, - task_name: `metrics`, - form_data: metrics, - method: 'post', - path: PATH, - }); -} - -/** - * @private - */ -const MEDIA_PATH = 'signage/media'; - -/** Convert raw server data to an signagemedia object */ -function processMedia(item: Partial) { - return new SignageMedia(item); -} - -/** - * Query the available media - * @param query_params Query parameters to add the to request URL - */ -export function querySignageMedia(query_params: SignageMediaQueryOptions = {}) { - return query({ query_params, fn: processMedia, path: MEDIA_PATH }); -} - -/** List the distinct tags in use by signage media */ -export function listSignageMediaTags( - query_params: SignageMediaTagsOptions = {}, -) { - return show({ - id: 'tags', - query_params, - fn: (i) => i as string[], - path: MEDIA_PATH, - }); -} - -/** List the distinct tags in use by signage media, with the count of media using each */ -export function listSignageMediaTagCounts( - query_params: SignageMediaTagsOptions = {}, -) { - return show>({ - id: 'tag_counts', - query_params, - fn: (i) => i as Record, - path: MEDIA_PATH, - }); -} - -/** Rename a tag on all signage media in the selected scope */ -export function renameSignageMediaTag( - query_params: SignageMediaTagRenameOptions, -): Promise { - const q = toQueryString(query_params); - return patch( - `${apiEndpoint()}/${MEDIA_PATH}/tags?${q}`, - {}, - { - response_type: 'void', - }, - ); -} - -/** Remove a tag, or remove tagged media, in the selected scope */ -export function removeSignageMediaTag( - query_params: SignageMediaTagRemoveOptions, -): Promise { - const q = toQueryString(query_params); - return del(`${apiEndpoint()}/${MEDIA_PATH}/tags?${q}`, { - response_type: 'void', - }); -} - -/** - * Get the data for a media item - * @param id ID of the media item to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showSignageMedia( - id: string, - query_params: SignageMediaQueryOptions = {}, -) { - return show({ id, query_params, fn: processMedia, path: MEDIA_PATH }); -} - -/** - * Update the media item in the database - * @param id ID of the media item - * @param form_data New values for the media item - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSignageMedia( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processMedia, - path: MEDIA_PATH, - }); -} - -/** - * Add a new media item to the database - * @param form_data Media item data - * @param query_params Query parameters to add the to request URL - */ -export function addSignageMedia( - form_data: Partial, - query_params: SignageCreateOptions = {}, -) { - return create({ - form_data, - query_params, - fn: processMedia, - path: MEDIA_PATH, - }); -} - -/** - * Remove a media item from the library, or unlink it from a single group - * when `group_id` is set - * @param id ID of the media item - * @param query_params Query parameters to add the to request URL - */ -export function removeSignageMedia( - id: string, - query_params: SignageRemoveOptions = {}, -) { - return remove({ id, query_params, path: MEDIA_PATH }); -} - -/** - * Get the thumbnail URL for a media item. - * This is the endpoint resolves to the image for the media item's thumbnail. - */ -export function mediaThumbnail(id: string): string { - return `${apiEndpoint()}/${MEDIA_PATH}/${id}/thumbnail`; -} - -/** Share one or more media items into another signage group */ -export function shareSignageMedia(query_params: SignageShareOptions) { - const q = toQueryString(query_params); - return post( - `${apiEndpoint()}/${MEDIA_PATH}/share${q ? '?' + q : ''}`, - {}, - ).then((response) => response as unknown as SignageShareResult); -} - -/** - * @private - */ -const PLAYLISTS_PATH = 'signage/playlists'; - -/** Convert raw server data to an playlist object */ -function processPlaylist(item: Partial) { - return new SignagePlaylist(item); -} - -function processPlaylistMedia(item: Partial) { - return new SignagePlaylistMedia(item); -} - -function processPlaylistItemSchedule( - item: Partial, -) { - return new SignagePlaylistItemSchedule(item); -} - -/** - * Query the available playlists - * @param query_params Query parameters to add the to request URL - */ -export function querySignagePlaylists( - query_params: SignagePlaylistQueryOptions = {}, -) { - return query({ query_params, fn: processPlaylist, path: PLAYLISTS_PATH }); -} - -/** - * Get the data for a playlist - * @param id ID of the playlist to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showSignagePlaylist( - id: string, - query_params: SignagePlaylistQueryOptions = {}, -) { - return show({ - id, - query_params, - fn: processPlaylist, - path: PLAYLISTS_PATH, - }); -} - -/** - * Update the playlist in the database - * @param id ID of the playlist - * @param form_data New values for the playlist - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSignagePlaylist( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processPlaylist, - path: PLAYLISTS_PATH, - }); -} - -/** - * Add a new playlist to the database - * @param form_data Playlist data - * @param query_params Query parameters to add the to request URL - */ -export function addSignagePlaylist( - form_data: Partial, - query_params: SignageCreateOptions = {}, -) { - return create({ - form_data, - query_params, - fn: processPlaylist, - path: PLAYLISTS_PATH, - }); -} - -/** - * Remove an playlist from the database - * @param id ID of the playlist - * @param query_params Query parameters to add the to request URL - */ -export function removeSignagePlaylist( - id: string, - query_params: SignageRemoveOptions = {}, -) { - return remove({ id, query_params, path: PLAYLISTS_PATH }); -} - -/** - * Get the current revision of the media list for a playlist - * @param id ID of the playlist - */ -export function listSignagePlaylistMedia(id: string) { - return task({ - id, - task_name: 'media', - form_data: {}, - method: 'get', - callback: processPlaylistMedia, - path: PLAYLISTS_PATH, - }); -} - -/** - * List all versions of the media lists for a playlist - * @param id ID of the playlist - * @param query_params Query parameters to add the to request URL - */ -export function listSignagePlaylistMediaRevisions( - id: string, - query_params: SignagePlaylistRevisionsOptions = {}, -) { - return task({ - id, - task_name: 'media/revisions', - form_data: query_params, - method: 'get', - callback: (list: SignagePlaylistMedia[]) => - list.map(processPlaylistMedia), - path: PLAYLISTS_PATH, - }); -} - -/** - * Approve the latest revision of the media list for a playlist - * @param id ID of the playlist to approve - */ -export function approveSignagePlaylist(id: string) { - return task({ - id, - task_name: 'media/approve', - method: 'post', - path: PLAYLISTS_PATH, - }); -} - -/** - * Request an approval for the latest revision of the media list for a playlist - * @param id ID of the playlist to approve - * @param group_id ID of the user group to message for approvals - * @param message Optional message to send to the approver - */ -export function requestApprovalSignagePlaylist( - id: string, - group_id: string, - message: string = '', - approver_id: string = '', -) { - const q = toQueryString({ group_id, approver_id }); - return task({ - id, - task_name: `media/request_approval${q ? '?' + q : ''}`, - method: 'post', - path: PLAYLISTS_PATH, - form_data: { message }, - }); -} - -/** - * List the approvers for the selected group of media list for a playlist - * @param group_id ID of the user group to list approvers for - */ -export function listSignagePlaylistApprovers(group_id: string) { - return show({ - id: 'approvers', - query_params: { group_id }, - fn: (r) => { - return r as SignagePlaylistApprover[]; - }, - path: PLAYLISTS_PATH, - }); -} - -/** - * Update the media for a playlist - * @param id ID of the playlist - * @param form_data New list of media IDs for the playlist - */ -export function updateSignagePlaylistMedia(id: string, form_data: string[]) { - return task({ - id, - task_name: 'media', - form_data, - method: 'post', - path: PLAYLISTS_PATH, - callback: processPlaylistMedia, - }); -} - -/** Add scheduled media to a distribution playlist */ -export function scheduleSignagePlaylistMedia( - id: string, - form_data: Partial, -) { - return task({ - id, - task_name: 'media/schedule', - form_data, - method: 'post', - path: PLAYLISTS_PATH, - callback: processPlaylistMedia, - }); -} - -/** Update scheduled media on a playlist */ -export function updateSignagePlaylistMediaSchedule( - id: string, - item_id: string, - form_data: Partial, -) { - return patch( - `${apiEndpoint()}/${PLAYLISTS_PATH}/${id}/media/schedule/${item_id}`, - form_data, - ).then(processPlaylistItemSchedule); -} - -/** Share one or more playlists into another signage group */ -export function shareSignagePlaylists(query_params: SignageShareOptions) { - const q = toQueryString(query_params); - return post( - `${apiEndpoint()}/${PLAYLISTS_PATH}/share${q ? '?' + q : ''}`, - {}, - ).then((response) => response as unknown as SignageShareResult); -} - -/** - * @private - */ -const PLUGINS_PATH = 'signage/plugins'; - -/** Convert raw server data to a signage plugin object */ -function processPlugin(item: Partial) { - return new SignagePlugin(item); -} - -/** - * Query the available signage plugins - * @param query_params Query parameters to add the to request URL - */ -export function querySignagePlugins( - query_params: SignagePluginQueryOptions = {}, -) { - return query({ query_params, fn: processPlugin, path: PLUGINS_PATH }); -} - -/** - * Get the data for a signage plugin - * @param id ID of the signage plugin to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showSignagePlugin( - id: string, - query_params: SignagePluginQueryOptions = {}, -) { - return show({ - id, - query_params, - fn: processPlugin, - path: PLUGINS_PATH, - }); -} - -/** - * Update the signage plugin in the database - * @param id ID of the signage plugin - * @param form_data New values for the signage plugin - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSignagePlugin( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processPlugin, - path: PLUGINS_PATH, - }); -} - -/** - * Add a new signage plugin to the database - * @param form_data Signage plugin data - */ -export function addSignagePlugin(form_data: Partial) { - return create({ - form_data, - query_params: {}, - fn: processPlugin, - path: PLUGINS_PATH, - }); -} - -/** - * Remove a signage plugin from the database - * @param id ID of the signage plugin - * @param query_params Query parameters to add the to request URL - */ -export function removeSignagePlugin( - id: string, - query_params: Record = {}, -) { - return remove({ id, query_params, path: PLUGINS_PATH }); -} - -/** - * @private - */ -const TEMPLATES_PATH = 'signage/templates'; - -/** Convert raw server data to a signage template object */ -function processTemplate(item: Partial) { - return new SignageTemplate(item); -} - -/** Query the approved signage templates available to the current authority */ -export function querySignageTemplates( - query_params: SignageTemplateQueryOptions = {}, -) { - return query({ query_params, fn: processTemplate, path: TEMPLATES_PATH }); -} - -/** Get a signage template, resolving a pending draft by default */ -export function showSignageTemplate( - id: string, - query_params: SignageTemplateShowOptions = {}, -) { - return show({ - id, - query_params, - fn: processTemplate, - path: TEMPLATES_PATH, - }); -} - -/** Add a new signage template */ -export function addSignageTemplate( - form_data: Partial, - query_params: SignageCreateOptions = {}, -) { - return create({ - form_data, - query_params, - fn: processTemplate, - path: TEMPLATES_PATH, - }); -} - -/** Update a signage template */ -export function updateSignageTemplate( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processTemplate, - path: TEMPLATES_PATH, - }); -} - -/** - * Remove a signage template, or unlink it from a single group when - * `group_id` is set. Pending drafts and group links cascade - */ -export function removeSignageTemplate( - id: string, - query_params: SignageRemoveOptions = {}, -) { - return remove({ id, query_params, path: TEMPLATES_PATH }); -} - -/** Discard the pending draft for a signage template */ -export function removeSignageTemplateDraft(id: string) { - return task({ - id, - task_name: 'draft', - method: 'del', - path: TEMPLATES_PATH, - }); -} - -/** Share one or more templates into another signage group */ -export function shareSignageTemplates(query_params: SignageShareOptions) { - const q = toQueryString(query_params); - return post( - `${apiEndpoint()}/${TEMPLATES_PATH}/share${q ? '?' + q : ''}`, - {}, - ).then((response) => response as unknown as SignageShareResult); -} - -/** Approve the pending changes for a signage template */ -export function approveSignageTemplate(id: string) { - return task({ - id, - task_name: 'approve', - method: 'post', - path: TEMPLATES_PATH, - callback: processTemplate, - }); -} - -/** List users who can approve signage templates for a group */ -export function listSignageTemplateApprovers(group_id: string) { - return show({ - id: 'approvers', - query_params: { group_id }, - fn: (response) => response as SignageTemplateApprover[], - path: TEMPLATES_PATH, - }); -} - -/** Request approval for a signage template's pending changes */ -export function requestApprovalSignageTemplate( - id: string, - group_id: string, - message: string = '', - approver_id?: string, -) { - const q = toQueryString({ group_id, approver_id }); - return task({ - id, - task_name: `request_approval${q ? '?' + q : ''}`, - method: 'post', - path: TEMPLATES_PATH, - form_data: { message }, - }); -} - -/** - * @private - */ -const TEMPLATE_MAPPINGS_PATH = 'signage/template_mappings'; - -/** Convert raw server data to a signage template mapping object */ -function processTemplateMapping(item: Partial) { - return new SignageTemplateMapping(item); -} - -/** Query signage template mappings in the current authority */ -export function querySignageTemplateMappings( - query_params: SignageTemplateMappingQueryOptions = {}, -) { - return query({ - query_params, - fn: processTemplateMapping, - path: TEMPLATE_MAPPINGS_PATH, - }); -} - -/** Get the details of a signage template mapping */ -export function showSignageTemplateMapping(id: string) { - return show({ - id, - query_params: {}, - fn: processTemplateMapping, - path: TEMPLATE_MAPPINGS_PATH, - }); -} - -/** Apply a signage template to a display or zone */ -export function addSignageTemplateMapping( - form_data: Partial, -) { - return create({ - form_data, - query_params: {}, - fn: processTemplateMapping, - path: TEMPLATE_MAPPINGS_PATH, - }); -} - -/** Update the schedule of a signage template mapping */ -export function updateSignageTemplateMapping( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processTemplateMapping, - path: TEMPLATE_MAPPINGS_PATH, - }); -} - -/** Remove a signage template mapping */ -export function removeSignageTemplateMapping(id: string) { - return remove({ id, query_params: {}, path: TEMPLATE_MAPPINGS_PATH }); -} diff --git a/src/signage/interfaces.ts b/src/signage/interfaces.ts deleted file mode 100644 index 993dbd410..000000000 --- a/src/signage/interfaces.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; -import { SignagePluginType } from './plugin.class'; - -export interface SignageMetrics { - play_through_counts: Record; - playlist_counts: Record; - media_counts: Record; -} - -export interface SignagePlaylistSchedule { - readonly play_cron: string; - readonly play_period: number; - /** One-off play time as unix epoch seconds. Do not set with `play_at_local` */ - readonly play_at?: number; - /** - * One-off play time in the local timezone of the display. - * ISO 8601 with no offset, e.g. `2027-01-01T00:00:00`. Do not set with `play_at` - */ - readonly play_at_local?: string; - readonly play_takeover: boolean; - /** Unix epoch seconds this schedule becomes valid. Required when `mask` is set */ - readonly valid_from?: number; - /** Ignore when not truthy */ - readonly valid_until?: number; - /** - * Bitmask of `0`s and `1`s (max 128 chars). Active when not empty. - * Requires `valid_from` - */ - readonly mask?: string; -} - -export interface SignagePlaylistApprover { - id: string; - name: string; -} - -/** Allowable query parameters for the signage display endpoint */ -export interface SignageDisplayOptions { - /** ID of the currently playing item, if the player is playing content */ - item_id?: string; - /** Ignore state changes to the display. Used by the preview player */ - preview?: boolean; -} - -/** Allowable query parameters for signage media index endpoint */ -export interface SignageMediaQueryOptions extends PlaceResourceQueryOptions { - /** ID of the group to scope media to */ - group_id?: string; - /** Return media carrying any of these tags */ - tags?: string[] | string; -} - -/** Allowable query parameters for the signage media tag endpoints */ -export interface SignageMediaTagsOptions { - /** ID of the group to scope media tags to */ - group_id?: string; -} - -/** Allowable query parameters when creating signage content */ -export interface SignageCreateOptions { - /** Group to link the new item to */ - group_id?: string; -} - -/** Query parameters for renaming a signage media tag */ -export interface SignageMediaTagRenameOptions extends SignageMediaTagsOptions { - /** Existing tag name */ - current_tag: string; - /** Replacement tag name */ - new_tag: string; -} - -/** Query parameters for removing a signage media tag */ -export interface SignageMediaTagRemoveOptions extends SignageMediaTagsOptions { - /** Tag name to remove */ - tag: string; - /** Remove tagged media instead of removing the tag from each item */ - remove_media?: boolean; -} - -/** Allowable query parameters when removing a media item or template */ -export interface SignageRemoveOptions { - /** - * Unlink the item from this group instead of deleting it outright. - * Requires `Delete` or `Manage` permission on the group - */ - group_id?: string; -} - -/** Allowable query parameters for signage playlists index endpoint */ -export interface SignagePlaylistQueryOptions extends PlaceResourceQueryOptions { - /** ID of the group to scope playlists to */ - group_id?: string; -} - -/** Allowable query parameters for signage playlist media revisions endpoint */ -export interface SignagePlaylistRevisionsOptions { - /** Maximum number of revisions to return */ - limit?: number; -} - -/** Allowable query parameters for signage plugins index endpoint */ -export interface SignagePluginQueryOptions extends PlaceResourceQueryOptions { - /** Only return plugins that are enabled */ - enabled?: boolean; - /** Only return plugins of this type */ - plugin_type?: SignagePluginType; -} - -/** Allowable query parameters for signage templates index endpoint */ -export interface SignageTemplateQueryOptions extends PlaceResourceQueryOptions { - /** ID of the group to scope templates to */ - group_id?: string; - /** Return approved versions instead of pending drafts */ - approved?: boolean; -} - -/** Allowable query parameters when creating a signage template */ -export type SignageTemplateCreateOptions = SignageCreateOptions; - -/** Allowable query parameters for signage template show endpoint */ -export interface SignageTemplateShowOptions { - /** Return the approved template even when a pending draft exists */ - approved?: boolean; -} - -/** Allowable query parameters for signage template mappings index endpoint */ -export interface SignageTemplateMappingQueryOptions - extends PlaceResourceQueryOptions { - /** ID of the display to filter mappings by */ - control_system_id?: string; - /** ID of the zone to filter mappings by */ - zone_id?: string; - /** ID of the template to filter mappings by */ - template_id?: string; -} - -export interface SignageTemplateApprover { - id: string; - name: string; -} - -/** Query parameters for the media, playlist and template share endpoints */ -export interface SignageShareOptions { - /** IDs of the items to share into the target group */ - items: string[] | string; - /** Destination signage group ID */ - to: string; -} - -/** Result of sharing media, playlists or templates into a group */ -export interface SignageShareResult { - /** IDs newly linked to the target group */ - linked: string[]; - /** IDs already linked to the target group */ - already_present: string[]; -} - -/** @deprecated Use {@link SignageShareOptions} */ -export type SignageTemplateShareOptions = SignageShareOptions; - -/** @deprecated Use {@link SignageShareResult} */ -export type SignageTemplateShareResult = SignageShareResult; diff --git a/src/signage/media.class.ts b/src/signage/media.class.ts deleted file mode 100644 index 94c52e58a..000000000 --- a/src/signage/media.class.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { getUnixTime } from 'date-fns'; -import { HashMap } from '../utilities/types'; -import { SignagePlaylist } from './playlist.class'; - -export type MediaType = - | 'unknown' - | 'image' - | 'video' - | 'audio' - | 'plugin' - | 'webpage' - | 'externalimage' - | 'external_image'; - -export enum MediaAnimation { - Default = 'default', - Cut = 'cut', - CrossFade = 'cross_fade', - SlideTop = 'slide_top', - SlideLeft = 'slide_left', - SlideRight = 'slide_right', - SlideBottom = 'slide_bottom', -} - -export type MediaOrientation = - | 'unspecified' - | 'portrait' - | 'landscape' - | 'square'; - -export class SignageMedia { - public readonly id: string; - public readonly created_at: number; - public readonly updated_at: number; - public readonly name: string; - public readonly description: string; - public readonly authority_id: string; - public readonly start_time: number; - public readonly play_time: number; - public readonly video_length: number; - public readonly animation?: MediaAnimation; - public readonly media_type: MediaType; - public readonly orientation: MediaOrientation; - public readonly media_uri: string; - public readonly media_id: string; - public readonly thumbnail_id: string; - public readonly plugin_id: string; - public readonly plugin_params: HashMap; - public readonly play_count: number; - public readonly valid_from?: number; - public readonly valid_until?: number; - public readonly tags: string[]; - /** User groups that the media item is shared with. Only set on the show requests result not the query */ - public readonly shared_with: { id: string, name: string }[]; - /** Playlists that the media item is included within. Only set on the show requests result not the query */ - public readonly playlists: SignagePlaylist[]; - - public get media_url() { - return this.media_id - ? `/api/engine/v2/uploads/${this.media_id}/url` - : this.media_uri; - } - - public get thumbnail_url() { - return `/api/engine/v2/uploads/${this.thumbnail_id}/url`; - } - - constructor(data: Partial) { - this.id = data.id || ''; - this.created_at = data.created_at || getUnixTime(Date.now()); - this.updated_at = data.updated_at || getUnixTime(Date.now()); - this.name = data.name || ''; - this.description = data.description || ''; - this.authority_id = data.authority_id || ''; - this.start_time = data.start_time || 0; - this.play_time = data.play_time || 0; - this.video_length = data.video_length || 0; - this.animation = data.animation; - this.media_type = data.media_type || 'unknown'; - this.orientation = data.orientation || 'unspecified'; - this.media_uri = data.media_uri || ''; - this.media_id = data.media_id || ''; - this.thumbnail_id = data.thumbnail_id || ''; - this.plugin_id = data.plugin_id || ''; - this.plugin_params = data.plugin_params || {}; - this.play_count = data.play_count || 0; - this.valid_from = data.valid_from; - this.valid_until = data.valid_until; - this.tags = data.tags || []; - this.shared_with = data.shared_with || []; - this.playlists = data.playlists || []; - } -} diff --git a/src/signage/playlist.class.ts b/src/signage/playlist.class.ts deleted file mode 100644 index dc1d3b517..000000000 --- a/src/signage/playlist.class.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { SignagePlaylistSchedule } from './interfaces'; -import { MediaAnimation, SignageMedia } from './media.class'; - -export class SignagePlaylistMedia { - public readonly id: string; - public readonly playlist_id: string; - public readonly items: string[]; - public readonly media: SignageMedia[]; - public readonly schedules: SignagePlaylistItemSchedule[]; - public readonly created_at: number; - public readonly updated_at: number; - - public readonly user_id: string; - public readonly user_name: string; - public readonly user_email: string; - - public readonly approved: boolean; - public readonly approval_requested: boolean; - public readonly requested_by_id: string; - public readonly approved_by_id: string; - public readonly approved_by_email: string; - public readonly approved_by_name: string; - public readonly shared_with: { id: string, name: string }[]; - - constructor(data: Partial = {}) { - this.id = data.id || ''; - this.playlist_id = data.playlist_id || ''; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - - this.items = data.items || []; - this.media = data.media || []; - this.schedules = data.schedules || []; - - this.approved = !!data.approved; - this.approval_requested = !!data.approval_requested; - this.requested_by_id = data.requested_by_id || ''; - this.approved_by_id = data.approved_by_id || ''; - this.approved_by_email = data.approved_by_email || ''; - this.approved_by_name = data.approved_by_name || ''; - - this.user_id = data.user_id || ''; - this.user_name = data.user_name || ''; - this.user_email = data.user_email || ''; - this.shared_with = data.shared_with || []; - } -} - -export class SignagePlaylistItemSchedule { - public readonly id: string; - public readonly playlist_id: string; - public readonly item_id: string; - public readonly schedules: SignagePlaylistSchedule[]; - public readonly created_at: number; - public readonly updated_at: number; - public readonly media: SignageMedia; - - constructor(data: Partial = {}) { - this.id = data.id || ''; - this.playlist_id = data.playlist_id || ''; - this.item_id = data.item_id || ''; - this.schedules = data.schedules || []; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - this.media = data.media || new SignageMedia({}); - } -} - -export class SignagePlaylist { - public readonly id: string; - public readonly created_at: number; - public readonly updated_at: number; - public readonly name: string; - public readonly description: string; - public readonly authority_id: string; - public readonly orientation: string; - public readonly play_count: number; - public readonly play_through_count: number; - public readonly default_animation: MediaAnimation; - public readonly random: boolean; - public readonly enabled: boolean; - public readonly distribution: boolean; - public readonly default_duration: number; - public readonly schedules: SignagePlaylistSchedule[]; - public readonly valid_from?: number; - public readonly valid_until?: number; - public readonly shared_with: { id: string, name: string }[]; - - constructor(data: Partial) { - this.id = data.id || ''; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - this.name = data.name || ''; - this.description = data.description || ''; - this.authority_id = data.authority_id || ''; - this.orientation = data.orientation || ''; - this.play_count = data.play_count || 0; - this.play_through_count = data.play_through_count || 0; - this.default_animation = data.default_animation || MediaAnimation.Cut; - this.random = data.random || false; - this.enabled = data.enabled ?? true; - this.distribution = data.distribution || false; - this.default_duration = data.default_duration ?? 15 * 1000; - this.valid_from = data.valid_from; - this.valid_until = data.valid_until; - this.schedules = data.schedules || []; - this.shared_with = data.shared_with || []; - } -} diff --git a/src/signage/plugin.class.ts b/src/signage/plugin.class.ts deleted file mode 100644 index 325e52bcb..000000000 --- a/src/signage/plugin.class.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { HashMap } from '../utilities/types'; - -export type SignagePlaybackType = 'static' | 'interactive' | 'playsthrough'; - -/** Whether the plugin renders as full content or as a template widget */ -export type SignagePluginType = 'plugin' | 'widget'; - -export class SignagePlugin { - public readonly id: string; - public readonly created_at: number; - public readonly updated_at: number; - public readonly name: string; - public readonly description: string; - public readonly uri: string; - public readonly playback_type: SignagePlaybackType; - public readonly plugin_type: SignagePluginType; - public readonly authority_id: string; - public readonly enabled: boolean; - public readonly params: HashMap; - public readonly defaults: HashMap; - - constructor(data: Partial = {}) { - this.id = data.id || ''; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - this.name = data.name || ''; - this.description = data.description || ''; - this.uri = data.uri || ''; - this.playback_type = data.playback_type || 'static'; - this.plugin_type = data.plugin_type || 'plugin'; - this.authority_id = data.authority_id || ''; - this.enabled = data.enabled ?? true; - this.params = data.params || {}; - this.defaults = data.defaults || {}; - } -} diff --git a/src/signage/template.class.ts b/src/signage/template.class.ts deleted file mode 100644 index 283efa5ef..000000000 --- a/src/signage/template.class.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { SignagePlaylistSchedule } from './interfaces'; - -export type SignageTemplateLayoutPosition = - | 'top' - | 'bottom' - | 'left' - | 'right' - | 'floating'; - -export interface SignageTemplateLayout { - plugin_id?: string; - position: SignageTemplateLayoutPosition; - x_pos?: number; - y_pos?: number; - plugin_params: Record; -} - -export class SignageTemplate { - public readonly created_at: string; - public readonly updated_at: string; - public readonly id: string; - public readonly name: string; - public readonly description: string; - public readonly tags: string[]; - public readonly authority_id: string; - public readonly background_item_id: string; - public readonly layouts: SignageTemplateLayout[]; - public readonly full_screen_takeover: boolean; - public readonly merge: boolean; - public readonly approval_requested: boolean; - public readonly requested_by_id: string; - public readonly approved: boolean; - public readonly approved_by_id: string; - public readonly approved_by_name: string; - public readonly approved_by_email: string; - public readonly live_template_id: string; - public readonly shared_with: { id: string, name: string }[]; - - constructor(data: Partial = {}) { - this.created_at = data.created_at || ''; - this.updated_at = data.updated_at || ''; - this.id = data.id || ''; - this.name = data.name || ''; - this.description = data.description || ''; - this.tags = data.tags || []; - this.authority_id = data.authority_id || ''; - this.background_item_id = data.background_item_id || ''; - this.layouts = data.layouts || []; - this.full_screen_takeover = data.full_screen_takeover || false; - this.merge = data.merge ?? false; - this.approval_requested = data.approval_requested || false; - this.requested_by_id = data.requested_by_id || ''; - this.approved = data.approved || false; - this.approved_by_id = data.approved_by_id || ''; - this.approved_by_name = data.approved_by_name || ''; - this.approved_by_email = data.approved_by_email || ''; - this.live_template_id = data.live_template_id || ''; - this.shared_with = data.shared_with || []; - } -} - -export class SignageTemplateMapping { - public readonly created_at: string; - public readonly updated_at: string; - public readonly id: string; - public readonly control_system_id: string; - public readonly zone_id: string; - public readonly template_id: string; - public readonly schedule: SignagePlaylistSchedule | null; - - constructor(data: Partial = {}) { - this.created_at = data.created_at || ''; - this.updated_at = data.updated_at || ''; - this.id = data.id || ''; - this.control_system_id = data.control_system_id || ''; - this.zone_id = data.zone_id || ''; - this.template_id = data.template_id || ''; - this.schedule = data.schedule || null; - } -} diff --git a/src/staff.ts b/src/staff.ts index db062c79a..2cb1fe154 100644 --- a/src/staff.ts +++ b/src/staff.ts @@ -1,41 +1,19 @@ -export { - addSurvey, - querySurveys, - removeSurvey, - showSurvey, - updateSurvey, -} from './staff/surveys/functions'; -export type { - SurveyQueryOptions, - SurveyShowOptions, -} from './staff/surveys/interfaces'; -export { Survey } from './staff/surveys/model'; - -export { - addInvitation, - queryInvitations, - removeInvitation, - showInvitation, - updateInvitation, -} from './staff/invitations/functions'; -export type { - InvitationQueryOptions, - InvitationShowOptions, -} from './staff/invitations/interfaces'; -export { SurveyInvitation } from './staff/invitations/model'; - -export { - addQuestion, - queryQuestions, - removeQuestion, - showQuestion, -} from './staff/questions/functions'; -export type { - QuestionQueryOptions, - QuestionShowOptions, -} from './staff/questions/interfaces'; -export { SurveyQuestion } from './staff/questions/model'; - -export { addAnswer, queryAnswers } from './staff/answers/functions'; -export type { AnswerQueryOptions } from './staff/answers/interfaces'; -export { SurveyAnswer } from './staff/answers/model'; +/** + * The PlaceOS staff API client, at `@placeos/ts-client/staff`. It uses the client of `configure`, + * as the REST API functions do: + * + * ```ts + * import { configure } from '@placeos/ts-client'; + * import { bookings } from '@placeos/ts-client/staff'; + * + * configure({ baseUrl: '', auth: session.clientAuth }); + * const result = await bookings.query({ period_start, period_end, type: 'desk' }); + * ``` + * + * The staff API has its own schemas, such as `Booking`. A schema that both APIs have, such as + * `Zone`, is in both entries with the same shape. + * + * @module + */ +export * from './generated/staff/operations/index.ts'; +export * from './generated/staff/schemas.ts'; diff --git a/src/staff/answers/functions.ts b/src/staff/answers/functions.ts deleted file mode 100644 index ee43f69f4..000000000 --- a/src/staff/answers/functions.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { get, post } from '../../api'; -import { toQueryString } from '../../utilities/api'; -import { AnswerQueryOptions } from './interfaces'; -import { SurveyAnswer } from './model'; - -/** - * @private - */ -const PATH = '/api/staff/v1/surveys/answers'; - -/** - * Query the available answers - * @param query_params Query parameters to add the to request URL - */ -export function queryAnswers(query_params: AnswerQueryOptions = {}) { - const query = toQueryString(query_params); - return get(`${PATH}${query ? '?' + query : ''}`).then((l: any) => - l.map((_: any) => new SurveyAnswer(_)), - ); -} - -/** - * Add a new answer to the database - * @param form_data Answer data - * @param query_params Query parameters to add the to request URL - */ -export function addAnswer(form_data: Partial[]) { - return post(`${PATH}`, form_data).then((l: any) => - l.map((_: any) => new SurveyAnswer(_)), - ); -} diff --git a/src/staff/answers/interfaces.ts b/src/staff/answers/interfaces.ts deleted file mode 100644 index 7120f00eb..000000000 --- a/src/staff/answers/interfaces.ts +++ /dev/null @@ -1 +0,0 @@ -export interface AnswerQueryOptions {} diff --git a/src/staff/answers/model.ts b/src/staff/answers/model.ts deleted file mode 100644 index 9dc4f58a8..000000000 --- a/src/staff/answers/model.ts +++ /dev/null @@ -1,15 +0,0 @@ -export class SurveyAnswer { - id: number; - question_id: number; - survey_id: number; - type: string; - answer_json: Record; - - constructor(_data: Partial) { - this.id = _data.id || 0; - this.question_id = _data.question_id || 0; - this.survey_id = _data.survey_id || 0; - this.type = _data.type || ''; - this.answer_json = _data.answer_json || {}; - } -} diff --git a/src/staff/invitations/functions.ts b/src/staff/invitations/functions.ts deleted file mode 100644 index c74d850a6..000000000 --- a/src/staff/invitations/functions.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { del, get, patch, post, put } from '../../api'; -import { toQueryString } from '../../utilities/api'; -import { InvitationQueryOptions, InvitationShowOptions } from './interfaces'; -import { SurveyInvitation } from './model'; - -/** - * @private - */ -const PATH = '/api/staff/v1/surveys/invitations'; - -/** - * Query the available invitations - * @param query_params Query parameters to add the to request URL - */ -export function queryInvitations(query_params: InvitationQueryOptions = {}) { - const query = toQueryString(query_params); - return get(`${PATH}${query ? '?' + query : ''}`).then((l: any) => - l.map((_: any) => new SurveyInvitation(_)), - ); -} - -/** - * Get the data for an invitation - * @param id ID of the surveyinvitation to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showInvitation( - token: string, - query_params: InvitationShowOptions = {}, -) { - const query = toQueryString(query_params); - return get(`${PATH}/${token}${query ? '?' + query : ''}`).then( - (l: any) => new SurveyInvitation(l), - ); -} - -/** - * Update the surveyinvitation in the database - * @param id ID of the invitation - * @param form_data New values for the invitation - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateInvitation( - token: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return (method === 'put' ? put : patch)(`${PATH}/${token}`, form_data).then( - (l: any) => new SurveyInvitation(l), - ); -} - -/** - * Add a new surveyinvitation to the database - * @param form_data SurveyInvitation data - * @param query_params Query parameters to add the to request URL - */ -export function addInvitation(form_data: Partial) { - return post(`${PATH}`, form_data).then((l: any) => new SurveyInvitation(l)); -} - -/** - * Remove an surveyinvitation from the database - * @param id ID of the invitation - * @param query_params Query parameters to add the to request URL - */ -export function removeInvitation( - token: string, - query_params: Record = {}, -) { - const query = toQueryString(query_params); - return del(`${PATH}/${token}${query ? '?' + query : ''}`); -} diff --git a/src/staff/invitations/interfaces.ts b/src/staff/invitations/interfaces.ts deleted file mode 100644 index c804a4075..000000000 --- a/src/staff/invitations/interfaces.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface InvitationQueryOptions { - survey_id?: string; - sent?: boolean; -} - -export interface InvitationShowOptions {} diff --git a/src/staff/invitations/model.ts b/src/staff/invitations/model.ts deleted file mode 100644 index 1712a79c1..000000000 --- a/src/staff/invitations/model.ts +++ /dev/null @@ -1,15 +0,0 @@ -export class SurveyInvitation { - id: number; - survey_id: number; - token: string; - email: string; - sent: boolean; - - constructor(_data: Partial) { - this.id = _data.id || 0; - this.survey_id = _data.survey_id || 0; - this.token = _data.token || ''; - this.email = _data.email || ''; - this.sent = _data.sent ?? false; - } -} diff --git a/src/staff/questions/functions.ts b/src/staff/questions/functions.ts deleted file mode 100644 index 6ee67aa94..000000000 --- a/src/staff/questions/functions.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { del, get, patch, post, put } from '../../api'; -import { toQueryString } from '../../utilities/api'; -import { QuestionQueryOptions, QuestionShowOptions } from './interfaces'; -import { SurveyQuestion } from './model'; - -/** - * @private - */ -const PATH = '/api/staff/v1/surveys/questions'; - -/** - * Query the available questions - * @param query_params Query parameters to add the to request URL - */ -export function queryQuestions(query_params: QuestionQueryOptions = {}) { - const query = toQueryString(query_params); - return get(`${PATH}${query ? '?' + query : ''}`).then((l: any) => - l.map((_: any) => new SurveyQuestion(_)), - ); -} - -/** - * Get the data for an question - * @param id ID of the surveyquestion to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showQuestion( - id: string, - query_params: QuestionShowOptions = {}, -) { - const query = toQueryString(query_params); - return get(`${PATH}/${id}${query ? '?' + query : ''}`).then( - (l: any) => new SurveyQuestion(l), - ); -} - -/** - * Add a new surveyquestion to the database - * @param form_data SurveyQuestion data - * @param query_params Query parameters to add the to request URL - */ -export function addQuestion(form_data: Partial) { - return post(`${PATH}`, form_data).then((l: any) => new SurveyQuestion(l)); -} - -/** - * Update the question in the database - * @param id ID of the question - * @param form_data New values for the question - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateQuestion( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return (method === 'put' ? put : patch)(`${PATH}/${id}`, form_data).then( - (l: any) => new SurveyQuestion(l), - ); -} - -/** - * Remove an surveyquestion from the database - * @param id ID of the question - * @param query_params Query parameters to add the to request URL - */ -export function removeQuestion( - id: string, - query_params: Record = {}, -) { - const query = toQueryString(query_params); - return del(`${PATH}/${id}${query ? '?' + query : ''}`); -} diff --git a/src/staff/questions/interfaces.ts b/src/staff/questions/interfaces.ts deleted file mode 100644 index 660c11bd9..000000000 --- a/src/staff/questions/interfaces.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface QuestionQueryOptions { - survey_id?: string; - deleted?: boolean; -} - -export interface QuestionShowOptions {} diff --git a/src/staff/questions/model.ts b/src/staff/questions/model.ts deleted file mode 100644 index 22fdaccad..000000000 --- a/src/staff/questions/model.ts +++ /dev/null @@ -1,25 +0,0 @@ -export class SurveyQuestion { - id: number; - title: string; - description?: string; - type: string; - options: any; - required: boolean; - max_rating: number; - choices: Array; - tags: Array; - deleted: boolean; - - constructor(_data: Partial) { - this.id = _data.id || 0; - this.title = _data.title || ''; - this.description = _data.description || ''; - this.type = _data.type || ''; - this.options = _data.options || {}; - this.required = _data.required || false; - this.max_rating = _data.max_rating || 0; - this.choices = _data.choices || []; - this.tags = _data.tags || []; - this.deleted = _data.deleted || false; - } -} diff --git a/src/staff/surveys/functions.ts b/src/staff/surveys/functions.ts deleted file mode 100644 index 5ace24b13..000000000 --- a/src/staff/surveys/functions.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { del, get, patch, post, put } from '../../api'; -import { toQueryString } from '../../utilities/api'; -import { SurveyQueryOptions, SurveyShowOptions } from './interfaces'; -import { Survey } from './model'; - -/** - * @private - */ -const PATH = '/api/staff/v1/surveys'; - -/** - * Query the available surveys - * @param query_params Query parameters to add the to request URL - */ -export function querySurveys(query_params: SurveyQueryOptions = {}) { - const query = toQueryString(query_params); - return get(`${PATH}${query ? '?' + query : ''}`).then((l: any) => - l.map((_: any) => new Survey(_)), - ); -} - -/** - * Get the data for an survey - * @param id ID of the survey to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showSurvey(id: string, query_params: SurveyShowOptions = {}) { - const query = toQueryString(query_params); - return get(`${PATH}/${id}${query ? '?' + query : ''}`).then( - (l: any) => new Survey(l), - ); -} - -/** - * Update the survey in the database - * @param id ID of the survey - * @param form_data New values for the survey - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSurvey( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return (method === 'put' ? put : patch)(`${PATH}/${id}`, form_data).then( - (l: any) => new Survey(l), - ); -} - -/** - * Add a new survey to the database - * @param form_data Survey data - * @param query_params Query parameters to add the to request URL - */ -export function addSurvey(form_data: Partial) { - return post(`${PATH}`, form_data).then((l: any) => new Survey(l)); -} - -/** - * Remove an survey from the database - * @param id ID of the survey - * @param query_params Query parameters to add the to request URL - */ -export function removeSurvey( - id: string, - query_params: Record = {}, -) { - const query = toQueryString(query_params); - return del(`${PATH}/${id}${query ? '?' + query : ''}`); -} diff --git a/src/staff/surveys/interfaces.ts b/src/staff/surveys/interfaces.ts deleted file mode 100644 index 084fb443e..000000000 --- a/src/staff/surveys/interfaces.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface SurveyQueryOptions {} - -export interface SurveyShowOptions {} diff --git a/src/staff/surveys/model.ts b/src/staff/surveys/model.ts deleted file mode 100644 index 25e55a5f0..000000000 --- a/src/staff/surveys/model.ts +++ /dev/null @@ -1,25 +0,0 @@ -export class Survey { - public readonly id: number; - public readonly title: string; - public readonly description?: string; - public readonly trigger: string; - public readonly building_id: string; - public readonly zone_id: string; - public readonly pages: SurveyPage[]; - - constructor(_data: Partial) { - this.id = _data.id || 0; - this.title = _data.title || ''; - this.description = _data.description || ''; - this.building_id = _data.building_id || ''; - this.zone_id = _data.zone_id || ''; - this.pages = _data.pages || []; - this.trigger = _data.trigger || 'NONE'; - } -} - -export interface SurveyPage { - title: string; - description?: string; - question_order: number[]; -} diff --git a/src/storages/functions.ts b/src/storages/functions.ts deleted file mode 100644 index 0b0293be4..000000000 --- a/src/storages/functions.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { create, query, remove, show, update } from '../resources/functions'; -import { PlaceStorage } from './storage.class'; -import { PlaceStorageQueryOptions } from './interfaces'; - -/** - * @private - */ -const PATH = 'storages'; - -/** Convert raw server data to a storage object */ -function processStorage(item: Partial) { - return new PlaceStorage(item); -} - -/** - * Query the available storages - * @param query_params Query parameters to add to the request URL - */ -export function queryStorages(query_params: PlaceStorageQueryOptions = {}) { - return query({ - query_params, - fn: processStorage, - path: PATH, - }); -} - -/** - * Get the data for a storage - * @param id ID of the storage to retrieve - * @param query_params Query parameters to add to the request URL - */ -export function showStorage( - id: string, - query_params: Record = {}, -) { - return show({ - id, - query_params, - fn: processStorage, - path: PATH, - }); -} - -/** - * Update a storage in the database - * @param id ID of the storage - * @param form_data New values for the storage - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateStorage( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: processStorage, - path: PATH, - }); -} - -/** - * Add a new storage to the database - * @param form_data Storage data - */ -export function addStorage(form_data: Partial) { - return create({ - form_data, - query_params: {}, - fn: processStorage, - path: PATH, - }); -} - -/** - * Remove a storage from the database - * @param id ID of the storage - * @param query_params Query parameters to add to the request URL - */ -export function removeStorage( - id: string, - query_params: Record = {}, -) { - return remove({ id, query_params, path: PATH }); -} diff --git a/src/storages/interfaces.ts b/src/storages/interfaces.ts deleted file mode 100644 index 32dd199e6..000000000 --- a/src/storages/interfaces.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Mapping of available query parameters for the storages index endpoint */ -export interface PlaceStorageQueryOptions extends PlaceResourceQueryOptions { - /** Return storages which are in the authority provided */ - auth_id?: string; -} diff --git a/src/storages/storage.class.ts b/src/storages/storage.class.ts deleted file mode 100644 index f826bc02a..000000000 --- a/src/storages/storage.class.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Storage type enumeration */ -export type StorageType = 's3' | 'azure' | 'google'; - -export class PlaceStorage { - readonly id: string; - readonly storage_type: StorageType | null; - readonly bucket_name: string; - readonly region: string; - readonly access_key: string; - readonly access_secret: string; - readonly authority_id: string; - readonly endpoint: string; - readonly is_default: boolean; - readonly ext_filter: string[]; - readonly mime_filter: string[]; - readonly created_at: number; - readonly updated_at: number; - - constructor(data: Partial) { - this.id = data.id || ''; - this.storage_type = data.storage_type || null; - this.bucket_name = data.bucket_name || ''; - this.region = data.region || ''; - this.access_key = data.access_key || ''; - this.access_secret = data.access_secret || ''; - this.authority_id = data.authority_id || ''; - this.endpoint = data.endpoint || ''; - this.is_default = data.is_default ?? false; - this.ext_filter = data.ext_filter || []; - this.mime_filter = data.mime_filter || []; - this.created_at = data.created_at || 0; - this.updated_at = data.updated_at || 0; - } -} diff --git a/src/systems/functions.ts b/src/systems/functions.ts deleted file mode 100644 index ef3398bbd..000000000 --- a/src/systems/functions.ts +++ /dev/null @@ -1,450 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { PlaceSettings } from '../settings/settings'; -import { PlaceTrigger } from '../triggers/trigger'; -import { HashMap } from '../utilities/types'; -import { PlaceZone } from '../zones/zone'; -import { - PlaceModuleFunctionMap, - PlaceSystemControlOptions, - PlaceSystemMetadataOptions, - PlaceSystemModuleTypes, - PlaceSystemShowOptions, - PlaceSystemsQueryOptions, - PlaceSystemStartStopOptions, - PlaceSystemsWithEmailsOptions, - PlaceSystemTriggerShowOptions, - PlaceSystemTriggersQueryOptions, -} from './interfaces'; -import { PlaceSystem } from './system'; - -/** - * @private - */ -const PATH = 'systems'; - -/** Convert raw server data to an system object */ -function process(item: Partial) { - return new PlaceSystem(item); -} - -/** - * Query the available systems - * @param query_params Query parameters to add the to request URL - */ -export function querySystems(query_params: PlaceSystemsQueryOptions = {}) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Query the available systems by email addresses - * @param query_params Query parameters to add the to request URL - */ -export function querySystemsWithEmails( - query_params: PlaceSystemsWithEmailsOptions, -) { - return query({ query_params, fn: process, path: `${PATH}/with_emails` }); -} - -/** - * Get the data for a system - * @param id ID of the system to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showSystem( - id: string, - query_params: PlaceSystemShowOptions = {}, -) { - return show({ id, query_params, fn: process, path: PATH }); -} - -/** - * Update the system in the database - * @param id ID of the system - * @param form_data New values for the system - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSystem( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new system to the database - * @param form_data System data - * @param query_params Query parameters to add the to request URL - */ -export function addSystem(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a system from the database - * @param id ID of the system - */ -export function removeSystem(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} - -/** - * Add module to the given system - * @param id System ID - * @param module_id ID of the module to add - */ -export function addSystemModule( - id: string, - module_id: string, - data: HashMap = {}, -): Promise { - return task({ - id, - task_name: `module/${module_id}`, - form_data: data, - method: 'put', - callback: (d) => process(d), - path: PATH, - }); -} - -/** - * Remove module from the given system - * @param id System ID - * @param module_id ID of the module to remove - */ -export function removeSystemModule( - id: string, - module_id: string, -): Promise { - return task({ - id, - task_name: `module/${module_id}`, - form_data: {}, - method: 'del', - callback: (d) => process(d), - path: PATH, - }); -} - -/** - * Start the given system and clears any existing caches - * @param id System ID - * @param query_params Query parameters to add the to request URL - */ -export function startSystem( - id: string, - query_params: PlaceSystemStartStopOptions = {}, -): Promise { - return task({ - id, - task_name: 'start', - form_data: query_params, - path: PATH, - }); -} - -/** - * Stops all modules in the given system - * @param id System ID - * @param query_params Query parameters to add the to request URL - */ -export function stopSystem( - id: string, - query_params: PlaceSystemStartStopOptions = {}, -): Promise { - return task({ - id, - task_name: 'stop', - form_data: query_params, - path: PATH, - }); -} - -/** - * Execute a function of the given system module - * @param id System ID - * @param method Name of the function to execute - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - * @param index Module index. Defaults to `1` - * @param args Array of arguments to pass to the executed method - */ -export function executeOnSystem( - id: string, - method: string, - module: string, - index: number = 1, - args: any[] = [], -): Promise { - return task({ - id, - task_name: `${module}_${index}/${encodeURIComponent(method)}`, - form_data: args, - path: PATH, - }); -} - -/** - * Get the state of the given system module - * @param id System ID - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - * @param index Module index. Defaults to `1` - * @param lookup Status variable of interest. If set it will return only the state of this variable - */ -export function systemModuleState( - id: string, - module: string, - index: number = 1, -): Promise { - return task({ - id, - task_name: `${module}_${index}`, - method: 'get', - path: PATH, - }); -} - -/** - * Get the state of the given system module - * @param id System ID - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - * @param index Module index. Defaults to `1` - * @param lookup Status variable of interest. If set it will return only the state of this variable - */ -export function lookupSystemModuleState( - id: string, - module: string, - index: number = 1, - lookup: string, -): Promise { - return task({ - id, - task_name: `${module}_${index}/${lookup}`, - method: 'get', - path: PATH, - }); -} - -/** - * Get the list of functions for the given system module - * @param id System ID - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - * @param index Module index. Defaults to `1` - */ -export function functionList( - id: string, - module: string, - index: number = 1, -): Promise { - return task({ - id, - task_name: `functions/${module}_${index}`, - method: 'get', - path: PATH, - }); -} - -/** - * Occurances of a particular type of module in the given system - * @param id System ID - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - */ -export function moduleCount( - id: string, - module: string, -): Promise<{ count: number }> { - return task({ - id, - task_name: 'count', - form_data: { module }, - method: 'get', - path: PATH, - }); -} - -/** - * List types of modules and counts in the given system - * @param id System ID - */ -export function moduleTypes(id: string): Promise> { - return task({ id, task_name: 'count', method: 'get', path: PATH }); -} - -/** List types of modules and counts in the given system */ -export function systemModuleTypes(id: string): Promise { - return task({ id, task_name: 'types', method: 'get', path: PATH }); -} - -/** - * Get list of Zones for system - * @param id System ID - */ -export function listSystemZones(id: string) { - return query({ - query_params: {}, - fn: (i: HashMap) => new PlaceZone(i), - path: `${PATH}/${id}/zones`, - }); -} - -/** - * Get list of triggers for system - * @param id System ID - * @param query_params Query parameters to add the to request URL - */ -export function listSystemTriggers( - id: string, - query_params: PlaceSystemTriggersQueryOptions = {}, -) { - return query({ - query_params, - fn: (i: HashMap) => new PlaceTrigger(i), - path: `${PATH}/${id}/triggers`, - }); -} - -/** - * Get list of triggers for system - * @param id System ID - * @param data Values for trigger properties - */ -export function addSystemTrigger( - id: string, - data: Partial, -): Promise { - return task({ - id, - task_name: 'triggers', - form_data: data, - method: 'post', - callback: (item: Partial) => new PlaceTrigger(item), - path: PATH, - }); -} - -/** - * Remove trigger from system - * @param id System ID - * @param trigger_id ID of the trigger - */ -export function removeSystemTrigger( - id: string, - trigger_id: string, -): Promise { - return task({ - id, - task_name: `triggers/${trigger_id}`, - method: 'del', - path: PATH, - }); -} - -/** - * Fetch settings of modules, zones and drivers associated with the system - * @param id System ID - */ -export function systemSettings(id: string): Promise { - return task({ - id, - task_name: 'settings', - method: 'get', - callback: (list) => - list.map((item: Partial) => new PlaceSettings(item)), - path: PATH, - }); -} - -/** - * Get the websocket API endpoint URL for system control. - * @param query_params Query parameters to add to the URL - */ -export function systemControlUrl( - query_params: PlaceSystemControlOptions = {}, -): string { - const endpoint = apiEndpoint(); - const wsProtocol = endpoint.startsWith('https') ? 'wss:' : 'ws:'; - const httpProtocol = endpoint.startsWith('https') ? 'https:' : 'http:'; - let url = `${endpoint.replace(httpProtocol, wsProtocol).replace(/\/$/, '')}/${PATH}/control`; - if (query_params.fixed_device) { - url += `?fixed_device=${encodeURIComponent(String(query_params.fixed_device))}`; - } - return url; -} - -/** - * Get metadata for the system - * @param id System ID - * @param query_params Query parameters to add to the request - */ -export function systemMetadata( - id: string, - query_params: PlaceSystemMetadataOptions = {}, -): Promise { - return task({ - id, - task_name: 'metadata', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Get a particular trigger instance - * @param sys_id System ID - * @param trig_id Trigger ID - * @param query_params Query parameters to add to the request - */ -export function showSystemTrigger( - sys_id: string, - trig_id: string, - query_params: PlaceSystemTriggerShowOptions = {}, -): Promise { - return task({ - id: sys_id, - task_name: `triggers/${encodeURIComponent(trig_id)}`, - form_data: query_params, - method: 'get', - callback: (item: Partial) => new PlaceTrigger(item), - path: PATH, - }); -} - -/** - * Update the details of a trigger instance - * @param sys_id System ID - * @param trig_id Trigger ID - * @param data Values for trigger properties - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateSystemTrigger( - sys_id: string, - trig_id: string, - data: Partial, - method: 'put' | 'patch' = 'patch', -): Promise { - return task({ - id: sys_id, - task_name: `triggers/${encodeURIComponent(trig_id)}`, - form_data: data, - method, - callback: (item: Partial) => new PlaceTrigger(item), - path: PATH, - }); -} diff --git a/src/systems/interfaces.ts b/src/systems/interfaces.ts deleted file mode 100644 index e4b6cf232..000000000 --- a/src/systems/interfaces.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; -import { HashMap } from '../utilities/types'; - -export interface PlaceModuleFunctionMap extends HashMap {} - -export interface PlaceModuleFunction { - /** Arity of the function. See https://apidock.com/ruby/Method/arity */ - arity: number; - /** Map of available paramters for the function */ - params: HashMap<[string, any] | [string]>; - /** Order of the parameters to pass to the server */ - order: string[]; -} - -/** Allowable query parameters for systems index endpoint */ -export interface PlaceSystemsQueryOptions extends PlaceResourceQueryOptions { - /** Return only bookable or non-bookable rooms (returns both when not specified) */ - bookable?: boolean; - /** Return only rooms with capacity equal or greater than provided */ - capacity?: number; - /** Return only systems whose resource address matches one of the emails provided */ - email?: string; - /** Comma separated list of features. Return only rooms with all requested features */ - features?: string; - /** Return only systems which have this module ID */ - module_id?: string; - /** Return systems using this trigger ID */ - trigger_id?: string; - /** Zone ID to filter the returned values on */ - zone_id?: string; - /** Group ID to filter systems by */ - group_id?: string; - /** Only return systems linked to this subsystem */ - subsystem?: string; - /** Return systems which are public */ - public?: boolean; - /** Only return systems that have signage capabilities */ - signage?: boolean; -} - -/** Allowable query parameters for systems with_emails endpoint */ -export interface PlaceSystemsWithEmailsOptions { - /** Comma separated list of email addresses (required) */ - in: string; -} - -/** Allowable query parameters for systems show endpoint */ -export interface PlaceSystemShowOptions { - /** Return the system with zone, module, and driver information collected */ - complete?: boolean; -} - -/** Allowable query parameters for systems update endpoint */ -export interface PlaceSystemUpdateOptions { - /** Version number to prevent overwriting newer config (required for PUT/PATCH) */ - version: number; -} - -/** Allowable query parameters for system start/stop endpoints */ -export interface PlaceSystemStartStopOptions { - /** Start/stop modules that only occur in the selected system */ - single_occurrence?: boolean; -} - -/** Allowable query parameters for system triggers index endpoint */ -export interface PlaceSystemTriggersQueryOptions extends PlaceResourceQueryOptions { - /** Provide the control system details */ - complete?: boolean; - /** Only return triggers marked as important */ - important?: boolean; - /** Only return triggers that have recently been triggered */ - triggered?: boolean; - /** Filter by a particular trigger type */ - trigger_id?: string; - /** Return triggers updated before the time specified (unix epoch) */ - as_of?: number; -} - -/** Allowable query parameters for systems control endpoint */ -export interface PlaceSystemControlOptions { - /** Fixed device identifier */ - fixed_device?: boolean; -} - -/** Allowable query parameters for system metadata endpoint */ -export interface PlaceSystemMetadataOptions { - /** Name of the metadata key */ - name?: string; -} - -/** Allowable query parameters for system trigger show endpoint */ -export interface PlaceSystemTriggerShowOptions { - /** Return the full trigger details */ - complete?: boolean; -} - -export interface PlaceSystemModuleTypes extends HashMap {} diff --git a/src/systems/system.ts b/src/systems/system.ts deleted file mode 100644 index bce2cffd4..000000000 --- a/src/systems/system.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { getUnixTime } from 'date-fns'; -import { PlaceModule } from '../modules/module'; -import { PlaceResource } from '../resources/resource'; -import { EncryptionLevel } from '../settings/interfaces'; -import { PlaceSettings } from '../settings/settings'; - -/** - * @hidden - */ -export interface PlaceSystemComplete extends Partial { - module_data?: PlaceModule[]; -} - -export class PlaceSystem extends PlaceResource { - /** Tuple of user settings of differring encryption levels for the system */ - public readonly settings: [ - PlaceSettings | null, - PlaceSettings | null, - PlaceSettings | null, - PlaceSettings | null, - ] = [null, null, null, null]; - /** Display name of the system */ - public readonly display_name: string; - /** Description of the system */ - public readonly description: string; - /** Email address associated with the system */ - public readonly email: string; - /** Email address associated with the system */ - public readonly code: string; - /** Capacity of the space associated with the system */ - public readonly capacity: number; - /** Features associated with the system */ - public readonly features: string[]; - /** Whether system is bookable by end users */ - public readonly bookable: boolean; - /** Whether system is public accessible */ - public readonly public: boolean; - /** Count of UI devices attached to the system */ - public readonly installed_ui_devices: number; - /** Support URL for the system */ - public readonly support_url: string; - /** URL for the timetable UI linked to the system */ - public readonly timetable_url: string; - /** URLs for requesting snapshots of the assosiated camera */ - public readonly camera_snapshot_url: string; - /** URLs for requesting snapshots of the assosiated camera */ - public readonly camera_snapshot_urls: string[]; - /** URL for managing the attached camera */ - public readonly camera_url: string; - /** External booking URL for the system */ - public readonly room_booking_url: string; - /** ID on the SVG Map associated with this system */ - public readonly map_id: string; - /** List of module IDs that belong to the system */ - public readonly modules: readonly string[]; - /** List of images associated with the system */ - public readonly images: readonly string[]; - /** List of the zone IDs that the system belongs */ - public readonly zones: readonly string[]; - /** Timezone of the associated real world space */ - public readonly timezone: string; - /** - * List of modules associated with the system. - * Only available from the show method with the `complete` query parameter - */ - public module_list: readonly PlaceModule[] = []; - /** Whether the system has signage capabilities */ - public readonly signage: boolean; - /** List of playlist IDs associated with the system */ - public readonly playlists: readonly string[]; - /** List of security groups with access to the system */ - public readonly security_groups: readonly string[]; - /** Unix timestamp of the last ping from the signage player UI */ - public readonly signage_last_seen: number; - public readonly approval: boolean; - /** Orientation of the signage system */ - public readonly orientation: - | 'unspecified' - | 'portrait' - | 'landscape' - | 'square'; - - constructor(raw_data: PlaceSystemComplete = {}) { - super(raw_data); - this.display_name = raw_data.display_name || ''; - this.description = raw_data.description || ''; - this.email = raw_data.email || ''; - this.code = raw_data.code || ''; - this.capacity = raw_data.capacity || 0; - this.features = raw_data.features || []; - this.bookable = raw_data.bookable || false; - this.public = raw_data.public ?? false; - this.installed_ui_devices = raw_data.installed_ui_devices || 0; - this.support_url = raw_data.support_url || ''; - this.camera_snapshot_url = raw_data.camera_snapshot_url || ''; - this.camera_snapshot_urls = raw_data.camera_snapshot_urls || []; - this.camera_url = raw_data.camera_url || ''; - this.timetable_url = raw_data.timetable_url || ''; - this.room_booking_url = raw_data.room_booking_url || ''; - this.map_id = raw_data.map_id || ''; - this.modules = raw_data.modules || []; - this.images = raw_data.images || []; - this.zones = raw_data.zones || []; - this.settings = raw_data.settings || [null, null, null, null]; - this.timezone = raw_data.timezone || ''; - this.signage = raw_data.signage || false; - this.playlists = raw_data.playlists || []; - this.security_groups = raw_data.security_groups || []; - this.orientation = raw_data.orientation || 'unspecified'; - this.approval = raw_data.approval || false; - this.signage_last_seen = - raw_data.signage_last_seen || getUnixTime(Date.now()); - if (typeof this.settings !== 'object') { - (this as any).settings = [null, null, null, null]; - } - for (const level in EncryptionLevel) { - if (!isNaN(Number(level)) && !this.settings[level]) { - this.settings[level] = new PlaceSettings({ - parent_id: this.id, - encryption_level: +level, - }); - } - } - if (raw_data.module_data && raw_data.module_data instanceof Array) { - this.module_list = raw_data.module_data.map( - (mod) => new PlaceModule(mod), - ); - } - } -} diff --git a/src/systems/utilities.ts b/src/systems/utilities.ts deleted file mode 100644 index 21d841230..000000000 --- a/src/systems/utilities.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { startOfMinute, sub } from 'date-fns'; - -export function generateMockSystem(overrides: any = {}) { - if (typeof overrides !== 'object' || !overrides) { - overrides = {}; - } - const id = `sys-${Math.floor(Math.random() * 999_999)}`; - const created = sub(startOfMinute(new Date()), { - minutes: Math.floor(Math.random() * 99) * 15, - }).getTime(); - return { - id, - name: `System ${Math.floor(Math.random() * 999_999)}`, - description: ``, - email: `${id}@placeos.com`, - capacity: Math.floor(Math.random() * 11 + 1) * 2, - features: 'VC', - bookable: Math.floor(Math.random() * 99999999) % 2 === 0, - installed_ui_devices: Math.floor(Math.random() * 50), - zones: Array(Math.floor(Math.random() * 5)) - .fill(0) - .map(() => `zone_test-${Math.floor(Math.random() * 999_999)}`), - modules: Array(Math.floor(Math.random() * 5)) - .fill(0) - .map(() => `mod_test-${Math.floor(Math.random() * 999_999)}`), - settings: {}, - created_at: Math.floor(created / 1000), - support_url: `/control/${id}`, - ...overrides, - }; -} diff --git a/src/triggers/functions.ts b/src/triggers/functions.ts deleted file mode 100644 index 8c6d48a13..000000000 --- a/src/triggers/functions.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { - PlaceTriggerQueryOptions, - PlaceTriggerShowOptions, -} from './interfaces'; -import { PlaceTrigger } from './trigger'; - -/** - * @private - */ -const PATH = 'triggers'; - -/** Convert raw server data to a trigger object */ -function process(item: Partial) { - return new PlaceTrigger(item); -} - -/** - * Query the available triggers - * @param query_params Query parameters to add the to request URL - */ -export function queryTriggers(query_params: PlaceTriggerQueryOptions = {}) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for a trigger - * @param id ID of the trigger to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showTrigger( - id: string, - query_params: PlaceTriggerShowOptions = {}, -) { - return show({ id, query_params, fn: process, path: PATH }); -} - -/** - * Update the trigger in the database - * @param id ID of the trigger - * @param form_data New values for the trigger - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateTrigger( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new trigger to the database - * @param form_data Trigger data - * @param query_params Query parameters to add the to request URL - */ -export function addTrigger(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a trigger from the database - * @param id ID of the trigger - */ -export function removeTrigger(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} - -/** - * List systems that contain instances of a trigger - * @param id ID of the trigger to grab system instances for - */ -export function listTriggerInstances(id: string): Promise { - return task({ - id, - task_name: `instances`, - form_data: {}, - method: 'get', - callback: (data: Partial[]) => - data.map((i) => new PlaceTrigger(i)), - path: PATH, - }); -} diff --git a/src/triggers/interfaces.ts b/src/triggers/interfaces.ts deleted file mode 100644 index 1f9689e35..000000000 --- a/src/triggers/interfaces.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; -import { HashMap } from '../utilities/types'; - -/** Mapping of available query parameters for the triggers index endpoint */ -export interface PlaceTriggerQueryOptions extends PlaceResourceQueryOptions {} - -/** Mapping of available query parameters for the triggers show endpoint */ -export interface PlaceTriggerShowOptions { - /** Return the instances associated with this trigger */ - instances?: boolean; -} - -export interface TriggerActions { - /** List of functions to execute when the trigger is activated */ - functions: TriggerFunction[]; - /** List of emails to send when the trigger is activated */ - mailers: TriggerMailer[]; -} - -export interface TriggerMailer { - /** List of email addresses to mail to */ - emails: string[]; - /** Contents of the email to send */ - content: string; -} - -export interface TriggerFunction { - /** Module to execute the function on */ - mod: string; - /** Name of the function to execute */ - method: string; - /** Map of arguments to pass to the function */ - args?: ExecuteArgs; -} - -/** Mapping of method parameters to argument value */ -export type ExecuteArgs = HashMap; - -export interface TriggerConditions { - /** List of comparisions used to activate the trigger */ - comparisons: TriggerComparison[]; - /** List of time based activators for the trigger */ - time_dependents: TriggerTimeCondition[]; -} - -export interface TriggerComparison { - /** Left hand side details for the comparision */ - left: TriggerConditionValue; - /** Operator to use for comparing both sides */ - operator: TriggerConditionOperator; - /** Right hand side details for the comparision */ - right: TriggerConditionValue; -} - -export enum TriggerConditionOperator { - EQ = 'equal', - NEQ = 'not_equal', - GT = 'greater_than', - GTE = 'greater_than_or_equal', - LT = 'less_than', - LTE = 'less_than_or_equal', - AND = 'and', - OR = 'or', - XOR = 'exclusive_or', -} - -export type TriggerConditionValue = - | TriggerStatusVariable - | TriggerConditionConstant; - -export type TriggerConditionConstant = number | string | boolean; - -export interface TriggerStatusVariable { - /** Module class name associated with the status variable */ - mod: string; - /** Name of the status variable */ - status: string; - /** Sub keys to look at in the status variable's data */ - keys: string[]; -} - -export type TriggerTimeCondition = - | TriggerAtTimeCondition - | TriggerCronTimeCondition; - -export interface TriggerAtTimeCondition { - /** Type of time condition. Either a specific time or cron string */ - type: TriggerTimeConditionType.AT; - /** Unix epoch in seconds */ - time: number; -} - -export interface TriggerCronTimeCondition { - /** Type of time condition. Either a specific time or cron string */ - type: TriggerTimeConditionType.CRON; - /** CRON tab string */ - cron: string; - /** Timezone associated with the schedule */ - timezone: string; -} - -export enum TriggerTimeConditionType { - AT = 'at', - CRON = 'cron', -} - -export interface TriggerWebhook { - type: TriggerWebhookType; - payload?: string; -} - -export enum TriggerWebhookType { - ExecuteBefore, - ExecuteAfter, - PayloadOnly, - IgnorePayload, -} diff --git a/src/triggers/trigger.ts b/src/triggers/trigger.ts deleted file mode 100644 index 86af74b4f..000000000 --- a/src/triggers/trigger.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { HttpVerb } from '../http/interfaces'; -import { PlaceResource } from '../resources/resource'; -import { PlaceSystem } from '../systems/system'; -import { TriggerActions, TriggerConditions } from './interfaces'; - -/** - * @hidden - */ -export interface PlaceTriggerComplete extends Partial { - trigger_count?: number; - control_system?: PlaceSystem; -} - -export class PlaceTrigger extends PlaceResource { - /** Name of the system assocaited with the trigger */ - public readonly system_name: string; - /** Number of times the trigger has been activated/triggered */ - public readonly activated_count: number; - /** Description of the trigger */ - public readonly description: string; - /** Duration with which to ignore sequential activations of the trigger */ - public readonly debounce_period: number; - /** Whether the trigger should take priority */ - public readonly important: boolean; - /** Whether trigger is enabled on the associated zone or system */ - public readonly enabled: boolean; - /** Whether the trigger can call webhooks */ - public readonly enable_webhook: boolean; - /** Whether the trigger instance can execute methods */ - public readonly exec_enabled: boolean; - /** Auth key for trigger's webhook */ - public readonly webhook_secret: string; - /** HTTP verbs supported by the webhook */ - public readonly supported_methods: readonly HttpVerb[]; - /** ID of the system associated with the trigger */ - public readonly control_system_id: string; - /** ID of the zone associated with the trigger */ - public readonly zone_id: string; - /** ID of the Parent trigger */ - public readonly trigger_id: string; - /** List of playlist IDs associated with the system */ - public readonly playlists: readonly string[]; - // Whether condition checks should match any single condition to pass or all of them - public readonly any_match: boolean; - - /** ID of the system associated with the trigger */ - public get system_id(): string { - return this.control_system_id; - } - - /** Actions to perform when the trigger is activated */ - public get actions(): TriggerActions { - const actions = this._actions; - const fn_list = (actions.functions || []).map((i) => ({ - ...i, - args: { ...i.args }, - })); - const mail_list = (actions.mailers || []).map((i) => ({ - ...i, - emails: [...i.emails], - })); - return { functions: fn_list, mailers: mail_list }; - } - /** Conditions for activating the trigger */ - public get conditions(): TriggerConditions { - const conditions = this._conditions; - const cmp_list = (conditions.comparisons || []).map((i) => ({ - ...i, - left: typeof i.left === 'object' ? { ...i.left } : i.left, - right: typeof i.right === 'object' ? { ...i.right } : i.right, - })); - const time_list = (conditions.time_dependents || []).map((i) => ({ - ...i, - })); - return { comparisons: cmp_list, time_dependents: time_list }; - } - - /** Actions to perform when the trigger is activated */ - private _actions: TriggerActions; - /** Conditions for activating the trigger */ - private _conditions: TriggerConditions; - - constructor(raw_data: PlaceTriggerComplete = {}) { - super(raw_data); - this.description = raw_data.description || ''; - this._actions = raw_data.actions || { functions: [], mailers: [] }; - this._conditions = raw_data.conditions || { - comparisons: [], - time_dependents: [], - }; - this.debounce_period = raw_data.debounce_period || 0; - this.important = raw_data.important || false; - this.enabled = raw_data.enabled || false; - this.webhook_secret = raw_data.webhook_secret || ''; - this.control_system_id = - raw_data.system_id || raw_data.control_system_id || ''; - this.zone_id = raw_data.zone_id || ''; - this.system_name = - raw_data.system_name || - (raw_data.control_system ? raw_data.control_system.name : ''); - this.enable_webhook = raw_data.enable_webhook || false; - this.exec_enabled = raw_data.exec_enabled || false; - this.supported_methods = raw_data.supported_methods || ['POST']; - this.activated_count = - raw_data.activated_count || raw_data.trigger_count || 0; - this.playlists = raw_data.playlists || []; - this.trigger_id = raw_data.trigger_id || ''; - this.any_match = raw_data.any_match || false; - } -} diff --git a/src/url-proxy/functions.ts b/src/url-proxy/functions.ts deleted file mode 100644 index 67ddb4c55..000000000 --- a/src/url-proxy/functions.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { get } from '../http/functions'; -import { HttpBlobOptions } from '../http/interfaces'; -import { toQueryString } from '../utilities/api'; - -export type UrlProxyOptions = Omit< - HttpBlobOptions, - 'response_type' | 'skip_auth' ->; - -/** - * Fetch a remote HTTP resource through PlaceOS. - * - * The proxy route is public, so this request does not attach the PlaceOS - * access token. Pass headers in `options` when the upstream resource needs - * them. - */ -export function proxyUrl( - url: string, - options: UrlProxyOptions = {}, -): Promise { - const query = toQueryString({ url }); - return get(`${apiEndpoint()}/proxy?${query}`, { - ...options, - response_type: 'blob', - skip_auth: true, - }); -} diff --git a/src/users/functions.ts b/src/users/functions.ts deleted file mode 100644 index 98ef5063b..000000000 --- a/src/users/functions.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { del, get, post } from '../http/functions'; -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { toQueryString } from '../utilities/api'; -import { HashMap } from '../utilities/types'; -import { - PlaceUserDeleteOptions, - PlaceUserGroupResponse, - PlaceUserGroupsOptions, - PlaceUserMetadataOptions, - PlaceUserMetadataSearchOptions, - PlaceUserQueryOptions, - PlaceUserResourceToken, - PlaceUserShowOptions, -} from './interfaces'; -import { PlaceUser } from './user'; - -/** - * @private - */ -const PATH = 'users'; - -/** Convert raw server data to a trigger object */ -function process(item: Partial) { - return new PlaceUser(item); -} - -/** - * Query the available triggers - * @param query_params Query parameters to add the to request URL - */ -export function queryUsers(query_params: PlaceUserQueryOptions = {}) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * Get the data for a user - * @param id ID of the user to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showUser(id: string, query_params: PlaceUserShowOptions = {}) { - return show({ id, query_params, fn: process, path: PATH }); -} - -/** - * Get the data for the currently logged in user - * @param query_params Query parameters to add the to request URL - */ -export function currentUser(query_params: PlaceUserShowOptions = {}) { - return show({ id: 'current', query_params, fn: process, path: PATH }); -} - -/** - * Update the trigger in the database - * @param id ID of the trigger - * @param form_data New values for the trigger - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateUser( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new trigger to the database - * @param form_data Trigger data - * @param query_params Query parameters to add the to request URL - */ -export function addUser(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a user from the database - * @param id ID of the user - * @param query_params Query parameters to add the to request URL - */ -export function removeUser( - id: string, - query_params: PlaceUserDeleteOptions = {}, -) { - return remove({ id, query_params, path: PATH }); -} - -/** - * Get the groups that users are in - * @param query_params Query parameters including email addresses - */ -export function queryUserGroups( - query_params: PlaceUserGroupsOptions, -): Promise { - const q = toQueryString(query_params); - const url = `${apiEndpoint()}/${PATH}/groups${q ? '?' + q : ''}`; - return get(url).then((resp: HashMap) => resp as PlaceUserGroupResponse[]); -} - -/** - * Search user metadata with provided JSON Path query - * @param query_params Query parameters including filter - */ -export function searchUserMetadata( - query_params: PlaceUserMetadataSearchOptions, -): Promise { - const q = toQueryString(query_params); - const url = `${apiEndpoint()}/${PATH}/metadata/search${q ? '?' + q : ''}`; - return get(url).then((resp: HashMap) => - ((resp || []) as HashMap[]).map((item) => process(item)), - ); -} - -/** - * Obtain a token to the current user's SSO resources - */ -export function currentUserResourceToken(): Promise { - const url = `${apiEndpoint()}/${PATH}/resource_token`; - return post(url, {}).then( - (resp: HashMap) => resp as PlaceUserResourceToken, - ); -} - -/** - * Get a user's metadata - * @param id User ID - * @param query_params Query parameters to add to the request - */ -export function userMetadata( - id: string, - query_params: PlaceUserMetadataOptions = {}, -): Promise { - return task({ - id, - task_name: 'metadata', - form_data: query_params, - method: 'get', - path: PATH, - }); -} - -/** - * Remove the saved resource token of a user - * @param id User ID - */ -export function removeUserResourceToken(id: string): Promise { - const url = `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}/resource_token`; - return del(url, { response_type: 'void' }); -} - -/** - * Obtain a token to the specified user's SSO resources - * @param id User ID - */ -export function userResourceToken(id: string): Promise { - const url = `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}/resource_token`; - return post(url, {}).then( - (resp: HashMap) => resp as PlaceUserResourceToken, - ); -} - -/** - * Undelete a user - * @param id User ID - */ -export function reviveUser(id: string): Promise { - return task({ - id, - task_name: 'revive', - form_data: {}, - method: 'post', - callback: (item: Partial) => process(item), - path: PATH, - }); -} diff --git a/src/users/interfaces.ts b/src/users/interfaces.ts deleted file mode 100644 index 0a2783caa..000000000 --- a/src/users/interfaces.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Mapping of available query parameters for the users index endpoint */ -export interface PlaceUserQueryOptions extends PlaceResourceQueryOptions { - /** Include soft deleted users in the results */ - include_deleted?: boolean; - /** Include user metadata in the response */ - include_metadata?: boolean; - /** Admin users can view other domains (ignored for other users) */ - authority_id?: string; -} - -/** Mapping of available query parameters for the users show endpoint */ -export interface PlaceUserShowOptions { - /** Include user metadata in the response */ - include_metadata?: boolean; -} - -/** Mapping of available query parameters for the users delete endpoint */ -export interface PlaceUserDeleteOptions { - /** Force permanent removal of user */ - force_removal?: boolean; -} - -/** Mapping of available query parameters for the users groups endpoint */ -export interface PlaceUserGroupsOptions { - /** List of email addresses */ - emails: string | string[]; -} - -/** Response for the users groups endpoint */ -export interface PlaceUserGroupResponse { - /** ID of the user */ - id?: string; - /** Email address of the user */ - email?: string; - /** Groups associated with the user */ - groups: string[]; -} - -/** Response for user resource token endpoints */ -export interface PlaceUserResourceToken { - /** Resource access token */ - token: string; - /** Unix epoch timestamp when the token expires */ - expires?: number; -} - -/** Mapping of available query parameters for the users metadata search endpoint */ -export interface PlaceUserMetadataSearchOptions { - /** JSON Path query filter */ - filter: string; - /** Maximum number of results to return */ - limit?: number; - /** Offset for pagination */ - offset?: number; -} - -/** Mapping of available query parameters for the user metadata endpoint */ -export interface PlaceUserMetadataOptions { - /** Name of the metadata key */ - name?: string; -} diff --git a/src/users/user.ts b/src/users/user.ts deleted file mode 100644 index d63027ab7..000000000 --- a/src/users/user.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { PlaceResource } from '../resources/resource'; - -export interface WorktimePreference { - /* Index of the day of the week. `0` being Sunday */ - day_of_week: 0 | 1 | 2 | 3 | 4 | 5 | 6; - blocks: WorktimeBlock[]; -} - -export interface WorktimeBlock { - /* Start time of work hours. e.g. `7.5` being 7:30AM */ - start_time: number; - /* End time of work hours. e.g. `18.5` being 6:30PM */ - end_time: number; - /** Name of the location the work is being performed at */ - location?: string; -} - -/** - * Representation of the user model in Place - */ -export class PlaceUser extends PlaceResource { - /** Hash of the email address of the user */ - public readonly email_digest: string; - /** ID of the authority associated with the user */ - public readonly authority_id: string; - /** Email address of the user */ - public readonly email: string; - /** Phone number of the user */ - public readonly phone: string; - /** Display nickname of the user */ - public readonly nickname: string; - /** Country that the user resides in */ - public readonly country: string; - /** Office building the user is associated */ - public readonly building: string; - /** Access control groups that user is associated */ - public readonly groups: string[]; - /** Avatar image for the user */ - public readonly image: string; - /** Additional metadata associated with the user */ - public readonly metadata: string; - /** Miscellaneous user data */ - public readonly misc: string; - /** Username credential of the user */ - public readonly login_name: string; - /** Organisation ID of the user */ - public readonly staff_id: string; - /** First name of the user */ - public readonly first_name: string; - /** Last name of the user */ - public readonly last_name: string; - /** Whether user is a support role */ - public readonly support: boolean; - /** Whether user is a system admin role */ - public readonly sys_admin: boolean; - /** Name of the active theme on the displayed UI */ - public readonly ui_theme: string; - /** Preferred language of the user */ - public readonly preferred_language: string; - /** Card Number associated with the user */ - public readonly card_number: string; - /** Organisational department the user belongs */ - public readonly department: string; - /** Default worktime preferences for the user */ - public readonly work_preferences: WorktimePreference[]; - /** Overrides of the worktime preferences for the user */ - public readonly work_overrides: Record; - /** ID of the user's photo in the PlaceOS uploads service */ - public readonly photo_upload_id: string; - /** Whether the user has opted in to location tracking */ - public readonly locatable: boolean; - /** Password */ - protected password = ''; - /** Password */ - protected confirm_password = ''; - - public readonly deleted?: boolean; - - constructor(raw_data: Partial = {}) { - super(raw_data); - this.authority_id = raw_data.authority_id || ''; - this.email = raw_data.email || ''; - this.email_digest = raw_data.email_digest || ''; - this.phone = raw_data.phone || ''; - this.nickname = raw_data.nickname || ''; - this.country = raw_data.country || ''; - this.building = raw_data.building || ''; - this.image = raw_data.image || ''; - this.metadata = raw_data.metadata || ''; - this.misc = raw_data.misc || ''; - this.login_name = raw_data.login_name || ''; - this.staff_id = raw_data.staff_id || ''; - this.first_name = raw_data.first_name || ''; - this.last_name = raw_data.last_name || ''; - this.support = !!raw_data.support; - this.sys_admin = !!raw_data.sys_admin; - this.ui_theme = raw_data.ui_theme || ''; - this.preferred_language = raw_data.preferred_language || ''; - this.card_number = raw_data.card_number || ''; - this.groups = raw_data.groups || []; - this.department = raw_data.department || ''; - this.photo_upload_id = raw_data.photo_upload_id || ''; - this.work_preferences = raw_data.work_preferences || []; - this.work_overrides = raw_data.work_overrides || ({} as any); - this.locatable = raw_data.locatable ?? true; - this.deleted = raw_data.deleted ?? false; - } -} diff --git a/src/utilities/abort-controller.ts b/src/utilities/abort-controller.ts deleted file mode 100644 index a366ff936..000000000 --- a/src/utilities/abort-controller.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { log } from './general'; - -/* istanbul ignore file */ -export class AbortControllerStub { - public abort() { - log('Stub', 'Aborted'); - } -} diff --git a/src/utilities/api.ts b/src/utilities/api.ts deleted file mode 100644 index b003ae67c..000000000 --- a/src/utilities/api.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { HashMap } from './types'; - -/** - * Convert map into a query string - * @param map Key value pairs to convert - */ -export function toQueryString(map: HashMap) { - let str = ''; - if (map) { - for (const key in map) { - if ( - map.hasOwnProperty(key) && - map[key] !== undefined && - map[key] !== null - ) { - str += `${str ? '&' : ''}${key}=${encodeURIComponent( - map[key], - )}`; - } - } - } - return str; -} diff --git a/src/utilities/async.ts b/src/utilities/async.ts deleted file mode 100644 index 9342f18fb..000000000 --- a/src/utilities/async.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Unsubscribe } from './signal'; - -/* istanbul ignore file */ - -/** - * @private - * Store for named timers - */ -const _timers: { [name: string]: number } = {}; -/** - * @private - * Store for named intervals - */ -const _intervals: { [name: string]: number } = {}; -/** - * @private - * Store for named subscription unsub callbacks - */ -type SubscriptionLike = { unsubscribe: () => void } | Unsubscribe; - -const _subscriptions: { [name: string]: SubscriptionLike } = {}; - -/** - * @private - * Perform any cleanup actions needed before the item is deleted - */ -export function destroyWaitingAsync() { - // Clear local timers - for (const key in _timers) { - if (_timers.hasOwnProperty(key)) { - clearAsyncTimeout(key); - } - } - // Clear local intervals - for (const key in _intervals) { - if (_intervals.hasOwnProperty(key)) { - clearAsyncInterval(key); - } - } - // Clear local subscriptions - for (const key in _subscriptions) { - if (_subscriptions.hasOwnProperty(key)) { - unsub(key); - } - } -} - -/** - * @private - * Creates a named timer - * @param name Name of the timer - * @param fn Callback function for the timer - * @param delay Callback delay - */ -export function timeout(name: string, fn: () => void, delay: number = 300) { - if (name && fn && fn instanceof Function) { - clearAsyncTimeout(name); - _timers[name] = setTimeout(() => { - fn(); - delete _timers[name]; - }, delay) as any; - } else { - throw new Error( - name - ? 'Cannot create named timeout without a name' - : 'Cannot create a timeout without a callback', - ); - } -} - -/** - * @private - * Clears the named timer - * @param name Timer name - */ -export function clearAsyncTimeout(name: string) { - if (_timers[name]) { - clearTimeout(_timers[name]); - delete _timers[name]; - } -} - -/** - * @private - * Creates a named interval - * @param name Name of the interval - * @param fn Callback function for the interval - * @param delay Callback delay - */ -export function interval(name: string, fn: () => void, delay: number = 300) { - if (name && fn && fn instanceof Function) { - clearAsyncInterval(name); - _intervals[name] = setInterval(() => fn(), delay) as any; - } else { - throw new Error( - name - ? 'Cannot create named interval without a name' - : 'Cannot create a interval without a callback', - ); - } -} - -/** - * @private - * Clears the named interval - * @param name Timer name - */ -export function clearAsyncInterval(name: string) { - if (_intervals[name]) { - clearInterval(_intervals[name]); - delete _intervals[name]; - } -} - -/** - * @private - * Store named subscription - * @param name Name of the subscription - * @param fn Unsubscribe callback or Subscription-like object - */ -export function subscription(name: string, fn: SubscriptionLike) { - unsub(name); - _subscriptions[name] = fn; -} - -/** - * @private - * Call unsubscribe callback with the given name - * @param name Name of the subscription - */ -export function unsub(name: string) { - if (_subscriptions && _subscriptions[name]) { - typeof _subscriptions[name] === 'function' - ? (_subscriptions[name] as Unsubscribe)() - : ( - _subscriptions[name] as { unsubscribe: () => void } - ).unsubscribe(); - delete _subscriptions[name]; - } -} diff --git a/src/utilities/general.ts b/src/utilities/general.ts deleted file mode 100644 index 71dde8cfc..000000000 --- a/src/utilities/general.ts +++ /dev/null @@ -1,286 +0,0 @@ -import { HashMap } from './types'; - -declare global { - interface Window { - debug: boolean; - } -} - -/** - * @hidden - */ -export type ConsoleIOStream = - | 'log' - | 'warn' - | 'debug' - | 'error' - | 'info' - | 'group' - | 'groupCollapsed' - | 'groupEnd'; -/* istanbul ignore next */ -/** - * Log message to the console - * @hidden - * @param type Where the message is from - * @param msg Body of the message - * @param args Javascript data to post after the message - * @param out IO stream to post message to - * @param color CSS colour to set the `type` value printed to the console - */ -export function log( - type: string, - msg: string, - args?: any, - out: ConsoleIOStream = 'debug', - color?: string, -) { - if (window.debug) { - const clr = color ? color : '#009688'; - const COLOURS = ['color: #0288D1', `color:${clr}`, 'color: default']; - if (args) { - if (consoleHasColours()) { - console[out]( - `%c[PlaceOS]%c[${type}] %c${msg}`, - ...COLOURS, - args, - ); - } else { - console[out](`[PlaceOS][${type}] ${msg}`, args); - } - } else { - if (consoleHasColours()) { - console[out](`%c[PlaceOS]%c[${type}] %c${msg}`, ...COLOURS); - } else { - console[out](`[PlaceOS][${type}] ${msg}`); - } - } - } -} - -export function scoped_log(scope: string) { - const payload = (args: any[]) => - args.length <= 0 ? undefined : args.length === 1 ? args[0] : args; - const write = (out: ConsoleIOStream, msg: string, args: any[]) => - log(scope, msg, payload(args), out); - const logger = (msg: string, ...args: any) => write('debug', msg, args); - logger.debug = (msg: string, ...args: any) => write('debug', msg, args); - logger.info = (msg: string, ...args: any) => write('info', msg, args); - logger.error = (msg: string, ...args: any) => write('error', msg, args); - logger.warn = (msg: string, ...args: any) => write('warn', msg, args); - logger.log = (msg: string, ...args: any) => write('log', msg, args); - logger.group = (msg: string, ...args: any) => write('group', msg, args); - logger.groupCollapsed = (msg: string, ...args: any) => - write('groupCollapsed', msg, args); - logger.groupEnd = (msg: string, ...args: any) => - write('groupEnd', msg, args); - return logger; -} - -/* istanbul ignore next */ -/** - * @private - * Whether the console has colours - * @hidden - */ -export function consoleHasColours() { - const doc = document as any; - return !(doc.documentMode || /Edge/.test(navigator.userAgent)); -} - -/** - * Get URL paramters from hash or query string - */ -export function getFragments(): HashMap { - const hash = window.location?.hash - ? window.location?.hash.slice(1) - : window.location?.href.split('#')[1] || ''; - let query = window.location?.search - ? window.location?.search.slice(1) - : window.location?.href.split('?')[1] || ''; - let hash_fragments = {}; - if (hash) { - // Hash can also contain the query so we need to check for it - if (hash.indexOf('?') >= 0) { - const parts = hash.split('?'); - hash_fragments = convertPairStringToMap(parts[0]); - /* istanbul ignore else */ - if (!query) { - query = parts[1]; - } - } else { - hash_fragments = convertPairStringToMap(hash); - } - } - let query_fragments = {}; - if (query) { - query_fragments = convertPairStringToMap(query); - } - return { ...hash_fragments, ...query_fragments }; -} - -/** - * @private - * Convert string of key value pairs to a dictionary object - * @param str String of values - */ -export function convertPairStringToMap(str: string): HashMap { - const map: HashMap = {}; - const str_pairs = str.split('&'); - for (const str_pair of str_pairs) { - const split_pair = str_pair.split('='); - if (split_pair[1]) { - map[decodeURIComponent(split_pair[0])] = decodeURIComponent( - split_pair[1], - ); - } - } - return map; -} - -/** - * @hidden - */ -const NONCE_CHARS = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - -/** - * @private - * Create a nonce with the given length - * @param length Length of the nonce string. Defaults to 40 characters - */ -export function generateNonce(length: number = 40): string { - let nonce = ''; - const crypto = window?.crypto; - if (crypto?.getRandomValues) { - // Rejection sampling to avoid modulo bias - const limit = 256 - (256 % NONCE_CHARS.length); - const buffer = new Uint8Array(length * 2); - while (nonce.length < length) { - crypto.getRandomValues(buffer); - for (const byte of buffer) { - if (byte < limit && nonce.length < length) { - nonce += NONCE_CHARS.charAt(byte % NONCE_CHARS.length); - } - } - } - return nonce; - } - for (let i = 0; i < length; i++) { - nonce += NONCE_CHARS.charAt( - Math.floor(Math.random() * NONCE_CHARS.length), - ); - } - return nonce; -} - -/** - * @private - * Replace the URL fragment with the given name - * @param name Name of the fragment to remove - */ -export function removeFragment(name: string) { - const new_hash = (window.location?.hash || '') - .replace(new RegExp(`${name}[a-zA-Z0-9_+-.%=]*&?`, 'g'), '') - .replace(/&&/g, '&') - .replace(/#&/g, '#') - .replace(/&$/g, '#'); - const new_search = (window.location?.search || '') - .replace(new RegExp(`${name}[a-zA-Z0-9_+-.%=]*&?`, 'g'), '') - .replace(/&&/g, '&') - .replace(/\?&/g, '#') - .replace(/&$/g, '#'); - if (window.history?.replaceState) - window.history?.replaceState( - null, - '', - `${window.location?.pathname}${new_hash}${new_search}`, - ); -} - -/** - * Convert byte values into a display string - * @param bytes Number of bytes - */ -export function humanReadableByteCount(bytes: number, si: boolean = false) { - const unit = si ? 1000.0 : 1024.0; - - if (bytes < unit) { - return bytes + (si ? ' iB' : ' B'); - } - - const exp = Math.floor(Math.log(bytes) / Math.log(unit)); - const pre = (si ? 'kMGTPE' : 'KMGTPE').charAt(exp - 1) + (si ? 'iB' : 'B'); - - return (bytes / Math.pow(unit, exp)).toFixed(2) + ' ' + pre; -} - -/** - * @private - * Parse URLs from Link header string - * @param header Header value - */ -export function parseLinkHeader(header: string): HashMap { - if (header.length === 0) { - throw new Error('Input must not be of zero length'); - } - - // Split parts by comma - const parts = header.split(','); - const links: HashMap = {}; - // Parse each part into a named link - for (const part of parts) { - const section = part.split(';'); - if (section.length !== 2) { - throw new Error("Section could not be split on ';'"); - } - const url = section[0].replace(/<(.*)>/, '$1').trim(); - const name = section[1].replace(/rel="(.*)"/, '$1').trim(); - links[name] = url; - } - return links; -} - -/** - * @private - * Remove properties from object with given values - * @param object Object to clean - * @param delete_values List of property values to remove - */ -export function cleanObject(object: HashMap, delete_values: any[]) { - for (const key in object) { - if ( - object.hasOwnProperty(key) && - delete_values.indexOf(object[key]) >= 0 - ) { - delete object[key]; - } - } - return object; -} - -export function isMobileSafari() { - return ( - [ - 'iPad Simulator', - 'iPhone Simulator', - 'iPod Simulator', - 'iPad', - 'iPhone', - 'iPod', - ].includes(navigator.platform) || - // iPad on iOS 13 detection - (navigator.userAgent.includes('Mac') && 'ontouchend' in document) - ); -} - -export function isNestedFrame() { - return window.location !== window.parent.location; -} - -export function simplifiedTime( - time: number = Date.now(), - interval: number = 60 * 1000, -) { - return Math.floor(time / interval); -} diff --git a/src/utilities/nodejs.ts b/src/utilities/nodejs.ts deleted file mode 100644 index 9faab1dc7..000000000 --- a/src/utilities/nodejs.ts +++ /dev/null @@ -1,19 +0,0 @@ -const store: Record = {}; - -/** istanbul ignore */ -export async function preSetupNode() { - const global_space: any = globalThis; - global_space.debug = true; - global_space.document = {}; - global_space.navigator = {}; - global_space.webSocket = (await import('websocket' as any)).w3cwebsocket; - global_space.fetch = await import('node-fetch' as any); - global_space.localStorage = (globalThis as any).sessionStorage = { - getItem: (s: any) => store[s], - setItem: (s: any, v: any) => (store[s] = v), - removeItem: (s: any) => delete store[s], - length: 0, - keys: () => Object.keys(store), - }; - (globalThis as any).window = globalThis; -} diff --git a/src/utilities/signal.ts b/src/utilities/signal.ts deleted file mode 100644 index 12cf16904..000000000 --- a/src/utilities/signal.ts +++ /dev/null @@ -1,85 +0,0 @@ -export type SignalListener = (value: T, previous: T) => void; -export type Unsubscribe = () => void; - -export interface SubscribeOptions { - emitCurrent?: boolean; -} - -export interface Signal { - (): T; - readonly value: T; - subscribe( - listener: SignalListener, - options?: SubscribeOptions, - ): Unsubscribe; -} - -export interface WritableSignal extends Signal { - set(value: T): void; - update(fn: (value: T) => T): void; - asReadonly(): Signal; -} - -export function createSignal(initial: T): WritableSignal { - let current = initial; - const listeners = new Set>(); - - const signal = (() => current) as WritableSignal; - Object.defineProperty(signal, 'value', { - get: () => current, - enumerable: true, - }); - signal.subscribe = ( - listener: SignalListener, - options: SubscribeOptions = {}, - ) => { - listeners.add(listener); - if (options.emitCurrent !== false) listener(current, current); - return () => listeners.delete(listener); - }; - signal.set = (value: T) => { - if (Object.is(value, current)) return; - const previous = current; - current = value; - for (const listener of [...listeners]) { - listener(current, previous); - } - }; - signal.update = (fn: (value: T) => T) => signal.set(fn(current)); - signal.asReadonly = () => signal as Signal; - return signal; -} - -export function computedSignal( - compute: () => T, - dependencies: Signal[], -): Signal { - const signal = createSignal(compute()); - for (const dependency of dependencies) { - dependency.subscribe(() => signal.set(compute()), { - emitCurrent: false, - }); - } - return signal.asReadonly(); -} - -export function waitForSignal( - signal: Signal, - predicate: (value: T) => boolean = Boolean as any, -): Promise { - if (predicate(signal.value)) return Promise.resolve(signal.value); - return new Promise((resolve) => { - const unsubscribe = signal.subscribe( - (value) => { - if (!predicate(value)) return; - unsubscribe(); - resolve(value); - }, - { emitCurrent: false }, - ); - }); -} - -export function sleep(delay: number): Promise { - return new Promise((resolve) => setTimeout(resolve, delay)); -} diff --git a/src/utilities/types.ts b/src/utilities/types.ts deleted file mode 100644 index 97184228e..000000000 --- a/src/utilities/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface HashMap { - [name: string]: T; -} diff --git a/src/utilities/websocket.ts b/src/utilities/websocket.ts deleted file mode 100644 index 2ce1f9bd9..000000000 --- a/src/utilities/websocket.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { Unsubscribe } from './signal'; - -export interface WebSocketConnection { - next(value: T): void; - complete(): void; - subscribe( - next: (value: T) => void, - error?: (error: any) => void, - complete?: () => void, - ): Unsubscribe; -} - -export interface WebSocketConfig { - url: string; - serializer?: ( - value: T, - ) => string | ArrayBufferLike | Blob | ArrayBufferView; - deserializer?: (event: MessageEvent) => T; -} - -export class MemoryWebSocket implements WebSocketConnection { - private _listeners = new Set<(value: T) => void>(); - private _error_listeners = new Set<(error: any) => void>(); - private _complete_listeners = new Set<() => void>(); - private _closed = false; - - public next(value: T): void { - if (this._closed) return; - for (const listener of [...this._listeners]) listener(value); - } - - public error(error: any): void { - if (this._closed) return; - for (const listener of [...this._error_listeners]) listener(error); - this._closed = true; - this._clear(); - } - - public complete(): void { - if (this._closed) return; - for (const listener of [...this._complete_listeners]) listener(); - this._closed = true; - this._clear(); - } - - public subscribe( - next: (value: T) => void, - error?: (error: any) => void, - complete?: () => void, - ): Unsubscribe { - if (this._closed) { - complete?.(); - return () => null; - } - this._listeners.add(next); - if (error) this._error_listeners.add(error); - if (complete) this._complete_listeners.add(complete); - return () => { - this._listeners.delete(next); - if (error) this._error_listeners.delete(error); - if (complete) this._complete_listeners.delete(complete); - }; - } - - private _clear(): void { - this._listeners.clear(); - this._error_listeners.clear(); - this._complete_listeners.clear(); - } -} - -export class BrowserWebSocket - extends MemoryWebSocket - implements WebSocketConnection -{ - private _socket: WebSocket; - private _queue: T[] = []; - - constructor(private _config: WebSocketConfig) { - super(); - this._socket = new WebSocket(_config.url); - this._socket.onopen = () => { - const queue = [...this._queue]; - this._queue = []; - for (const value of queue) this.next(value); - }; - this._socket.onmessage = (event) => { - super.next(this._deserialize(event)); - }; - this._socket.onerror = (event) => this.error(event); - this._socket.onclose = () => super.complete(); - } - - public override next(value: T): void { - if (this._socket.readyState === WebSocket.OPEN) { - this._socket.send(this._serialize(value)); - } else { - this._queue.push(value); - } - } - - public override complete(): void { - this._socket.close(); - super.complete(); - } - - private _serialize( - value: T, - ): string | ArrayBufferLike | Blob | ArrayBufferView { - return this._config.serializer - ? this._config.serializer(value) - : `${value}`; - } - - private _deserialize(event: MessageEvent): T { - return this._config.deserializer - ? this._config.deserializer(event) - : (event.data as T); - } -} - -export function webSocket( - config: string | WebSocketConfig, -): WebSocketConnection { - return new BrowserWebSocket( - typeof config === 'string' ? { url: config } : config, - ); -} diff --git a/src/webhook/functions.ts b/src/webhook/functions.ts deleted file mode 100644 index b8a38866c..000000000 --- a/src/webhook/functions.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { apiEndpoint } from '../auth/functions'; -import { get } from '../http/functions'; -import { PlaceTrigger } from '../triggers/trigger'; -import { toQueryString } from '../utilities/api'; -import { HashMap } from '../utilities/types'; -import { WebhookShowOptions } from './interfaces'; - -const PATH = 'webhook'; - -/** Get webhook trigger details */ -export function showWebhook( - id: string, - query_params: WebhookShowOptions = {}, -): Promise { - const q = toQueryString(query_params); - const url = `${apiEndpoint()}/${PATH}/${encodeURIComponent(id)}${q ? '?' + q : ''}`; - return get(url).then((resp: HashMap) => new PlaceTrigger(resp)); -} diff --git a/src/webhook/interfaces.ts b/src/webhook/interfaces.ts deleted file mode 100644 index 55a93d967..000000000 --- a/src/webhook/interfaces.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface WebhookShowOptions { - secret?: string; -} diff --git a/src/webrtc/functions.ts b/src/webrtc/functions.ts deleted file mode 100644 index fc1358758..000000000 --- a/src/webrtc/functions.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { apiEndpoint } from '../auth'; -import { get, post } from '../http/functions'; -import { toQueryString } from '../utilities/api'; -import { HashMap } from '../utilities/types'; -import { - PlaceGuestParticipant, - PlaceKickReason, - PlaceWebrtcMember, - PlaceWebrtcRoomDetails, - PlaceWebrtcRoomsQueryOptions, -} from './interfaces'; - -/** - * @private - */ -const PATH = 'webrtc'; - -/** - * Query the list of public chat rooms for the current domain - * @param query_params Query parameters to add to the request URL - */ -export function queryWebrtcRooms( - query_params: PlaceWebrtcRoomsQueryOptions = {}, -): Promise { - const query = toQueryString(query_params); - const url = `${apiEndpoint()}/${PATH}/rooms${query ? '?' + query : ''}`; - return get(url).then((resp: HashMap) => resp as PlaceWebrtcRoomDetails[]); -} - -/** - * Get the details of a public chat room - * @param system_id Either a system ID or a unique permalink - */ -export function showWebrtcRoom( - system_id: string, -): Promise { - const url = `${apiEndpoint()}/${PATH}/room/${encodeURIComponent(system_id)}`; - return get(url).then((resp: HashMap) => resp as PlaceWebrtcRoomDetails); -} - -/** - * Get a list of connected users in a chat session - * @param session_id ID of the chat session - */ -export function webrtcSessionMembers( - session_id: string, -): Promise { - const url = `${apiEndpoint()}/${PATH}/members/${encodeURIComponent(session_id)}`; - return get(url).then((resp: HashMap) => resp as PlaceWebrtcMember[]); -} - -/** - * Request guest access to an anonymous chat room. - * The guest participant details will be forwarded to any listening systems. - * Additional fields provided as part of the guest post will also be forwarded. - * @param system_id Either a system ID or a unique permalink - * @param participant Guest participant details - */ -export function webrtcGuestEntry( - system_id: string, - participant: PlaceGuestParticipant, -): Promise { - const url = `${apiEndpoint()}/${PATH}/guest_entry/${encodeURIComponent(system_id)}`; - return post(url, participant).then(() => undefined); -} - -/** - * End a guest call gracefully. - * This will remove the authentication token and close any open websockets. - */ -export function webrtcGuestExit(): Promise { - const url = `${apiEndpoint()}/${PATH}/guest/exit`; - return post(url, {}).then(() => undefined); -} - -/** - * Kick a user from a chat session. - * Similar to guest exit without the token expiration. - * Other members of the call will stop communicating with them. - * @param user_id ID of the user to kick - * @param session_id ID of the chat session - * @param reason Reason for kicking the user - */ -export function webrtcKickUser( - user_id: string, - session_id: string, - reason: PlaceKickReason, -): Promise { - const url = `${apiEndpoint()}/${PATH}/kick/${encodeURIComponent(user_id)}/${encodeURIComponent(session_id)}`; - return post(url, reason).then(() => undefined); -} - -/** - * Transfer a user from one chat to another. - * For authorized users to move people from one chat to another. - * @param user_id ID of the user to transfer - * @param session_id ID of the current chat session - * @param connection_details Optional custom connection details for the transfer - */ -export function webrtcTransferUser( - user_id: string, - session_id: string, - connection_details?: Record, -): Promise { - const url = `${apiEndpoint()}/${PATH}/transfer/${encodeURIComponent(user_id)}/${encodeURIComponent(session_id)}`; - return post(url, connection_details || {}).then(() => undefined); -} - -/** - * Get the WebRTC signaller websocket URL. - * This is the endpoint for managing call participants. - */ -export function webrtcSignallerUrl(): string { - const endpoint = apiEndpoint(); - const wsProtocol = endpoint.startsWith('https') ? 'wss:' : 'ws:'; - const httpProtocol = endpoint.startsWith('https') ? 'https:' : 'http:'; - return endpoint.replace(httpProtocol, wsProtocol) + `${PATH}/signaller`; -} diff --git a/src/webrtc/interfaces.ts b/src/webrtc/interfaces.ts deleted file mode 100644 index 424b68a81..000000000 --- a/src/webrtc/interfaces.ts +++ /dev/null @@ -1,49 +0,0 @@ -import type { PlaceSystem } from '../systems/system'; -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Mapping of available query parameters for the webrtc rooms index endpoint */ -export interface PlaceWebrtcRoomsQueryOptions extends PlaceResourceQueryOptions {} - -/** Guest participant details for joining an anonymous chat room */ -export interface PlaceGuestParticipant { - /** Captcha token for verification (required) */ - captcha: string; - /** Display name for the guest (required) */ - name: string; - /** User ID for the guest (required) */ - user_id: string; - /** Session ID for the chat (required) */ - session_id: string; - /** Email address of the guest */ - email?: string; - /** Phone number of the guest */ - phone?: string; - /** Type of participant */ - type?: string; - /** User ID of the person to chat with directly */ - chat_to_user_id?: string; -} - -/** Reason for kicking a user from a chat */ -export interface PlaceKickReason { - /** Reason for ending the call (required) */ - reason: string; -} - -/** Details of a WebRTC public chat room */ -export interface PlaceWebrtcRoomDetails { - /** System information for the room */ - system?: Partial; -} - -/** Member details in a WebRTC chat session */ -export interface PlaceWebrtcMember { - /** User ID of the member */ - user_id?: string; - /** Display name of the member */ - name?: string; - /** Email of the member */ - email?: string; - /** Whether the member is a guest */ - is_guest?: boolean; -} diff --git a/src/zones/functions.ts b/src/zones/functions.ts deleted file mode 100644 index cefa70585..000000000 --- a/src/zones/functions.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { - create, - query, - remove, - show, - task, - update, -} from '../resources/functions'; -import { PlaceResourceQueryOptions } from '../resources/interface'; -import { PlaceTrigger } from '../triggers/trigger'; -import { HashMap } from '../utilities/types'; -import { - PlaceZoneMetadataQueryOptions, - PlaceZoneQueryOptions, - PlaceZoneShowOptions, -} from './interfaces'; -import { PlaceZone } from './zone'; - -/** - * @private - */ -const PATH = 'zones'; - -/** Convert raw server data to an application object */ -function process(item: Partial) { - return new PlaceZone(item); -} - -/** - * Query the available applications - * @param query_params Query parameters to add the to request URL - */ -export function queryZones(query_params: PlaceZoneQueryOptions = {}) { - return query({ query_params, fn: process, path: PATH }); -} - -/** - * List the set of tags on the existing zones - * @param query_params - */ -export function listZoneTags(query_params: PlaceZoneQueryOptions = {}) { - return show({ - id: 'tags', - query_params, - fn: (i) => i as string[], - path: PATH, - }); -} - -/** - * Get the data for an application - * @param id ID of the application to retrieve - * @param query_params Query parameters to add the to request URL - */ -export function showZone(id: string, query_params: PlaceZoneShowOptions = {}) { - return show({ id, query_params, fn: process, path: PATH }); -} - -/** - * Update the application in the database - * @param id ID of the application - * @param form_data New values for the application - * @param query_params Query parameters to add the to request URL - * @param method HTTP verb to use on request. Defaults to `patch` - */ -export function updateZone( - id: string, - form_data: Partial, - method: 'put' | 'patch' = 'patch', -) { - return update({ - id, - form_data, - query_params: {}, - method, - fn: process, - path: PATH, - }); -} - -/** - * Add a new application to the database - * @param form_data Application data - * @param query_params Query parameters to add the to request URL - */ -export function addZone(form_data: Partial) { - return create({ form_data, query_params: {}, fn: process, path: PATH }); -} - -/** - * Remove a zone from the database - * @param id ID of the zone - */ -export function removeZone(id: string) { - return remove({ id, query_params: {}, path: PATH }); -} - -/** - * Query the triggers for a zone - * @param id ID of the zone - * @param query_params Query parameters to add the to request URL - */ -export function listZoneTriggers( - id: string, - query_params: PlaceResourceQueryOptions = {}, -) { - return query({ - query_params, - fn: (i: Partial) => new PlaceTrigger(i), - path: `${PATH}/${id}/triggers`, - }); -} - -/** - * Execute a function of the system's module under a given zone - * @param id Zone ID - * @param method Name of the function to execute - * @param module Class name of the Module e.g. `Display`, `Lighting` etc. - * @param index Module index. Defaults to `1` - * @param args Array of arguments to pass to the executed method - */ -export function executeOnZone( - id: string, - method: string, - module: string, - index: number = 1, - args: any[] = [], -): Promise { - return task({ - id, - task_name: `exec/${encodeURIComponent( - module + '_' + index, - )}/${encodeURIComponent(method)}`, - form_data: args, - path: PATH, - }); -} - -/** - * Get metadata associated with the selected zone - * @param id Zone ID - * @param query_params Query parameters to add to the request - */ -export function zoneMetadata( - id: string, - query_params: PlaceZoneMetadataQueryOptions = {}, -): Promise { - return task({ - id, - task_name: 'metadata', - form_data: query_params, - method: 'get', - path: PATH, - }); -} diff --git a/src/zones/interfaces.ts b/src/zones/interfaces.ts deleted file mode 100644 index 1812a16a8..000000000 --- a/src/zones/interfaces.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { PlaceResourceQueryOptions } from '../resources/interface'; - -/** Mapping of available query parameters for the zones index endpoint */ -export interface PlaceZoneQueryOptions extends PlaceResourceQueryOptions { - /** ID of the parent zone to filter the results (supports comma-separated list) */ - parent_id?: string; - /** List of space separated tags to filter the results */ - tags?: string; - /** ID of the system to filter the results */ - control_system_id?: string; - /** Whether zones should include a count of their children */ - include_children_count?: boolean; -} - -/** Mapping of available query parameters for the zones show endpoint */ -export interface PlaceZoneShowOptions { - /** Includes trigger data in the response (must have support or admin permissions) */ - complete?: boolean; - - /** - * Returns the specified settings key if the key exists - * in the zone (available to all authenticated users) - */ - data?: string; -} - -/** Mapping of available query parameters for the zone metadata endpoint */ -export interface PlaceZoneMetadataQueryOptions { - /** The name of the metadata key to retrieve */ - name?: string; -} diff --git a/src/zones/zone.ts b/src/zones/zone.ts deleted file mode 100644 index 535c43e7d..000000000 --- a/src/zones/zone.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { PlaceResource } from '../resources/resource'; -import { EncryptionLevel } from '../settings/interfaces'; -import { PlaceSettings } from '../settings/settings'; -import { PlaceTrigger } from '../triggers/trigger'; - -/** - * @hidden - */ -export interface PlaceZoneComplete extends Partial { - trigger_data?: PlaceTrigger[]; -} - -export class PlaceZone extends PlaceResource { - /** Tuple of user settings of differring encryption levels for the zone */ - public readonly settings: [ - PlaceSettings | null, - PlaceSettings | null, - PlaceSettings | null, - PlaceSettings | null, - ] = [null, null, null, null]; - /** Description of the zone's purpose */ - public readonly description: string; - /** ID of the parent zone */ - public readonly parent_id: string; - /** List of triggers associated with the zone */ - public readonly triggers: readonly string[]; - /** List of tags associated with the zone */ - public readonly tags: string[]; - /** Geo-location details associated with the zone */ - public readonly location: string; - /** Custom display name for the zone */ - public readonly display_name: string; - /** Organisational code associated with the zone */ - public readonly code: string; - /** Organisational categorisation of the zone */ - public readonly type: string; - /** Count of resources associated with the zone */ - public readonly count: number; - /** Count of child zones for this zone */ - public readonly children_count?: number; - /** Amount of physical capacity associated with the zone */ - public readonly capacity: number; - /** ID or URL of or in a map associated with the zone */ - public readonly map_id: string; - /** List of image URLs */ - public readonly images: string[]; - /** Timezone of the associated real world location */ - public readonly timezone: string; - /** List of playlist IDs associated with the system */ - public readonly playlists: readonly string[]; - /** - * List of modules associated with the system. - * Only available from the show method with the `complete` query parameter - */ - public readonly trigger_list: readonly PlaceTrigger[] = []; - - constructor(raw_data: PlaceZoneComplete = {}) { - super(raw_data); - this.description = raw_data.description || ''; - this.tags = raw_data.tags || []; - this.triggers = raw_data.triggers || []; - this.settings = raw_data.settings || [null, null, null, null]; - this.parent_id = raw_data.parent_id || ''; - this.location = raw_data.location || ''; - this.display_name = raw_data.display_name || ''; - this.code = raw_data.code || ''; - this.type = raw_data.type || ''; - this.count = raw_data.count || 0; - this.capacity = raw_data.capacity || 0; - this.map_id = raw_data.map_id || ''; - this.timezone = raw_data.timezone || ''; - this.images = raw_data.images || []; - this.playlists = raw_data.playlists || []; - if (isFinite(Number(raw_data.children_count))) - this.children_count = raw_data.children_count; - if (typeof this.settings !== 'object') { - (this as any).settings = [null, null, null, null]; - } - for (const level in EncryptionLevel) { - if (!isNaN(Number(level)) && !this.settings[level]) { - this.settings[level] = new PlaceSettings({ - parent_id: this.id, - encryption_level: +level, - }); - } - } - if (raw_data.trigger_data && raw_data.trigger_data instanceof Array) { - this.trigger_list = raw_data.trigger_data.map( - (trigger) => new PlaceTrigger(trigger), - ); - } - } -} diff --git a/test/alerts/alert.spec.ts b/test/alerts/alert.spec.ts deleted file mode 100644 index 69d88c511..000000000 --- a/test/alerts/alert.spec.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceAlert } from '../../src/alerts/alert'; -import { PlaceAlertDashboard } from '../../src/alerts/dashboard'; - -describe('PlaceAlert', () => { - let alert: PlaceAlert; - - beforeEach(() => { - alert = new PlaceAlert({ - id: 'alert-test', - alert_dashboard_id: 'dashboard-123', - authority_id: 'auth-456', - description: 'Test alert for monitoring', - enabled: true, - conditions: { - time_dependents: [], - comparisons: [ - { - left: 'temperature', - operator: 'gt', - right: 25, - }, - ], - }, - severity: 'high', - alert_type: 'threshold', - debounce_period: 300, - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(alert).toBeTruthy(); - expect(alert).toBeInstanceOf(PlaceAlert); - }); - - test('should expose alert_dashboard_id', () => { - expect(alert.alert_dashboard_id).toBe('dashboard-123'); - }); - - test('should expose authority_id', () => { - expect(alert.authority_id).toBe('auth-456'); - }); - - test('should expose description', () => { - expect(alert.description).toBe('Test alert for monitoring'); - }); - - test('should expose enabled status', () => { - expect(alert.enabled).toBe(true); - }); - - test('should expose conditions', () => { - expect(alert.conditions).toBeTruthy(); - expect(alert.conditions.comparisons).toHaveLength(1); - expect(alert.conditions.comparisons[0].left).toBe('temperature'); - }); - - test('should expose severity', () => { - expect(alert.severity).toBe('high'); - }); - - test('should expose alert_type', () => { - expect(alert.alert_type).toBe('threshold'); - }); - - test('should expose debounce_period', () => { - expect(alert.debounce_period).toBe(300); - }); - - test('should have default values', () => { - const minimal = new PlaceAlert({}); - expect(minimal.authority_id).toBe(''); - expect(minimal.description).toBe(''); - expect(minimal.enabled).toBe(false); - expect(minimal.conditions).toEqual({ - time_dependents: [], - comparisons: [], - }); - expect(minimal.severity).toBe('low'); - expect(minimal.alert_type).toBe('threshold'); - expect(minimal.debounce_period).toBe(0); - expect(minimal.alert_dashboard_id).toBe(''); - expect(minimal.alert_dashboard_details).toBeUndefined(); - }); - - test('should include alert_dashboard_details if provided', () => { - const dashboard = new PlaceAlertDashboard({ - id: 'dashboard-123', - authority_id: 'auth-456', - description: 'Dashboard description', - enabled: true, - }); - - const alertWithDashboard = new PlaceAlert({ - id: 'alert-test', - alert_dashboard_id: 'dashboard-123', - authority_id: 'auth-456', - alert_dashboard_details: dashboard, - }); - - expect(alertWithDashboard.alert_dashboard_details).toBeTruthy(); - expect(alertWithDashboard.alert_dashboard_details).toBeInstanceOf( - PlaceAlertDashboard, - ); - }); -}); diff --git a/test/alerts/dashboard.spec.ts b/test/alerts/dashboard.spec.ts deleted file mode 100644 index fd68f135a..000000000 --- a/test/alerts/dashboard.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceAlertDashboard } from '../../src/alerts/dashboard'; - -describe('PlaceAlertDashboard', () => { - let dashboard: PlaceAlertDashboard; - - beforeEach(() => { - dashboard = new PlaceAlertDashboard({ - id: 'dashboard-test', - authority_id: 'auth-789', - description: 'Main monitoring dashboard', - enabled: true, - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(dashboard).toBeTruthy(); - expect(dashboard).toBeInstanceOf(PlaceAlertDashboard); - }); - - test('should expose authority_id', () => { - expect(dashboard.authority_id).toBe('auth-789'); - }); - - test('should expose description', () => { - expect(dashboard.description).toBe('Main monitoring dashboard'); - }); - - test('should expose enabled status', () => { - expect(dashboard.enabled).toBe(true); - }); - - test('should have default values', () => { - const minimal = new PlaceAlertDashboard({}); - expect(minimal.authority_id).toBe(''); - expect(minimal.description).toBe(''); - expect(minimal.enabled).toBe(false); - }); -}); diff --git a/test/alerts/functions.spec.ts b/test/alerts/functions.spec.ts deleted file mode 100644 index ce9f2437d..000000000 --- a/test/alerts/functions.spec.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import { PlaceAlert } from '../../src/alerts/alert'; -import { PlaceAlertDashboard } from '../../src/alerts/dashboard'; -import * as SERVICE from '../../src/alerts/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Alert Dashboards API', () => { - test('should allow querying alert dashboards', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAlertDashboards(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAlertDashboard); - list = await SERVICE.queryAlertDashboards({}); - }); - - test('should allow showing alert dashboard details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showAlertDashboard('1'); - expect(item).toBeInstanceOf(PlaceAlertDashboard); - }); - - test('should allow creating new alert dashboards', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAlertDashboard({}); - expect(item).toBeInstanceOf(PlaceAlertDashboard); - }); - - test('should allow updating alert dashboard details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAlertDashboard('1', {}); - expect(item).toBeInstanceOf(PlaceAlertDashboard); - item = await SERVICE.updateAlertDashboard('1', {}, 'patch'); - }); - - test('should allow removing alert dashboards', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeAlertDashboard('1'); - expect(item).toBeFalsy(); - }); - - test('should allow listing dashboard alerts', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.listDashboardAlerts('dashboard-1'); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAlert); - }); -}); - -describe('Alerts API', () => { - test('should allow querying alerts', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAlerts(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAlert); - list = await SERVICE.queryAlerts({}); - }); - - test('should allow showing alert details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showAlert('1'); - expect(item).toBeInstanceOf(PlaceAlert); - item = await SERVICE.showAlert('1', {}); - }); - - test('should allow creating new alerts', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAlert({}); - expect(item).toBeInstanceOf(PlaceAlert); - }); - - test('should allow updating alert details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAlert('1', {}); - expect(item).toBeInstanceOf(PlaceAlert); - item = await SERVICE.updateAlert('1', {}, 'patch'); - }); - - test('should allow removing alerts', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeAlert('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/applications/application.spec.ts b/test/applications/application.spec.ts deleted file mode 100644 index d70d7b894..000000000 --- a/test/applications/application.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceApplication } from '../../src/applications/application'; - -describe('PlaceApplication', () => { - let application: PlaceApplication; - - beforeEach(() => { - application = new PlaceApplication({ - id: 'dep-test', - owner_id: 'test-man', - uid: 'no-so-unique', - secret: "Shhh... It's a secret", - scopes: 'office,building,over,there', - redirect_uri: 'https://over.yonder/oauth.html', - skip_authorization: true, - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(application).toBeTruthy(); - expect(application).toBeInstanceOf(PlaceApplication); - }); - - test('should expose owner ID', () => { - expect(application.owner_id).toBe('test-man'); - }); - - test('should expose scopes', () => { - expect(application.scopes).toBe('office,building,over,there'); - }); - - test('should expose redirect_uri', () => { - expect(application.redirect_uri).toBe('https://over.yonder/oauth.html'); - }); - - test('should expose skip_authorization', () => { - expect(application.skip_authorization).toBe(true); - }); - - test('should expose unique ID', () => { - expect(application.uid).toBe('no-so-unique'); - }); - - test('should expose secret', () => { - expect(application.secret).toBe("Shhh... It's a secret"); - }); -}); diff --git a/test/applications/functions.spec.ts b/test/applications/functions.spec.ts deleted file mode 100644 index 071cc712f..000000000 --- a/test/applications/functions.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import { PlaceApplication } from '../../src/applications/application'; -import * as SERVICE from '../../src/applications/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Applications API', () => { - test('should allow querying applications', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryApplications(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceApplication); - list = await SERVICE.queryApplications({}); - }); - - test('should allow showing application details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showApplication('1'); - expect(item).toBeInstanceOf(PlaceApplication); - }); - - test('should allow creating new applications', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addApplication({}); - expect(item).toBeInstanceOf(PlaceApplication); - }); - - test('should allow updating application details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateApplication('1', {}); - expect(item).toBeInstanceOf(PlaceApplication); - item = await SERVICE.updateApplication('1', {}, 'patch'); - }); - - test('should allow removing applications', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeApplication('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/assets/assets.spec.ts b/test/assets/assets.spec.ts deleted file mode 100644 index 81f3c5b52..000000000 --- a/test/assets/assets.spec.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { - PlaceAsset, - PlaceAssetCategory, - PlaceAssetPurchaseOrder, - PlaceAssetType, -} from '../../src/assets/assets.class'; - -describe('PlaceAssetCategory', () => { - let category: PlaceAssetCategory; - - beforeEach(() => { - category = new PlaceAssetCategory({ - id: 'cat-test', - authority_id: 'authority-1', - parent_category_id: 'cat-parent', - name: 'Test Category', - description: 'A test category', - hidden: true, - created_at: 1000, - updated_at: 2000, - }); - }); - - test('should create instance', () => { - expect(category).toBeTruthy(); - expect(category).toBeInstanceOf(PlaceAssetCategory); - }); - - test('should expose id', () => { - expect(category.id).toBe('cat-test'); - }); - - test('should expose authority_id', () => { - expect(category.authority_id).toBe('authority-1'); - }); - - test('should expose parent_category_id', () => { - expect(category.parent_category_id).toBe('cat-parent'); - }); - - test('should expose name', () => { - expect(category.name).toBe('Test Category'); - }); - - test('should expose description', () => { - expect(category.description).toBe('A test category'); - }); - - test('should expose hidden', () => { - expect(category.hidden).toBe(true); - }); - - test('should expose created_at', () => { - expect(category.created_at).toBe(1000); - }); - - test('should expose updated_at', () => { - expect(category.updated_at).toBe(2000); - }); - - test('should use default values for missing properties', () => { - const emptyCategory = new PlaceAssetCategory({}); - expect(emptyCategory.id).toBe(''); - expect(emptyCategory.authority_id).toBe(''); - expect(emptyCategory.parent_category_id).toBe(''); - expect(emptyCategory.name).toBe(''); - expect(emptyCategory.description).toBe(''); - expect(emptyCategory.hidden).toBe(false); - expect(emptyCategory.created_at).toBe(0); - expect(emptyCategory.updated_at).toBe(0); - }); -}); - -describe('PlaceAssetPurchaseOrder', () => { - let purchaseOrder: PlaceAssetPurchaseOrder; - - beforeEach(() => { - purchaseOrder = new PlaceAssetPurchaseOrder({ - id: 'po-test', - purchase_order_number: 'PO-12345', - invoice_number: 'INV-67890', - supplier_details: { name: 'Acme Corp', contact: 'john@acme.com' }, - purchase_date: 1609459200, - unit_price: 999, - expected_service_start_date: 1609545600, - expected_service_end_date: 1640995200, - created_at: 1000, - updated_at: 2000, - }); - }); - - test('should create instance', () => { - expect(purchaseOrder).toBeTruthy(); - expect(purchaseOrder).toBeInstanceOf(PlaceAssetPurchaseOrder); - }); - - test('should expose id', () => { - expect(purchaseOrder.id).toBe('po-test'); - }); - - test('should expose purchase_order_number', () => { - expect(purchaseOrder.purchase_order_number).toBe('PO-12345'); - }); - - test('should expose invoice_number', () => { - expect(purchaseOrder.invoice_number).toBe('INV-67890'); - }); - - test('should expose supplier_details', () => { - expect(purchaseOrder.supplier_details).toEqual({ - name: 'Acme Corp', - contact: 'john@acme.com', - }); - }); - - test('should expose purchase_date', () => { - expect(purchaseOrder.purchase_date).toBe(1609459200); - }); - - test('should expose unit_price', () => { - expect(purchaseOrder.unit_price).toBe(999); - }); - - test('should expose expected_service_start_date', () => { - expect(purchaseOrder.expected_service_start_date).toBe(1609545600); - }); - - test('should expose expected_service_end_date', () => { - expect(purchaseOrder.expected_service_end_date).toBe(1640995200); - }); - - test('should expose created_at', () => { - expect(purchaseOrder.created_at).toBe(1000); - }); - - test('should expose updated_at', () => { - expect(purchaseOrder.updated_at).toBe(2000); - }); - - test('should use default values for missing properties', () => { - const emptyPO = new PlaceAssetPurchaseOrder({}); - expect(emptyPO.id).toBe(''); - expect(emptyPO.purchase_order_number).toBe(''); - expect(emptyPO.invoice_number).toBe(''); - expect(emptyPO.supplier_details).toEqual({}); - expect(emptyPO.purchase_date).toBe(0); - expect(emptyPO.unit_price).toBe(0); - expect(emptyPO.expected_service_start_date).toBe(0); - expect(emptyPO.expected_service_end_date).toBe(0); - expect(emptyPO.created_at).toBe(0); - expect(emptyPO.updated_at).toBe(0); - }); -}); - -describe('PlaceAssetType', () => { - let assetType: PlaceAssetType; - - beforeEach(() => { - assetType = new PlaceAssetType({ - id: 'type-test', - category_id: 'cat-123', - name: 'Test Asset Type', - brand: 'Acme', - description: 'A test asset type', - model_number: 'MODEL-001', - images: ['image1.jpg', 'image2.jpg'], - created_at: 1000, - updated_at: 2000, - }); - }); - - test('should create instance', () => { - expect(assetType).toBeTruthy(); - expect(assetType).toBeInstanceOf(PlaceAssetType); - }); - - test('should expose id', () => { - expect(assetType.id).toBe('type-test'); - }); - - test('should expose category_id', () => { - expect(assetType.category_id).toBe('cat-123'); - }); - - test('should expose name', () => { - expect(assetType.name).toBe('Test Asset Type'); - }); - - test('should expose brand', () => { - expect(assetType.brand).toBe('Acme'); - }); - - test('should expose description', () => { - expect(assetType.description).toBe('A test asset type'); - }); - - test('should expose model_number', () => { - expect(assetType.model_number).toBe('MODEL-001'); - }); - - test('should expose images', () => { - expect(assetType.images).toEqual(['image1.jpg', 'image2.jpg']); - }); - - test('should expose created_at', () => { - expect(assetType.created_at).toBe(1000); - }); - - test('should expose updated_at', () => { - expect(assetType.updated_at).toBe(2000); - }); - - test('should use default values for missing properties', () => { - const emptyType = new PlaceAssetType({}); - expect(emptyType.id).toBe(''); - expect(emptyType.category_id).toBe(''); - expect(emptyType.name).toBe(''); - expect(emptyType.brand).toBe(''); - expect(emptyType.description).toBe(''); - expect(emptyType.model_number).toBe(''); - expect(emptyType.images).toEqual([]); - expect(emptyType.created_at).toBe(0); - expect(emptyType.updated_at).toBe(0); - }); -}); - -describe('PlaceAsset', () => { - let asset: PlaceAsset; - - beforeEach(() => { - asset = new PlaceAsset({ - id: 'asset-test', - parent_id: 'asset-parent', - asset_type_id: 'type-123', - purchase_order_id: 'po-456', - zone_id: 'zone-789', - identifier: 'ASSET-001', - serial_number: 'SN-12345', - other_data: { custom: 'data' }, - barcode: 'BC-12345', - name: 'Test Asset', - client_ids: { system1: 'id1', system2: 'id2' }, - map_id: 'map-123', - bookable: true, - accessible: true, - zones: ['zone1', 'zone2'], - place_groups: ['group1', 'group2'], - assigned_to: 'user-123', - assigned_name: 'John Doe', - features: ['feature1', 'feature2'], - images: ['asset1.jpg', 'asset2.jpg'], - notes: 'Some notes', - security_system_groups: ['sec1', 'sec2'], - created_at: 1000, - updated_at: 2000, - }); - }); - - test('should create instance', () => { - expect(asset).toBeTruthy(); - expect(asset).toBeInstanceOf(PlaceAsset); - }); - - test('should expose id', () => { - expect(asset.id).toBe('asset-test'); - }); - - test('should expose parent_id', () => { - expect(asset.parent_id).toBe('asset-parent'); - }); - - test('should expose asset_type_id', () => { - expect(asset.asset_type_id).toBe('type-123'); - }); - - test('should expose purchase_order_id', () => { - expect(asset.purchase_order_id).toBe('po-456'); - }); - - test('should expose zone_id', () => { - expect(asset.zone_id).toBe('zone-789'); - }); - - test('should expose identifier', () => { - expect(asset.identifier).toBe('ASSET-001'); - }); - - test('should expose serial_number', () => { - expect(asset.serial_number).toBe('SN-12345'); - }); - - test('should expose other_data', () => { - expect(asset.other_data).toEqual({ custom: 'data' }); - }); - - test('should expose barcode', () => { - expect(asset.barcode).toBe('BC-12345'); - }); - - test('should expose name', () => { - expect(asset.name).toBe('Test Asset'); - }); - - test('should expose client_ids', () => { - expect(asset.client_ids).toEqual({ system1: 'id1', system2: 'id2' }); - }); - - test('should expose map_id', () => { - expect(asset.map_id).toBe('map-123'); - }); - - test('should expose bookable', () => { - expect(asset.bookable).toBe(true); - }); - - test('should expose accessible', () => { - expect(asset.accessible).toBe(true); - }); - - test('should expose zones', () => { - expect(asset.zones).toEqual(['zone1', 'zone2']); - }); - - test('should expose place_groups', () => { - expect(asset.place_groups).toEqual(['group1', 'group2']); - }); - - test('should expose assigned_to', () => { - expect(asset.assigned_to).toBe('user-123'); - }); - - test('should expose assigned_name', () => { - expect(asset.assigned_name).toBe('John Doe'); - }); - - test('should expose features', () => { - expect(asset.features).toEqual(['feature1', 'feature2']); - }); - - test('should expose images', () => { - expect(asset.images).toEqual(['asset1.jpg', 'asset2.jpg']); - }); - - test('should expose notes', () => { - expect(asset.notes).toBe('Some notes'); - }); - - test('should expose security_system_groups', () => { - expect(asset.security_system_groups).toEqual(['sec1', 'sec2']); - }); - - test('should expose created_at', () => { - expect(asset.created_at).toBe(1000); - }); - - test('should expose updated_at', () => { - expect(asset.updated_at).toBe(2000); - }); - - test('should use default values for missing properties', () => { - const emptyAsset = new PlaceAsset({}); - expect(emptyAsset.id).toBe(''); - expect(emptyAsset.parent_id).toBe(''); - expect(emptyAsset.asset_type_id).toBe(''); - expect(emptyAsset.purchase_order_id).toBe(''); - expect(emptyAsset.zone_id).toBe(''); - expect(emptyAsset.identifier).toBe(''); - expect(emptyAsset.serial_number).toBe(''); - expect(emptyAsset.other_data).toEqual({}); - expect(emptyAsset.barcode).toBe(''); - expect(emptyAsset.name).toBe(''); - expect(emptyAsset.client_ids).toEqual({}); - expect(emptyAsset.map_id).toBe(''); - expect(emptyAsset.bookable).toBe(false); - expect(emptyAsset.accessible).toBe(false); - expect(emptyAsset.zones).toEqual([]); - expect(emptyAsset.place_groups).toEqual([]); - expect(emptyAsset.assigned_to).toBe(''); - expect(emptyAsset.assigned_name).toBe(''); - expect(emptyAsset.features).toEqual([]); - expect(emptyAsset.images).toEqual([]); - expect(emptyAsset.notes).toBe(''); - expect(emptyAsset.security_system_groups).toEqual([]); - expect(emptyAsset.created_at).toBe(0); - expect(emptyAsset.updated_at).toBe(0); - }); -}); diff --git a/test/assets/functions.spec.ts b/test/assets/functions.spec.ts deleted file mode 100644 index b032b88f7..000000000 --- a/test/assets/functions.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Api from '../../src/api'; -import * as Auth from '../../src/auth/functions'; -import { - PlaceAsset, - PlaceAssetCategory, - PlaceAssetPurchaseOrder, - PlaceAssetType, -} from '../../src/assets/assets.class'; -import * as SERVICE from '../../src/assets/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Assets API', () => { - test('should allow querying assets', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAssets(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAsset); - list = await SERVICE.queryAssets({}); - }); - - test('should allow showing asset details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showAsset('1'); - expect(item).toBeInstanceOf(PlaceAsset); - item = await SERVICE.showAsset('1', {}); - }); - - test('should allow creating new assets', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAsset({}); - expect(item).toBeInstanceOf(PlaceAsset); - }); - - test('should allow updating asset details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAsset('1', {}); - expect(item).toBeInstanceOf(PlaceAsset); - item = await SERVICE.updateAsset('1', {}, 'patch'); - }); - - test('should allow removing assets', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeAsset('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeAsset('1'); - }); - - test('should allow bulk creating assets', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Api, 'post'); - spy.mockImplementation(() => Promise.resolve([{}, {}] as any)); - const items = await SERVICE.addAssets([{}, {}]); - expect(spy.mock.calls[0][0]).toBe('/api/engine/v2/assets/bulk'); - expect(items).toBeTruthy(); - expect(items.length).toBe(2); - expect(items[0]).toBeInstanceOf(PlaceAsset); - expect(items[1]).toBeInstanceOf(PlaceAsset); - }); - - test('should allow bulk updating assets', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const patchSpy = vi.spyOn(Api, 'patch'); - patchSpy.mockImplementation(() => Promise.resolve([{}, {}] as any)); - let items = await SERVICE.updateAssets([{}, {}]); - expect(patchSpy.mock.calls[0][0]).toBe('/api/engine/v2/assets/bulk'); - expect(items).toBeTruthy(); - expect(items.length).toBe(2); - expect(items[0]).toBeInstanceOf(PlaceAsset); - - const putSpy = vi.spyOn(Api, 'put'); - putSpy.mockImplementation(() => Promise.resolve([{}] as any)); - items = await SERVICE.updateAssets([{}], 'put'); - expect(items.length).toBe(1); - }); - - test('should allow bulk removing assets', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Api, 'del'); - spy.mockImplementation(() => Promise.resolve([{}, {}] as any)); - const items = await SERVICE.removeAssets(['1', '2']); - expect(spy.mock.calls[0][0]).toBe('/api/engine/v2/assets/bulk'); - expect(items).toBeTruthy(); - expect(items.length).toBe(2); - }); -}); - -describe('Asset Types API', () => { - test('should allow querying asset types', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAssetTypes(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAssetType); - list = await SERVICE.queryAssetTypes({}); - }); - - test('should allow showing asset type details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showAssetType('1'); - expect(item).toBeInstanceOf(PlaceAssetType); - item = await SERVICE.showAssetType('1', {}); - }); - - test('should allow creating new asset types', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAssetType({}); - expect(item).toBeInstanceOf(PlaceAssetType); - }); - - test('should allow updating asset type details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAssetType('1', {}); - expect(item).toBeInstanceOf(PlaceAssetType); - item = await SERVICE.updateAssetType('1', {}, 'patch'); - }); - - test('should allow removing asset types', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeAssetType('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeAssetType('1'); - }); -}); - -describe('Asset Categories API', () => { - test('should allow querying asset categories', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAssetCategories(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAssetCategory); - list = await SERVICE.queryAssetCategories({}); - }); - - test('should allow showing asset category details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showAssetCategory('1'); - expect(item).toBeInstanceOf(PlaceAssetCategory); - item = await SERVICE.showAssetCategory('1', {}); - }); - - test('should allow creating new asset categories', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAssetCategory({}); - expect(item).toBeInstanceOf(PlaceAssetCategory); - }); - - test('should allow updating asset category details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAssetCategory('1', {}); - expect(item).toBeInstanceOf(PlaceAssetCategory); - item = await SERVICE.updateAssetCategory('1', {}, 'patch'); - }); - - test('should allow removing asset categories', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeAssetCategory('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeAssetCategory('1'); - }); -}); - -describe('Asset Purchase Orders API', () => { - test('should allow querying asset purchase orders', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryAssetPurchaseOrders(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceAssetPurchaseOrder); - list = await SERVICE.queryAssetPurchaseOrders({}); - }); - - test('should allow showing asset purchase order details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showAssetPurchaseOrder('1'); - expect(item).toBeInstanceOf(PlaceAssetPurchaseOrder); - item = await SERVICE.showAssetPurchaseOrder('1', {}); - }); - - test('should allow creating new asset purchase orders', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addAssetPurchaseOrder({}); - expect(item).toBeInstanceOf(PlaceAssetPurchaseOrder); - }); - - test('should allow updating asset purchase order details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateAssetPurchaseOrder('1', {}); - expect(item).toBeInstanceOf(PlaceAssetPurchaseOrder); - item = await SERVICE.updateAssetPurchaseOrder('1', {}, 'patch'); - }); - - test('should allow removing asset purchase orders', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeAssetPurchaseOrder('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeAssetPurchaseOrder('1'); - }); -}); diff --git a/v2/test/auth.test.ts b/test/auth.test.ts similarity index 98% rename from v2/test/auth.test.ts rename to test/auth.test.ts index dde8f58fb..a56470cb1 100644 --- a/v2/test/auth.test.ts +++ b/test/auth.test.ts @@ -1,5 +1,5 @@ /** - * Goal: the auth session gets credentials as v1 does, and refuses credentials that it did not ask + * Goal: the auth session gets credentials as 6.x does, and refuses credentials that it did not ask * for. Method: run the session against a fake environment and a fake PlaceOS server, then check * the requests, the navigations, the storage and the result. */ @@ -16,7 +16,7 @@ import { object, parameters, string } from '../src/core/schema.ts'; import type { Result } from '../src/core/result.ts'; const REDIRECT_URI = 'http://localhost:4200/oauth-resp.html'; -/** `md5(REDIRECT_URI)`, as v1 computes it with `ts-md5`. */ +/** `md5(REDIRECT_URI)`, as 6.x computes it with `ts-md5`. */ const CLIENT_ID = '0de3afb200b5eb82c9bb317c870665ab'; const NOW_MS = 1_700_000_000_000; @@ -143,7 +143,7 @@ async function startLogin(world: ReturnType, config: Partial { - test('the client ID is the MD5 of the redirect URI, as in v1', () => { + test('the client ID is the MD5 of the redirect URI, as in 6.x', () => { expect(session(fake()).clientId).toBe(CLIENT_ID); }); @@ -349,7 +349,7 @@ describe('login page', () => { }); describe('trusted applications and refresh tokens', () => { - test('a trusted application keeps its tokens in the v1 storage keys', async () => { + test('a trusted application keeps its tokens in the 6.x storage keys', async () => { const world = fake({ url: 'http://localhost:4200/?trust=true' }); const state = (await startLogin(world)).get('state') ?? ''; world.setUrl(`http://localhost:4200/?code=abc&state=${state}`); diff --git a/test/auth/functions.spec.ts b/test/auth/functions.spec.ts deleted file mode 100644 index 970375784..000000000 --- a/test/auth/functions.spec.ts +++ /dev/null @@ -1,598 +0,0 @@ -import { Md5 } from 'ts-md5'; -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import { PlaceAuthority } from '../../src/auth/interfaces'; - -/** Save a login nonce, as `createLoginURL` does before it redirects */ -function pendingLogin(redirect_uri = '', storage: Storage = localStorage) { - storage.setItem(`${Md5.hashStr(redirect_uri)}_nonce`, 'nonce'); -} - -describe('Auth', () => { - beforeEach(() => { - Object.defineProperty(window, 'location', { - writable: true, - value: { - assign: vi.fn(), - protocol: 'http:', - origin: 'http://undefined', - href: 'http://undefined', - host: 'undefined', - hostname: 'undefined', - }, - }); - window.fetch = vi.fn().mockImplementation(async () => ({ - ok: true, - json: async () => - ({ - version: '1.0.0', - login_url: '/login?continue={{url}}', - session: true, - }) as PlaceAuthority, - })); - }); - - afterEach(() => { - localStorage.clear(); - Auth.cleanupAuth(); - }); - - test('should allow setting up auth', async () => { - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '1', - scope: 'public', - }); - expect(Auth.authority).toBeTruthy(); - const client_id = Auth.clientId(); - await Auth.setup(undefined as any); - expect(client_id).toBe(Auth.clientId()); - }); - - test('should send client ID and app details in app headers', async () => { - expect(Auth.appHeaders()).toEqual({}); - Auth.setAppHeaders('workplace', '2026-10-08', 'abcd1234'); - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '1', - scope: 'public', - }); - expect(Auth.appHeaders()).toEqual({ - 'X-App-Id': Auth.clientId(), - 'X-App-Name': 'workplace', - 'X-App-Date': '2026-10-08', - 'X-App-Build': 'abcd1234', - }); - }); - - test('should allow setting up auth with username and password', async () => { - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - auth_type: 'password', - }); - expect(Auth.authority()).toBeTruthy(); - }); - - test('should expose the API endpoint', () => { - expect(Auth.apiEndpoint()).toBe( - `${location.origin}${Auth.httpRoute()}`, - ); - }); - - // test('should expose the API route', async () => { - // vi.useFakeTimers(); - // expect(Auth.httpRoute()).toBe('/api/engine/v2'); - // const promise = Auth.setup({ - // auth_uri: '', - // token_uri: '', - // redirect_uri: '', - // scope: 'public', - // }); - // vi.runOnlyPendingTimers(); - // await promise; - // expect(Auth.httpRoute()).toBe('/control/api'); - // vi.useRealTimers(); - // }); - - test('should expose the options', () => { - expect(Auth.isMock()).toBe(false); - expect(Auth.isSecure()).toBe(false); - expect(Auth.isOnline()).toBe(false); - expect(Auth.authority()).toBeFalsy(); - expect(Auth.redirectUri()).toBe(undefined); - expect(Auth.host()).toBe(location.host); - Auth.setup({ - host: 'localhost', - auth_uri: '/auth/authorize', - token_uri: '/auth/token', - redirect_uri: '/oauth-resp.html', - scope: 'public', - mock: true, - secure: true, - }); - expect(Auth.clientId()).toBe(Md5.hashStr('/oauth-resp.html')); - expect(Auth.redirectUri()).toBe('/oauth-resp.html'); - expect(Auth.host()).toBe('localhost'); - expect(Auth.apiEndpoint()).toBeTruthy(); - expect(Auth.isMock()).toBe(true); - expect(Auth.isSecure()).toBe(true); - expect(Auth.isOnline()).toBe(true); - expect(Auth.hasToken()).toBe(!!Auth.token()); - expect(Auth.authority()).toBeTruthy(); - expect(Auth.onlineState()).toBeInstanceOf(Function); - expect(Auth.onlineState().value).toBe(true); - }); - - test('should expose the API token', async () => { - expect(Auth.token()).toBeFalsy(); - const options = { - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - mock: true, - }; - await Auth.setup(options); - expect(Auth.token()).toBe('mock-token'); - pendingLogin(); - window.location.search = - '?access_token=test&expires_in=3600&state=nonce'; - await Auth.setup({ ...options, mock: false }); - await Auth.authorise(); - expect(Auth.token()).toBe('test'); - }); - - test('should clear expired tokens', async () => { - pendingLogin(); - window.location.search = - '?access_token=test&expires_in=3600&state=nonce'; - const options = { - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - }; - await Auth.setup(options); - expect(Auth.token()).toBe('test'); - localStorage.setItem( - `${Auth.clientId()}_expires_at`, - `${new Date().getTime() - 3600}`, - ); - expect(Auth.token()).toBe('test'); - expect(Auth.token()).toBe(''); - }); - - test('should expose the refresh token', async () => { - pendingLogin(); - window.location.search = '?code=test&state=nonce'; - const options = { - auth_uri: '', - token_uri: 'token', - redirect_uri: '', - scope: 'public', - }; - (window.fetch as any) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => - ({ - version: '1.0.0', - login_url: '/login?continue={{url}}', - session: true, - }) as PlaceAuthority, - })) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => ({ - access_token: 'today', - refresh_token: 'tomorrow', - expires_in: 3600, - }), - })); - await Auth.setup({ ...options, mock: false }); - expect(window.fetch).toHaveBeenCalledTimes(2); - // expect(Auth.token()).toBe('today'); - // expect(Auth.refreshToken()).toBe('tomorrow'); - }); - - test('should expose the authority', async () => { - expect(Auth.authority()).toBeFalsy(); - const promise = Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - }); - await promise; - expect(Auth.authority()).toBeTruthy(); - }); - - test('should allow using session storage', async () => { - pendingLogin('', sessionStorage); - window.location.search = - '?access_token=test&expires_in=3600&state=nonce&trust=true'; - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - storage: 'session', - }); - expect(Auth.token()).toBe('test'); - expect( - localStorage.getItem(`${Auth.clientId()}_access_token`), - ).toBeNull(); - expect(sessionStorage.getItem(`${Auth.clientId()}_access_token`)).toBe( - 'test', - ); - }); - - test('should handle refresh token in URL', async () => { - pendingLogin(); - window.location.search = - '?access_token=test&refresh_token=hehe&expires_in=3600&state=nonce;^_^&&trust=true'; - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - }); - expect(Auth.token()).toBe('test'); - expect(localStorage.getItem(`${Auth.clientId()}_access_token`)).toBe( - 'test', - ); - expect(localStorage.getItem(`${Auth.clientId()}_refresh_token`)).toBe( - 'hehe', - ); - expect(localStorage.getItem(`${Auth.clientId()}_nonce`)).toBeNull(); - }); - - test('should reject URL credentials when no login is pending', async () => { - Auth.setStorage('local'); - window.location.search = '?access_token=attacker&expires_in=3600'; - expect(await Auth.checkForAuthParameters()).toBe(false); - expect(Auth.token()).toBe(''); - }); - - test('should reject URL credentials with a mismatched state', async () => { - Auth.setStorage('local'); - localStorage.setItem(`${Auth.clientId()}_nonce`, 'nonce'); - window.location.search = - '?access_token=attacker&expires_in=3600&state=other'; - expect(await Auth.checkForAuthParameters()).toBe(false); - expect(Auth.token()).toBe(''); - // A crafted link must not cancel the login that is pending - expect(localStorage.getItem(`${Auth.clientId()}_nonce`)).toBe('nonce'); - }); - - test('should fail to authorise before authority loaded', async () => { - expect.assertions(1); - await Auth.authorise().catch((err) => { - expect(err).toBe('Authority is not loaded'); - }); - }); - - test('should authorise after failing before authority loaded', async () => { - await Auth.authorise().catch(() => null); - await Auth.setup({ - auth_uri: '/auth/oauth/authorize', - token_uri: '', - redirect_uri: '', - scope: 'public', - }); - expect(window.location.assign).toHaveBeenCalledWith( - expect.stringContaining('/auth/oauth/authorize'), - ); - }); - - test('should keep the PKCE verifier while an iFrame auth is in flight', async () => { - window.fetch = vi.fn().mockImplementation(async () => ({ - ok: true, - json: async () => ({ version: '1.0.0', session: false }), - })); - await Auth.setup({ - auth_uri: '/auth/oauth/authorize', - token_uri: '', - redirect_uri: '', - scope: 'public', - auth_type: 'auth_code', - use_iframe: true, - handle_login: false, - }); - Auth.sendToAuthorize().catch(() => null); - const key = `${Auth.clientId()}_challenge`; - const verifier = sessionStorage.getItem(key); - expect(verifier).toBeTruthy(); - Auth.sendToAuthorize().catch(() => null); - expect(sessionStorage.getItem(key)).toBe(verifier); - expect(document.querySelectorAll('#place-authorize')).toHaveLength(1); - document.getElementById('place-authorize')?.remove(); - }); - - // test('should redirect to login when user has no session', async (done) => { - // window.fetch = vi.fn().mockImplementation(async () => ({ - // ok: true, - // json: async () => - // ({ - // version: '1.0.0', - // } as PlaceAuthority), - // })); - // await Auth.setup({ - // auth_uri: '', - // token_uri: '', - // redirect_uri: '', - // scope: 'public', - // }).catch(); - // setTimeout(() => { - // expect(location.assign).toHaveBeenCalled(); - // done(); - // }, 400); - // }); - - // test('should handle logging out', async (done) => { - // window.location.search = '?access_token=test&expires_in=3600'; - // const spy = vi.spyOn(location, 'assign'); - // await Auth.setup({ - // auth_uri: '', - // token_uri: '', - // redirect_uri: '', - // scope: 'public', - // storage: 'session', - // }); - // expect(Auth.token()).toBe('test'); - // Auth.logout(); - // setTimeout(() => { - // expect(window.fetch).toHaveBeenCalledTimes(2); - // expect(Auth.token()).toBeFalsy(); - // expect(spy).toHaveBeenCalled(); - // done(); - // }, 400); - // }); - - // test('should allow refreshing the authority', async () => { - // vi.useFakeTimers(); - // expect(Auth.authority()).toBeFalsy(); - // await Auth.setup({ - // auth_uri: '', - // token_uri: '', - // redirect_uri: '', - // scope: 'public', - // }); - // expect(Auth.authority()).toBeTruthy(); - // window.fetch = vi.fn().mockImplementation(async () => ({ - // ok: true, - // json: async () => - // ({ - // version: '2.0.0', - // login_url: '/login?continue={{url}}', - // session: true, - // } as PlaceAuthority), - // })); - // vi.runOnlyPendingTimers(); - // await Auth.refreshAuthority(); - // expect(Auth.authority()?.version).toBe('2.0.0'); - // vi.useRealTimers(); - // }); - - // test('should handle error when loading authority', async () => { - // window.fetch = jest - // .fn() - // .mockImplementationOnce(async () => ({ - // status: 500, - // ok: false, - // json: async () => ({}), - // })) - // .mockImplementation(async () => ({ - // ok: true, - // json: async () => - // ({ - // version: '2.0.0', - // } as PlaceAuthority), - // })); - // await Auth.setup({ - // auth_uri: '', - // token_uri: '', - // redirect_uri: '', - // secure: true, - // scope: 'public', - // }); - // expect(Auth.authority()).toBeTruthy(); - // }); - - test('should allow listening to changes to token', () => - new Promise((resolve) => { - (async () => { - pendingLogin(); - window.location.search = - '?access_token=test&expires_in=3600&state=nonce'; - Auth.listenForToken().subscribe((token) => { - if (token) { - resolve(); - } - }); - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - secure: true, - scope: 'public', - }); - })(); - })); - - test('should reload authority on focus when there is no session', async () => { - window.fetch = vi.fn().mockImplementation(async () => ({ - ok: true, - json: async () => - ({ - version: '2.0.0', - login_url: '/login?continue={{url}}', - session: false, - }) as PlaceAuthority, - })); - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - handle_login: false, - }); - expect(Auth.authority()?.session).toBe(false); - expect(window.fetch).toHaveBeenCalledTimes(1); - (window.fetch as any).mockImplementation(async () => ({ - ok: true, - json: async () => - ({ - version: '2.0.0', - login_url: '/login?continue={{url}}', - session: true, - }) as PlaceAuthority, - })); - document.dispatchEvent(new Event('visibilitychange')); - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(window.fetch).toHaveBeenCalledTimes(2); - expect(Auth.authority()?.session).toBe(true); - }); - - test('should not reload authority on focus with a current session', async () => { - await Auth.setup({ - auth_uri: '', - token_uri: '', - redirect_uri: '', - scope: 'public', - handle_login: false, - }); - expect(Auth.authority()?.session).toBe(true); - expect(window.fetch).toHaveBeenCalledTimes(1); - document.dispatchEvent(new Event('visibilitychange')); - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(window.fetch).toHaveBeenCalledTimes(1); - }); - - test('should handle auth redirects from native wrappers', async () => { - (window.fetch as any) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => - ({ - version: '2.0.0', - login_url: '/login?continue={{url}}', - session: false, - }) as PlaceAuthority, - })) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => ({ - access_token: 'today', - refresh_token: 'tomorrow', - expires_in: 3600, - }), - })); - await Auth.setup({ - auth_uri: '', - token_uri: 'token', - redirect_uri: '', - scope: 'public', - handle_login: false, - }); - pendingLogin(); - const token = await Auth.handleAuthRedirect( - 'myapp://oauth/callback?code=abc123&state=nonce', - ); - expect(token).toBe('today'); - expect(sessionStorage.getItem('ENGINE.auth.params')).toBeNull(); - }); - - test('should exchange an Entra token when no other credentials exist', async () => { - (window.fetch as any) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => - ({ - version: '2.0.0', - login_url: '/login?continue={{url}}', - session: false, - }) as PlaceAuthority, - })) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => ({ - access_token: 'placeos', - refresh_token: 'refresh', - expires_in: 3600, - issued_token_type: - 'urn:ietf:params:oauth:token-type:access_token', - }), - })); - await Auth.setup({ - auth_uri: '', - token_uri: '/auth/oauth/token', - redirect_uri: '/addin', - scope: 'public', - entra_token: async () => 'entra-jwt', - }); - expect(Auth.token()).toBe('placeos'); - expect(window.location.assign).not.toHaveBeenCalled(); - const [url, init] = (window.fetch as any).mock.calls[1]; - const body = new URLSearchParams(init.body); - expect(url).toBe('/auth/oauth/token'); - expect(body.get('grant_type')).toBe( - 'urn:ietf:params:oauth:grant-type:token-exchange', - ); - expect(body.get('client_id')).toBe(Md5.hashStr('/addin')); - expect(body.get('subject_token')).toBe('entra-jwt'); - expect(body.get('subject_token_type')).toBe( - 'urn:ietf:params:oauth:token-type:access_token', - ); - expect(body.get('scope')).toBe('public'); - }); - - test('should complete auth on focus with params stored while backgrounded', async () => { - (window.fetch as any) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => - ({ - version: '2.0.0', - login_url: '/login?continue={{url}}', - session: false, - }) as PlaceAuthority, - })) - .mockImplementationOnce(async () => ({ - ok: true, - json: async () => ({ - access_token: 'today', - refresh_token: 'tomorrow', - expires_in: 3600, - }), - })); - await Auth.setup({ - auth_uri: '', - token_uri: 'token', - redirect_uri: '', - scope: 'public', - handle_login: false, - }); - expect(Auth.hasToken()).toBe(false); - pendingLogin(); - sessionStorage.setItem( - 'ENGINE.auth.params', - JSON.stringify({ code: 'abc123', state: 'nonce' }), - ); - document.dispatchEvent(new Event('visibilitychange')); - await new Promise((resolve) => setTimeout(resolve, 100)); - expect(Auth.token()).toBe('today'); - }); - - test('should allow generating challenge pairs', () => { - const { challenge, verify } = Auth.generateChallenge(); - expect(challenge).toBeTruthy(); - expect(challenge).toHaveLength(43); - expect(verify).toBeTruthy(); - }); -}); diff --git a/test/broker/broker.spec.ts b/test/broker/broker.spec.ts deleted file mode 100644 index e77c62948..000000000 --- a/test/broker/broker.spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { AuthType, PlaceMQTTBroker } from '../../src/broker/broker'; - -describe('PlaceMQTTBroker', () => { - let broker: PlaceMQTTBroker; - - beforeEach(() => { - broker = new PlaceMQTTBroker({ - id: 'dep-test', - name: 'here.today', - auth_type: AuthType.Certificate, - host: 'broker.place.tech', - port: 12345, - tls: true, - username: 'user', - password: 'pass', - certificate: 'cert', - secret: 'secret :)', - filters: ['Test'], - description: 'In a galaxy far far away...', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(broker).toBeTruthy(); - expect(broker).toBeInstanceOf(PlaceMQTTBroker); - }); - - test('should expose properties', () => { - expect(broker.host).toBe('broker.place.tech'); - expect(broker.port).toBe(12345); - expect(broker.tls).toBeTruthy(); - expect(broker.username).toBe('user'); - expect(broker.password).toBe('pass'); - expect(broker.certificate).toBe('cert'); - expect(broker.secret).toBe('secret :)'); - expect(broker.filters).toEqual(['Test']); - expect(broker.description).toBe('In a galaxy far far away...'); - }); - - test('should allow converting to JSON object', () => { - expect(broker.toJSON()).toBeTruthy(); - }); -}); diff --git a/test/broker/functions.spec.ts b/test/broker/functions.spec.ts deleted file mode 100644 index 71d26285f..000000000 --- a/test/broker/functions.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import { PlaceMQTTBroker } from '../../src/broker/broker'; -import * as SERVICE from '../../src/broker/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('MQTT Broker API', () => { - test('should allow querying brokers', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryBrokers(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceMQTTBroker); - list = await SERVICE.queryBrokers({}); - }); - - test('should allow showing broker details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showBroker('1'); - expect(item).toBeInstanceOf(PlaceMQTTBroker); - item = await SERVICE.showBroker('1', {}); - }); - - test('should allow creating new brokers', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addBroker({}); - expect(item).toBeInstanceOf(PlaceMQTTBroker); - item = await SERVICE.addBroker({}); - }); - - test('should allow updating broker details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateBroker('1', {}); - expect(item).toBeInstanceOf(PlaceMQTTBroker); - item = await SERVICE.updateBroker('1', {}, 'patch'); - }); - - test('should allow removing brokers', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeBroker('1'); - expect(item).toBeFalsy(); - item = await SERVICE.removeBroker('1', {}); - }); -}); diff --git a/v2/test/client.test.ts b/test/client.test.ts similarity index 100% rename from v2/test/client.test.ts rename to test/client.test.ts diff --git a/test/clusters/clusters.spec.ts b/test/clusters/clusters.spec.ts deleted file mode 100644 index 778d4814e..000000000 --- a/test/clusters/clusters.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceCluster } from '../../src/clusters/cluster'; - -describe('PlaceCluster', () => { - let application: PlaceCluster; - - beforeEach(() => { - // PlaceCluster.service = service; - application = new PlaceCluster({ - id: '01E2PRBSNE4GXM9WGVM7M3KEZX', - compiled_drivers: ['drivers_aca_private_helper_fe33588'], - available_repositories: ['drivers', 'aca-drivers'], - running_drivers: 1, - module_instances: 1, - unavailable_repositories: [], - unavailable_drivers: [], - hostname: 'core', - cpu_count: 3, - core_cpu: 0, - total_cpu: 0, - memory_total: 8155620, - memory_usage: 3028124, - core_memory: 3028124, - }); - }); - - test('should create instance', () => { - expect(application).toBeTruthy(); - expect(application).toBeInstanceOf(PlaceCluster); - let app = new PlaceCluster({ - id: '01E2PRBSNE4GXM9WGVM7M3KEZX', - load: { - local: { - hostname: 'core', - cpu_count: 3, - core_cpu: 0, - total_cpu: 0, - memory_total: 8155620, - memory_usage: 3028124, - core_memory: 3028124, - }, - edge: [{}], - }, - } as any); - expect(app.edge_nodes.length).toBe(1); - app = new PlaceCluster({ - id: '01E2PRBSNE4GXM9WGVM7M3KEZX', - run_counts: { local: { drivers: 2, modules: 1 } }, - } as any); - }); - - test('should expose ID', () => { - expect(application.id).toBe('01E2PRBSNE4GXM9WGVM7M3KEZX'); - }); - - test('should allow generating display string for memory usage', () => { - expect(application.used_memory).toBe('2.89 GB'); - }); - - test('should allow generating display string for memory total', () => { - expect(application.total_memory).toBe('7.78 GB'); - }); -}); diff --git a/test/clusters/functions.spec.ts b/test/clusters/functions.spec.ts deleted file mode 100644 index 532a48593..000000000 --- a/test/clusters/functions.spec.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import { PlaceCluster } from '../../src/clusters/cluster'; -import * as SERVICE from '../../src/clusters/functions'; -import { PlaceProcess } from '../../src/clusters/process'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; - -vi.mock('../../src/resources/functions'); - -describe('Cluster API', () => { - test('should allow querying clusters', async () => { - (Resources.query as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ data: [_.fn({})] })); - const list = await SERVICE.queryClusters(); - expect(list).toBeTruthy(); - expect(list?.data.length).toBe(1); - expect(list?.data[0]).toBeInstanceOf(PlaceCluster); - }); - - test('should allow querying processes', async () => { - (Resources.show as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.fn([{}]) as any)); - const list = await SERVICE.queryProcesses('1'); - expect(list).toBeTruthy(); - expect(list.length).toBe(1); - expect(list[0]).toBeInstanceOf(PlaceProcess); - }); - - test('should allow terminating processes', async () => { - (Resources.remove as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - await SERVICE.terminateProcess('1', { driver: 'driver-1' }); - }); - - test('should allow triggering cluster rebalance', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - await SERVICE.clusterRebalance(); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/cluster/rebalance', - {}, - ); - }); - - test('should allow getting cluster versions', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => - Promise.resolve({ - 'node-1': '1.0.0', - 'node-2': '1.0.1', - }) as any, - ); - - const result = await SERVICE.clusterVersions(); - expect(result).toBeTruthy(); - expect(result!['node-1']).toBe('1.0.0'); - expect(httpSpy).toHaveBeenCalledWith('/api/engine/v2/cluster/versions'); - }); -}); diff --git a/test/clusters/process.spec.ts b/test/clusters/process.spec.ts deleted file mode 100644 index 5e2f545e2..000000000 --- a/test/clusters/process.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceProcess } from '../../src/clusters/process'; - -describe('Cluster Process', () => { - let process: PlaceProcess; - - beforeEach(() => { - process = new PlaceProcess('test-cluster', { - driver: '/app/bin/drivers/drivers_aca_private_helper_fe33588', - modules: ['mod-ETbLjPMTRfb'], - running: true, - module_instances: 1, - last_exit_code: 0, - launch_count: 1, - launch_time: 1583459286, - percentage_cpu: 0, - memory_total: 8155620, - memory_usage: 92468, - }); - }); - - test('should create instance', () => { - expect(process).toBeTruthy(); - expect(process).toBeInstanceOf(PlaceProcess); - }); - - test('should expose ID', () => { - expect(process.id).toBe( - '/app/bin/drivers/drivers_aca_private_helper_fe33588', - ); - }); - - test('should allow generating display string for memory usage', () => { - expect(process.used_memory).toBe('90.30 MB'); - }); - - test('should allow generating display string for memory total', () => { - expect(process.total_memory).toBe('7.78 GB'); - }); -}); diff --git a/v2/test/compat.test.ts b/test/compat.test.ts similarity index 94% rename from v2/test/compat.test.ts rename to test/compat.test.ts index 602f5fe48..c435d2dd1 100644 --- a/v2/test/compat.test.ts +++ b/test/compat.test.ts @@ -1,7 +1,7 @@ /** - * Goal: the v1 mocks of `@placeos/ts-client/compat` work with the v2 client and the v2 realtime + * Goal: the 6.x mocks of `@placeos/ts-client/compat` work with the 7.x client and the 7.x realtime * client, so that a mock mode and the tests of an app still work after the migration. - * Method: register v1 style endpoints and systems, and use them through v2 calls. + * Method: register 6.x style endpoints and systems, and use them through 7.x calls. */ import { afterEach, expect, test } from 'bun:test'; import { @@ -22,8 +22,8 @@ import { createClient } from '../src/core/client.ts'; import { createRealtime, type BindingState } from '../src/realtime/realtime.ts'; import { zones } from '../src/generated/operations/index.ts'; -// An app gives `baseUrl: ''`. Outside a browser, a URL needs an origin. v1 mock data often has -// only some fields. `missingFields: 'zero'` fills the others, as the v1 classes did. +// An app gives `baseUrl: ''`. Outside a browser, a URL needs an origin. 6.x mock data often has +// only some fields. `missingFields: 'zero'` fills the others, as the 6.x classes did. const client = createClient({ baseUrl: 'http://mock.invalid', auth: { kind: 'none' }, @@ -37,7 +37,7 @@ afterEach(() => { deregisterSystem('sys-1'); }); -test('a v2 call gets the response of a v1 mock endpoint', async () => { +test('a 7.x call gets the response of a 6.x mock endpoint', async () => { const requests: MockHttpRequest[] = []; registerMockEndpoint({ path: '/api/engine/v2/zones/:id', @@ -119,7 +119,7 @@ test('mockReply and mockPage make the results of test doubles', () => { }); }); -test('a v2 binding and call use a v1 mock system', async () => { +test('a 7.x binding and call use a 6.x mock system', async () => { registerSystem('sys-1', { Display: [ { diff --git a/test/domains/domain.spec.ts b/test/domains/domain.spec.ts deleted file mode 100644 index df985d0cc..000000000 --- a/test/domains/domain.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceDomain } from '../../src/domains/domain'; - -describe('PlaceDomain', () => { - let domain: PlaceDomain; - - beforeEach(() => { - domain = new PlaceDomain({ - id: 'dep-test', - domain: 'here.today', - login_url: 'somewhere.today', - logout_url: 'no-where.today', - description: 'In a galaxy far far away...', - config: { today: false, future: 'Yeah!' }, - internals: { today: true, future: 'Nope!' }, - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(domain).toBeTruthy(); - expect(domain).toBeInstanceOf(PlaceDomain); - }); - - test('should expose domain', () => { - expect(domain.domain).toBe('here.today'); - }); - - test('should expose login URL', () => { - expect(domain.login_url).toBe('somewhere.today'); - }); - - test('should expose logout URL', () => { - expect(domain.logout_url).toBe('no-where.today'); - }); - - test('should expose description', () => { - expect(domain.description).toBe('In a galaxy far far away...'); - }); - - test('should expose config', () => { - expect(domain.config).toEqual({ today: false, future: 'Yeah!' }); - }); - - test('should expose internals', () => { - expect(domain.internals).toEqual({ today: true, future: 'Nope!' }); - }); - - test('should allow converting to JSON object', () => { - expect(domain.toJSON()).toBeTruthy(); - }); -}); diff --git a/test/domains/functions.spec.ts b/test/domains/functions.spec.ts deleted file mode 100644 index 0dd387554..000000000 --- a/test/domains/functions.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import { PlaceDomain } from '../../src/domains/domain'; -import * as SERVICE from '../../src/domains/functions'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Domains API', () => { - test('should allow querying domain', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryDomains(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceDomain); - list = await SERVICE.queryDomains({}); - }); - - test('should allow showing domain details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showDomain('1'); - expect(item).toBeInstanceOf(PlaceDomain); - }); - - test('should allow creating new domains', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addDomain({}); - expect(item).toBeInstanceOf(PlaceDomain); - item = await SERVICE.addDomain({}); - }); - - test('should allow updating domain details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateDomain('1', {}); - expect(item).toBeInstanceOf(PlaceDomain); - item = await SERVICE.updateDomain('1', {}, 'patch'); - }); - - test('should allow removing domains', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeDomain('1'); - expect(item).toBeFalsy(); - }); - - test('should allow looking up domain by email', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation(() => Promise.resolve('example.com') as any); - - const result = await SERVICE.lookupDomainByEmail('user@example.com'); - expect(result).toBe('example.com'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/domains/lookup/user%40example.com', - ); - }); -}); diff --git a/test/drivers/driver.spec.ts b/test/drivers/driver.spec.ts deleted file mode 100644 index 7cd044ef1..000000000 --- a/test/drivers/driver.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceDriver } from '../../src/drivers/driver'; -import { PlaceDriverRole } from '../../src/drivers/enums'; -import { PlaceSettings } from '../../src/settings/settings'; - -describe('PlaceDriver', () => { - let driver: PlaceDriver; - - beforeEach(() => { - driver = new PlaceDriver({ - id: 'dep-test', - description: 'In a galaxy far far away...', - module_name: 'SteamShip', - role: PlaceDriverRole.Logic, - default_uri: 'Sometimes we default', - default_port: 1234, - ignore_connected: false, - settings: [ - { settings_string: "{ today: false, future: 'Yeah!' }" }, - ] as any, - class_name: '::ACA::SolveProblem', - created_at: 999, - repository_id: 'my-repo', - file_name: 'fancy-driver.cr', - commit: 'some-hash', - }); - }); - - test('should create instance', () => { - expect(driver).toBeTruthy(); - expect(driver).toBeInstanceOf(PlaceDriver); - }); - - test('should expose properties', () => { - expect(driver.description).toBe('In a galaxy far far away...'); - expect(driver.module_name).toBe('SteamShip'); - expect(driver.role).toBe(PlaceDriverRole.Logic); - expect(driver.default_uri).toBe('Sometimes we default'); - expect(driver.default_port).toBe(1234); - expect(driver.ignore_connected).toBe(false); - expect(driver.settings).toBeInstanceOf(Array); - expect(driver.repository_id).toBe('my-repo'); - expect(driver.file_name).toBe('fancy-driver.cr'); - expect(driver.commit).toBe('some-hash'); - expect(driver.class_name).toEqual('::ACA::SolveProblem'); - expect(driver.created_at).toEqual(999); - }); - - test('should handle no settings', () => { - driver = new PlaceDriver(); - expect(driver.settings).toBeInstanceOf(Array); - expect(driver.settings[0]).toBeInstanceOf(PlaceSettings); - }); -}); diff --git a/test/drivers/functions.spec.ts b/test/drivers/functions.spec.ts deleted file mode 100644 index 937b1a9bf..000000000 --- a/test/drivers/functions.spec.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import { PlaceDriver } from '../../src/drivers/driver'; -import * as SERVICE from '../../src/drivers/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Drivers API', () => { - test('should allow querying drivers', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryDrivers(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceDriver); - list = await SERVICE.queryDrivers({}); - }); - - test('should allow showing driver details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}))); - let item = await SERVICE.showDriver('1'); - expect(item).toBeInstanceOf(PlaceDriver); - item = await SERVICE.showDriver('1', { - compilation_status: true, - }); - expect(item).toBeInstanceOf(PlaceDriver); - }); - - test('should allow creating new drivers', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}))); - let item = await SERVICE.addDriver({}); - expect(item).toBeInstanceOf(PlaceDriver); - item = await SERVICE.addDriver({}); - expect(item).toBeInstanceOf(PlaceDriver); - }); - - test('should allow updating driver details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateDriver('1', {}); - expect(item).toBeInstanceOf(PlaceDriver); - item = await SERVICE.updateDriver('1', {}, 'put'); - expect(item).toBeInstanceOf(PlaceDriver); - }); - - test('should allow removing drivers', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeDriver('1'); - expect(item).toBeFalsy(); - }); - - test('should allow recompiling drivers', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.recompileDriver('1'); - expect(item).toBeFalsy(); - }); - - test('should allow recompiling drivers', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.reloadDriver('1'); - expect(item).toBeFalsy(); - }); - - test('should allow checking driver is compiled', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.isDriverCompiled('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/edge/edge.spec.ts b/test/edge/edge.spec.ts deleted file mode 100644 index 44cce5b88..000000000 --- a/test/edge/edge.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceEdge } from '../../src/edge/edge'; - -describe('PlaceEdge', () => { - let edge: PlaceEdge; - - beforeEach(() => { - edge = new PlaceEdge({ - id: 'dep-test', - name: 'Test', - description: 'A Description', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(edge).toBeTruthy(); - expect(edge).toBeInstanceOf(PlaceEdge); - }); - - test('should expose properties', () => { - expect(edge.name).toBe('Test'); - expect(edge.description).toBe('A Description'); - }); -}); diff --git a/test/edge/functions.spec.ts b/test/edge/functions.spec.ts deleted file mode 100644 index db7a7aa47..000000000 --- a/test/edge/functions.spec.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import { PlaceEdge } from '../../src/edge/edge'; -import * as SERVICE from '../../src/edge/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Edge API', () => { - test('should allow querying Edges', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryEdges(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceEdge); - list = await SERVICE.queryEdges({}); - }); - - test('should allow showing Edge details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showEdge('1'); - expect(item).toBeInstanceOf(PlaceEdge); - }); - - test('should allow creating new Edges', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addEdge({}); - expect(item).toBeInstanceOf(PlaceEdge); - item = await SERVICE.addEdge({}); - }); - - test('should allow updating Edge details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateEdge('1', {}); - expect(item).toBeInstanceOf(PlaceEdge); - item = await SERVICE.updateEdge('1', {}, 'patch'); - }); - - test('should allow removing Edges', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeEdge('1'); - expect(item).toBeFalsy(); - }); - - test('should allow getting token for Edge', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({ token: 's' })); - const item = await SERVICE.retrieveEdgeToken('1'); - expect(item).toBeTruthy(); - expect(item.token).toBe('s'); - }); - - test('should generate correct edge control websocket URL for HTTPS', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('https://example.com/api/engine/v2/'); - - const url = SERVICE.edgeControlUrl(); - expect(url).toBe('wss://example.com/api/engine/v2/edges/control'); - }); - - test('should generate correct edge control websocket URL for HTTP', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('http://example.com/api/engine/v2/'); - - const url = SERVICE.edgeControlUrl(); - expect(url).toBe('ws://example.com/api/engine/v2/edges/control'); - }); -}); diff --git a/test/groups/functions.spec.ts b/test/groups/functions.spec.ts deleted file mode 100644 index 39d7fc438..000000000 --- a/test/groups/functions.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import { showGroupFeatures } from '../../src/groups/functions'; -import { PlaceGroup } from '../../src/groups/group'; -import * as Http from '../../src/http/functions'; - -describe('Groups API', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test('should get effective group features', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const features = { signage: { templates: true } }; - const spy = vi.spyOn(Http, 'get').mockResolvedValue(features); - - expect(await showGroupFeatures('grp-1')).toEqual(features); - expect(spy).toHaveBeenLastCalledWith( - '/api/engine/v2/groups/grp-1/features', - ); - - await showGroupFeatures('grp-1', { subsystem: 'signage' }); - expect(spy).toHaveBeenLastCalledWith( - '/api/engine/v2/groups/grp-1/features?subsystem=signage', - ); - }); - - test('should default group features to empty', () => { - expect(new PlaceGroup().features).toEqual({}); - }); -}); diff --git a/test/groups/group.spec.ts b/test/groups/group.spec.ts deleted file mode 100644 index f996ac34e..000000000 --- a/test/groups/group.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { PlaceGroupUser } from '../../src/group-users/group-user'; -import { PlaceGroup } from '../../src/groups/group'; - -describe('PlaceGroup', () => { - test('should expose default permissions and AD group mappings', () => { - const group = new PlaceGroup({ - default_permissions: 5, - ad_group_mappings: { 'ad-1': ['Staff', 1] }, - }); - expect(group.default_permissions).toBe(5); - expect(group.ad_group_mappings).toEqual({ 'ad-1': ['Staff', 1] }); - }); - - test('should default new fields when missing', () => { - const group = new PlaceGroup(); - expect(group.default_permissions).toBe(0); - expect(group.ad_group_mappings).toEqual({}); - }); -}); - -describe('PlaceGroupUser', () => { - test('should expose the AD group that added the membership', () => { - expect( - new PlaceGroupUser({ auto_assigned: 'ad-1' }).auto_assigned, - ).toBe('ad-1'); - expect(new PlaceGroupUser().auto_assigned).toBe(''); - }); -}); diff --git a/v2/test/hash.test.ts b/test/hash.test.ts similarity index 97% rename from v2/test/hash.test.ts rename to test/hash.test.ts index 98aa718f3..a3c6d8ace 100644 --- a/v2/test/hash.test.ts +++ b/test/hash.test.ts @@ -1,5 +1,5 @@ /** - * Goal: the hashes give the standard values, so the client ID matches v1 and PKCE matches the + * Goal: the hashes give the standard values, so the client ID matches 6.x and PKCE matches the * server. Method: compare with published test vectors and with the hashes of Bun. */ import { expect, test } from 'bun:test'; diff --git a/test/history/functions.spec.ts b/test/history/functions.spec.ts deleted file mode 100644 index a8f57efa4..000000000 --- a/test/history/functions.spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; - -import * as Auth from '../../src/auth/functions'; -import { - queryGroupHistory, - showGroupHistory, -} from '../../src/groups/functions'; -import * as SERVICE from '../../src/history/functions'; -import { PlaceHistory } from '../../src/history/history'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('History API', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test('should allow querying history', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.queryHistory({ - resource_types: ['zone', 'sys'], - correlation_id: 'group-1', - }); - expect(list.data[0]).toBeInstanceOf(PlaceHistory); - expect(spy).toHaveBeenLastCalledWith( - expect.objectContaining({ - path: 'history', - query_params: { - resource_types: ['zone', 'sys'], - correlation_id: 'group-1', - }, - }), - ); - }); - - test('should allow showing a history entry', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'get').mockResolvedValue({ id: 'h-1' }); - const item = await SERVICE.showHistory('h-1'); - expect(item).toBeInstanceOf(PlaceHistory); - expect(item.id).toBe('h-1'); - expect(spy).toHaveBeenLastCalledWith('/api/engine/v2/history/h-1'); - }); - - test('should allow restoring a deleted resource', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi - .spyOn(Http, 'post') - .mockResolvedValue({ id: 'zone-1' } as any); - expect(await SERVICE.undeleteResource('zone', 'zone-1')).toEqual({ - id: 'zone-1', - }); - expect(spy).toHaveBeenLastCalledWith( - '/api/engine/v2/history/undelete?resource_type=zone&resource_id=zone-1', - null, - ); - }); - - test('should return group history as history entries', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await queryGroupHistory({ group_id: 'group-1' }); - expect(list.data[0]).toBeInstanceOf(PlaceHistory); - - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - vi.spyOn(Http, 'get').mockResolvedValue({ id: 'h-1' }); - expect(await showGroupHistory('h-1')).toBeInstanceOf(PlaceHistory); - }); -}); diff --git a/test/history/history.spec.ts b/test/history/history.spec.ts deleted file mode 100644 index e85cd1ae9..000000000 --- a/test/history/history.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, test } from 'vitest'; - -import { PlaceHistory } from '../../src/history/history'; - -describe('PlaceHistory', () => { - test('should expose the change details', () => { - const entry = new PlaceHistory({ - id: 'h-1', - resource_type: 'zone', - resource_id: 'zone-1', - correlation_id: 'group-1', - action: 'update', - changed_fields: ['name'], - diff: { name: ['old', 'new'] }, - user_id: 'user-1', - user_email: 'user@place.tech', - context: { app_name: 'backoffice', ip: '10.0.0.1' }, - created_at: 1729382400, - }); - expect(entry.resource_type).toBe('zone'); - expect(entry.diff.name).toEqual(['old', 'new']); - expect(entry.context.app_name).toBe('backoffice'); - expect(entry.snapshot).toBeNull(); - expect(entry.created_at).toBe(1729382400); - }); - - test('should default missing fields', () => { - const entry = new PlaceHistory(); - expect(entry.id).toBe(''); - expect(entry.changed_fields).toEqual([]); - expect(entry.diff).toEqual({}); - expect(entry.context).toEqual({}); - expect(entry.created_at).toBe(0); - }); -}); diff --git a/test/http/expired-token.spec.ts b/test/http/expired-token.spec.ts deleted file mode 100644 index cb15b346a..000000000 --- a/test/http/expired-token.spec.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; - -import { - cleanupAuth, - clientId, - setToken, - setup, -} from '../../src/auth/functions'; -import { queryZones } from '../../src/zones/functions'; - -describe('zone requests with expired tokens', () => { - const fetch_mock = vi.fn(); - - beforeEach(async () => { - vi.useFakeTimers(); - localStorage.clear(); - sessionStorage.clear(); - vi.stubGlobal('fetch', fetch_mock); - fetch_mock.mockImplementation(async (input) => { - const url = String(input); - if (url.endsWith('/auth/authority')) { - return Response.json({ - id: 'authority-test', - version: '2.0.0', - config: {}, - }); - } - if (url.includes('/oauth/token')) { - return Response.json({ - access_token: 'synthetic-renewed-token', - refresh_token: 'synthetic-refresh-token', - expires_in: 3600, - created_at: Math.floor(Date.now() / 1000), - }); - } - return Response.json([ - { - id: 'level-test', - parent_id: 'building-test', - tags: ['level'], - }, - ]); - }); - const initialisation = setup({ - auth_uri: '/oauth/authorize', - token_uri: '/oauth/token', - redirect_uri: 'http://localhost/', - scope: 'public', - auth_type: 'auth_code', - }); - setToken('synthetic-initial-token', Date.now() + 60_000); - localStorage.setItem( - `${clientId()}_refresh_token`, - 'synthetic-refresh-token', - ); - await initialisation; - fetch_mock.mockClear(); - setToken('synthetic-expired-token', Date.now() - 1000); - }); - - afterEach(() => { - cleanupAuth(); - vi.clearAllTimers(); - vi.useRealTimers(); - vi.unstubAllGlobals(); - }); - - test('renews the token and completes concurrent level queries', async () => { - const queries = [ - queryZones({ tags: 'level', limit: 2500 }), - queryZones({ - tags: 'level', - limit: 2500, - parent_id: 'building-test', - }), - ]; - const completed = vi.fn(); - const results = Promise.all(queries).then(completed); - - await vi.advanceTimersByTimeAsync(1000); - - expect(completed).toHaveBeenCalledOnce(); - await results; - expect( - fetch_mock.mock.calls.filter(([url]) => - String(url).includes('/oauth/token'), - ), - ).toHaveLength(1); - expect( - fetch_mock.mock.calls.find(([url]) => - String(url).includes('/oauth/token'), - )?.[1]?.body, - ).toContain('grant_type=refresh_token'); - const zone_requests = fetch_mock.mock.calls.filter(([url]) => - String(url).includes('/zones'), - ); - expect(zone_requests).toHaveLength(2); - for (const [, options] of zone_requests) { - expect(options?.headers).toMatchObject({ - Authorization: 'Bearer synthetic-renewed-token', - }); - } - }); - - test('rejects the level query when token renewal never completes', async () => { - fetch_mock.mockImplementation(() => new Promise(() => {})); - const failed = vi.fn(); - const query = queryZones({ tags: 'level', limit: 2500 }).catch(failed); - - await vi.advanceTimersByTimeAsync(30_000); - - expect(failed).toHaveBeenCalledWith( - expect.objectContaining({ - message: 'Timed out waiting for authentication.', - }), - ); - await query; - fetch_mock.mockClear(); - setToken('synthetic-valid-token', Date.now() + 60_000); - await vi.advanceTimersByTimeAsync(1); - expect(fetch_mock).not.toHaveBeenCalled(); - }); -}); diff --git a/test/http/functions.spec.ts b/test/http/functions.spec.ts deleted file mode 100644 index 3a0c5b4fa..000000000 --- a/test/http/functions.spec.ts +++ /dev/null @@ -1,317 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { HttpError } from '../../src/http/interfaces'; -import { createSignal } from '../../src/utilities/signal'; - -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; - -vi.mock('../../src/auth/functions'); - -describe('Http', () => { - beforeEach(() => { - (Auth as any).refreshAuthority = vi.fn(() => Promise.resolve()); - (Auth as any).invalidateToken = vi.fn(() => Promise.resolve()); - (Auth as any).hasToken = vi.fn(); - (Auth as any).hasToken.mockReturnValue(true); - (Auth as any).listenForToken = vi.fn(() => - createSignal(true).asReadonly(), - ); - (Auth as any).hasToken.mockReturnValue(true); - window.fetch = vi.fn().mockImplementation( - async () => - ({ - status: 200, - ok: true, - json: async () => ({ message: 'MSG Received!!!' }), - text: async () => 'MSG Received!!!', - headers: { - Authorisation: 'test', - 'x-total-count': 100, - }, - }) as any, - ); - vi.useFakeTimers(); - }); - - afterEach(() => { - (window.fetch as any).mockReset(); - (window.fetch as any).mockRestore(); - vi.useRealTimers(); - }); - - test('should handle non 401 errors', async () => { - expect.assertions(2); - window.fetch = vi.fn().mockImplementation(async () => ({ - status: 400, - text: () => Promise.resolve('Bad Request'), - })); - await Http.request('GET', '_', {}).catch((error) => { - expect(Auth.refreshAuthority).not.toBeCalled(); - expect(error.status).toBe(400); - }); - }); - - test('should refresh auth on 401 errors', async () => { - expect.assertions(1); - window.fetch = vi - .fn() - .mockImplementation(async () => ({ - status: 200, - text: async () => 'Success', - json: async () => {}, - })) - .mockImplementationOnce(async () => ({ - status: 401, - text: async () => 'Unauthorised', - })); - (Auth as any).listenForToken = vi.fn(() => - createSignal(true).asReadonly(), - ); - setTimeout(() => (Auth as any).hasToken.mockReturnValue(true), 500); - await Http.request('GET', '_', {}).catch((_) => _); - expect(Auth.refreshAuthority).toBeCalled(); - }); - - test('should skip token wait for unauthenticated requests', async () => { - expect.assertions(2); - (Auth as any).listenForToken = vi.fn(() => - createSignal(false).asReadonly(), - ); - (Auth as any).token = vi.fn(); - - await Http.request('GET', '_', { skip_auth: true }); - - expect(window.fetch).toHaveBeenCalled(); - expect(Auth.token).not.toHaveBeenCalled(); - }); - - test('should not refresh auth for unauthenticated request failures', async () => { - expect.assertions(2); - window.fetch = vi.fn().mockImplementation(async () => ({ - status: 401, - ok: false, - text: async () => 'Unauthorised', - })); - - await expect( - Http.request('GET', '_', { skip_auth: true }), - ).rejects.toMatchObject({ status: 401 }); - expect(Auth.refreshAuthority).not.toBeCalled(); - }); - - test('should attach token without auth flow recovery when requested', async () => { - expect.assertions(3); - (Auth as any).token = vi.fn(() => 'public-token'); - window.fetch = vi.fn().mockImplementation(async () => ({ - status: 401, - ok: false, - text: async () => 'Unauthorised', - })); - - await expect( - Http.request('GET', '_', { skip_auth_flow: true }), - ).rejects.toMatchObject({ status: 401 }); - expect(window.fetch).toHaveBeenCalledWith( - '_', - expect.objectContaining({ - headers: expect.objectContaining({ - Authorization: 'Bearer public-token', - }), - }), - ); - expect(Auth.refreshAuthority).not.toBeCalled(); - }); - - test('should add app headers to every request', async () => { - (Auth as any).appHeaders = vi.fn(() => ({ - 'X-App-Id': 'client', - 'X-App-Build': 'abcd1234', - })); - await Http.get('test_url', { headers: { 'X-App-Build': 'override' } }); - expect(window.fetch).toHaveBeenCalledWith( - 'test_url', - expect.objectContaining({ - headers: expect.objectContaining({ - 'X-App-Id': 'client', - 'X-App-Build': 'override', - }), - }), - ); - }); - - test('should expose response headers', () => { - expect(Http.responseHeaders('/test')).toEqual({}); - }); - - test('should store response headers from mock requests', async () => { - const mock_handler = vi.fn(async () => ({ - body: [1], - headers: { link: '; rel="next"' }, - })); - const data = await Http.request( - 'GET', - '/items', - {}, - () => true, - mock_handler, - ); - expect(data).toEqual([1]); - expect(window.fetch).not.toHaveBeenCalled(); - expect(Http.responseHeaders(`${location.origin}/items`)).toEqual({ - link: '; rel="next"', - }); - }); - - test('should allow GET requests', async () => { - expect.assertions(2); - const data = await Http.get('test_url'); - expect(data).toEqual({ message: 'MSG Received!!!' }); - expect(window.fetch).toHaveBeenCalled(); - await (Http as any).get('', undefined, () => Promise.resolve()); - }); - - test('should allow returning text data for GET', async () => { - expect.assertions(2); - const data = await Http.get('test_url', { response_type: 'text' }); - expect(window.fetch).toHaveBeenCalled(); - expect(data).toBe('MSG Received!!!'); - }); - - test('should allow returning blob data for GET', async () => { - const blob = new Blob(['image-data'], { type: 'image/png' }); - window.fetch = vi.fn().mockImplementation(async () => ({ - status: 200, - ok: true, - blob: async () => blob, - headers: {}, - })); - - const data = await Http.get('test_url', { response_type: 'blob' }); - - expect(data).toBe(blob); - }); - - test('should allow custom headers for GET', async () => { - expect.assertions(1); - await Http.get('test_url', { - headers: { 'CUSTOM-HEADER-X': 'Trump Cards :)' }, - }); - expect(window.fetch).toHaveBeenCalled(); - }); - - test('should handle GET errors ', async () => { - expect.assertions(1); - (window.fetch as any).mockImplementation(async () => ({ - status: 400, - text: async () => 'Bad Request', - })); - await expect(Http.get('_')).rejects.toMatchObject({ status: 400 }); - }); - - test('should allow POST requests', async () => { - expect.assertions(2); - const data = await Http.post('test_url', 'test_body'); - expect(data).toEqual({ message: 'MSG Received!!!' }); - expect(window.fetch).toHaveBeenCalled(); - await (Http as any).post('', '', undefined, () => Promise.resolve()); - }); - - test('should allow returning POST text data', async () => { - expect.assertions(2); - const data = await Http.post('test_url', 'test_body', { - response_type: 'text', - }); - expect(data).toBe('MSG Received!!!'); - expect(window.fetch).toHaveBeenCalled(); - }); - - test('should allow custom headers on POST', async () => { - expect.assertions(1); - await Http.post('test_url', 'test_body', { - headers: { 'CUSTOM-HEADER-X': 'Trump Cards :)' }, - }); - expect(window.fetch).toHaveBeenCalled(); - }); - - test('should handle POST errors', async () => { - expect.assertions(1); - (window.fetch as any).mockImplementation(async () => ({ - status: 400, - text: async () => 'Bad Request', - })); - await expect(Http.post('_', '')).rejects.toMatchObject({ status: 400 }); - }); - - test('should allow PUT requests', async () => { - expect.assertions(2); - const data = await Http.put('test_url', 'test_body'); - expect(data).toEqual({ message: 'MSG Received!!!' }); - expect(window.fetch).toHaveBeenCalled(); - await (Http as any).put('', '', undefined, () => Promise.resolve()); - }); - - test('should handle PUT errors', async () => { - expect.assertions(1); - (window.fetch as any).mockImplementation(async () => ({ - status: 400, - text: async () => 'Bad Request', - })); - await expect(Http.put('_', '')).rejects.toMatchObject({ status: 400 }); - }); - - test('should allow PATCH requests', async () => { - expect.assertions(2); - const data = await Http.patch('test_url', 'test_body'); - expect(data).toEqual({ message: 'MSG Received!!!' }); - expect(window.fetch).toHaveBeenCalled(); - await (Http as any).patch('', '', undefined, () => Promise.resolve()); - }); - - test('should handle PATCH errors', async () => { - expect.assertions(1); - (window.fetch as any).mockImplementation(async () => ({ - status: 400, - text: async () => 'Bad Request', - })); - await expect(Http.patch('_', '')).rejects.toMatchObject({ - status: 400, - } satisfies Partial); - }); - - test('should allow DELETE requests', async () => { - expect.assertions(2); - const data = await Http.del('test_url'); - expect(data).toBeUndefined(); - expect(window.fetch).toHaveBeenCalled(); - await (Http as any).del('', undefined, () => Promise.resolve()); - }); - - test('should allow returning json data on DELETE', async () => { - expect.assertions(2); - const data = await Http.del('test_url', { - response_type: 'json', - }); - expect(data).toEqual({ message: 'MSG Received!!!' }); - expect(window.fetch).toHaveBeenCalled(); - }); - - test('should allow returning text data on DELETE', async () => { - expect.assertions(2); - const data = await Http.del('test_url', { - response_type: 'text', - }); - expect(data).toEqual('MSG Received!!!'); - expect(window.fetch).toHaveBeenCalled(); - }); - - test('should handle DELETE errors', async () => { - expect.assertions(1); - (window.fetch as any).mockImplementation(async () => ({ - status: 400, - text: async () => 'Bad Request', - })); - await expect(Http.del('_')).rejects.toMatchObject({ - status: 400, - } satisfies Partial); - }); -}); diff --git a/test/http/mock.spec.ts b/test/http/mock.spec.ts deleted file mode 100644 index 7b99de652..000000000 --- a/test/http/mock.spec.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { MockHttpRequestHandlerOptions } from '../../src/http/interfaces'; - -import * as MockHttp from '../../src/http/mock'; - -describe('MockHttp', () => { - const global_handlers: MockHttpRequestHandlerOptions[] = [ - { - path: 'test/path', - method: 'GET', - metadata: {}, - callback: () => 'test', - }, - { - path: '/test/path2', - method: 'GET', - metadata: {}, - callback: () => 'test', - }, - ]; - - beforeEach(() => { - for (const handler of global_handlers) { - MockHttp.registerMockEndpoint(handler); - } - vi.useFakeTimers(); - }); - - afterEach(() => { - MockHttp.clearMockEndpoints(); - MockHttp.setMockNotFoundHandler((method, url) => { - const error = new Error( - `Mock endpoint not found: ${method} ${url}`, - ); - (error as any).status = 404; - return Promise.reject(error); - }); - vi.useRealTimers(); - }); - - test('should register global handlers', () => { - let handler = MockHttp.findRequestHandler('GET', 'test/path'); - expect(handler).toBeTruthy(); - handler = MockHttp.findRequestHandler('GET', '/test/path'); - expect(handler).toBeTruthy(); - handler = MockHttp.findRequestHandler('GET', 'test/path2'); - expect(handler).toBeTruthy(); - handler = MockHttp.findRequestHandler('GET', '/test/path2'); - expect(handler).toBeTruthy(); - }); - - test('should register new handlers', () => { - MockHttp.registerMockEndpoint({ - path: 'please/delete/me', - method: 'DELETE', - }); - let handler = MockHttp.findRequestHandler('DELETE', 'please/delete/me'); - expect(handler).toBeTruthy(); - // Check registration of handlers with route parameters - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - method: 'GET', - }); - handler = MockHttp.findRequestHandler('GET', 'please/join/me'); - expect(handler).toBeTruthy(); - }); - - test('should handle route parameters', async () => { - expect.assertions(3); - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - method: 'GET', - }); - const handler = MockHttp.findRequestHandler('GET', 'please/join/me'); - expect(handler).toBeTruthy(); - expect((handler || ({} as any)).path_structure).toEqual([ - '', - 'get', - '', - ]); - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - metadata: null, - method: 'GET', - callback: (request) => { - expect(request.route_params).toEqual({ get: 'help' }); - }, - }); - const promise = MockHttp.mockRequest( - 'GET', - 'please/help/me?query=true', - ); - vi.runOnlyPendingTimers(); - await promise; - }); - - test('should handle query parameters', async () => { - expect.assertions(1); - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - method: 'GET', - callback: (request) => { - expect(request.query_params).toEqual({ query: 'true' }); - }, - }); - const promise = MockHttp.mockRequest( - 'GET', - 'please/help/me?query=true', - ); - vi.runOnlyPendingTimers(); - await promise; - }); - - test('should handle request body', async () => { - expect.assertions(1); - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - method: 'POST', - callback: (request) => { - expect(request.body).toEqual({ help: false }); - }, - }); - const promise = MockHttp.mockRequest( - 'POST', - 'please/help/me?query=true', - { - help: false, - }, - ); - vi.runOnlyPendingTimers(); - await promise; - }); - - test('should return response headers', async () => { - MockHttp.registerMockEndpoint({ - path: 'items', - method: 'GET', - callback: () => [1, 2], - headers: (request) => ({ - Link: `; rel="next"`, - 'X-Total-Count': '10', - }), - }); - const promise = MockHttp.mockRequest('GET', 'items?offset=2'); - vi.runOnlyPendingTimers(); - await expect(promise).resolves.toEqual({ - body: [1, 2], - headers: { - link: '; rel="next"', - 'x-total-count': '10', - }, - }); - }); - - test('should return promise errors from handler callbacks', async () => { - const error = new Error('Callback failure'); - MockHttp.registerMockEndpoint({ - path: 'please/:get/me', - method: 'GET', - callback: () => { - throw error; - }, - }); - await expect( - MockHttp.mockRequest('GET', 'please/help/me'), - ).rejects.toBe(error); - }); - - test('should return promise errors from not found handlers', async () => { - const error = new Error('Not found handler failure'); - MockHttp.setMockNotFoundHandler(() => { - throw error; - }); - await expect( - MockHttp.mockRequest('GET', 'missing/endpoint'), - ).rejects.toBe(error); - }); -}); diff --git a/test/ldap-sources/functions.spec.ts b/test/ldap-sources/functions.spec.ts deleted file mode 100644 index 45d2e40ce..000000000 --- a/test/ldap-sources/functions.spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as SERVICE from '../../src/ldap-sources/functions'; -import { PlaceLDAPSource } from '../../src/ldap-sources/ldap-source'; -import * as Resources from '../../src/resources/functions'; - -describe('LDAPSources API', () => { - test('should allow querying ldapsources', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.queryLDAPSources(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceLDAPSource); - }); - - test('should allow showing ldapsource details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showLDAPSource('1'); - expect(item).toBeInstanceOf(PlaceLDAPSource); - }); - - test('should allow creating new LDAP sources', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addLDAPSource({}); - expect(item).toBeInstanceOf(PlaceLDAPSource); - }); - - test('should allow updating LDAP source details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.updateLDAPSource('1', {}); - expect(item).toBeInstanceOf(PlaceLDAPSource); - }); - - test('should allow removing ldapsources', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeLDAPSource('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/ldap-sources/ldap-source.spec.ts b/test/ldap-sources/ldap-source.spec.ts deleted file mode 100644 index f7af703b0..000000000 --- a/test/ldap-sources/ldap-source.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceLDAPSource } from '../../src/ldap-sources/ldap-source'; - -describe('PlaceLdapSource', () => { - let auth_source: PlaceLDAPSource; - - beforeEach(() => { - auth_source = new PlaceLDAPSource({ - id: 'dep-test', - authority_id: 'test-authority', - host: 'test', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(auth_source).toBeTruthy(); - expect(auth_source).toBeInstanceOf(PlaceLDAPSource); - }); - - test('should not allow editing the authority ID', () => { - expect(auth_source.authority_id).toBe('test-authority'); - }); - - test('should allow editing fields', () => { - expect(auth_source.host).toBe('test'); - }); -}); diff --git a/v2/test/loose/consumer.ts b/test/loose/consumer.ts similarity index 97% rename from v2/test/loose/consumer.ts rename to test/loose/consumer.ts index f94b22977..5d474d1cc 100644 --- a/v2/test/loose/consumer.ts +++ b/test/loose/consumer.ts @@ -13,7 +13,7 @@ export async function calls(): Promise { const page = await zones.query({ limit: 10 }).then(orThrowPage); await zones.update({ id: zone.id, body: { name: 'name' } }).then(orThrow); await metadata.show({ id: 'zone-1', name: 'settings' }).then(orThrow); - // A v1 enum value fits the v2 field. + // A 6.x enum value fits the 7.x field. const role: Driver['role'] = PlaceDriverRole.Logic; // @ts-expect-error the body is missing await zones.update({ id: 'zone-1' }); diff --git a/v2/test/loose/tsconfig.json b/test/loose/tsconfig.json similarity index 100% rename from v2/test/loose/tsconfig.json rename to test/loose/tsconfig.json diff --git a/test/metadata/functions.spec.ts b/test/metadata/functions.spec.ts deleted file mode 100644 index 233d69cc7..000000000 --- a/test/metadata/functions.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as SERVICE from '../../src/metadata/functions'; -import { PlaceMetadata } from '../../src/metadata/metadata'; -import { PlaceZoneMetadata } from '../../src/metadata/zone-metadata'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; - -describe('Applications API', () => { - test('should allow listing metadata', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!([{}]) as any)); - const item = await SERVICE.listMetadata('1'); - expect(item[0]).toBeInstanceOf(PlaceMetadata); - }); - - test('should allow getting metadata', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showMetadata('1', 'test'); - expect(item).toBeInstanceOf(PlaceMetadata); - }); - - test('should allow creating new metadata', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addMetadata({}); - expect(item).toBeInstanceOf(PlaceMetadata); - item = await SERVICE.addMetadata({}); - }); - - test('should allow updating metadata details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateMetadata('1', {}); - expect(item).toBeInstanceOf(PlaceMetadata); - item = await SERVICE.updateMetadata('1', {}, 'patch'); - }); - - test('should allow removing metadata', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeMetadata('1', { - name: 'test', - }); - expect(item).toBeFalsy(); - }); - - test('should allow listing child zone metadata', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_: any) => - Promise.resolve(_.callback([{ metadata: {} }]) as any), - ); - const item = await SERVICE.listChildMetadata('1', {}); - expect(item[0]).toBeInstanceOf(PlaceZoneMetadata); - }); - - test('should allow renaming metadata', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'patch'); - spy.mockImplementation(() => - Promise.resolve({ parent_id: '1', name: 'new-name', details: {} }) as any, - ); - - const item = await SERVICE.renameMetadata('1', { - current_name: 'old-name', - new_name: 'new-name', - }); - - expect(item).toBeInstanceOf(PlaceMetadata); - expect(spy).toHaveBeenCalledWith('/api/engine/v2/metadata/1/name', { - current_name: 'old-name', - new_name: 'new-name', - }); - }); -}); diff --git a/test/metadata/metadata.spec.ts b/test/metadata/metadata.spec.ts deleted file mode 100644 index d7f08162d..000000000 --- a/test/metadata/metadata.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceMetadata } from '../../src/metadata/metadata'; - -describe('PlaceMetadata', () => { - let metadata: PlaceMetadata; - - beforeEach(() => { - metadata = new PlaceMetadata({ - parent_id: 'dep-test', - name: 'catering', - description: 'In a galaxy far far away...', - details: [], - schema_id: 'schema-1', - }); - }); - - test('should create instance', () => { - expect(metadata).toBeTruthy(); - expect(metadata).toBeInstanceOf(PlaceMetadata); - }); - - test('should expose properties', () => { - expect(metadata.id).toBe('dep-test'); - expect(metadata.parent_id).toBe('dep-test'); - expect(metadata.name).toBe('catering'); - expect(metadata.description).toBe('In a galaxy far far away...'); - expect(metadata.details).toEqual([]); - expect(metadata.schema_id).toBe('schema-1'); - expect(metadata.schema).toBe('schema-1'); - }); -}); diff --git a/test/metadata/zone-metadata.spec.ts b/test/metadata/zone-metadata.spec.ts deleted file mode 100644 index 7f503f40b..000000000 --- a/test/metadata/zone-metadata.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceZoneMetadata } from '../../src/metadata/zone-metadata'; -import { PlaceZone } from '../../src/zones/zone'; - -describe('PlaceMetadata', () => { - let metadata: PlaceZoneMetadata; - - beforeEach(() => { - metadata = new PlaceZoneMetadata({ - zone: {} as any, - metadata: { test: {} } as any, - keys: ['test'], - }); - }); - - test('should create instance', () => { - expect(metadata).toBeTruthy(); - expect(metadata).toBeInstanceOf(PlaceZoneMetadata); - new PlaceZoneMetadata(); - }); - - test('should expose properties', () => { - expect(metadata.zone).toBeInstanceOf(PlaceZone); - expect(metadata.keys).toBeInstanceOf(Array); - expect(metadata.metadata).toBeInstanceOf(Object); - expect(metadata.metadata.test).toBeTruthy(); - }); -}); diff --git a/v2/test/migrate.test.ts b/test/migrate.test.ts similarity index 91% rename from v2/test/migrate.test.ts rename to test/migrate.test.ts index 684f2d2f1..a8d0d24f7 100644 --- a/v2/test/migrate.test.ts +++ b/test/migrate.test.ts @@ -1,7 +1,7 @@ /** - * Goal: the migration tool rewrites v1 calls to the correct v2 calls, and it does not change a use + * Goal: the migration tool rewrites 6.x calls to the correct 7.x calls, and it does not change a use * that it cannot rewrite safely. - * Method: run `migrateSource` with the generated map on small v1 files, and compare the text. + * Method: run `migrateSource` with the generated map on small 6.x files, and compare the text. */ import { expect, test } from 'bun:test'; import * as ts from 'typescript-5'; @@ -55,7 +55,7 @@ test('maps path templates, default values, members and picked keys', () => { expect(result.text.split('\n').slice(2)).toEqual([ "zones.zoneExecute({ id, module_slug: 'Display_1', method: 'power', body: [] }).then(orThrow);", 'metadata.show({ id: zone.id, name }).then(orThrow).then((data) => data[name]);', - // v1 sent `form_data.version || 0`. + // 6.x sent `form_data.version || 0`. 'systems.update({ sys_id: system.id, version: system.version ?? 0, body: system }).then(orThrow);', ]); }); @@ -63,7 +63,7 @@ test('maps path templates, default values, members and picked keys', () => { test('keeps the uses that it cannot rewrite, with a finding', () => { const text = [ "import { addSystemModule, getModule, listMetadata, showMetadata, showZone } from '@placeos/ts-client';", - // v1 made a list of the metadata, which v2 gives by name. + // 6.x made a list of the metadata, which 7.x gives by name. 'listMetadata(zone.id);', "addSystemModule('sys-1', 'mod-1', { a: 1 });", 'showMetadata(id, names()[0]);', @@ -113,13 +113,13 @@ test('rewrites calls and spies on a namespace import', () => { "vi.spyOn(client.zones, 'show');", "jest.fn().mockName('showZone');", ]); - // Another string with a v1 name can be a test double that the tool does not know. + // Another string with a 6.x name can be a test double that the tool does not know. expect(result.findings.map((finding) => finding.message)).toEqual([ - 'a test double of v1: make it for the v2 call (zones.show)', + 'a test double of 6.x: make it for the 7.x call (zones.show)', ]); }); -test('a namespace import reads the v1 enums and types from the compat module', () => { +test('a namespace import reads the 6.x enums and types from the compat module', () => { const result = migrate( [ "import * as client from '@placeos/ts-client';", @@ -135,7 +135,7 @@ test('a namespace import reads the v1 enums and types from the compat module', ( ]); }); -test('moves the v1 enums and the QueryResponse type to the compat module', () => { +test('moves the 6.x enums and the QueryResponse type to the compat module', () => { const result = migrate( [ "import { PlaceDriverRole, QueryResponse } from '@placeos/ts-client';", @@ -160,7 +160,7 @@ test('a second run changes nothing', () => { const second = migrate(first.text); expect(second.text).toBe(first.text); expect(second.changes).toBe(0); - // The v2 names of the first run are not findings. + // The 7.x names of the first run are not findings. expect(second.findings.map((finding) => finding.name)).toEqual(['getModule']); }); @@ -189,11 +189,11 @@ test('rewrites test doubles: the function, the mock values and the argument chec "vi.mocked(zones.show).mockRejectedValue(new Error('403'));", "expect(zones.show).toHaveBeenCalledWith({ id: 'zone-1' });", 'expect(zones.show).not.toHaveBeenCalled();', - // An implementation gets the v1 arguments, and its value becomes a v2 result. + // An implementation gets the 6.x arguments, and its value becomes a 7.x result. "(zones.show as Mock).mockImplementation(fromV1Mock((id) => Promise.resolve({ id }), ['id', '...']));", - // The v2 call gives the data by key, so the value goes under the key. + // The 7.x call gives the data by key, so the value goes under the key. "vi.mocked(metadata.show).mockImplementation(fromV1Mock(() => ({ details: {} }), ['id', 'name'], 'data', 'name'));", - // The check leaves out the `version` that v2 reads from the data. + // The check leaves out the `version` that 7.x reads from the data. "expect(systems.update).toHaveBeenCalledWith(expect.objectContaining({ sys_id: 'sys-1', body: expect.objectContaining({ name: 'A' }) }));", ]); expect(result.findings).toEqual([]); @@ -213,7 +213,7 @@ test('rewrites a spy on a namespace import, and finds an automock', () => { expect(result.findings.map((finding) => finding.name)).toEqual(['@placeos/ts-client']); }); -test('rewrites the v1 functions of a vi.mock factory to v2 namespaces', () => { +test('rewrites the 6.x functions of a vi.mock factory to 7.x namespaces', () => { const result = migrate( [ "import { authority, queryZones, showMetadata, showZone } from '@placeos/ts-client';", @@ -235,7 +235,7 @@ test('rewrites the v1 functions of a vi.mock factory to v2 namespaces', () => { ]); }); -test('fromV1Mock gives the v1 arguments and a v2 result', async () => { +test('fromV1Mock gives the 6.x arguments and a 7.x result', async () => { const { fromV1Mock, orThrow, orThrowPage } = await import('../src/compat/index.ts'); const calls: unknown[][] = []; const record = (...args: unknown[]) => { @@ -245,7 +245,7 @@ test('fromV1Mock gives the v1 arguments and a v2 result', async () => { const show = fromV1Mock(record, ['id', '...']); expect(orThrow(await show({ id: 'zone-1' }))).toEqual({ id: 'zone-1' }); await show({ id: 'zone-1', complete: true }); - // An empty last argument is left out, as the v1 call left it out. + // An empty last argument is left out, as the 6.x call left it out. expect(calls).toEqual([['zone-1'], ['zone-1', { complete: true }]]); const query = fromV1Mock(() => ({ data: [1], total: 9 }), ['...'], 'page'); expect(orThrowPage(await query({})).total).toBe(9); @@ -255,7 +255,7 @@ test('fromV1Mock gives the v1 arguments and a v2 result', async () => { }); }); -test('a v2 type gets an alias when the v1 class stays for a value use', () => { +test('a 7.x type gets an alias when the 6.x class stays for a value use', () => { const result = migrate( [ "import { SignagePlugin } from '@placeos/ts-client';", @@ -268,7 +268,7 @@ test('a v2 type gets an alias when the v1 class stays for a value use', () => { ]); }); -test('rewrites the v1 staff functions to @placeos/ts-client/staff', () => { +test('rewrites the 6.x staff functions to @placeos/ts-client/staff', () => { const result = migrate( [ "import { querySurveys, showSurvey, Survey, showZone } from '@placeos/ts-client';", @@ -284,13 +284,13 @@ test('rewrites the v1 staff functions to @placeos/ts-client/staff', () => { "import { orThrow } from '@placeos/ts-client/compat';", 'const assets = 1;', 'const survey: Survey = await surveys.show({ id }).then(orThrow);', - // v1 `querySurveys` gave a list, not a page. + // 6.x `querySurveys` gave a list, not a page. 'const list = await surveys.query({ zone_id: zone }).then(orThrow);', 'await zones.show({ id }).then(orThrow);', ]); }); -test('the hoisted helper goes with the new imports, also when the last v1 import goes', () => { +test('the hoisted helper goes with the new imports, also when the last 6.x import goes', () => { const result = migrate( [ "import { showZone } from '@placeos/ts-client';", @@ -354,7 +354,7 @@ test('a factory keeps a mock as a mock, and finds a function whose arguments it ].join('\n'), 'zone.spec.ts', ); - // `${module}_${index}` of `executeOnZone` has two v1 arguments in one input value. + // `${module}_${index}` of `executeOnZone` has two 6.x arguments in one input value. expect(result.text).toContain( "zones: { show: vi.fn(fromV1Mock(vi.fn().mockResolvedValue(zone), ['id', '...'])) }", ); @@ -374,7 +374,7 @@ test('a file deeper than the limit stays as it is, with a finding', () => { expect(result.findings[0]?.message).toContain('deeper than'); }); -test('a test double of a function whose arguments the tool cannot rebuild stays v1', () => { +test('a test double of a function whose arguments the tool cannot rebuild stays 6.x', () => { const text = [ "import { executeOnZone } from '@placeos/ts-client';", 'vi.mocked(executeOnZone).mockImplementation((id, method, module, index) => Promise.resolve(index));', diff --git a/v2/test/mock.test.ts b/test/mock.test.ts similarity index 100% rename from v2/test/mock.test.ts rename to test/mock.test.ts diff --git a/test/modules/functions.spec.ts b/test/modules/functions.spec.ts deleted file mode 100644 index be1fdc199..000000000 --- a/test/modules/functions.spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as SERVICE from '../../src/modules/functions'; -import { PlaceModule } from '../../src/modules/module'; -import * as Resources from '../../src/resources/functions'; -import { PlaceSettings } from '../../src/settings/settings'; - -describe('Modules API', () => { - test('should allow querying modules', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryModules(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceModule); - list = await SERVICE.queryModules({}); - }); - - test('should allow showing module details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showModule('1'); - expect(item).toBeInstanceOf(PlaceModule); - item = await SERVICE.showModule('1', {}); - }); - - test('should allow creating new modules', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addModule({}); - expect(item).toBeInstanceOf(PlaceModule); - item = await SERVICE.addModule({}); - }); - - test('should allow updating module details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateModule('1', {}); - expect(item).toBeInstanceOf(PlaceModule); - item = await SERVICE.updateModule('1', {}, 'patch'); - }); - - test('should allow removing modules', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeModule('1'); - expect(item).toBeFalsy(); - }); - - test('should allow starting a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.startModule('1'); - expect(item).toBeFalsy(); - }); - - test('should allow stopping a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.stopModule('1'); - expect(item).toBeFalsy(); - }); - - test('should allow pinging a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => - Promise.resolve({ host: '', pingable: false }), - ); - const item = await SERVICE.pingModule('1'); - expect(item).toBeTruthy(); - }); - - test('should allow getting state of a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.moduleState('1'); - expect(item).toBeTruthy(); - }); - - test('should allow lookup of module state', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.lookupModuleState('1', 'connected'); - expect(item).toBeTruthy(); - }); - - test('should allow loading module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.loadModule('1'); - expect(item).toBeTruthy(); - }); - - test('should allow settings for a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_: any) => - Promise.resolve(_.callback([{}]) as any), - ); - const item = await SERVICE.moduleSettings('1'); - expect(item).toBeTruthy(); - expect(item[0]).toBeInstanceOf(PlaceSettings); - }); - - test('should allow executing a method on a module', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({ result: 'success' })); - let item = await SERVICE.executeOnModule('1', 'test_method'); - expect(item).toEqual({ result: 'success' }); - item = await SERVICE.executeOnModule('1', 'test_method', [ - 'arg1', - 'arg2', - ]); - }); -}); diff --git a/test/modules/module.spec.ts b/test/modules/module.spec.ts deleted file mode 100644 index 913c2702e..000000000 --- a/test/modules/module.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceDriverRole } from '../../src/drivers/enums'; -import { PlaceModule } from '../../src/modules/module'; - -describe('PlaceModule', () => { - let module: PlaceModule; - - beforeEach(() => { - module = new PlaceModule({ - id: 'mod_test', - driver_id: 'dep-001', - control_system_id: 'sys-001', - ip: '1.1.1.1', - tls: false, - udp: false, - port: 32000, - makebreak: false, - uri: 'test.com', - custom_name: 'mi-name', - settings: { settings_string: "{ star: 'death' }" } as any, - role: PlaceDriverRole.Device, - notes: 'Clone wars', - ignore_connected: false, - control_system: { id: 'sys-001', name: 'A System' } as any, - driver: { id: 'dep-001', name: 'A Driver' } as any, - }); - }); - - test('should create instance', () => { - expect(module).toBeTruthy(); - expect(module).toBeInstanceOf(PlaceModule); - expect(new PlaceModule()).toBeInstanceOf(PlaceModule); - }); - - test('should expose properties', () => { - expect(module.driver_id).toBe('dep-001'); - expect(module.control_system_id).toBe('sys-001'); - expect(module.system_id).toBe('sys-001'); - expect(module.ip).toBe('1.1.1.1'); - expect(module.tls).toBe(false); - expect(module.udp).toBe(false); - expect(module.port).toBe(32000); - expect(module.makebreak).toBe(false); - expect(module.uri).toBe('test.com'); - expect(module.custom_name).toBe('mi-name'); - expect(module.settings).toBeInstanceOf(Object); - expect(module.role).toBe(PlaceDriverRole.Device); - expect(module.notes).toEqual('Clone wars'); - expect(module.ignore_connected).toBe(false); - }); - - test('should remove system id for non-logic modules', () => { - module = new PlaceModule({ - control_system_id: 'sys-test', - role: PlaceDriverRole.Logic, - }); - expect(module.toJSON().control_system_id).toBe('sys-test'); - module = new PlaceModule({ - control_system_id: 'sys-test', - role: PlaceDriverRole.Websocket, - }); - expect(module.toJSON().control_system_id).toBeFalsy(); - module = new PlaceModule({ - control_system_id: 'sys-test', - role: PlaceDriverRole.Service, - }); - expect(module.toJSON().control_system_id).toBeFalsy(); - module = new PlaceModule({ - control_system_id: 'sys-test', - role: PlaceDriverRole.Device, - }); - expect(module.toJSON().control_system_id).toBeFalsy(); - module = new PlaceModule({ - control_system_id: 'sys-test', - role: PlaceDriverRole.SSH, - }); - expect(module.toJSON().control_system_id).toBeFalsy(); - expect(module.toJSON(true).control_system_id).toBe('sys-test'); - }); -}); diff --git a/test/oauth-sources/functions.spec.ts b/test/oauth-sources/functions.spec.ts deleted file mode 100644 index 490adb864..000000000 --- a/test/oauth-sources/functions.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as SERVICE from '../../src/oauth-sources/functions'; -import { PlaceOAuthSource } from '../../src/oauth-sources/oauth-source'; -import * as Resources from '../../src/resources/functions'; - -describe('OAuthSources API', () => { - test('should allow querying oauth sources', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.queryOAuthSources(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceOAuthSource); - }); - - test('should allow showing oauth source details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showOAuthSource('1'); - expect(item).toBeInstanceOf(PlaceOAuthSource); - }); - - test('should allow creating new oauth sources', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addOAuthSource({}); - expect(item).toBeInstanceOf(PlaceOAuthSource); - item = await SERVICE.addOAuthSource({}); - }); - - test('should allow updating oauth source details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateOAuthSource('1', {}); - expect(item).toBeInstanceOf(PlaceOAuthSource); - item = await SERVICE.updateOAuthSource('1', {}, 'patch'); - }); - - test('should allow removing oauth sources', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeOAuthSource('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/oauth-sources/oauth-source.spec.ts b/test/oauth-sources/oauth-source.spec.ts deleted file mode 100644 index 2759dae9c..000000000 --- a/test/oauth-sources/oauth-source.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceOAuthSource } from '../../src/oauth-sources/oauth-source'; - -describe('PlaceOAuthSource', () => { - let auth_source: PlaceOAuthSource; - - beforeEach(() => { - auth_source = new PlaceOAuthSource({ - id: 'dep-test', - authority_id: 'test-authority', - client_id: 'test', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(auth_source).toBeTruthy(); - expect(auth_source).toBeInstanceOf(PlaceOAuthSource); - }); - - test('should not allow editing the authority ID', () => { - expect(auth_source.authority_id).toBe('test-authority'); - }); - - test('should allow editing fields', () => { - expect(auth_source.client_id).toBe('test'); - }); -}); diff --git a/v2/test/pagination.test.ts b/test/pagination.test.ts similarity index 100% rename from v2/test/pagination.test.ts rename to test/pagination.test.ts diff --git a/v2/test/realtime.test.ts b/test/realtime.test.ts similarity index 100% rename from v2/test/realtime.test.ts rename to test/realtime.test.ts diff --git a/test/realtime/binding.spec.ts b/test/realtime/binding.spec.ts deleted file mode 100644 index 2375e3148..000000000 --- a/test/realtime/binding.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { getModule, getSystem } from '../../src/realtime/binding'; -import { PlaceModuleBinding } from '../../src/realtime/module'; -import { PlaceSystemBinding } from '../../src/realtime/system'; - -describe('PlaceBindingService', () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - test('should allow getting systems', () => { - const system = getSystem('sys-A0'); - expect(system).toBeInstanceOf(PlaceSystemBinding); - expect(system.id).toBe('sys-A0'); - }); - - test('should allow getting modules', () => { - const module = getModule('sys-A0', 'Test'); - expect(module).toBeInstanceOf(PlaceModuleBinding); - expect(module.id).toBe('Test_1'); - expect(module.name).toBe('Test'); - expect(module.index).toBe(1); - }); -}); diff --git a/test/realtime/functions.spec.ts b/test/realtime/functions.spec.ts deleted file mode 100644 index 2e5bc8329..000000000 --- a/test/realtime/functions.spec.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; - -import { PlaceResponse } from '../../src/realtime/interfaces'; -import { HashMap } from '../../src/utilities/types'; - -import * as Auth from '../../src/auth/functions'; -import * as ws from '../../src/realtime/functions'; -import * as mock_ws from '../../src/realtime/mock'; -import * as websocket from '../../src/utilities/websocket'; - -vi.mock('../../src/auth/functions'); - -const DELAY = Math.pow(2, 40); - -describe('Realtime API', () => { - let fake_socket: websocket.MemoryWebSocket; - let another_fake_socket: websocket.MemoryWebSocket; - let ws_spy: any; - let error_spy: any; - let conn_spy: any; - let count = 0; - let debug_state = false; - - beforeEach(() => { - vi.useFakeTimers(); - fake_socket = new websocket.MemoryWebSocket(); - another_fake_socket = new websocket.MemoryWebSocket(); - debug_state = window.debug; - error_spy = vi.spyOn(console, 'error').mockImplementation(() => null); - (Auth as any).token = vi.fn().mockReturnValue('test'); - (Auth as any).apiEndpoint = vi.fn().mockReturnValue('/api/engine/v2'); - (Auth as any).authority = vi.fn().mockReturnValue({}); - (Auth as any).isMock = vi.fn().mockReturnValue(false); - (Auth as any).refreshAuthority = vi - .fn() - .mockImplementation(async () => null); - (Auth as any).invalidateToken = vi - .fn() - .mockImplementation(async () => null); - ws_spy = vi.spyOn(websocket, 'webSocket'); - ws_spy - .mockImplementationOnce(() => fake_socket) - .mockImplementationOnce(() => another_fake_socket) - .mockImplementation(() => fake_socket); - ws.ignore({ sys: 'sys-A0', mod: 'mod', index: 1, name: 'power' }, 0); - count++; - conn_spy = vi.spyOn(ws, 'isConnected'); - conn_spy.mockReturnValue(true); - vi.runOnlyPendingTimers(); - }); - - afterEach(() => { - count = 0; - window.debug = debug_state; - ws.cleanupRealtime(); - ws_spy.mockRestore(); - error_spy.mockRestore(); - conn_spy.mockRestore(); - vi.useRealTimers(); - }); - - const test_method = ( - method: 'bind' | 'unbind' | 'debug' | 'ignore', - done: () => void, - ) => { - const details = { - sys: `sys-B0-${method}`, - mod: 'mod', - index: 1, - name: 'power', - }; - const post = vi.fn().mockImplementation(async () => null); - let promise = (ws[method] as any)(details, DELAY, post); - expect(post).toHaveBeenCalledWith( - { - id: ++count, - cmd: method, - ...details, - }, - DELAY, - ); - // Test success - promise.then(() => { - post.mockImplementation(async () => { - throw { - id: 2, - type: 'error', - code: 7, - msg: 'test error', - } as PlaceResponse; - }); - promise = (ws[method] as any)(details, DELAY, post); - expect(post).toHaveBeenCalledWith( - { - id: ++count, - cmd: method, - ...details, - }, - DELAY, - ); - // Test error - promise.then(null, () => done()); - }); - }; - - test('should handle bind request', () => - new Promise((resolve) => test_method('bind', resolve))); - - test('should handle unbind request', () => - new Promise((resolve) => test_method('unbind', resolve))); - - test('should handle debug request', () => - new Promise((resolve) => test_method('debug', resolve))); - - test('should handle ignore request', () => - new Promise((resolve) => test_method('ignore', resolve))); - - test('should handle exec request', () => - new Promise((resolve) => { - const details = { - sys: 'sys-A3', - mod: 'mod', - index: 1, - name: 'power', - args: [true], - }; - const result = { test: 1 }; - const post = vi.fn().mockImplementation(async () => result); - let promise = (ws.execute as any)(details, DELAY, post); - expect(post).toHaveBeenCalledWith( - { - id: ++count, - cmd: 'exec', - ...details, - }, - DELAY, - ); - expect(promise).toBeInstanceOf(Promise); - // Test success - promise.then((resp: HashMap) => { - expect(resp).toEqual(result); - post.mockImplementation(async () => { - throw { - id: 2, - type: 'error', - code: 7, - msg: 'test error', - } as PlaceResponse; - }); - promise = (ws.execute as any)(details, DELAY, post); - expect(post).toHaveBeenCalledWith( - { - id: ++count, - cmd: 'exec', - ...details, - }, - DELAY, - ); - // Test error - promise.then(null).catch(() => resolve()); - }); - })); - - test('should handle notify responses', () => - new Promise((resolve) => { - const binding = { - sys: 'sys-A2', - mod: 'mod', - index: 1, - name: 'power', - }; - ws.listen(binding).subscribe((value) => { - if (value) { - expect(value).toBe('Yeah'); - resolve(); - } - }); - fake_socket.next({ - type: 'notify', - value: 'Yeah', - meta: binding, - } as PlaceResponse); - })); - - test('should reconnect the websocket', () => - new Promise((resolve) => { - vi.useRealTimers(); - let actions = 0; - ws.status().subscribe((connected: boolean) => { - if (actions === 0) { - actions++; - // Websocket connected - expect(connected).toBe(true); - fake_socket.error({ - status: 401, - message: 'Invalid auth token', - }); - // vi.runOnlyPendingTimers(); - } else if (actions === 1) { - actions++; - // Websocket disconnected - expect(connected).toBe(false); - // vi.runOnlyPendingTimers(); - } else if (actions === 2) { - actions++; - // Setup websocket - expect(connected).toBe(true); - resolve(); - } - // vi.runOnlyPendingTimers(); - }); - })); - - test('should allow retrieving the current value of a binding', () => - new Promise((resolve) => { - const metadata = { - sys: 'sys-A0', - mod: 'mod', - index: 1, - name: 'power', - }; - const post = vi.fn().mockImplementation(async () => null); - expect(ws.value(metadata)).toBeUndefined(); - const promise = (ws as any).bind(metadata, DELAY, post); - promise.then(() => { - fake_socket.next({ - type: 'notify', - value: 'Yeah', - meta: metadata, - } as PlaceResponse); - expect(ws.value(metadata)).toBe('Yeah'); - resolve(); - }); - fake_socket.next({ id: 1, type: 'success' } as PlaceResponse); - })); - - test('should handle engine errors', () => { - window.debug = true; - fake_socket.next({ - id: 0, - type: 'error', - code: 0, - msg: 'test error', - } as PlaceResponse); - // fake_socket.next({ id: 1, type: 'error', code: 1, msg: 'test error' } as PlaceResponse); - fake_socket.next({ - id: 2, - type: 'error', - code: 2, - msg: 'test error', - } as PlaceResponse); - fake_socket.next({ - id: 3, - type: 'error', - code: 3, - msg: 'test error', - } as PlaceResponse); - fake_socket.next({ - id: 4, - type: 'error', - code: 4, - msg: 'test error', - } as PlaceResponse); - fake_socket.next({ - id: 5, - type: 'error', - code: 5, - msg: 'test error', - } as PlaceResponse); - fake_socket.next({ - id: 6, - type: 'error', - code: 6, - msg: 'test error', - } as PlaceResponse); - fake_socket.next({ - id: 7, - type: 'error', - code: 7, - msg: 'test error', - } as PlaceResponse); - vi.advanceTimersByTime(1000); - expect(error_spy).toBeCalledTimes(7); - expect(error_spy).toHaveBeenCalledWith( - expect.stringContaining('[ERROR] PARSE ERROR(0): test error'), - expect.any(String), - expect.any(String), - expect.any(String), - ); - expect(error_spy).toHaveBeenCalledWith( - expect.stringContaining( - '[ERROR] UNEXPECTED FAILURE(7): test error', - ), - expect.any(String), - expect.any(String), - expect.any(String), - ); - }); - - test('should log error when engine message is invalid', () => { - window.debug = true; - const message = {}; - fake_socket.next(message); - expect(error_spy).toHaveBeenCalledWith( - expect.stringContaining('[PlaceOS]'), - expect.any(String), - expect.any(String), - expect.any(String), - message, - ); - expect(error_spy.mock.calls[0][0]).toContain( - 'Invalid websocket message', - ); - }); - - test('should delay requests while reconnecting', () => - new Promise((resolve) => { - const metadata = { - sys: 'sys-A0', - mod: 'mod', - index: 1, - name: 'power', - }; - another_fake_socket.subscribe((msg_str: string) => { - if (msg_str !== 'ping' && typeof msg_str === 'string') { - const expected: HashMap = { - id: 1, - cmd: 'bind', - ...metadata, - }; - const message: HashMap = JSON.parse(msg_str); - for (const key in message) { - if (message[key]) { - expect(message[key]).toBe(expected[key]); - } - } - } - }); - (Auth as any).token.mockReturnValue('test'); - (ws.isConnected as any).mockReturnValue(false); - ws.bind(metadata); - vi.advanceTimersByTime(ws.REQUEST_TIMEOUT / 2); - (ws.isConnected as any).mockReturnValue(true); - another_fake_socket.next({ - id: 1, - type: 'success', - } as PlaceResponse); - vi.advanceTimersByTime(ws.REQUEST_TIMEOUT / 2 - 1); - resolve(); - })); - - test('should ping the websocket every X seconds', () => - new Promise((resolve) => { - fake_socket.subscribe((message: any) => { - expect(message).toBe('ping'); - resolve(); - }); - vi.runOnlyPendingTimers(); - })); - - test('should retry connecting if websocket fails to create', () => { - // TODO - expect(1).toBe(1); - }); - - test('should bind to mock system modules', () => - new Promise((resolve) => { - let checked = false; - vi.useRealTimers(); - mock_ws.registerSystem('sys-A9', { - Test: [ - { - test: 0, - $testCall() { - return (this as any)._system.Test[0].test++; - }, - }, - ], - }); - ws.cleanupRealtime(); - vi.spyOn(Auth, 'isMock').mockReturnValue(true); - const binding = { - sys: 'sys-A9', - mod: 'Test', - index: 1, - name: 'test', - }; - ws.bind(binding).then(() => { - ws.listen(binding).subscribe((value) => { - if (!value || checked) return; - expect(ws.value(binding)).toBe(value); - expect(ws.value(binding)).toBe(10); - resolve(); - checked = true; - }); - mock_ws.mockSystem('sys-A9').Test[0].test = 10; - }); - })); -}); diff --git a/test/realtime/mock-module.spec.ts b/test/realtime/mock-module.spec.ts deleted file mode 100644 index 32b966b24..000000000 --- a/test/realtime/mock-module.spec.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { MockPlaceWebsocketModule } from '../../src/realtime/mock-module'; - -class TestModule { - public value = 0; - $testFn() { - this.value++; - } -} - -describe('MockPlaceWebsocketModule', () => { - let module: MockPlaceWebsocketModule; - let test_mod: MockPlaceWebsocketModule; - const system = { - Bookings: [ - { - test: 10, - $namespaceTest: 99, - namespaceTestFn: () => 1, - $method: () => 10, - $methodWithOneArg: (arg1: number) => arg1 + 1, - $methodWithTwoArgs: (arg1: number, arg2: number) => arg1 + arg2, - $updateOtherModule() { - return (this as any)._system.Other[0].test--; - }, - }, - ], - Test: [new TestModule()], - Other: [ - { - test: 20, - }, - ], - }; - - beforeEach(() => { - module = new MockPlaceWebsocketModule( - system as any, - system.Bookings[0], - ); - test_mod = new MockPlaceWebsocketModule(system as any, system.Test[0]); - }); - - test('should create an instance', () => { - expect(module).toBeTruthy(); - expect(test_mod).toBeTruthy(); - }); - - test('should allow getting binding values', () => { - expect(module.test).toBe(10); - }); - - test('should allow setting binding values', () => { - expect(module.test).toBe(10); - module.test = 20; - expect(module.test).toBe(20); - }); - - test('should allow listening to binding values', () => - new Promise((resolve) => { - let test_count = 0; - module.listen('test').subscribe((value: any) => { - if (test_count === 0) { - expect(value).toBe(10); - test_count++; - } else if (test_count === 1) { - expect(value).toBe(20); - resolve(); - } - }); - setTimeout(() => (module.test = 20)); - })); - - test('should allow listening to non-predefined binding values', () => - new Promise((resolve) => { - let test_count = 0; - module.listen('other_test').subscribe((value: any) => { - if (test_count === 0) { - expect(value).toBe(null); - test_count++; - } else if (test_count === 1) { - expect(value).toBe(20); - resolve(); - } - }); - setTimeout(() => (module.other_test = 20)); - })); - - test('should allow for executing methods', () => { - expect(module.call('method')).toBe(10); - expect(module.call('methodWithOneArg', [10])).toBe(11); - expect(module.call('methodWithTwoArgs', [10, 11])).toBe(21); - expect(module.call('falseFn')).toBe(null); - }); - - test('should remove namespace from value bindings', () => { - expect(module.namespaceTest).toBe(99); - }); - - test('should namespace executable methods', () => { - expect(module.namespaceTestFn).toBeUndefined(); - expect(module.call('namespaceTestFn')).toBe(1); - }); - - test('should allow for access to parent system', () => { - expect(module.call('updateOtherModule')).toBe(20); - expect(system.Other[0].test).toBe(19); - }); -}); diff --git a/test/realtime/mock-system.spec.ts b/test/realtime/mock-system.spec.ts deleted file mode 100644 index 87f557489..000000000 --- a/test/realtime/mock-system.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { MockPlaceWebsocketModule } from '../../src/realtime/mock-module'; -import { MockPlaceWebsocketSystem } from '../../src/realtime/mock-system'; - -describe('MockPlaceWebsocketSystem', () => { - let system: MockPlaceWebsocketSystem; - - beforeEach(() => { - const system_metadata = { - Bookings: [ - { - test: 10, - $method: () => 10, - $methodWithOneArg: (arg1: number) => arg1 + 1, - $methodWithTwoArgs: (arg1: number, arg2: number) => - arg1 + arg2, - }, - ], - Other: [ - { - test: 20, - }, - { - test: 11, - }, - ], - }; - system = new MockPlaceWebsocketSystem(system_metadata); - }); - - test('should create an instance', () => { - expect(system).toBeTruthy(); - }); - - test('should expose the modules', () => { - expect(system.Bookings[0]).toBeInstanceOf(MockPlaceWebsocketModule); - expect(system.Other[0]).toBeInstanceOf(MockPlaceWebsocketModule); - expect(system.Other[1]).toBeInstanceOf(MockPlaceWebsocketModule); - }); -}); diff --git a/test/realtime/mock.spec.ts b/test/realtime/mock.spec.ts deleted file mode 100644 index 5edd9a6d5..000000000 --- a/test/realtime/mock.spec.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { PlaceErrorCodes } from '../../src/realtime/interfaces'; -import { - deregisterSystem, - mockSystem, - registerSystem, -} from '../../src/realtime/mock'; - -import * as Auth from '../../src/auth/functions'; -import * as ws from '../../src/realtime/functions'; - -describe('MockEngineWebsocket', () => { - beforeEach(() => { - vi.spyOn(Auth, 'isMock').mockReturnValue(true); - vi.spyOn(Auth, 'authority').mockReturnValue({} as any); - registerSystem('sys-A0', { - Test: [ - { - test: 10, - $testCall() { - setTimeout(() => (this.test += 1)); - return this.test; - }, - }, - ], - }); - }); - - afterEach(() => { - deregisterSystem('sys-A0'); - ws.cleanupRealtime(); - }); - - test('should bind to mock system modules', (done) => { - let checked = false; - const binding = { sys: 'sys-A0', mod: 'Test', index: 1, name: 'test' }; - ws.listen(binding).subscribe((value) => { - if (value && !checked) { - expect(ws.value(binding)).toBe(10); - done(); - checked = true; - } - }); - ws.bind(binding); - }); - - test('post binding value updates', (done) => { - let checked = false; - const binding = { sys: 'sys-A0', mod: 'Test', index: 1, name: 'test' }; - let count = 0; - ws.listen(binding).subscribe((value) => { - if (count === 0) { - expect(value).toBeUndefined(); - count++; - } else if (value && !checked) { - expect(value).toBe(10); - done(); - checked = true; - } - }); - ws.bind(binding); - }); - - test('should unbind from mock system modules', (done) => { - const binding = { sys: 'sys-A0', mod: 'Test', index: 1, name: 'test' }; - ws.listen(binding).subscribe((value) => { - if (value) { - expect(ws.value(binding)).toBe(10); - ws.unbind(binding).then(() => { - mockSystem('sys-A0').Test[0].test = 20; - setTimeout(() => { - expect(ws.value(binding)).not.toBe(20); - done(); - }, 200); - }); - } - }); - ws.bind(binding); - }); - - test('should exec mock system module methods', (done) => { - const binding = { sys: 'sys-A0', mod: 'Test', index: 1, name: 'test' }; - const unsubscribe = ws.listen(binding).subscribe((value) => { - if (!value) return; - unsubscribe(); - ws.execute({ ...binding, name: 'testCall' }).then((value) => { - expect(value).toBe(10); - setTimeout(() => { - expect(ws.value(binding)).toBe(11); - done(); - }, 200); - }); - }); - ws.bind(binding); - }); - - test('should reject when mock listener setup throws', async () => { - const binding = { sys: 'sys-A0', mod: 'Test', index: 1, name: 'test' }; - (mockSystem('sys-A0').Test[0] as any).listen = () => { - throw new Error('Listener failure'); - }; - await expect(ws.bind(binding)).rejects.toMatchObject({ - type: 'error', - code: PlaceErrorCodes.UNEXPECTED_FAILURE, - msg: 'Listener failure', - }); - }); - - test('should reject when mock execute throws', async () => { - mockSystem('sys-A0').Test[0].$testCall = () => { - throw new Error('Execute failure'); - }; - await expect( - ws.execute({ - sys: 'sys-A0', - mod: 'Test', - index: 1, - name: 'testCall', - }), - ).rejects.toMatchObject({ - type: 'error', - code: PlaceErrorCodes.UNEXPECTED_FAILURE, - msg: 'Execute failure', - }); - }); - - test('should error if binding module not found', (done) => { - const binding = { - sys: 'sys-A0', - mod: 'Testing', - index: 1, - name: 'test', - }; - ws.bind(binding).then(null, () => done()); - }); - - test('should error if binding system not found', (done) => { - const binding = { sys: 'sys-B0', mod: 'Test', index: 1, name: 'test' }; - ws.bind(binding).then(null, () => done()); - }); -}); diff --git a/test/realtime/module.spec.ts b/test/realtime/module.spec.ts deleted file mode 100644 index d33bcc730..000000000 --- a/test/realtime/module.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; - -import { PlaceModuleBinding } from '../../src/realtime/module'; -import { PlaceVariableBinding } from '../../src/realtime/status-variable'; -import { createSignal } from '../../src/utilities/signal'; - -import * as ws from '../../src/realtime/functions'; - -vi.mock('../../src/realtime/functions'); - -describe('PlaceSystemBinding', () => { - let module: PlaceModuleBinding; - let fake_system: any; - - beforeEach(() => { - vi.useFakeTimers(); - (ws as any).status.mockImplementation(() => - createSignal(true).asReadonly(), - ); - (ws as any).execute.mockImplementation(() => Promise.resolve()); - fake_system = { id: 'sys-A0' }; - module = new PlaceModuleBinding(fake_system, 'Test_1'); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - test('should create an instance', () => { - expect(module).toBeTruthy(); - }); - - test('should expose system', () => { - expect(module.system).toBe(fake_system); - }); - - test("should expose it's name and index", () => { - expect(module.name).toBe('Test'); - expect(module.index).toBe(1); - module = new PlaceModuleBinding(fake_system, ''); - expect(module.index).toBe(1); - }); - - test('should return bindings', () => { - const binding = module.binding('test'); - expect(binding).toBeTruthy(); - expect(binding).toBeInstanceOf(PlaceVariableBinding); - expect(module.binding('test')).toBe(binding); - }); - - test('should allow methods to be executed', () => { - const promise = module.execute('testCall'); - expect(promise).toBeInstanceOf(Promise); - expect(ws.execute).toBeCalledWith( - { - sys: fake_system.id, - mod: module.name, - index: module.index, - name: 'testCall', - args: undefined, - }, - ws.REQUEST_TIMEOUT, - ); - }); -}); diff --git a/test/realtime/status-variable.spec.ts b/test/realtime/status-variable.spec.ts deleted file mode 100644 index 0bbd2bc22..000000000 --- a/test/realtime/status-variable.spec.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; - -import { PlaceVariableBinding } from '../../src/realtime/status-variable'; -import { WritableSignal, createSignal } from '../../src/utilities/signal'; - -import * as ws from '../../src/realtime/functions'; - -vi.mock('../../src/realtime/functions'); - -describe('PlaceVariableBinding', () => { - let status: PlaceVariableBinding; - let fake_module: any; - let fake_system: any; - let state_subject: WritableSignal; - let status_value: WritableSignal; - - beforeEach(() => { - vi.useFakeTimers(); - state_subject = createSignal(false); - status_value = createSignal(undefined); - (ws as any).status.mockImplementation(() => state_subject.asReadonly()); - (ws as any).bind.mockImplementation((_: any) => Promise.resolve()); - (ws as any).unbind.mockImplementation((_: any) => Promise.resolve()); - (ws as any).listen.mockImplementation(() => status_value.asReadonly()); - (ws as any).value.mockImplementation((_: any) => status_value.value); - fake_system = { id: 'sys-A0' }; - fake_module = { system: fake_system, name: 'Test', index: 1 }; - status = new PlaceVariableBinding(fake_module, 'test'); - }); - - afterEach(() => { - (ws.bind as any).mockRestore(); - vi.useRealTimers(); - }); - - test('should create an instance', () => { - expect(status).toBeTruthy(); - }); - - test('should expose it name', () => { - expect(status.name).toBe('test'); - }); - - test('should bind to the status variable', () => - new Promise((resolve) => { - vi.useRealTimers(); - const unbind = status.bind(); - expect(unbind).toBeInstanceOf(Function); - expect(ws.bind).toBeCalled(); - setTimeout(() => { - expect(status.count).toBe(1); - resolve(); - }); - })); - - test('should unbind to the status variable', () => - new Promise((resolve) => { - vi.useRealTimers(); - status.bind(); - const unbind = status.bind(); - setTimeout(() => { - expect(status.count).toBe(2); - unbind(); - setTimeout(() => { - expect(status.count).toBe(1); - status.unbind(); - setTimeout(() => { - expect(status.count).toBe(0); - expect(ws.unbind).toBeCalledTimes(1); - // Check that the binding count doesn't go below 0 - status.unbind(); - setTimeout(() => { - expect(status.count).toBe(0); - resolve(); - }); - }); - }); - }); - })); - - test('should expose the binding value', () => { - expect(status.value).toBeUndefined(); - status_value.set(10); - expect(status.value).toBe(10); - }); - - test('should allow for subscribing to the binding value', () => - new Promise((resolve) => { - status.listen().subscribe((value: any) => { - if (value) { - expect(value).toBe(10); - resolve(); - } - }); - status_value.set(10); - })); - - test('should rebind to bindings on websocket reconnect', () => - new Promise((resolve) => { - vi.useRealTimers(); - state_subject.set(true); - state_subject.set(false); - setTimeout(() => { - expect(ws.bind).not.toBeCalled(); - status.bind(); - setTimeout(() => { - state_subject.set(false); - state_subject.set(true); - setTimeout(() => { - expect(ws.bind).toBeCalled(); - resolve(); - }); - }); - }); - })); -}); diff --git a/test/realtime/system.spec.ts b/test/realtime/system.spec.ts deleted file mode 100644 index 57920b52c..000000000 --- a/test/realtime/system.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import { PlaceModuleBinding } from '../../src/realtime/module'; -import { PlaceSystemBinding } from '../../src/realtime/system'; - -describe('PlaceSystemBinding', () => { - let system: PlaceSystemBinding; - - beforeEach(() => { - vi.useFakeTimers(); - system = new PlaceSystemBinding('sys-A0'); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - test('should create an instance', () => { - expect(system).toBeTruthy(); - }); - - test('should have an ID', () => { - expect(system.id).toBe('sys-A0'); - }); - - test('should return modules', () => { - expect(() => system.module('')).toThrow(); - const test = system.module('Test'); - expect(test).toBeInstanceOf(PlaceModuleBinding); - expect(test).toBe(system.module('Test')); - expect(test).toBe(system.module('Test_1')); - expect(test).toBe(system.module('Test', -1)); - expect(test).not.toBe(system.module('Test', 2)); - }); -}); diff --git a/test/repositories/functions.spec.ts b/test/repositories/functions.spec.ts deleted file mode 100644 index a22b8c30c..000000000 --- a/test/repositories/functions.spec.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as SERVICE from '../../src/repositories/functions'; -import { PlaceRepository } from '../../src/repositories/repository'; -import * as Resources from '../../src/resources/functions'; - -describe('Repositories API', () => { - test('should allow querying repositories', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryRepositories(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceRepository); - list = await SERVICE.queryRepositories({}); - }); - - test('should allow showing repository details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showRepository('1'); - expect(item).toBeInstanceOf(PlaceRepository); - }); - - test('should allow creating new repositories', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addRepository({}); - expect(item).toBeInstanceOf(PlaceRepository); - item = await SERVICE.addRepository({}); - }); - - test('should allow updating repository details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateRepository('1', {}); - expect(item).toBeInstanceOf(PlaceRepository); - item = await SERVICE.updateRepository('1', {}, 'patch'); - }); - - test('should allow removing repositories', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeRepository('1'); - expect(item).toBeFalsy(); - }); - - test('should allow listing remote repository default branch', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation(() => Promise.resolve('')); - let item = await SERVICE.listRemoteRepositoryDefaultBranch({ - repository_url: 'test', - }); - expect(item).toEqual(''); - }); - - test('should allow listing remote repository branches', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation(() => Promise.resolve([])); - let item = await SERVICE.listRemoteRepositoryBranches({ - repository_url: 'test', - }); - expect(item).toEqual([]); - }); - - test('should allow listing remote repository commits', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation(() => Promise.resolve([])); - let item = await SERVICE.listRemoteRepositoryCommits({ - repository_url: 'test', - }); - expect(item).toEqual([]); - }); - - test('should allow listing remote repository tags', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation(() => Promise.resolve([])); - let item = await SERVICE.listRemoteRepositoryTags({ - repository_url: 'test', - }); - expect(item).toEqual([]); - }); - - test('should allow listing interface repositories', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.listInterfaceRepositories(); - expect(item).toEqual({}); - }); - - test('should allow listing repository drivers', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve(['/driver'])); - let item = await SERVICE.listRepositoryDrivers('1'); - expect(item).toEqual(['/driver']); - item = await SERVICE.listRepositoryDrivers('1', {}); - }); - - test('should allow listing repository releases', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve([{}])); - const item = await SERVICE.listRepositoryReleases('1'); - expect(item).toEqual([{}]); - }); - - test('should allow listing repository commits', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve([{}])); - const item = await SERVICE.listRepositoryCommits('1'); - expect(item).toEqual([{}]); - }); - - test('should allow listing repository branches', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve(['master'])); - const item = await SERVICE.listRepositoryBranches('1'); - expect(item).toEqual(['master']); - }); - - test('should allow listing repository default branch', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve('master')); - const item = await SERVICE.listRepositoryDefaultBranch('1'); - expect(item).toEqual('master'); - }); - - test('should allow listing repository tags', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve(['v1.0.0'])); - const item = await SERVICE.listRepositoryTags('1'); - expect(item).toEqual(['v1.0.0']); - }); - - test('should allow getting repository driver details', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve(['/driver'])); - const item = await SERVICE.listRepositoryDriverDetails('1', { - driver: '/driver', - commit: '1', - }); - expect(item).toEqual(['/driver']); - }); - - test('should allow pulling latest changes to repository', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.pullRepositoryChanges('1'); - expect(item).toEqual({}); - }); - - test('should allow listing repository folders', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => - Promise.resolve(['src/', 'test/', 'lib/']), - ); - let item = await SERVICE.listRepositoryFolders('1'); - expect(item).toEqual(['src/', 'test/', 'lib/']); - item = await SERVICE.listRepositoryFolders('1', { - include_dots: true, - }); - }); - - test('should allow listing repository files by pattern', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve(['/plugins/index.html'])); - const files = await SERVICE.listRepositoryFiles('1', { - pattern: '*.html', - }); - expect(files).toEqual(['/plugins/index.html']); - expect(spy).toHaveBeenCalledWith({ - id: '1', - task_name: 'files', - form_data: { pattern: '*.html' }, - method: 'get', - path: 'repositories', - }); - }); -}); diff --git a/test/repositories/repository.spec.ts b/test/repositories/repository.spec.ts deleted file mode 100644 index 48a730ce4..000000000 --- a/test/repositories/repository.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceRepositoryType } from '../../src/repositories/interfaces'; -import { PlaceRepository } from '../../src/repositories/repository'; -import { generateMockRepository } from '../../src/repositories/utilities'; - -describe('PlaceRepository', () => { - let repository: PlaceRepository; - let mock_data: any; - - beforeEach(() => { - mock_data = generateMockRepository({ - repo_type: PlaceRepositoryType.Driver, - }); - repository = new PlaceRepository(mock_data); - }); - - test('should create instance', () => { - expect(repository).toBeTruthy(); - expect(repository).toBeInstanceOf(PlaceRepository); - }); - - test('should expose properties', () => { - expect(repository.commit_hash).toBe(mock_data.commit_hash); - expect(repository.folder_name).toBe(mock_data.folder_name); - expect(repository.description).toBe(mock_data.description); - expect(repository.uri).toBe(mock_data.uri); - expect(repository.type).toBe(PlaceRepositoryType.Driver); - }); -}); diff --git a/test/resources/functions.spec.ts b/test/resources/functions.spec.ts deleted file mode 100644 index dd1ac83c2..000000000 --- a/test/resources/functions.spec.ts +++ /dev/null @@ -1,295 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import * as Http from '../../src/http/functions'; -import * as Resource from '../../src/resources/functions'; - -vi.mock('../../src/http/functions'); - -describe('Resource API', () => { - let resp_header_spy: any; - - async function testRequest( - method: 'get' | 'post' | 'patch' | 'put' | 'del', - func: (...args: any[]) => Promise, - result: any, - test1: any[], - test2: any[], - ) { - const item = result.hasOwnProperty('results') ? result.results : result; - (Http[method] as any) - .mockReturnValueOnce(Promise.resolve(result)) - .mockReturnValueOnce(Promise.resolve(result)) - .mockImplementationOnce(() => Promise.reject('An Error Value')); - const value: any = await func({ - fn: (_: any) => _, - path: 'resource', - ...test1[0], - }); - vi.runOnlyPendingTimers(); - expect(value.data ? value.data : value).toEqual(item || []); - // Test request with parameters - await func({ - fn: (_: any) => _, - path: 'resource', - ...test2[0], - }); - vi.runOnlyPendingTimers(); - // Test error handling - try { - await func({ - fn: (_: any) => _, - path: 'resource', - ...test1[0], - }); - throw new Error('Failed to error'); - } catch (e) { - expect(e).toBe('An Error Value'); - } - vi.runOnlyPendingTimers(); - } - - beforeEach(() => { - vi.useFakeTimers(); - resp_header_spy = vi.spyOn(Http, 'responseHeaders'); - window.fetch = vi.fn().mockImplementation(async () => ({ - json: async () => ({ - version: '1.0.0', - login_url: '/login?continue={{url}}', - }), - })); - }); - - afterEach(() => { - vi.useRealTimers(); - Resource.cleanupAPI(); - const methods: any[] = ['get', 'post', 'patch', 'put', 'del']; - for (const method of methods) { - (Http as any)[method].mockReset(); - (Http as any)[method].mockRestore(); - } - }); - - test('should return 0 from total requests by default', () => { - expect(Resource.requestTotal('any')).toBe(0); - expect(Resource.lastRequestTotal('any')).toBe(0); - }); - - test('should allow querying the index endpoint', async () => { - expect.assertions(8); - const item = { id: 'test', name: 'Test' }; - await testRequest( - 'get', - Resource.query, - { results: [item] }, - [{}], - [{ query_params: { cache: 100, test: true } }], - ); - await testRequest( - 'get', - Resource.query, - { total: 10, results: [item] }, - [{}], - [{ query_params: { test: true } }], - ); - await testRequest( - 'get', - Resource.query, - { total: 10, results: [] }, - [{}], - [{ query_params: { test: true } }], - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource', - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource?test=true', - ); - }); - - test('should save index request totals', async () => { - expect.assertions(6); - const item = { id: 'test', name: 'Test' }; - const headers = { 'x-total-count': '10' }; - resp_header_spy.mockReturnValue(headers); - await testRequest( - 'get', - Resource.query, - { total: 10, results: [item] }, - [{ query_params: { offset: 10 } }], - [{ query_params: { offset: 10 } }], - ); - headers['x-total-count'] = '25'; - resp_header_spy.mockReturnValue(headers); - await testRequest( - 'get', - Resource.query, - { total: 25, results: [item] }, - [{ query_params: { test: true } }], - [{ query_params: { test: true } }], - ); - expect(Resource.requestTotal('resource')).toBe(10); - expect(Resource.lastRequestTotal('resource')).toBe(25); - }); - - test('should reuse identical query requests for 300ms', async () => { - const item = { id: 'test', name: 'Test' }; - (Http.get as any).mockResolvedValue({ results: [item] }); - - const first = Resource.query({ - fn: (_: any) => _, - path: 'resource', - query_params: { test: true }, - }); - const second = Resource.query({ - fn: (_: any) => _, - path: 'resource', - query_params: { test: true }, - }); - - expect(first).toBe(second); - expect(Http.get).toHaveBeenCalledTimes(1); - expect((await first).data).toEqual([item]); - - Resource.query({ - fn: (_: any) => _, - path: 'resource', - query_params: { other: true }, - }); - expect(Http.get).toHaveBeenCalledTimes(2); - - vi.advanceTimersByTime(300); - Resource.query({ - fn: (_: any) => _, - path: 'resource', - query_params: { test: true }, - }); - expect(Http.get).toHaveBeenCalledTimes(3); - }); - - test('should allow for grabbing the show endpoint for an item', async () => { - const item = { id: 'test', name: 'Test' }; - await testRequest( - 'get', - Resource.show, - item, - [{ id: 'test' }], - [{ id: 'test', query_params: { test: true } }], - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test', - undefined, - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test?test=true', - undefined, - ); - }); - - test('should allow adding new items', async () => { - expect.assertions(3); - const item = { id: 'test', name: 'Test' }; - await testRequest( - 'post', - Resource.create, - item, - [{ form_data: item }], - [{ form_data: item }], - ); - expect(Http.post).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource', - item, - ); - }); - - test('should allow running POST tasks on items', async () => { - expect.assertions(4); - await testRequest( - 'post', - Resource.task, - 'success', - [{ id: 'test', task_name: 'a_task' }], - [{ id: 'test', task_name: 'a_task', form_data: { test: true } }], - ); - expect(Http.post).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test/a_task', - undefined, - ); - expect(Http.post).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test/a_task', - { - test: true, - }, - ); - }); - - test('should allow updating items', async () => { - expect.assertions(3); - const item = { id: 'test', name: 'Test' }; - await testRequest( - 'patch', - Resource.update, - item, - [{ id: 'test', form_data: item }], - [{ id: 'test', form_data: item }], - ); - expect(Http.patch).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test?version=0', - item, - ); - // expect(Http.put).toHaveBeenCalledWith( - // 'http://localhost:3000/api/engine/v2/resource/test?version=0', - // item - // ); - }); - - test('should allow deleting items', async () => { - expect.assertions(4); - const item = { id: 'test', name: 'Test' }; - await testRequest( - 'del', - Resource.remove, - item, - [{ id: 'test' }], - [{ id: 'test', query_params: { test: true } }], - ); - expect(Http.del).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test', - ); - expect(Http.del).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test?test=true', - ); - }); - - test('should allow running GET tasks on items', async () => { - expect.assertions(4); - await testRequest( - 'get', - Resource.task, - 'success', - [{ id: 'test', task_name: 'a_task', method: 'get' }], - [ - { - id: 'test', - task_name: 'a_task', - form_data: { test: true }, - method: 'get', - }, - ], - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test/a_task', - { - response_type: 'json', - }, - ); - expect(Http.get).toHaveBeenCalledWith( - 'http://localhost:3000/api/engine/v2/resource/test/a_task?test=true', - { - response_type: 'json', - }, - ); - }); - - test('should allow getting the next page', () => { - expect(Resource.next()).toBeFalsy(); - }); -}); diff --git a/test/resources/resource.spec.ts b/test/resources/resource.spec.ts deleted file mode 100644 index ab633a658..000000000 --- a/test/resources/resource.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { beforeEach, describe, expect, test, vi } from 'vitest'; -import { PlaceResource } from '../../src/resources/resource'; - -class Resource extends PlaceResource {} - -describe('PlaceResource', () => { - let resource: Resource; - let service: any; - - beforeEach(() => { - service = { - add: vi.fn(), - delete: vi.fn(), - update: vi.fn(), - }; - service.add.mockReturnValue(Promise.resolve()); - service.delete.mockReturnValue(Promise.resolve()); - service.update.mockReturnValue(Promise.resolve()); - resource = new Resource({ - id: 'test', - name: 'Test', - created_at: 999, - updated_at: 999, - }); - }); - - test('should expose id', () => { - expect(resource.id).toBe('test'); - }); - - test('should expose name', () => { - expect(resource.name).toBe('Test'); - }); - - test('should expose creation time', () => { - expect(resource.created_at).toEqual(999); - }); - - test('should expose updated time', () => { - expect(resource.updated_at).toEqual(999); - }); -}); diff --git a/test/root/functions.spec.ts b/test/root/functions.spec.ts deleted file mode 100644 index 17ccd7d80..000000000 --- a/test/root/functions.spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import * as SERVICE from '../../src/root/functions'; - -describe('Root API', () => { - afterEach(() => vi.restoreAllMocks()); - - const status = { - state: 'clearing', - clear: true, - started_at: '2026-10-15T00:00:00Z', - cleared: 0, - metadata: 0, - }; - - test('should allow starting a resync of the MQTT brokers', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const http = vi - .spyOn(Http, 'post') - .mockImplementation(() => Promise.resolve(status) as any); - - expect(await SERVICE.sourceResync(true)).toEqual(status); - expect(http).toHaveBeenCalledWith( - '/api/engine/v2/source/resync?clear=true', - {}, - ); - - await SERVICE.sourceResync(); - expect(http).toHaveBeenLastCalledWith( - '/api/engine/v2/source/resync?clear=false', - {}, - ); - }); - - test('should allow reading where the resync got to', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const http = vi - .spyOn(Http, 'get') - .mockImplementation(() => Promise.resolve(status) as any); - - expect(await SERVICE.sourceResyncStatus()).toEqual(status); - expect(http).toHaveBeenCalledWith('/api/engine/v2/source/resync'); - }); -}); diff --git a/test/saml-sources/functions.spec.ts b/test/saml-sources/functions.spec.ts deleted file mode 100644 index d01af869c..000000000 --- a/test/saml-sources/functions.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; - -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/saml-sources/functions'; -import { PlaceSAMLSource } from '../../src/saml-sources/saml-source'; - -describe('SAML Auth Sources API', () => { - test('should allow querying ldapsources', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.querySAMLSources(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceSAMLSource); - list = await SERVICE.querySAMLSources({}); - }); - - test('should allow showing SAML source details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showSAMLSource('1'); - expect(item).toBeInstanceOf(PlaceSAMLSource); - }); - - test('should allow creating new SAML sources', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addSAMLSource({}); - expect(item).toBeInstanceOf(PlaceSAMLSource); - item = await SERVICE.addSAMLSource({}); - }); - - test('should allow updating SAML source details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateSAMLSource('1', {}); - expect(item).toBeInstanceOf(PlaceSAMLSource); - item = await SERVICE.updateSAMLSource('1', {}, 'patch'); - }); - - test('should allow removing SAML sources', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeSAMLSource('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/saml-sources/saml-source.spec.ts b/test/saml-sources/saml-source.spec.ts deleted file mode 100644 index 5d647852e..000000000 --- a/test/saml-sources/saml-source.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; - -import { PlaceSAMLSource } from '../../src/saml-sources/saml-source'; - -describe('PlaceSamlSource', () => { - let auth_source: PlaceSAMLSource; - - beforeEach(() => { - auth_source = new PlaceSAMLSource({ - id: 'dep-test', - authority_id: 'test-authority', - idp_cert: 'test', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(auth_source).toBeTruthy(); - expect(auth_source).toBeInstanceOf(PlaceSAMLSource); - }); - - test('should not allow editing the authority ID', () => { - expect(auth_source.authority_id).toBe('test-authority'); - }); - - test('should allow editing fields', () => { - expect(auth_source.idp_cert).toBe('test'); - }); -}); diff --git a/v2/test/schema.test.ts b/test/schema.test.ts similarity index 100% rename from v2/test/schema.test.ts rename to test/schema.test.ts diff --git a/test/settings/functions.spec.ts b/test/settings/functions.spec.ts deleted file mode 100644 index a94fc1e8b..000000000 --- a/test/settings/functions.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; - -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/settings/functions'; -import { PlaceSettings } from '../../src/settings/settings'; - -describe('Settings API', () => { - test('should allow querying settings', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.querySettings(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceSettings); - }); - - test('should allow showing settings details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showSettings('1'); - expect(item).toBeInstanceOf(PlaceSettings); - }); - - test('should allow creating new settings', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addSettings({}); - expect(item).toBeInstanceOf(PlaceSettings); - item = await SERVICE.addSettings({}, {}); - }); - - test('should allow updating settings details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateSettings('1', {}); - expect(item).toBeInstanceOf(PlaceSettings); - item = await SERVICE.updateSettings('1', {}, {}, 'patch'); - }); - - test('should allow removing settings', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeSettings('1'); - expect(item).toBeFalsy(); - }); - - test('should allow getting settings history', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_: any) => - Promise.resolve(_.callback([{}]) as any), - ); - let item = await SERVICE.settingsHistory('1', {}); - expect(item).toBeInstanceOf(Array); - item = await SERVICE.settingsHistory('1'); - }); -}); diff --git a/test/settings/settings.spec.ts b/test/settings/settings.spec.ts deleted file mode 100644 index 4776c29c3..000000000 --- a/test/settings/settings.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; - -import { PlaceSettings } from '../../src/settings/settings'; -import { generateMockSettings } from '../../src/settings/utilities'; - -describe('PlaceSettings', () => { - let settings: PlaceSettings; - let item: any; - - beforeEach(() => { - item = generateMockSettings(); - item = generateMockSettings({ name: 'Test' }); - settings = new PlaceSettings(item); - }); - - test('should create instance', () => { - expect(settings).toBeTruthy(); - expect(settings).toBeInstanceOf(PlaceSettings); - }); - - test('should expose parent ID', () => { - expect(settings.parent_id).toBe(item.parent_id); - }); - - test('should expose last update time', () => { - expect(settings.updated_at).toBe(item.updated_at); - }); - - test('should expose encryption level', () => { - expect(settings.encryption_level).toBe(item.encryption_level); - }); - - test('should expose settings value', () => { - expect(settings.settings_string).toBe(item.settings_string); - expect(settings.value).toBe(item.settings_string); - }); - - test('should expose top level keys', () => { - expect(settings.keys).toEqual(item.keys); - }); -}); diff --git a/test/short-url/functions.spec.ts b/test/short-url/functions.spec.ts deleted file mode 100644 index d1166c222..000000000 --- a/test/short-url/functions.spec.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/short-url/functions'; -import { PlaceShortUrl } from '../../src/short-url/short-url.class'; - -describe('Short URL API', () => { - test('should allow querying short URLs', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryShortUrls(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceShortUrl); - list = await SERVICE.queryShortUrls({}); - }); - - test('should allow showing short URL details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showShortUrl('1'); - expect(item).toBeInstanceOf(PlaceShortUrl); - item = await SERVICE.showShortUrl('1', {}); - }); - - test('should allow creating new short URLs', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addShortUrl({}); - expect(item).toBeInstanceOf(PlaceShortUrl); - }); - - test('should allow updating short URL details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateShortUrl('1', {}); - expect(item).toBeInstanceOf(PlaceShortUrl); - item = await SERVICE.updateShortUrl('1', {}, 'patch'); - item = await SERVICE.updateShortUrl('1', {}, 'put'); - }); - - test('should allow removing short URLs', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeShortUrl('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeShortUrl('1'); - }); -}); - -describe('Short URL Redirect', () => { - test('should generate correct redirect URL', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.shortUrlRedirectUrl('test-id'); - expect(url).toBe('/api/engine/v2/short_url/test-id/redirect'); - }); - - test('should encode special characters in ID', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.shortUrlRedirectUrl('test/id with spaces'); - expect(url).toBe( - '/api/engine/v2/short_url/test%2Fid%20with%20spaces/redirect', - ); - }); -}); - -describe('Short URL QR Code SVG', () => { - test('should fetch SVG QR code', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => Promise.resolve('...') as any, - ); - - const result = await SERVICE.getShortUrlQrCodeSvg('test-id'); - expect(result).toBe('...'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/short_url/test-id/qr_code.svg', - { response_type: 'text' }, - ); - }); -}); - -describe('Short URL QR Code PNG URL', () => { - test('should generate correct PNG QR code URL', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.shortUrlQrCodePngUrl('test-id'); - expect(url).toBe('/api/engine/v2/short_url/test-id/qr_code.png'); - }); - - test('should include size parameter', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.shortUrlQrCodePngUrl('test-id', { size: 256 }); - expect(url).toBe( - '/api/engine/v2/short_url/test-id/qr_code.png?size=256', - ); - }); - - test('should encode special characters in ID', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.shortUrlQrCodePngUrl('test/id'); - expect(url).toBe('/api/engine/v2/short_url/test%2Fid/qr_code.png'); - }); -}); - -describe('QR Code URL Generator', () => { - test('should generate correct QR code URL with required params', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.qrCodeUrl({ - content: 'https://example.com', - id: 'qr-123', - }); - expect(url).toContain('/api/engine/v2/short_url/qr_code?'); - expect(url).toContain('content=https%3A%2F%2Fexample.com'); - expect(url).toContain('id=qr-123'); - expect(url).toContain('format=svg'); - }); - - test('should support PNG format', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.qrCodeUrl({ - content: 'test', - id: 'qr-123', - format: 'png', - }); - expect(url).toContain('format=png'); - }); - - test('should include size parameter', () => { - const spy = vi.spyOn(Auth, 'apiEndpoint'); - spy.mockReturnValue('/api/engine/v2'); - const url = SERVICE.qrCodeUrl({ - content: 'test', - id: 'qr-123', - size: 128, - }); - expect(url).toContain('size=128'); - }); -}); - -describe('Generate QR Code', () => { - test('should generate SVG QR code with custom content', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => Promise.resolve('custom') as any, - ); - - const result = await SERVICE.generateQrCode({ - content: 'https://example.com', - id: 'qr-123', - }); - - expect(result).toBe('custom'); - expect(httpSpy).toHaveBeenCalledWith( - expect.stringContaining('/api/engine/v2/short_url/qr_code?'), - { response_type: 'text' }, - ); - }); - - test('should include size in request', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation(() => Promise.resolve('') as any); - - await SERVICE.generateQrCode({ - content: 'test', - id: 'qr-123', - size: 200, - }); - - expect(httpSpy).toHaveBeenCalledWith( - expect.stringContaining('size=200'), - expect.any(Object), - ); - }); -}); diff --git a/test/short-url/short-url.class.spec.ts b/test/short-url/short-url.class.spec.ts deleted file mode 100644 index 27f61cd67..000000000 --- a/test/short-url/short-url.class.spec.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceShortUrl } from '../../src/short-url/short-url.class'; - -describe('PlaceShortUrl', () => { - let shortUrl: PlaceShortUrl; - - beforeEach(() => { - shortUrl = new PlaceShortUrl({ - id: 'short-123', - name: 'Test Short URL', - uri: 'https://example.com/long-url-path', - description: 'A test short URL', - user_id: 'user-456', - user_email: 'user@example.com', - user_name: 'Test User', - redirect_count: 42, - enabled: true, - valid_from: '2024-01-01T00:00:00Z', - valid_until: '2024-12-31T23:59:59Z', - authority_id: 'auth-789', - created_at: 1704067200, - updated_at: 1704153600, - }); - }); - - test('should create instance', () => { - expect(shortUrl).toBeTruthy(); - expect(shortUrl).toBeInstanceOf(PlaceShortUrl); - }); - - test('should expose id', () => { - expect(shortUrl.id).toBe('short-123'); - }); - - test('should expose name', () => { - expect(shortUrl.name).toBe('Test Short URL'); - }); - - test('should expose uri', () => { - expect(shortUrl.uri).toBe('https://example.com/long-url-path'); - }); - - test('should expose description', () => { - expect(shortUrl.description).toBe('A test short URL'); - }); - - test('should expose user_id', () => { - expect(shortUrl.user_id).toBe('user-456'); - }); - - test('should expose user_email', () => { - expect(shortUrl.user_email).toBe('user@example.com'); - }); - - test('should expose user_name', () => { - expect(shortUrl.user_name).toBe('Test User'); - }); - - test('should expose redirect_count', () => { - expect(shortUrl.redirect_count).toBe(42); - }); - - test('should expose enabled', () => { - expect(shortUrl.enabled).toBe(true); - }); - - test('should expose valid_from', () => { - expect(shortUrl.valid_from).toBe('2024-01-01T00:00:00Z'); - }); - - test('should expose valid_until', () => { - expect(shortUrl.valid_until).toBe('2024-12-31T23:59:59Z'); - }); - - test('should expose authority_id', () => { - expect(shortUrl.authority_id).toBe('auth-789'); - }); - - test('should expose created_at', () => { - expect(shortUrl.created_at).toBe(1704067200); - }); - - test('should expose updated_at', () => { - expect(shortUrl.updated_at).toBe(1704153600); - }); - - test('should use default values for missing properties', () => { - const emptyShortUrl = new PlaceShortUrl({}); - expect(emptyShortUrl.id).toBe(''); - expect(emptyShortUrl.name).toBe(''); - expect(emptyShortUrl.uri).toBe(''); - expect(emptyShortUrl.description).toBe(''); - expect(emptyShortUrl.user_id).toBe(''); - expect(emptyShortUrl.user_email).toBe(''); - expect(emptyShortUrl.user_name).toBe(''); - expect(emptyShortUrl.redirect_count).toBe(0); - expect(emptyShortUrl.enabled).toBe(true); - expect(emptyShortUrl.valid_from).toBe(''); - expect(emptyShortUrl.valid_until).toBe(''); - expect(emptyShortUrl.authority_id).toBe(''); - expect(emptyShortUrl.created_at).toBe(0); - expect(emptyShortUrl.updated_at).toBe(0); - }); - - test('should handle enabled=false explicitly', () => { - const disabledShortUrl = new PlaceShortUrl({ enabled: false }); - expect(disabledShortUrl.enabled).toBe(false); - }); -}); diff --git a/test/signage/ai/functions.spec.ts b/test/signage/ai/functions.spec.ts deleted file mode 100644 index a515d965c..000000000 --- a/test/signage/ai/functions.spec.ts +++ /dev/null @@ -1,306 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../../src/auth'; -import * as Http from '../../../src/http/functions'; -import * as Resources from '../../../src/resources/functions'; -import * as SERVICE from '../../../src/signage/ai/functions'; - -describe('Signage AI API', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test('should allow listing AI capabilities', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve( - _.fn!({ - enabled: true, - providers: [], - aspect_ratios: ['16:9'], - qualities: ['standard'], - max_candidates: 4, - logo_layer: true, - quota: { - user_remaining_today: 12, - domain_remaining_month: 400, - }, - }) as any, - ), - ); - - const capabilities = await SERVICE.signageAICapabilities(); - - expect(capabilities.enabled).toBe(true); - expect(capabilities.quota.user_remaining_today).toBe(12); - expect(spy).toHaveBeenCalledWith({ - id: 'capabilities', - query_params: {}, - fn: expect.any(Function), - path: 'signage/ai', - }); - }); - - test('should allow generating an image', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'post'); - spy.mockResolvedValue({ id: 'job-123', state: 'queued' } as any); - - const request = { - prompt: 'A quiet foyer at dawn', - aspect_ratio: '16:9', - candidates: 2, - use_branding: false, - group_id: 'group-123', - idempotency_key: 'key-123', - }; - const job = await SERVICE.generateSignageImage(request); - - expect(job.id).toBe('job-123'); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/ai/generate', - request, - ); - }); - - test('should allow editing an image', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'post'); - spy.mockResolvedValue({ id: 'job-456', kind: 'edit' } as any); - - const request = { - prompt: 'Warmer light', - source_upload_id: 'upload-123', - source_item_id: 'item-123', - parent_job_id: 'job-123', - group_id: 'group-123', - }; - const job = await SERVICE.editSignageImage(request); - - expect(job.kind).toBe('edit'); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/ai/edit', - request, - ); - }); - - test('should long poll an AI job without the query cache', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!({ id: 'job-123', version: 4 }) as any), - ); - - const job = await SERVICE.showSignageAIJob( - 'job-123', - { wait: 25, since: 3 }, - { skip_auth_flow: true }, - ); - - expect(job.version).toBe(4); - expect(spy).toHaveBeenCalledWith({ - id: 'job-123', - query_params: { wait: 25, since: 3 }, - fn: expect.any(Function), - path: 'signage/ai/jobs', - options: { skip_auth_flow: true }, - }); - }); - - test('should allow listing recent AI jobs', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!([{ id: 'job-123' }]) as any), - ); - - const jobs = await SERVICE.querySignageAIJobs({ mine: true, limit: 5 }); - - expect(jobs.length).toBe(1); - expect(jobs[0].id).toBe('job-123'); - expect(spy).toHaveBeenCalledWith({ - id: 'jobs', - query_params: { mine: true, limit: 5 }, - fn: expect.any(Function), - path: 'signage/ai', - }); - }); - - test('should allow cancelling and claiming AI jobs', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_) => - Promise.resolve(_.callback!({ id: _.id }) as any), - ); - - const cancelled = await SERVICE.cancelSignageAIJob('job-123'); - const claimed = await SERVICE.claimSignageAIImage('job-123', { - upload_id: 'upload-123', - item_id: 'item-123', - }); - - expect(cancelled.id).toBe('job-123'); - expect(claimed.id).toBe('job-123'); - expect(spy).toHaveBeenNthCalledWith(1, { - id: 'job-123', - task_name: 'cancel', - method: 'post', - path: 'signage/ai/jobs', - callback: expect.any(Function), - }); - expect(spy).toHaveBeenNthCalledWith(2, { - id: 'job-123', - task_name: 'claim', - form_data: { upload_id: 'upload-123', item_id: 'item-123' }, - method: 'post', - path: 'signage/ai/jobs', - callback: expect.any(Function), - }); - }); - - test('should allow listing AI usage', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve( - _.fn!([ - { - provider: 'OPENAI', - model: 'gpt-image-1', - jobs: 3, - candidates: 6, - images_produced: 6, - cost_units: 0.42, - }, - ]) as any, - ), - ); - - const usage = await SERVICE.signageAIUsage({ from: 1, to: 2 }); - - expect(usage[0].cost_units).toBe(0.42); - expect(spy).toHaveBeenCalledWith({ - id: 'usage', - query_params: { from: 1, to: 2 }, - fn: expect.any(Function), - path: 'signage/ai', - }); - }); - - test('should allow querying AI providers', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ - total: 1, - next: () => null, - data: [_.fn!({ id: 'provider-123' })], - }), - ); - - const result = await SERVICE.querySignageAIProviders({ - include_shared: false, - q: 'OpenAI', - limit: 10, - }); - - expect(result.data[0].id).toBe('provider-123'); - expect(spy).toHaveBeenCalledWith({ - query_params: { - include_shared: false, - q: 'OpenAI', - limit: 10, - }, - fn: expect.any(Function), - path: 'signage/ai/providers', - }); - }); - - test('should allow showing an AI provider', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!({ id: 'provider-123' }) as any), - ); - - const provider = await SERVICE.showSignageAIProvider('provider-123'); - - expect(provider.id).toBe('provider-123'); - expect(spy).toHaveBeenCalledWith({ - id: 'provider-123', - query_params: {}, - fn: expect.any(Function), - path: 'signage/ai/providers', - }); - }); - - test('should allow adding an AI provider', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'post'); - spy.mockResolvedValue({ id: 'provider-123' } as any); - - const form_data = { - name: 'OpenAI', - provider: 'OPENAI' as const, - credentials: { api_key: 'secret' }, - }; - const provider = await SERVICE.addSignageAIProvider(form_data); - - expect(provider.id).toBe('provider-123'); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/ai/providers', - form_data, - ); - }); - - test('should update an AI provider without a version', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const patch_spy = vi.spyOn(Http, 'patch'); - patch_spy.mockResolvedValue({ id: 'provider-123' } as any); - const put_spy = vi.spyOn(Http, 'put'); - put_spy.mockResolvedValue({ id: 'provider-123' } as any); - - await SERVICE.updateSignageAIProvider('provider-123', { - enabled: false, - }); - await SERVICE.updateSignageAIProvider( - 'provider-123', - { enabled: true }, - 'put', - ); - - expect(patch_spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/ai/providers/provider-123', - { enabled: false }, - ); - expect(put_spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/ai/providers/provider-123', - { enabled: true }, - ); - }); - - test('should allow removing an AI provider', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockResolvedValue({}); - - await SERVICE.removeSignageAIProvider('provider-123'); - - expect(spy).toHaveBeenCalledWith({ - id: 'provider-123', - query_params: {}, - path: 'signage/ai/providers', - }); - }); - - test('should allow testing an AI provider', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_) => - Promise.resolve(_.callback!({ ok: true, latency_ms: 1200 }) as any), - ); - - const result = await SERVICE.testSignageAIProvider('provider-123'); - - expect(result.ok).toBe(true); - expect(result.latency_ms).toBe(1200); - expect(spy).toHaveBeenCalledWith({ - id: 'provider-123', - task_name: 'test', - method: 'post', - path: 'signage/ai/providers', - callback: expect.any(Function), - }); - }); -}); diff --git a/test/signage/functions.spec.ts b/test/signage/functions.spec.ts deleted file mode 100644 index 3d68e3eed..000000000 --- a/test/signage/functions.spec.ts +++ /dev/null @@ -1,389 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/signage/functions'; -import { - SignageTemplate, - SignageTemplateMapping, -} from '../../src/signage/template.class'; - -describe('Signage API', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test('should allow listing media tags', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!(['promo']) as any)); - - const tags = await SERVICE.listSignageMediaTags({ - group_id: 'group-123', - }); - - expect(tags).toEqual(['promo']); - expect(spy).toHaveBeenCalledWith({ - id: 'tags', - query_params: { group_id: 'group-123' }, - fn: expect.any(Function), - path: 'signage/media', - }); - }); - - test('should allow listing media tag counts', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!({ promo: 3 }) as any), - ); - - const counts = await SERVICE.listSignageMediaTagCounts({ - group_id: 'group-123', - }); - - expect(counts).toEqual({ promo: 3 }); - expect(spy).toHaveBeenCalledWith({ - id: 'tag_counts', - query_params: { group_id: 'group-123' }, - fn: expect.any(Function), - path: 'signage/media', - }); - }); - - test('should allow linking new media and playlists to a group', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockResolvedValue({} as any); - - await SERVICE.addSignageMedia( - { name: 'Welcome' }, - { group_id: 'group-123' }, - ); - await SERVICE.addSignagePlaylist( - { name: 'Lobby' }, - { group_id: 'group-123' }, - ); - - expect(spy).toHaveBeenNthCalledWith(1, { - form_data: { name: 'Welcome' }, - query_params: { group_id: 'group-123' }, - fn: expect.any(Function), - path: 'signage/media', - }); - expect(spy).toHaveBeenNthCalledWith(2, { - form_data: { name: 'Lobby' }, - query_params: { group_id: 'group-123' }, - fn: expect.any(Function), - path: 'signage/playlists', - }); - }); - - test('should allow renaming media tags', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'patch'); - spy.mockResolvedValue(); - - await SERVICE.renameSignageMediaTag({ - current_tag: 'old & tired', - new_tag: 'new/tag', - group_id: 'group-123', - }); - - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/media/tags?current_tag=old%20%26%20tired&new_tag=new%2Ftag&group_id=group-123', - {}, - { response_type: 'void' }, - ); - }); - - test('should allow removing media tags and tagged media', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'del'); - spy.mockResolvedValue(); - - await SERVICE.removeSignageMediaTag({ tag: 'promo' }); - await SERVICE.removeSignageMediaTag({ - tag: 'expired', - remove_media: true, - group_id: 'group-123', - }); - - expect(spy).toHaveBeenNthCalledWith( - 1, - '/api/engine/v2/signage/media/tags?tag=promo', - { response_type: 'void' }, - ); - expect(spy).toHaveBeenNthCalledWith( - 2, - '/api/engine/v2/signage/media/tags?tag=expired&remove_media=true&group_id=group-123', - { response_type: 'void' }, - ); - }); - - test('should allow unlinking media from a group', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockResolvedValue({}); - - await SERVICE.removeSignageMedia('media-123', { - group_id: 'group-123', - }); - - expect(spy).toHaveBeenCalledWith({ - id: 'media-123', - query_params: { group_id: 'group-123' }, - path: 'signage/media', - }); - }); - - test('should allow unlinking playlists from a group', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockResolvedValue({}); - - await SERVICE.removeSignagePlaylist('playlist-123', { - group_id: 'group-123', - }); - - expect(spy).toHaveBeenCalledWith({ - id: 'playlist-123', - query_params: { group_id: 'group-123' }, - path: 'signage/playlists', - }); - }); - - test('should allow unlinking templates from a group', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockResolvedValue({}); - - await SERVICE.removeSignageTemplate('template-123', { - group_id: 'group-123', - }); - - expect(spy).toHaveBeenCalledWith({ - id: 'template-123', - query_params: { group_id: 'group-123' }, - path: 'signage/templates', - }); - }); - - test('should allow posting player metrics', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockResolvedValue({} as any); - - const metrics = { - play_through_counts: { 'playlist-123': 2 }, - playlist_counts: { 'playlist-123': 5 }, - media_counts: { 'media-123': 7 }, - }; - await SERVICE.updateSignageMetrics('sys-123', metrics); - - expect(spy).toHaveBeenCalledWith({ - id: 'sys-123', - task_name: 'metrics', - form_data: metrics, - method: 'post', - path: 'signage', - }); - }); - - test('should allow scheduling playlist media', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_) => Promise.resolve(_.callback!({}) as any)); - - await SERVICE.scheduleSignagePlaylistMedia('playlist-123', { - item_id: 'media-123', - schedules: [ - { - play_cron: '* * * * *', - play_period: 30, - play_takeover: false, - }, - ], - }); - - expect(spy).toHaveBeenCalledWith({ - id: 'playlist-123', - task_name: 'media/schedule', - form_data: { - item_id: 'media-123', - schedules: [ - { - play_cron: '* * * * *', - play_period: 30, - play_takeover: false, - }, - ], - }, - method: 'post', - path: 'signage/playlists', - callback: expect.any(Function), - }); - }); - - test('should allow updating playlist media schedules', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'patch'); - spy.mockImplementation((_) => - Promise.resolve({ - id: 'schedule-123', - playlist_id: 'playlist-123', - item_id: 'media-123', - } as any), - ); - - const schedule = await SERVICE.updateSignagePlaylistMediaSchedule( - 'playlist-123', - 'media-123', - { - schedules: [ - { - play_cron: '* * * * *', - play_period: 30, - play_takeover: true, - }, - ], - }, - ); - - expect(schedule.item_id).toBe('media-123'); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/playlists/playlist-123/media/schedule/media-123', - { - schedules: [ - { - play_cron: '* * * * *', - play_period: 30, - play_takeover: true, - }, - ], - }, - ); - }); - - test('should allow querying signage templates', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ - total: 1, - next: () => null, - data: [_.fn!({ id: 'template-123' })], - }), - ); - - const result = await SERVICE.querySignageTemplates({ - group_id: 'group-123', - approved: true, - }); - - expect(result.data[0]).toBeInstanceOf(SignageTemplate); - expect(result.data[0].merge).toBe(false); - expect(spy).toHaveBeenCalledWith({ - query_params: { group_id: 'group-123', approved: true }, - fn: expect.any(Function), - path: 'signage/templates', - }); - }); - - test.each([false, true])( - 'should allow creating signage templates in a group with merge=%s', - async (merge) => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!({ id: 'template-123', ..._.form_data })), - ); - - const template = await SERVICE.addSignageTemplate( - { name: 'Welcome', merge }, - { group_id: 'group-123' }, - ); - - expect(template).toBeInstanceOf(SignageTemplate); - expect(template.merge).toBe(merge); - expect(spy).toHaveBeenCalledWith({ - form_data: { name: 'Welcome', merge }, - query_params: { group_id: 'group-123' }, - fn: expect.any(Function), - path: 'signage/templates', - }); - }, - ); - - test('should allow managing signage template approval', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_) => - Promise.resolve(_.callback ? _.callback({ id: _.id }) : {}), - ); - - const approved = await SERVICE.approveSignageTemplate('template-123'); - await SERVICE.requestApprovalSignageTemplate( - 'template-123', - 'group-123', - 'Please review', - 'user-123', - ); - await SERVICE.removeSignageTemplateDraft('template-123'); - - expect(approved).toBeInstanceOf(SignageTemplate); - expect(spy).toHaveBeenNthCalledWith(1, { - id: 'template-123', - task_name: 'approve', - method: 'post', - path: 'signage/templates', - callback: expect.any(Function), - }); - expect(spy).toHaveBeenNthCalledWith(2, { - id: 'template-123', - task_name: - 'request_approval?group_id=group-123&approver_id=user-123', - method: 'post', - path: 'signage/templates', - form_data: { message: 'Please review' }, - }); - expect(spy).toHaveBeenNthCalledWith(3, { - id: 'template-123', - task_name: 'draft', - method: 'del', - path: 'signage/templates', - }); - }); - - test('should allow sharing signage templates', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const spy = vi.spyOn(Http, 'post'); - spy.mockResolvedValue({ - linked: ['template-123'], - already_present: [], - }); - - const result = await SERVICE.shareSignageTemplates({ - items: ['template-123', 'template-456'], - to: 'group-123', - }); - - expect(result.linked).toEqual(['template-123']); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/signage/templates/share?items=template-123%2Ctemplate-456&to=group-123', - {}, - ); - }); - - test('should allow updating signage template mappings', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => - Promise.resolve(_.fn!({ id: _.id, ..._.form_data })), - ); - - const mapping = await SERVICE.updateSignageTemplateMapping( - 'mapping-123', - { schedule: null }, - ); - - expect(mapping).toBeInstanceOf(SignageTemplateMapping); - expect(mapping.schedule).toBeNull(); - expect(spy).toHaveBeenCalledWith({ - id: 'mapping-123', - form_data: { schedule: null }, - query_params: {}, - method: 'patch', - fn: expect.any(Function), - path: 'signage/template_mappings', - }); - }); -}); diff --git a/test/staff/answers/functions.spec.ts b/test/staff/answers/functions.spec.ts deleted file mode 100644 index 00b5bc831..000000000 --- a/test/staff/answers/functions.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import * as API from '../../../src/api'; -import * as Http from '../../../src/http/functions'; -import * as ANSWERS from '../../../src/staff/answers/functions'; -import { SurveyAnswer } from '../../../src/staff/answers/model'; - -vi.mock('../../../src/http/functions'); -vi.mock('../../../src/api'); - -describe('Staff Survey Answers API', () => { - beforeEach(() => vi.useFakeTimers()); - - afterEach(() => { - vi.useRealTimers(); - const methods: any[] = ['get', 'post', 'patch', 'put', 'del']; - for (const method of methods) { - ((Http as any)[method] as vi.Mock).mockReset(); - ((Http as any)[method] as vi.Mock).mockRestore(); - } - }); - - test('should allow querying answers', async () => { - (API.get as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve([{}])); - let list = await ANSWERS.queryAnswers(); - expect(list).toBeTruthy(); - expect(list.length).toBe(1); - expect(list[0]).toBeInstanceOf(SurveyAnswer); - }); - - test('should allow adding new answers', async () => { - (API.post as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve([{}])); - let item = await ANSWERS.addAnswer([{}]); - expect(item.length).toBe(1); - expect(item[0]).toBeInstanceOf(SurveyAnswer); - }); -}); diff --git a/test/staff/questions/functions.spec.ts b/test/staff/questions/functions.spec.ts deleted file mode 100644 index f1e0b644d..000000000 --- a/test/staff/questions/functions.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; - -import * as API from '../../../src/api'; -import * as QUESTIONS from '../../../src/staff/questions/functions'; -import { SurveyQuestion } from '../../../src/staff/questions/model'; - -vi.mock('../../../src/http/functions'); -vi.mock('../../../src/api'); - -describe('Staff Survey Questions API', () => { - test('should allow querying questions', async () => { - (API.get as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve([{}])); - let list = await QUESTIONS.queryQuestions(); - expect(list).toBeTruthy(); - expect(list.length).toBe(1); - expect(list[0]).toBeInstanceOf(SurveyQuestion); - }); - - test('should allow showing question', async () => { - (API.get as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ id: '1' })); - let list = await QUESTIONS.showQuestion('1'); - expect(list).toBeTruthy(); - expect(list).toBeInstanceOf(SurveyQuestion); - expect(list?.id).toBe('1'); - }); - - test('should allow adding question', async () => { - (API.post as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ id: '1' })); - let item = await QUESTIONS.addQuestion({}); - expect(item).toBeTruthy(); - expect(item).toBeInstanceOf(SurveyQuestion); - expect(item?.id).toBe('1'); - }); - - test('should allow updating question', async () => { - (API.put as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ id: '1' })); - (API.patch as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ id: '1' })); - let item = await QUESTIONS.updateQuestion('1', {}); - expect(item).toBeTruthy(); - expect(item).toBeInstanceOf(SurveyQuestion); - expect(item?.id).toBe('1'); - }); - - test('should allow removing question', async () => { - (API.del as any) = vi.fn().mockImplementation((_) => Promise.resolve()); - let item = await QUESTIONS.removeQuestion('1'); - expect(item).toBeFalsy(); - }); -}); diff --git a/test/storages/functions.spec.ts b/test/storages/functions.spec.ts deleted file mode 100644 index 153c59425..000000000 --- a/test/storages/functions.spec.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/storages/functions'; -import { PlaceStorage } from '../../src/storages/storage.class'; - -describe('Storages API', () => { - test('should allow querying storages', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryStorages(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceStorage); - list = await SERVICE.queryStorages({}); - }); - - test('should allow querying storages with auth_id', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.queryStorages({ - auth_id: 'auth-123', - }); - expect(list).toBeTruthy(); - expect(spy).toHaveBeenCalledWith( - expect.objectContaining({ - query_params: { auth_id: 'auth-123' }, - }), - ); - }); - - test('should allow showing storage details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showStorage('1'); - expect(item).toBeInstanceOf(PlaceStorage); - item = await SERVICE.showStorage('1', {}); - }); - - test('should allow creating new storages', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addStorage({}); - expect(item).toBeInstanceOf(PlaceStorage); - }); - - test('should allow updating storage details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateStorage('1', {}); - expect(item).toBeInstanceOf(PlaceStorage); - item = await SERVICE.updateStorage('1', {}, 'patch'); - item = await SERVICE.updateStorage('1', {}, 'put'); - }); - - test('should allow removing storages', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeStorage('1', {}); - expect(item).toBeFalsy(); - item = await SERVICE.removeStorage('1'); - }); -}); diff --git a/test/storages/storage.class.spec.ts b/test/storages/storage.class.spec.ts deleted file mode 100644 index 9e9727831..000000000 --- a/test/storages/storage.class.spec.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceStorage } from '../../src/storages/storage.class'; - -describe('PlaceStorage', () => { - let storage: PlaceStorage; - - beforeEach(() => { - storage = new PlaceStorage({ - id: 'storage-123', - storage_type: 's3', - bucket_name: 'my-bucket', - region: 'us-east-1', - access_key: 'AKIAIOSFODNN7EXAMPLE', - access_secret: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', - authority_id: 'auth-456', - endpoint: 'https://s3.us-east-1.amazonaws.com', - is_default: true, - ext_filter: ['.jpg', '.png', '.pdf'], - mime_filter: ['image/jpeg', 'image/png', 'application/pdf'], - created_at: 1704067200, - updated_at: 1704153600, - }); - }); - - test('should create instance', () => { - expect(storage).toBeTruthy(); - expect(storage).toBeInstanceOf(PlaceStorage); - }); - - test('should expose id', () => { - expect(storage.id).toBe('storage-123'); - }); - - test('should expose storage_type', () => { - expect(storage.storage_type).toBe('s3'); - }); - - test('should expose bucket_name', () => { - expect(storage.bucket_name).toBe('my-bucket'); - }); - - test('should expose region', () => { - expect(storage.region).toBe('us-east-1'); - }); - - test('should expose access_key', () => { - expect(storage.access_key).toBe('AKIAIOSFODNN7EXAMPLE'); - }); - - test('should expose access_secret', () => { - expect(storage.access_secret).toBe('wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'); - }); - - test('should expose authority_id', () => { - expect(storage.authority_id).toBe('auth-456'); - }); - - test('should expose endpoint', () => { - expect(storage.endpoint).toBe('https://s3.us-east-1.amazonaws.com'); - }); - - test('should expose is_default', () => { - expect(storage.is_default).toBe(true); - }); - - test('should expose ext_filter', () => { - expect(storage.ext_filter).toEqual(['.jpg', '.png', '.pdf']); - }); - - test('should expose mime_filter', () => { - expect(storage.mime_filter).toEqual(['image/jpeg', 'image/png', 'application/pdf']); - }); - - test('should expose created_at', () => { - expect(storage.created_at).toBe(1704067200); - }); - - test('should expose updated_at', () => { - expect(storage.updated_at).toBe(1704153600); - }); - - test('should use default values for missing properties', () => { - const emptyStorage = new PlaceStorage({}); - expect(emptyStorage.id).toBe(''); - expect(emptyStorage.storage_type).toBe(null); - expect(emptyStorage.bucket_name).toBe(''); - expect(emptyStorage.region).toBe(''); - expect(emptyStorage.access_key).toBe(''); - expect(emptyStorage.access_secret).toBe(''); - expect(emptyStorage.authority_id).toBe(''); - expect(emptyStorage.endpoint).toBe(''); - expect(emptyStorage.is_default).toBe(false); - expect(emptyStorage.ext_filter).toEqual([]); - expect(emptyStorage.mime_filter).toEqual([]); - expect(emptyStorage.created_at).toBe(0); - expect(emptyStorage.updated_at).toBe(0); - }); - - test('should handle is_default=false explicitly', () => { - const nonDefaultStorage = new PlaceStorage({ is_default: false }); - expect(nonDefaultStorage.is_default).toBe(false); - }); - - test('should support azure storage type', () => { - const azureStorage = new PlaceStorage({ storage_type: 'azure' }); - expect(azureStorage.storage_type).toBe('azure'); - }); - - test('should support google storage type', () => { - const googleStorage = new PlaceStorage({ storage_type: 'google' }); - expect(googleStorage.storage_type).toBe('google'); - }); -}); diff --git a/v2/test/style.test.ts b/test/style.test.ts similarity index 95% rename from v2/test/style.test.ts rename to test/style.test.ts index ab40d81ea..21acd55f7 100644 --- a/v2/test/style.test.ts +++ b/test/style.test.ts @@ -9,7 +9,7 @@ import { join } from 'node:path'; const SOURCE_DIR = join(import.meta.dir, '..', 'src'); const ALLOWED_CASTS = ['parsed as O', 'checked as I', 'result as CallResult']; -/** The v1 mock types of the compat module keep `any`, so that the mocks of an app still compile. */ +/** The 6.x mock types of the compat module keep `any`, so that the mocks of an app still compile. */ const ALLOWED_ANY = [ 'compat/http-mock.ts: readonly metadata: any;', 'compat/http-mock.ts: readonly body: any;', diff --git a/test/systems/functions.spec.ts b/test/systems/functions.spec.ts deleted file mode 100644 index fa3f70387..000000000 --- a/test/systems/functions.spec.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Resources from '../../src/resources/functions'; -import { PlaceSettings } from '../../src/settings/settings'; -import * as SERVICE from '../../src/systems/functions'; -import { PlaceSystem } from '../../src/systems/system'; -import { PlaceTrigger } from '../../src/triggers/trigger'; -import { PlaceZone } from '../../src/zones/zone'; - -vi.mock('../../src/resources/functions'); - -describe('Systems API', () => { - test('should allow querying systems', async () => { - (Resources.query as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve({ data: [_.fn({})] })); - let list = await SERVICE.querySystems(); - expect(list).toBeTruthy(); - expect(list?.data.length).toBe(1); - expect(list?.data[0]).toBeInstanceOf(PlaceSystem); - list = await SERVICE.querySystems({}); - }); - - test('should allow showing system details', async () => { - (Resources.show as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.fn({}))); - let item = await SERVICE.showSystem('1'); - expect(item).toBeInstanceOf(PlaceSystem); - item = await SERVICE.showSystem('1', {}); - }); - - test('should allow creating new systems', async () => { - (Resources.create as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.fn({}) as any)); - let item = await SERVICE.addSystem({}); - expect(item).toBeInstanceOf(PlaceSystem); - item = await SERVICE.addSystem({}); - }); - - test('should allow updating system details', async () => { - (Resources.update as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.fn({}))); - let item = await SERVICE.updateSystem('1', {}); - expect(item).toBeInstanceOf(PlaceSystem); - item = await SERVICE.updateSystem('1', {}, 'patch'); - }); - - test('should allow removing systems', async () => { - (Resources.remove as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeSystem('1'); - expect(item).toBeFalsy(); - }); - - test('should allow adding a module to a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - let item = await SERVICE.addSystemModule('1', 'mod-1'); - expect(item).toBeFalsy(); - item = await SERVICE.addSystemModule('1', 'mod-1', {}); - }); - - test('should allow removing a module from a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeSystemModule('1', 'mod-1'); - expect(item).toBeFalsy(); - }); - - test('should allow starting a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - const item = await SERVICE.startSystem('1'); - expect(item).toBeFalsy(); - }); - - test('should allow stopping a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - const item = await SERVICE.stopSystem('1'); - expect(item).toBeFalsy(); - }); - - test('should allow excuting a method on a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - let item = await SERVICE.executeOnSystem('1', 'test', 'mod'); - expect(item).toEqual({}); - item = await SERVICE.executeOnSystem('1', 'test', 'mod', 2, ['Yeah']); - }); - - test('should allow gettings state of a system module', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - let item = await SERVICE.systemModuleState('1', 'mod'); - expect(item).toEqual({}); - item = await SERVICE.systemModuleState('1', 'mod', 2); - }); - - test('should allow lookup state of a system module', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - let item = await SERVICE.lookupSystemModuleState( - '1', - 'mod', - 1, - 'connected', - ); - expect(item).toEqual({}); - item = await SERVICE.lookupSystemModuleState( - '1', - 'mod', - undefined, - 'connected', - ); - }); - - test('should allow listing methods for system module', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - let item = await SERVICE.functionList('1', 'mod'); - expect(item).toEqual({}); - item = await SERVICE.functionList('1', 'mod', 3); - }); - - test('should allow getting module count', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.moduleCount('1', 'mod'); - expect(item).toEqual({}); - }); - - test('should allow getting types of modules in a syste', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({})); - const item = await SERVICE.moduleTypes('1'); - expect(item).toEqual({}); - }); - - test("should allow listing system's zones", async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback([{}]))); - const item = await SERVICE.listSystemZones('1'); - expect(item).toBeTruthy(); - expect(item?.data[0]).toBeInstanceOf(PlaceZone); - }); - - test("should allow listing system's triggers", async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback([{}]))); - const item = await SERVICE.listSystemTriggers('1'); - expect(item).toBeTruthy(); - expect(item?.data[0]).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow adding a trigger to a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback({}))); - const item = await SERVICE.addSystemTrigger('1', {}); - expect(item).toBeTruthy(); - expect(item).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow removing a trigger from a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeSystemTrigger('1', 'trig-1'); - expect(item).toBeFalsy(); - }); - - test('should allow listing settings for a system', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback([{}]))); - const item = await SERVICE.systemSettings('1'); - expect(item).toBeTruthy(); - expect(item?.[0]).toBeInstanceOf(PlaceSettings); - }); - - test('should generate correct system control websocket URL for HTTPS', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('https://example.com/api/engine/v2/'); - - const url = SERVICE.systemControlUrl(); - expect(url).toBe('wss://example.com/api/engine/v2/systems/control'); - }); - - test('should generate correct system control websocket URL for HTTP', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('http://example.com/api/engine/v2/'); - - const url = SERVICE.systemControlUrl(); - expect(url).toBe('ws://example.com/api/engine/v2/systems/control'); - }); - - test('should include fixed_device in system control URL', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('https://example.com/api/engine/v2/'); - - const url = SERVICE.systemControlUrl({ fixed_device: true }); - expect(url).toBe( - 'wss://example.com/api/engine/v2/systems/control?fixed_device=true', - ); - }); - - test('should allow getting system metadata', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({ key: 'value' })); - let item = await SERVICE.systemMetadata('1'); - expect(item).toEqual({ key: 'value' }); - item = await SERVICE.systemMetadata('1', { name: 'test' }); - }); - - test('should allow showing a system trigger', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback({}))); - let item = await SERVICE.showSystemTrigger('sys-1', 'trig-1'); - expect(item).toBeTruthy(); - expect(item).toBeInstanceOf(PlaceTrigger); - item = await SERVICE.showSystemTrigger('sys-1', 'trig-1', { - complete: true, - }); - }); - - test('should allow updating a system trigger', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback({}))); - let item = await SERVICE.updateSystemTrigger('sys-1', 'trig-1', {}); - expect(item).toBeTruthy(); - expect(item).toBeInstanceOf(PlaceTrigger); - item = await SERVICE.updateSystemTrigger('sys-1', 'trig-1', {}, 'put'); - }); -}); diff --git a/test/systems/system.spec.ts b/test/systems/system.spec.ts deleted file mode 100644 index e1b29374e..000000000 --- a/test/systems/system.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceSystem } from '../../src/systems/system'; - -describe('PlaceSystem', () => { - let system: PlaceSystem; - const features: string[] = ['test', 'device', 'here']; - const modules: string[] = ['test', 'device', 'here']; - const zones: string[] = ['test', 'device', 'here']; - - beforeEach(() => { - system = new PlaceSystem({ - id: 'sys-test', - description: 'A description', - email: 'system@placeos.com', - capacity: 10, - features, - bookable: true, - installed_ui_devices: 4, - support_url: '/support/test', - modules, - zones, - module_data: [{ id: 'mod-001', name: 'A Module' } as any], - settings: { settings_string: '{ test: 1 }' } as any, - }); - }); - - test('should have module data', () => - new Promise((resolve) => { - setTimeout(() => { - expect(system.module_list).toBeTruthy(); - expect(system.module_list.length).toBe(1); - resolve(); - }, 1); - })); - - test('should create instance', () => { - expect(system).toBeTruthy(); - expect(system).toBeInstanceOf(PlaceSystem); - }); - - test('should expose description', () => { - expect(system.description).toBe('A description'); - }); - - test('should expose email', () => { - expect(system.email).toBe('system@placeos.com'); - }); - - test('should expose capacity', () => { - expect(system.capacity).toBe(10); - }); - - test('should expose features', () => { - expect(system.features).toBe(features); - }); - - test('should expose bookable', () => { - expect(system.bookable).toBe(true); - }); - - test('should expose installed_ui_devices', () => { - expect(system.installed_ui_devices).toBe(4); - }); - - test('should expose support_url', () => { - expect(system.support_url).toBe('/support/test'); - }); - - test('should expose module list', () => { - expect(system.modules).toEqual(modules); - }); - - test('should expose zone list', () => { - expect(system.zones).toEqual(zones); - }); - - test('should expose settings', () => { - expect(system.settings).toBeInstanceOf(Object); - }); -}); diff --git a/test/systems/utilities.spec.ts b/test/systems/utilities.spec.ts deleted file mode 100644 index d8710e5c1..000000000 --- a/test/systems/utilities.spec.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { generateMockSystem } from '../../src/systems/utilities'; - -describe('System Utilities', () => { - describe('generateMockSystem', () => { - test('should create a randomly generated mock system', () => { - let system = generateMockSystem(); - expect(system).toBeInstanceOf(Object); - system = generateMockSystem('test'); - expect(system).toBeInstanceOf(Object); - }); - test('should allow for overriding fields', () => { - const system = generateMockSystem({ id: 'test' }); - expect(system).toBeInstanceOf(Object); - expect(system.id).toBe('test'); - }); - }); -}); diff --git a/test/triggers/functions.spec.ts b/test/triggers/functions.spec.ts deleted file mode 100644 index 41f671af9..000000000 --- a/test/triggers/functions.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; - -import { PlaceTrigger } from '../../src/triggers/trigger'; - -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/triggers/functions'; - -describe('Triggers API', () => { - test('should allow querying triggers', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - const list = await SERVICE.queryTriggers(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow showing trigger details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.showTrigger('1'); - expect(item).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow creating new triggers', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.addTrigger({}); - expect(item).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow updating trigger details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - const item = await SERVICE.updateTrigger('1', {}); - expect(item).toBeInstanceOf(PlaceTrigger); - }); - - test('should allow removing triggers', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeTrigger('1'); - expect(item).toBeFalsy(); - }); - - test("should allow listing trigger's instances", async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_: any) => - Promise.resolve(_.callback([{}]) as any), - ); - const item = await SERVICE.listTriggerInstances('1'); - expect(item[0]).toBeInstanceOf(PlaceTrigger); - }); -}); diff --git a/test/triggers/trigger.spec.ts b/test/triggers/trigger.spec.ts deleted file mode 100644 index eff7c39bd..000000000 --- a/test/triggers/trigger.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { - TriggerActions, - TriggerConditionOperator, - TriggerConditions, - TriggerTimeConditionType, -} from '../../src/triggers/interfaces'; -import { PlaceTrigger } from '../../src/triggers/trigger'; - -describe('PlaceTrigger', () => { - let trigger: PlaceTrigger; - const actions: TriggerActions = { - functions: [ - { mod: 'mod-42', method: 'meaning', args: { purpose: 'what' } }, - ], - mailers: [ - { - emails: ['support@placeos.net'], - content: 'Here be some contents', - }, - ], - }; - const conditions: TriggerConditions = { - comparisons: [ - { left: '', operator: TriggerConditionOperator.EQ, right: '2' }, - { - left: { mod: '1', status: 'he', keys: [] }, - operator: TriggerConditionOperator.EQ, - right: { mod: '2', status: 'con', keys: [] }, - }, - ], - time_dependents: [{ type: TriggerTimeConditionType.AT, time: 0 }], - }; - - beforeEach(() => { - trigger = new PlaceTrigger({ - id: 'tri-test', - control_system_id: 'sys-42', - description: 'In a galaxy far far away...', - debounce_period: 1000, - important: true, - enabled: true, - activated_count: 22, - control_system: { name: 'John' } as any, - created_at: 999, - actions, - conditions, - }); - }); - - test('should create instance', () => { - expect(trigger).toBeTruthy(); - expect(trigger).toBeInstanceOf(PlaceTrigger); - expect(new PlaceTrigger()).toBeInstanceOf(PlaceTrigger); - }); - - test('should expose properties', () => { - expect(trigger.system_id).toBe('sys-42'); - expect(trigger.description).toBe('In a galaxy far far away...'); - expect(trigger.debounce_period).toBe(1000); - expect(trigger.important).toBe(true); - expect(trigger.enabled).toBe(true); - expect(trigger.system_name).toBe('John'); - expect(trigger.activated_count).toBe(22); - expect(trigger.actions).toEqual(actions); - expect(trigger.conditions).toEqual(conditions); - }); - - test('should have default values', () => { - trigger = new PlaceTrigger({}); - expect(trigger.actions).toBeInstanceOf(Object); - expect(trigger.conditions).toBeInstanceOf(Object); - trigger = new PlaceTrigger({ actions: {}, conditions: {} } as any); - expect(trigger.actions).toBeInstanceOf(Object); - expect(trigger.conditions).toBeInstanceOf(Object); - }); -}); diff --git a/test/url-proxy/functions.spec.ts b/test/url-proxy/functions.spec.ts deleted file mode 100644 index 4343a3163..000000000 --- a/test/url-proxy/functions.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import { proxyUrl } from '../../src/url-proxy/functions'; - -describe('URL proxy API', () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - test('should proxy binary content without leaking PlaceOS auth', async () => { - vi.spyOn(Auth, 'apiEndpoint').mockReturnValue('/api/engine/v2'); - const blob = new Blob(['image-data'], { type: 'image/png' }); - const spy = vi.spyOn(Http, 'get'); - spy.mockResolvedValue(blob); - - const result = await proxyUrl( - 'https://example.com/image.png?size=large', - { headers: { Accept: 'image/png' } }, - ); - - expect(result).toBe(blob); - expect(spy).toHaveBeenCalledWith( - '/api/engine/v2/proxy?url=https%3A%2F%2Fexample.com%2Fimage.png%3Fsize%3Dlarge', - { - headers: { Accept: 'image/png' }, - response_type: 'blob', - skip_auth: true, - }, - ); - }); -}); diff --git a/test/users/functions.spec.ts b/test/users/functions.spec.ts deleted file mode 100644 index 713e0a32a..000000000 --- a/test/users/functions.spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import * as Resources from '../../src/resources/functions'; -import * as SERVICE from '../../src/users/functions'; -import { PlaceUser } from '../../src/users/user'; - -describe('Users API', () => { - test('should allow querying users', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryUsers(); - expect(list).toBeTruthy(); - expect(list.data.length).toBe(1); - expect(list.data[0]).toBeInstanceOf(PlaceUser); - list = await SERVICE.queryUsers({}); - }); - - test('should allow showing user details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showUser('1'); - expect(item).toBeInstanceOf(PlaceUser); - item = await SERVICE.showUser('1', {}); - }); - - test('should allow showing current user details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.currentUser(); - expect(item).toBeInstanceOf(PlaceUser); - item = await SERVICE.currentUser({}); - }); - - test('should allow creating new users', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addUser({}); - expect(item).toBeInstanceOf(PlaceUser); - item = await SERVICE.addUser({}); - }); - - test('should allow updating user details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateUser('1', {}); - expect(item).toBeInstanceOf(PlaceUser); - item = await SERVICE.updateUser('1', {}, 'patch'); - }); - - test('should allow removing users', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - let item = await SERVICE.removeUser('1'); - expect(item).toBeFalsy(); - item = await SERVICE.removeUser('1', { - force_removal: true, - }); - }); - - test('should allow querying user groups', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => - Promise.resolve([ - { id: 'user-1', email: 'user@example.com', groups: ['group1', 'group2'] }, - ]) as any, - ); - - const result = await SERVICE.queryUserGroups({ - emails: 'user@example.com', - }); - expect(result).toBeTruthy(); - expect(result).toEqual([ - { id: 'user-1', email: 'user@example.com', groups: ['group1', 'group2'] }, - ]); - expect(httpSpy).toHaveBeenCalledWith( - expect.stringContaining('emails=user%40example.com'), - ); - }); - - test('should allow searching user metadata', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => Promise.resolve([{ id: 'user-1', metadata: {} }]) as any, - ); - - const result = await SERVICE.searchUserMetadata({ - filter: '$.department == "engineering"', - }); - expect(result).toBeTruthy(); - expect(result!.length).toBe(1); - expect(httpSpy).toHaveBeenCalledWith( - expect.stringContaining('metadata/search'), - ); - }); - - test('should allow getting current user resource token', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation( - () => Promise.resolve({ token: 'abc123' }) as any, - ); - - const result = await SERVICE.currentUserResourceToken(); - expect(result).toBeTruthy(); - expect(result!.token).toBe('abc123'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/users/resource_token', - {}, - ); - }); - - test('should allow getting user metadata', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation(() => Promise.resolve({ key: 'value' })); - let item = await SERVICE.userMetadata('1'); - expect(item).toEqual({ key: 'value' }); - item = await SERVICE.userMetadata('1', { name: 'test' }); - }); - - test('should allow removing user resource token', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'del'); - httpSpy.mockImplementation(() => Promise.resolve(undefined) as any); - - await SERVICE.removeUserResourceToken('user-1'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/users/user-1/resource_token', - { response_type: 'void' }, - ); - }); - - test('should allow getting user resource token', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation( - () => Promise.resolve({ token: 'xyz789' }) as any, - ); - - const result = await SERVICE.userResourceToken('user-1'); - expect(result).toBeTruthy(); - expect(result!.token).toBe('xyz789'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/users/user-1/resource_token', - {}, - ); - }); - - test('should allow reviving a user', async () => { - const spy = vi.spyOn(Resources, 'task'); - spy.mockImplementation((_: any) => - Promise.resolve(_.callback({}) as any), - ); - const item = await SERVICE.reviveUser('user-1'); - expect(item).toBeInstanceOf(PlaceUser); - }); -}); diff --git a/test/users/user.spec.ts b/test/users/user.spec.ts deleted file mode 100644 index f81dc66d1..000000000 --- a/test/users/user.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceUser } from '../../src/users/user'; - -describe('PlaceUser', () => { - let user: PlaceUser; - - beforeEach(() => { - user = new PlaceUser({ - id: 'dep-test', - authority_id: "On who's authority", - email: 'jon@tron.game', - phone: '+612000000000', - country: 'Australia', - image: '', - metadata: 'there be none', - login_name: 'elitedarklord', - staff_id: 'PERSON_12345', - first_name: 'Bob', - last_name: 'Marley', - created_at: 999, - }); - }); - - test('should create instance', () => { - expect(user).toBeTruthy(); - expect(user).toBeInstanceOf(PlaceUser); - }); - - test('should expose Authority ID', () => { - expect(user.authority_id).toBe("On who's authority"); - }); - - test('should expose Email', () => { - expect(user.email).toBe('jon@tron.game'); - }); - - test('should expose Phone', () => { - expect(user.phone).toBe('+612000000000'); - }); - - test('should expose Country', () => { - expect(user.country).toBe('Australia'); - }); - - test('should expose image', () => { - expect(user.image).toBe(''); - }); - - test('should expose metadata', () => { - expect(user.metadata).toBe('there be none'); - }); - - test('should expose login name', () => { - expect(user.login_name).toBe('elitedarklord'); - }); - - test('should expose staff ID', () => { - expect(user.staff_id).toBe('PERSON_12345'); - }); - - test('should expose first name', () => { - expect(user.first_name).toBe('Bob'); - }); - - test('should expose last name', () => { - expect(user.last_name).toBe('Marley'); - }); -}); diff --git a/test/utilities/api.spec.ts b/test/utilities/api.spec.ts deleted file mode 100644 index 99971e73d..000000000 --- a/test/utilities/api.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { toQueryString } from '../../src/utilities/api'; - -describe('API Utilities', () => { - describe('generattoQueryStringeNonce', () => { - test('converts object into URL query string', () => { - // Check method - expect(toQueryString({ test: 'value' })).toBe('test=value'); - // Multiple properties - expect(toQueryString({ test: 'new_value', other: 'person' })).toBe( - 'test=new_value&other=person', - ); - // Number properties - expect(toQueryString({ number: 9 })).toBe('number=9'); - // Boolean properties - expect(toQueryString({ bool: false })).toBe('bool=false'); - expect(toQueryString({ bool: true })).toBe('bool=true'); - }); - }); -}); diff --git a/test/utilities/general.spec.ts b/test/utilities/general.spec.ts deleted file mode 100644 index 3a3424247..000000000 --- a/test/utilities/general.spec.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { - convertPairStringToMap, - generateNonce, - getFragments, - humanReadableByteCount, - parseLinkHeader, -} from '../../src/utilities/general'; - -describe('General Utilities', () => { - beforeEach(() => { - window.history.pushState({}, 'Empty', ''); - }); - - describe('generateNonce', () => { - test('should generate nonce', () => { - let nonce = generateNonce(); - expect(typeof nonce).toBe('string'); - expect(nonce.length).toBe(40); - const old_nonce = nonce; - nonce = generateNonce(60); - expect(nonce.length).toBe(60); - expect(/[A-Za-z0-9]*/g.test(nonce)).toBeTruthy(); - nonce = generateNonce(); - expect(nonce).not.toBe(old_nonce); - }); - }); - - describe('convertPairStringToMap', () => { - test('should covert string pairs into a dictionary', () => { - expect(convertPairStringToMap('test=false')).toEqual({ - test: `false`, - }); - expect(convertPairStringToMap('test=false&other=value')).toEqual({ - test: `false`, - other: `value`, - }); - }); - }); - - describe('getFragments', () => { - test('should convert URL hash into into a dictionary', () => { - window.history.pushState({}, 'Test', `#test=false`); - expect(getFragments()).toEqual({ test: `false` }); - window.history.pushState({}, 'Test', `#test=false&other=value`); - expect(getFragments()).toEqual({ test: `false`, other: `value` }); - }); - - test('should convert URL hash containing a search string into into a dictionary', () => { - window.history.pushState({}, 'Test', `#test=false?not_test=true`); - expect(getFragments()).toEqual({ not_test: `true`, test: 'false' }); - window.history.pushState( - {}, - 'Test', - `#test=false?not_test=true&other=value`, - ); - expect(getFragments()).toEqual({ - not_test: `true`, - test: 'false', - other: `value`, - }); - }); - - test('should convert URL query into into a dictionary', () => { - window.history.pushState({}, 'Test', `?test=false`); - expect(getFragments()).toEqual({ test: `false` }); - window.history.pushState({}, 'Test', `?test=false&other=value`); - expect(getFragments()).toEqual({ test: `false`, other: `value` }); - }); - - test('should convert URL search containing a hash string into into a dictionary', () => { - window.history.pushState({}, 'Test', `?test=false#not_test=true`); - expect(getFragments()).toEqual({ not_test: `true`, test: 'false' }); - window.history.pushState( - {}, - 'Test', - `?test=false#not_test=true&other=value`, - ); - expect(getFragments()).toEqual({ - not_test: `true`, - test: 'false', - other: `value`, - }); - }); - }); - - describe('parseLinkHeaders', () => { - test('should get the URL', () => { - const header = '; rel="next"'; - const map = parseLinkHeader(header); - expect(map.next).toBe('http://google.com/'); - }); - }); - - describe('humanReadableByteCount', () => { - test('should generate display value correctly', () => { - expect(humanReadableByteCount(234)).toBe('234 B'); - expect(humanReadableByteCount(23456)).toBe('22.91 KB'); - expect(humanReadableByteCount(23456789)).toBe('22.37 MB'); - expect(humanReadableByteCount(23456789012)).toBe('21.85 GB'); - expect(humanReadableByteCount(23456789012345)).toBe('21.33 TB'); - }); - }); -}); diff --git a/test/webrtc/functions.spec.ts b/test/webrtc/functions.spec.ts deleted file mode 100644 index 3014ac3f3..000000000 --- a/test/webrtc/functions.spec.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Auth from '../../src/auth/functions'; -import * as Http from '../../src/http/functions'; -import * as SERVICE from '../../src/webrtc/functions'; - -describe('WebRTC Rooms API', () => { - test('should query public chat rooms', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => Promise.resolve([{ system: { name: 'Room 1' } }]) as any, - ); - - const result = await SERVICE.queryWebrtcRooms(); - expect(result).toBeTruthy(); - expect(result!.length).toBe(1); - expect(httpSpy).toHaveBeenCalledWith('/api/engine/v2/webrtc/rooms'); - }); - - test('should query public chat rooms with query params', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation(() => Promise.resolve([]) as any); - - await SERVICE.queryWebrtcRooms({ q: 'test', limit: 10 }); - expect(httpSpy).toHaveBeenCalledWith(expect.stringContaining('q=test')); - expect(httpSpy).toHaveBeenCalledWith( - expect.stringContaining('limit=10'), - ); - }); - - test('should show room details', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => Promise.resolve({ system: { name: 'Test Room' } }) as any, - ); - - const result = await SERVICE.showWebrtcRoom('sys-123'); - expect(result).toBeTruthy(); - expect(result?.system?.name).toBe('Test Room'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/room/sys-123', - ); - }); - - test('should encode special characters in system ID', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - await SERVICE.showWebrtcRoom('sys/123'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/room/sys%2F123', - ); - }); -}); - -describe('WebRTC Session Members', () => { - test('should get session members', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'get'); - httpSpy.mockImplementation( - () => - Promise.resolve([ - { user_id: 'user-1', name: 'John' }, - { user_id: 'user-2', name: 'Jane', is_guest: true }, - ]) as any, - ); - - const result = await SERVICE.webrtcSessionMembers('session-123'); - expect(result).toBeTruthy(); - expect(result!.length).toBe(2); - expect(result![0].user_id).toBe('user-1'); - expect(result![1].is_guest).toBe(true); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/members/session-123', - ); - }); -}); - -describe('WebRTC Guest Entry', () => { - test('should request guest entry', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - const participant = { - captcha: 'captcha-token', - name: 'Guest User', - user_id: 'guest-123', - session_id: 'session-456', - email: 'guest@example.com', - }; - - await SERVICE.webrtcGuestEntry('sys-123', participant); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/guest_entry/sys-123', - participant, - ); - }); - - test('should encode special characters in system ID for guest entry', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - const participant = { - captcha: 'token', - name: 'Guest', - user_id: 'guest-1', - session_id: 'session-1', - }; - - await SERVICE.webrtcGuestEntry('sys/123', participant); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/guest_entry/sys%2F123', - participant, - ); - }); -}); - -describe('WebRTC Guest Exit', () => { - test('should call guest exit', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - await SERVICE.webrtcGuestExit(); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/guest/exit', - {}, - ); - }); -}); - -describe('WebRTC Kick User', () => { - test('should kick a user from a session', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - const reason = { reason: 'User requested' }; - - await SERVICE.webrtcKickUser('user-123', 'session-456', reason); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/kick/user-123/session-456', - reason, - ); - }); - - test('should encode special characters in user ID and session ID', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - const reason = { reason: 'Test' }; - - await SERVICE.webrtcKickUser('user/123', 'session/456', reason); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/kick/user%2F123/session%2F456', - reason, - ); - }); -}); - -describe('WebRTC Transfer User', () => { - test('should transfer a user to another session', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - const connectionDetails = { target_session: 'session-789' }; - - await SERVICE.webrtcTransferUser( - 'user-123', - 'session-456', - connectionDetails, - ); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/transfer/user-123/session-456', - connectionDetails, - ); - }); - - test('should transfer a user without connection details', async () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('/api/engine/v2'); - const httpSpy = vi.spyOn(Http, 'post'); - httpSpy.mockImplementation(() => Promise.resolve({}) as any); - - await SERVICE.webrtcTransferUser('user-123', 'session-456'); - expect(httpSpy).toHaveBeenCalledWith( - '/api/engine/v2/webrtc/transfer/user-123/session-456', - {}, - ); - }); -}); - -describe('WebRTC Signaller URL', () => { - test('should generate correct signaller websocket URL for HTTPS', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('https://example.com/api/engine/v2/'); - - const url = SERVICE.webrtcSignallerUrl(); - expect(url).toBe('wss://example.com/api/engine/v2/webrtc/signaller'); - }); - - test('should generate correct signaller websocket URL for HTTP', () => { - const authSpy = vi.spyOn(Auth, 'apiEndpoint'); - authSpy.mockReturnValue('http://example.com/api/engine/v2/'); - - const url = SERVICE.webrtcSignallerUrl(); - expect(url).toBe('ws://example.com/api/engine/v2/webrtc/signaller'); - }); -}); diff --git a/test/zones/functions.spec.ts b/test/zones/functions.spec.ts deleted file mode 100644 index 47fcd57ff..000000000 --- a/test/zones/functions.spec.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, test, vi } from 'vitest'; -import * as Resources from '../../src/resources/functions'; -import { PlaceTrigger } from '../../src/triggers/trigger'; -import * as SERVICE from '../../src/zones/functions'; -import { PlaceZone } from '../../src/zones/zone'; - -vi.mock('../../src/resources/functions'); - -describe('Zones API', () => { - test('should allow querying zones', async () => { - const spy = vi.spyOn(Resources, 'query'); - spy.mockImplementation((_) => - Promise.resolve({ data: [_.fn!({})] } as any), - ); - let list = await SERVICE.queryZones(); - expect(list).toBeTruthy(); - expect(list?.data.length).toBe(1); - expect(list?.data[0]).toBeInstanceOf(PlaceZone); - list = await SERVICE.queryZones({}); - }); - - test('should allow showing zone details', async () => { - const spy = vi.spyOn(Resources, 'show'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.showZone('1'); - expect(item).toBeInstanceOf(PlaceZone); - item = await SERVICE.showZone('1', {}); - }); - - test('should allow creating new zones', async () => { - const spy = vi.spyOn(Resources, 'create'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.addZone({}); - expect(item).toBeInstanceOf(PlaceZone); - item = await SERVICE.addZone({}); - }); - - test('should allow updating zone details', async () => { - const spy = vi.spyOn(Resources, 'update'); - spy.mockImplementation((_) => Promise.resolve(_.fn!({}) as any)); - let item = await SERVICE.updateZone('1', {}); - expect(item).toBeInstanceOf(PlaceZone); - item = await SERVICE.updateZone('1', {}, 'patch'); - }); - - test('should allow removing zones', async () => { - const spy = vi.spyOn(Resources, 'remove'); - spy.mockImplementation(() => Promise.resolve()); - const item = await SERVICE.removeZone('1'); - expect(item).toBeFalsy(); - }); - - test("should allow listing zone's triggers", async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation((_) => Promise.resolve(_.callback([{}]))); - let item = await SERVICE.listZoneTriggers('1'); - expect(item).toBeTruthy(); - expect(item?.data[0]).toBeInstanceOf(PlaceTrigger); - item = await SERVICE.listZoneTriggers('1', {}); - }); - - test('should allow getting zone metadata', async () => { - (Resources.task as any) = vi - .fn() - .mockImplementation(() => Promise.resolve({ key: 'value' })); - let item = await SERVICE.zoneMetadata('1'); - expect(item).toEqual({ key: 'value' }); - item = await SERVICE.zoneMetadata('1', { name: 'test' }); - }); -}); diff --git a/test/zones/zone.spec.ts b/test/zones/zone.spec.ts deleted file mode 100644 index fdae0e93b..000000000 --- a/test/zones/zone.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import { PlaceZone } from '../../src/zones/zone'; - -describe('PlaceZone', () => { - let zone: PlaceZone; - - beforeEach(() => { - zone = new PlaceZone({ - id: 'dep-test', - description: 'In a galaxy far far away...', - settings: { - settings_string: "{ today: false, future: 'Yeah!' }", - } as any, - triggers: ['trig-001'], - created_at: 999, - trigger_data: [{ id: 'trig-01', name: 'A trigger' } as any], - }); - }); - - test('should create instance', () => { - expect(zone).toBeTruthy(); - expect(zone).toBeInstanceOf(PlaceZone); - }); - - test('should have trigger data', () => - new Promise((resolve) => { - setTimeout(() => { - expect(zone.trigger_list).toBeTruthy(); - expect(zone.trigger_list.length).toBe(1); - resolve(); - }, 1); - })); - - test('should expose description', () => { - expect(zone.description).toBe('In a galaxy far far away...'); - }); - - test('should expose settings', () => { - expect(zone.settings).toBeInstanceOf(Object); - }); - - test('should expose triggers', () => { - expect(zone.triggers).toEqual(['trig-001']); - }); - - test('should expose class name', () => { - expect(zone.created_at).toEqual(999); - }); -}); diff --git a/v2/tsconfig.build.json b/tsconfig.build.json similarity index 100% rename from v2/tsconfig.build.json rename to tsconfig.build.json diff --git a/v2/tsconfig.cli.json b/tsconfig.cli.json similarity index 100% rename from v2/tsconfig.cli.json rename to tsconfig.cli.json diff --git a/tsconfig.json b/tsconfig.json index 0041b24f5..1b77bf424 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,25 +1,30 @@ { + // Type checks the library, the tests and the scripts. The scripts and tests run on Bun. "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "skipLibCheck": true, - - /* Bundler mode */ + "target": "ES2022", + "module": "preserve", "moduleResolution": "bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["bun"], + "noEmit": true, "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, "isolatedModules": true, "moduleDetection": "force", - "noEmit": true, + "skipLibCheck": true, - /* Linting */ "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "noPropertyAccessFromIndexSignature": true, "noUnusedLocals": true, "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true + "useUnknownInCatchVariables": true }, - "include": ["src"], - "exclude": ["scripts"] + "include": ["src", "test", "scripts"], + // `bun run build` checks it against `dist`, without `strict`. + "exclude": ["test/loose"] } diff --git a/v2/.gitignore b/v2/.gitignore deleted file mode 100644 index c925c21d5..000000000 --- a/v2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/dist -/node_modules diff --git a/v2/.prettierrc b/v2/.prettierrc deleted file mode 100644 index 969d4b941..000000000 --- a/v2/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "singleQuote": true, - "tabWidth": 4, - "semi": true, - "printWidth": 100 -} diff --git a/v2/README.md b/v2/README.md deleted file mode 100644 index e3b8ed2ca..000000000 --- a/v2/README.md +++ /dev/null @@ -1,525 +0,0 @@ -# @placeos/ts-client v2 - -A typed client for the PlaceOS REST API and the staff API. A script generates the types and the -request functions from the OpenAPI documents of -[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) and -[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api/blob/master/OPENAPI_DOC.yml). The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) -where possible. - -The library has no runtime dependencies. It runs in browsers, in Node 20.3 and later, and in Bun. - -## Use the client - -```ts -import { configure, zones } from '@placeos/ts-client'; - -// Do this one time, when the application starts. -configure({ - baseUrl: 'https://placeos.example.com', // Use '' for the origin of the page. - auth: { kind: 'bearer', token: () => localStorage.getItem('token') }, -}); - -const result = await zones.show({ id: 'zone-1234', complete: true }); -if (result.ok) { - console.log(result.value.data.name); -} else { - console.error(result.error.kind); -} -``` - -There is one namespace for each controller of the API, for example `zones`, `systems` and -`users`. Each function has the name of the server action: `show`, `create`, `update`, `destroy`, -or a custom action such as `systems.execute`. The `index` action is `query`, because a list -operation queries the items. The comment of each function gives the HTTP method and the path. - -The first argument has the path parameters, the query parameters and, for an operation with a -body, `body`. The second argument has the options of the request: - -```ts -await zones.update({ id: 'zone-1234', body: { name: 'Level 2' } }); -await systems.execute({ - sys_id: 'sys-1234', - module_slug: 'Display_1', - method: 'power', - body: [true], -}); -``` - -### Results and errors - -A function does not throw for an expected failure. It returns a `Result`. Examine `ok` first: - -| `error.kind` | Meaning | -| -------------------- | -------------------------------------------------------------------------- | -| `http` | The server sent a status that is not 2xx. See `status`, `message`, `body`. | -| `network` | The request got no response. For example, the network is down. | -| `timeout` | The request took more than `timeoutMs`. | -| `aborted` | The `signal` of the caller cancelled the request. | -| `auth_missing` | The auth had no token or credential. | -| `response_too_large` | The body was more than `responseBytesMax`. | -| `response_invalid` | The body does not match the API document. See `path` and `expected`. | - -A function throws only for a programmer error. For example, a parameter that the operation does -not have, an empty path parameter, or a call before `configure`. - -In a project without `strictNullChecks`, `if (!result.ok)` does not narrow the `Result`. Use -`if (result.ok === false)`. - -### More than one client - -`configure` makes the client that each call uses. To use a different client for one call, make it -with `createClient` and give it in the options. The configured client does not change: - -```ts -const other = createClient({ baseUrl: 'https://other.example.com', auth: { kind: 'none' } }); -await zones.query({}, { client: other }); -``` - -### Timeouts and cancel - -Each request has a time limit. The default is 30 seconds. Set a different limit for the client or -for one request: - -```ts -configure({ baseUrl: '', auth: { kind: 'none' }, timeoutMs: 10_000 }); -const controller = new AbortController(); -await zones.query({}, { signal: controller.signal, timeoutMs: 60_000 }); -``` - -### Pages - -A `query` operation returns one page. Use `pageInfo` to get the total and the next offset: - -```ts -import { pageInfo, zones } from '@placeos/ts-client'; - -const result = await zones.query({ limit: 100 }); -if (result.ok) { - const { total, nextOffset } = pageInfo(result.value.headers); -} -``` - -### Tests and mocks - -Give the client a `fetch` function. The client sends each request through it. A test can give -its own client in the options, so it does not change the configured client: - -```ts -const client = createClient({ - baseUrl: '', - auth: { kind: 'none' }, - fetch: async (url, init) => new Response(JSON.stringify({ id: 'zone-1' })), -}); -const result = await zones.show({ id: 'zone-1' }, { client }); -``` - -### Typed mocks - -`@placeos/ts-client/mock` answers the calls of an endpoint without a request. The compiler checks -the name of the endpoint, the input that the handler gets, and the data that it gives: - -```ts -import { endpointMocks, httpError, mockEndpoint, respond } from '@placeos/ts-client/mock'; - -configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); - -mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); -mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 1 })); -mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 300 }); -mockEndpoint('zones.destroy', () => { - throw httpError(403); -}); -``` - -- The client checks the input first, as for a request. Then it parses the data of the handler with - the response schema of the endpoint, as it parses a response. The data can leave out fields: a - missing required field gets its empty value, such as `''`, `0` or `[]`. A field with the wrong - type is a `response_invalid` error. -- `respond(data, { status, headers, total })` sets the status and the headers. `total` is the - `X-Total-Count` that `pageInfo` and `orThrowPage` read. -- `mockEndpoint` returns the function that removes the mock. `clearEndpointMocks()` removes all. -- A call to an endpoint without a mock goes to the `fetch` of the client. Give `mockFetch` of - `@placeos/ts-client/compat` to answer it from the v1 mock endpoints. -- `mock` of the client is a function. A test can give its own, which gets the name of the endpoint - (such as `zones.show`) and the input, and returns an answer or `null`. - -A test double of a v2 call gives a `Result`. `mockReply` and `mockPage` of -`@placeos/ts-client/compat` make one: - -```ts -vi.mock('@placeos/ts-client', { spy: true }); -vi.mocked(zones.show).mockResolvedValue(mockReply(zone)); -vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); -``` - -### Mock mode - -For new mocks, use [typed mocks](#typed-mocks). The v1 mock endpoints and mock systems are in -`@placeos/ts-client/compat`, with the same names. -Give `mockFetch` to the client, and `mockRealtimeEnvironment()` to the realtime client: - -```ts -registerMockEndpoint({ - path: '/api/engine/v2/zones/:id', - method: 'GET', - callback: (request) => ({ id: request.route_params['id'], name: 'Level 1' }), -}); -registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); - -configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch, missingFields: 'zero' }); -const realtime = createRealtime({ - baseUrl: '', - auth: { kind: 'none' }, - environment: mockRealtimeEnvironment(), -}); -``` - -- v2 parses each mock response with the schema of the operation. Mock data often has only some - fields. `missingFields: 'zero'` gives each missing required field its empty value, such as `''`, - `0` or `[]`, as the v1 classes did. A field with the wrong type is still an error, because the - real server does not send it. -- A mock endpoint that throws an error with a `status`, such as `404`, gives that HTTP status. -- A change to a variable of a mock module, such as `mockSystem('sys-1')['Display'][0]['power'] -= true`, notifies its bindings. - -## Staff API - -The staff API (bookings, events, guests, desks, surveys and more) is at -`@placeos/ts-client/staff`. It uses the client of `configure`, as the REST API functions do: - -```ts -import { bookings } from '@placeos/ts-client/staff'; - -const now = Math.floor(Date.now() / 1000); -const result = await bookings.query({ period_start: now, period_end: now + 86_400, type: 'desk' }); -``` - -- The staff API has its own schemas, such as `Booking` and `Guest`. A schema that both APIs have, - such as `Zone`, is in both entries with the same shape. -- The typed mocks of the staff API start with `staff.`: `mockEndpoint('staff.bookings.show', ...)`. -- Some routes of the staff API have an occurrence of a recurring booking: `bookings.showInstance` - is `GET /bookings/{id}/instance/{instance}`, the occurrence of `bookings.show`. - -## Log in - -`createAuthSession` does the OAuth login of PlaceOS and gives the client its credential: - -```ts -import { configure, createAuthSession } from '@placeos/ts-client'; - -const session = createAuthSession({ - baseUrl: '', - redirectUri: `${location.origin}/oauth-resp.html`, - scope: 'public', - grant: { kind: 'code' }, -}); -configure({ baseUrl: '', auth: session.clientAuth, headers: { 'X-App-Id': session.clientId } }); - -const result = await session.start(); -if (!result.ok && result.error.kind === 'redirecting') { - // The page goes to the login page now. -} -``` - -Copy `oauth-resp.html` from the package to your application, and use its URL as `redirectUri`. The -client ID is the MD5 of `redirectUri`, as in v1. - -`session.start()` loads `/auth/authority`, and gets a credential in this order: - -1. An API key from the URL or the storage (a fixed device), or an access token that is valid. -2. A code or a token from the redirect. The `state` must be the nonce of this client. -3. The refresh token. -4. The `password` or `entra` grant. -5. If the user has a session: the authorize page, with a redirect or, with `useFrame`, in a - hidden frame. -6. Else the login page of the authority. With `handleLogin: false`, the result is a - `login_required` error, and the application shows its own login. - -The grants are `code` (with PKCE), `implicit`, `password` and `entra`. PlaceOS auth.cr refuses -the `password` grant; only older auth services accept it. A trusted application (`?trust=true`) -keeps its tokens in the storage. Other applications keep them in memory only. - -After a 401, the client asks the session for a new token and sends the request again, one time. -Parallel requests share one renewal. After a 511, the session sends the user to the login page. - -Other parts of the session: - -- `session.status()` and `session.subscribe(listener)` give the state: `loading`, `signed_in`, - `redirecting` or `signed_out` with the error. -- `session.handleRedirect(url)` completes a login from a deep link, in a native wrapper. -- When the application comes back to the foreground without a session, the session loads the - authority again. The user can have logged in from a different tab. -- `session.useToken`, `session.useApiKey`, `session.invalidateToken` and `session.logout`. -- `createAuthSession({ ..., environment })` replaces the browser parts, for tests or a native - wrapper. See `AuthEnvironment`. - -### Changes from v1 - -- The session keeps the storage keys of v1, so a user stays logged in after the change. -- The default token path is `/auth/oauth/token`. PlaceOS auth.cr and the older Ruby auth service - both serve it. The Ruby auth service does not serve `/auth/token`. -- A relative login or logout URL of the authority is on `baseUrl`. v1 used the `domain` of the - authority, which has no port. -- A refused code stops the login with `token_rejected`. A new redirect could loop. -- The token requests send their parameters in the body, not in the URL. A password is not in the - URL. -- A trusted application with the `implicit` grant uses the code with PKCE. -- The frame login checks the `state`. It needs the `oauth-resp.html` of v2. -- The session removes `x-api-key` from the URL after it reads it. -- After a refused refresh token, the login continues immediately. -- A refusal on the consent page (`error=access_denied` with the state of this client) stops the - login with `authorization_denied`. v1 sent the user to the authorize page again. -- `/auth/authority` gets `AUTHORITY_ATTEMPTS_MAX` attempts, not an unlimited number. Then - `start` gives `authority_unavailable`. Call `start` again to try again. -- Not ported: `revokeToken`, the state of the application in `authorise(state)`, and the ACA - Engine API path. The mock mode is in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). - It does not need a login: give `auth: { kind: 'none' }`. - -## Realtime - -`createRealtime` opens one WebSocket to `systems/control`. It binds to the status variables of -modules, calls their functions and gets their logs: - -```ts -import { createRealtime } from '@placeos/ts-client'; - -const realtime = createRealtime({ baseUrl: '', auth: session.clientAuth }); - -const power = { sys: 'sys-1234', mod: 'Display', index: 1, name: 'power' }; -const release = realtime.bind(power, (state) => { - if (state.kind === 'value') console.log('power', state.value); -}); -const result = await realtime.exec(power, [true]); -release(); -``` - -- The client connects when the first binding or call needs it. `start` connects now. -- A binding has a count. The first `bind` sends `bind`. The last release sends `unbind`. -- After a new connection, the client binds each variable again. -- The client handles the messages of the server in batches. In one batch, many notifications for - one variable give one call to its listeners, with the last value. -- `exec` gives a `Result` with the return value of the function, or a `RealtimeError`: - `timeout`, `disconnected` (the socket closed after the server got the call), `stopped`, - `unavailable`, `too_many_requests` or `server` (with the error code and the status). -- The client sends `ping` each 15 seconds. A socket without a message for 60 seconds closes, and - the client connects again. It waits longer after each failure, to 5 seconds. After 40 attempts, - the status is `failed`. Call `start` to try again. -- `realtime.debug({ sys, moduleId }, listener)` gets the logs of a module. -- `splitModuleId('Display_2')` gives `{ mod: 'Display', index: 2 }`. -- In a browser, the token goes in a cookie on the socket path. In a frame and on mobile Safari it - goes in the query, as in v1. `createRealtime({ ..., environment })` replaces the socket, the - timers and the cookie, for tests. - -### Changes from v1 - -- A call that the server got fails with `disconnected` when the socket closes. v1 did not settle - these calls. -- Two calls with the same arguments are two calls. v1 merged them for one minute. -- Server errors have the correct code name. v1 read the HTTP style status as the error code. -- `iface: true` addresses an interface, such as `Interface::Sensor`. -- After 40 failed attempts, the status is `failed`. v1 reloaded the page. -- Not ported: the `connectionState` signal and the `/control/websocket` path of ACA Engine. The - mock systems are in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). - -## Types - -Each schema of the API document has a value and two types with the same base name: - -- `Zone` is the type of a zone from the server. Each field is present. A field that the server can - leave out is `null`. -- `ZoneInput` is the type of a zone that you send. Each field is optional. -- The `Zone` value is the schema. `parseResponse(Zone, value)` parses data from other sources. - -The parser removes the fields that the schema does not have. A request that has a field that the -schema does not have stops with an error, because a typing error in a field name is a bug. - -Some schemas have a name from the server code that does not say what they are. These have a -short name too. The short name is the same value and type: - -| Short name | Name in the API document | -| ------------------------ | ------------------------------- | -| `User` | `UserAdminMetadataResponse` | -| `System` | `ControlSystem` | -| `Application` | `DoorkeeperApplication` | -| `Domain` | `Authority` | -| `Metadata` | `MetadataInterface` | -| `ShortUrl` | `Shortener` | -| `SignageTemplateMapping` | `SignageTemplateSystemTemplate` | - -`TYPE_ALIASES` in `scripts/generate.ts` has the list. - -## Differences from the API document - -The generator changes some parts of the document. Each change has a comment in -`scripts/generate.ts`. - -- **Time fields.** The document says `date-time` for some fields that the server sends as Unix time - in seconds, for example `created_at` on most models. The generator changes these fields to - integers. The list comes from the source of PlaceOS/models. The generator stops if it finds a - `date-time` field that is not in a list, so each new field gets a decision. -- **Enum numbers.** The server sends some enums as numbers, for example `Driver.role` (`99` is - `logic`). The document gives their names. The generator changes these fields to the numbers. -- **Required fields in a request.** The document marks a field as required when the server always - sends it. The server can have a default for the same field in a request. Thus each field of a - request body is optional, and the server checks the body. Path and query parameters keep the - `required` of the document. -- **Arrays in a query.** The server reads an array parameter as one value with commas, for example - `zone_id=a,b`. The items of an array parameter must not contain commas. -- **PATCH and PUT.** The server sends PATCH and PUT of `update` to the same method. The client has - only `update`, which sends PATCH. -- **Numbered routes.** The document numbers the routes of one action: `show` and `show_2`. A second - path with the same signature is an alias, such as `checkin` for `check_in` in the staff API. The - client has only the first path. A path with more segments gets a name from them, such as - `showInstance` for `bookings/{id}/instance/{instance}`. -- **A query parameter named `body`.** `body` of the input is the request body, so the `body` query - parameter of `staff.events.book` (the description of the meeting) is `body_text` in the input. - The query keeps the name `body`. -- **Responses without a schema.** The data is a `Uint8Array` with the raw body. `systems.execute`, - `modules.execute` and `modules.stateValue` are exceptions: they return a `JsonValue`. -- **WebSocket endpoints** (`systems/control`, `webrtc/signaller` and others) are not in the - client. - -## Change the generated code - -Do not edit `src/generated`. The generator downloads the API documents from the master branches of -[PlaceOS/rest-api](https://github.com/PlaceOS/rest-api) and -[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api) on each run. It does not keep a copy in -this repository. `APIS` in `scripts/generate.ts` has the list: the repository, the output folder -and the prefix of the operation IDs and names. - -```sh -bun run generate # Downloads the documents and writes src/generated and src/generated/staff. -bun run generate:check # Fails if the generated files do not match the current documents. -``` - -The generated files are in the repository, so a change to the API shows as a diff. Examine the -diff before you commit it. `generate:check` can fail because the API changed, not because of your -change, so it is not part of `bun test` or of the checks of a PR. - -Each day, the `v2 regenerate` workflow regenerates the client from the API documents on master -(`scripts/regenerate-pr.sh`). When the output changes, it opens a PR with the diff and the results -of the checks. It also closes the older regeneration PRs, because the new one has their changes. -When master matches the documents again, it closes all of them. Each run deletes the -regeneration branches that have no open PR, such as the branch of a merged PR. `DRY_RUN=1 -scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. - -The generator stops with an assertion on a part of the document that it does not support. Add the -support to `scripts/generate.ts` and `src/core/schema.ts`. - -## Development - -```sh -bun install -bun run check # Type checks the library, the tests and the scripts. -bun test -bun run build # Writes dist/. Then it type checks test/loose without `strict`. -bun run v1-map # Writes the v1 to v2 map. It needs `npm install` in the v1 folder. -``` - -## Migrate from v1 - -The migration tool rewrites the v1 calls of a project to v2. Commit your work first, so that you -can examine and undo the changes. Run it in the folder of the project, because it uses the -`typescript` package of the project: - -```sh -npx -p @placeos/ts-client@2 placeos-migrate src # Shows the changes. Writes no file. -npx -p @placeos/ts-client@2 placeos-migrate --write src # Writes the changes. -``` - -The tool makes these changes: - -- A call of a v1 REST function becomes the v2 operation. `.then(orThrow)` gives the data, and an - error rejects the promise, as in v1. A v1 query function gets `.then(orThrowPage)`, which gives - `{ data, total, nextOffset }`. - - ```ts - // v1 - const zone = await showZone(id, { complete: true }); - const list = await queryZones({ limit: 10 }); - // v2, after the tool - const zone = await zones.show({ id, complete: true }).then(orThrow); - const list = await zones.query({ limit: 10 }).then(orThrowPage); - ``` - -- A type reference to a v1 class becomes the v2 type. For example, `PlaceZone` becomes `Zone`. -- The imports of the v1 enums, such as `PlaceDriverRole`, and of `QueryResponse` move to - `@placeos/ts-client/compat`. The enums have the v2 values, so they fit the v2 fields of the - data. A query parameter takes the name: the `role` of `drivers.query` is `'logic'`, not `99`. -- A new import gets another name when the file has the name. For example, a file with a - `zones` variable gets `zones as zonesV2`. - -The tool also changes the test doubles, so that the tests of the app still work: - -- `vi.mocked(showZone)`, `expect(showZone)`, `vi.spyOn(client, 'showZone')` and, in a spec file, - each other use of `showZone` become `zones.show`. -- A value of `mockResolvedValue` gets `mockReply` or `mockPage`. The arguments of - `toHaveBeenCalledWith` become the v2 input. -- A v1 implementation, such as the value of `mockImplementation`, gets `fromV1Mock`. It gives the - implementation the v1 arguments, and makes a v2 result of its value. -- The v1 functions of a `vi.mock('@placeos/ts-client', () => ({ ... }))` factory become v2 - namespaces: `showZone: vi.fn(impl)` becomes `zones: { show: vi.fn(fromV1Mock(impl, ['id', -'...'])) }`. The factory runs before the imports, so the tool adds `fromV1Mock` with - `vi.hoisted`. -- The v1 staff functions, such as `querySurveys`, become the operations of - `@placeos/ts-client/staff`, with their own import. -- The imports of the mock endpoints and mock systems move to `@placeos/ts-client/compat`. See - [Mock mode](#mock-mode). - -The tool does not change a use that it cannot rewrite safely. It shows each one with a hint, and -it keeps its v1 import, so the compiler also shows it. These uses are: - -- the login and the realtime functions, such as `setup`, `token` and `getModule`; -- `get`, `post` and the other HTTP functions; -- `new` and `instanceof` on a v1 class, because v2 has plain objects; -- the `next` function of a v1 page. v2 gives `nextOffset`; -- a function that is not called, out of a test; -- a `vi.mock` without a factory or `{ spy: true }`: its v2 functions give `undefined`, and - `.then(orThrow)` fails; -- a `jest.mock` factory with v1 functions; -- an argument that has no place in v2, and an argument with side effects that v2 uses two times. - -On a copy of backoffice, 329 of the 399 tests pass after the tool. v1 passes 394. The other tests -use v1 classes, the v1 `next` function or the v1 `createSignal`, or wait for one microtask only. -These are the uses that the tool shows. - -After the tool: - -1. Run Prettier, or your formatter. The tool writes long imports on one line. -2. Install v2, and call `configure` once before the first call (see [Log in](#log-in)). For a - mock mode, give `fetch: mockFetch` (see [Mock mode](#mock-mode)). -3. Run the compiler. It shows the differences of the data. For example, a field that can be - `null`, an array that is `readonly`, or a query parameter that has a different type in v2. -4. Change the uses that the tool showed. - -`orThrow` and `orThrowPage` keep the v1 behavior. In new code, examine the `Result`. - -The tool parses each file. It does not type check it. The map from v1 to v2 is -`src/migrate/v1-map.ts`. `scripts/v1-map.ts` makes it: it calls each v1 REST function with marker -arguments, and it finds the v2 operation with the same method and path. - -## What v1 has that v2 does not have - -- Classes with methods for each model. v2 has plain data and functions. - -## Where v2 does not follow TigerStyle - -- `orThrow` and `orThrowPage` of `@placeos/ts-client/compat` throw. They are for code that moves - from v1. -- The v1 mock types of `@placeos/ts-client/compat` (`MockHttpRequest.body`, `metadata` and - `MockModule`) keep `any`, so that the mocks of an app still compile. -- `missingFields: 'zero'` accepts data without its required fields. It is for mock data only. -- `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove - that the parser output has the type of the schema. The tests check the parser. -- `configure` keeps one client in module state, so a call does not need a client argument. A - call before `configure` is a run-time assertion, not a compile error. -- The mocks keep their registries in module state, as v1 did: the endpoints of - `registerMockEndpoint` and the systems of `registerSystem` (`@placeos/ts-client/compat`), and - the mocks of `mockEndpoint` (`@placeos/ts-client/mock`). A test owns them. It removes them with - `clearMockEndpoints`, `deregisterSystem` and `clearEndpointMocks`. Each registry has a named - limit. The status variables of a mock module are properties with setters that notify the - bindings, as in v1. -- `createAuthSession` keeps its state in a closure. The login is a state machine with I/O, and - one object with one owner is the clearest model of it. -- Records from the server are plain objects, not `Map`s. A `Map` does not go through - `JSON.stringify`, and the API sends these objects back and forth. diff --git a/v2/bun.lock b/v2/bun.lock deleted file mode 100644 index 77eb230af..000000000 --- a/v2/bun.lock +++ /dev/null @@ -1,72 +0,0 @@ -{ - "lockfileVersion": 2, - "configVersion": 1, - "workspaces": { - "": { - "name": "@placeos/ts-client", - "devDependencies": { - "@types/bun": "1.4.3", - "prettier": "3.9.10", - "typescript": "7.0.2", - "typescript-5": "npm:typescript@5.8.3", - }, - }, - }, - "packages": { - "@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="], - - "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], - - "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], - - "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], - - "@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="], - - "@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="], - - "@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="], - - "@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="], - - "@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="], - - "@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="], - - "@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="], - - "@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="], - - "@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="], - - "@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="], - - "@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="], - - "@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="], - - "@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="], - - "@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="], - - "@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="], - - "@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="], - - "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="], - - "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], - - "bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="], - - "prettier": ["prettier@3.9.10", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA=="], - - "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], - - "typescript-5": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "undici-types": ["undici-types@8.12.4", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="], - - "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], - } -} diff --git a/v2/package.json b/v2/package.json deleted file mode 100644 index 63360d08e..000000000 --- a/v2/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@placeos/ts-client", - "version": "2.0.0-alpha.0", - "description": "Typed PlaceOS REST API client, generated from the PlaceOS OpenAPI document", - "license": "MIT", - "type": "module", - "repository": { - "type": "git", - "url": "https://github.com/PlaceOS/ts-client.git", - "directory": "v2" - }, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./compat": { - "types": "./dist/compat/index.d.ts", - "default": "./dist/compat/index.js" - }, - "./staff": { - "types": "./dist/staff.d.ts", - "default": "./dist/staff.js" - }, - "./mock": { - "types": "./dist/mock/index.d.ts", - "default": "./dist/mock/index.js" - } - }, - "bin": { - "placeos-migrate": "./dist/migrate/cli.js" - }, - "files": [ - "dist", - "src", - "oauth-resp.html" - ], - "sideEffects": false, - "engines": { - "node": ">=20.3" - }, - "scripts": { - "generate": "bun scripts/generate.ts", - "generate:check": "bun scripts/generate.ts --check", - "v1-map": "bun scripts/v1-map.ts", - "v1-map:check": "bun scripts/v1-map.ts --check", - "check": "tsc --noEmit && tsc --noEmit -p tsconfig.build.json && tsc --noEmit -p tsconfig.cli.json", - "test": "bun test", - "build": "rm -rf dist && tsc -p tsconfig.build.json && tsc -p tsconfig.cli.json && tsc -p test/loose", - "format": "prettier --write ." - }, - "devDependencies": { - "@types/bun": "1.4.3", - "prettier": "3.9.10", - "typescript": "7.0.2", - "typescript-5": "npm:typescript@5.8.3" - } -} diff --git a/v2/src/compat/index.ts b/v2/src/compat/index.ts deleted file mode 100644 index 0e48c98c3..000000000 --- a/v2/src/compat/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Helpers for code that moves from v1, at `@placeos/ts-client/compat`. The migration tool moves - * the v1 imports of these names here. - * - * - `orThrow` and `orThrowPage` give the data of a v2 call, and throw on an error, as v1 did. - * - `mockReply` and `mockPage` make v2 results for the test doubles of v2 calls. - * - `registerMockEndpoint` and `mockFetch` are the v1 mock endpoints, for the v2 client. - * - `registerSystem` and `mockRealtimeEnvironment` are the v1 mock systems, for `createRealtime`. - * - The v1 enums, with the values of v2. - * - * @module - */ -export * from './enums.ts'; -export * from './http-mock.ts'; -export * from './realtime-mock.ts'; -export * from './result.ts'; diff --git a/v2/src/index.ts b/v2/src/index.ts deleted file mode 100644 index 4a6af26b8..000000000 --- a/v2/src/index.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * The PlaceOS REST API client. - * - * ```ts - * import { configure, zones } from '@placeos/ts-client'; - * - * configure({ baseUrl: '', auth: { kind: 'bearer', token: () => token } }); - * const result = await zones.show({ id: 'zone-1234' }); - * if (result.ok) console.log(result.value.data.name); - * ``` - * - * @module - */ -export { - browserEnvironment, - FRAME_MESSAGE_TYPE, - memoryStore, - type AuthEnvironment, - type FrameError, - type KeyValueStore, -} from './auth/environment.ts'; -export { - createAuthSession, - DomainAuthority, - type AuthError, - type DomainAuthorityInput, - type AuthSession, - type AuthSessionConfig, - type AuthStatus, - type Grant, -} from './auth/session.ts'; -export { assert, unreachable } from './core/assert.ts'; -export { - browserRealtimeEnvironment, - type RealtimeEnvironment, - type RealtimeSocket, - type SocketHandlers, - type TokenTransport, -} from './realtime/environment.ts'; -export { - createRealtime, - splitModuleId, - type BindingState, - type DebugMessage, - type DebugTarget, - type Realtime, - type RealtimeConfig, - type RealtimeError, - type RealtimeStatus, - type RealtimeTarget, -} from './realtime/realtime.ts'; -export { - call, - configure, - createClient, - operation, - RESPONSE_BYTES_MAX_DEFAULT, - TIMEOUT_MS_DEFAULT, - type AnyOperation, - type Auth, - type CallError, - type CallOptions, - type CallResult, - type Client, - type ClientConfig, - type Credential, - type FetchFunction, - type HttpMethod, - type Operation, - type OperationData, - type OperationInput, - type Reply, -} from './core/client.ts'; -export { pageInfo, type PageInfo } from './core/pagination.ts'; -export type { Result } from './core/result.ts'; -export { - checkRequest, - parseResponse, - type Input, - type JsonValue, - type Output, - type Schema, - type SchemaError, -} from './core/schema.ts'; -export * from './generated/operations/index.ts'; -export * from './generated/schemas.ts'; diff --git a/v2/src/staff.ts b/v2/src/staff.ts deleted file mode 100644 index 2cb1fe154..000000000 --- a/v2/src/staff.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * The PlaceOS staff API client, at `@placeos/ts-client/staff`. It uses the client of `configure`, - * as the REST API functions do: - * - * ```ts - * import { configure } from '@placeos/ts-client'; - * import { bookings } from '@placeos/ts-client/staff'; - * - * configure({ baseUrl: '', auth: session.clientAuth }); - * const result = await bookings.query({ period_start, period_end, type: 'desk' }); - * ``` - * - * The staff API has its own schemas, such as `Booking`. A schema that both APIs have, such as - * `Zone`, is in both entries with the same shape. - * - * @module - */ -export * from './generated/staff/operations/index.ts'; -export * from './generated/staff/schemas.ts'; diff --git a/v2/tsconfig.json b/v2/tsconfig.json deleted file mode 100644 index 1b77bf424..000000000 --- a/v2/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - // Type checks the library, the tests and the scripts. The scripts and tests run on Bun. - "compilerOptions": { - "target": "ES2022", - "module": "preserve", - "moduleResolution": "bundler", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "types": ["bun"], - "noEmit": true, - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "isolatedModules": true, - "moduleDetection": "force", - "skipLibCheck": true, - - "strict": true, - "noUncheckedIndexedAccess": true, - "exactOptionalPropertyTypes": true, - "noImplicitOverride": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "noPropertyAccessFromIndexSignature": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "useUnknownInCatchVariables": true - }, - "include": ["src", "test", "scripts"], - // `bun run build` checks it against `dist`, without `strict`. - "exclude": ["test/loose"] -} diff --git a/vite.config.ts b/vite.config.ts deleted file mode 100644 index 566aea31b..000000000 --- a/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -/// -import { resolve } from 'path'; -import { defineConfig } from 'vite'; -import { configDefaults } from 'vitest/config'; -import dts from 'vite-plugin-dts'; -// import pkg from './package.json'; - -// https://vitejs.dev/config/ -export default defineConfig({ - build: { - sourcemap: true, - lib: { - entry: resolve(__dirname, 'src/index.ts'), - name: 'cloud_uploads', - formats: ['es', 'cjs', 'umd'], - fileName: (format) => `index.${format}.js`, - }, - rollupOptions: { - external: [ - // ...Object.keys(pkg.dependencies), // don't bundle dependencies - /^node:.*/, // don't bundle built-in Node.js modules (use protocol imports!) - ], - }, - target: 'esnext', // transpile as little as possible - }, - test: { - environment: 'jsdom', - // v2 is a separate package with its own tests, which run on Bun. - exclude: [...configDefaults.exclude, 'v2/**'], - // Node 25+ has its own `localStorage`, which shadows jsdom's - execArgv: - Number(process.versions.node.split('.')[0]) >= 25 - ? ['--no-experimental-webstorage'] - : [], - }, - plugins: [dts()], -}); From 149eb0b6939fe136dc2b75f9d406b70d607af68d Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 14:23:55 +1100 Subject: [PATCH 13/29] ci: the regeneration bot commits as fix, so a merge publishes the client A chore commit makes no release, so a merged regeneration did not reach npm. The PR tells the reviewer to change the message to feat or add a BREAKING CHANGE footer when the diff needs it. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++++ scripts/regenerate-pr.sh | 9 +++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e9adbbded..a809fa5cc 100644 --- a/README.md +++ b/README.md @@ -411,6 +411,10 @@ When master matches the documents again, it closes all of them. Each run deletes regeneration branches that have no open PR, such as the branch of a merged PR. `DRY_RUN=1 scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. +The commit of a regeneration PR is a `fix`, so its merge publishes a patch release. Before the +merge, change the commit message to a `feat` for new operations, or add a `BREAKING CHANGE:` footer +for a change that breaks apps. + The generator stops with an assertion on a part of the document that it does not support. Add the support to `scripts/generate.ts` and `src/core/schema.ts`. diff --git a/scripts/regenerate-pr.sh b/scripts/regenerate-pr.sh index b48f6d14e..83a444e81 100755 --- a/scripts/regenerate-pr.sh +++ b/scripts/regenerate-pr.sh @@ -117,6 +117,10 @@ This regenerates \`src/generated\`, \`src/generated/staff\` and the 6.x migratio Examine the diff for changes that break apps, such as a field that is now \`null\` or a removed operation. +The commit is a \`fix\`, so a merge publishes a patch release. For new operations, change it to a +\`feat\` (a minor release). For a change that breaks apps, add a \`BREAKING CHANGE:\` footer (a +major release). + ${results} \`\`\` $(git diff --cached --stat -- "${GENERATED[@]}" | tail -n 25) @@ -129,12 +133,13 @@ EOF git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git switch -c "$branch" -git commit -q -m 'chore: regenerate the client from the API documents' +# A `fix` commit, so that semantic-release publishes the new client when the PR merges. +git commit -q -m 'fix: regenerate the client from the API documents' # A branch of this name can be left from a failed run on an older base. Only this script writes to # the prefix, so the push replaces it. remote git push --force origin "$branch" remote gh pr create --base "$BASE" --head "$branch" \ - --title 'chore: regenerate the client from the API documents' --body-file "$body" + --title 'fix: regenerate the client from the API documents' --body-file "$body" if [ "${DRY_RUN:-}" = 1 ]; then number='' From 0817a36b9bef623636e759f32dbebfee2215137d Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 15:23:03 +1100 Subject: [PATCH 14/29] feat!: snake_case names for variables, properties and namespaces The options and fields of the client had camelCase names, while the data of the server is snake_case. Variables, parameters, data properties and the namespaces are now snake_case. Functions and methods keep camelCase. Names that outside code fixes stay: server fields, the 6.x names of the migration map, vitest, OpenAPI and browser names. The rename used the TypeScript language service. The generator writes the new names, and the 6.x migration map has the new namespaces. BREAKING CHANGE: the options and fields are snake_case, for example `base_url`, `timeout_ms`, `redirect_uri`, `session.client_auth` and `next_offset`. The namespaces are snake_case, for example `alert_dashboards`, and so are the names of the typed mocks. Co-Authored-By: Claude Opus 5.5 --- README.md | 60 +-- scripts/generate.ts | 426 +++++++++--------- scripts/v1-map.ts | 70 +-- src/auth/environment.ts | 14 +- src/auth/hash.ts | 26 +- src/auth/session.ts | 341 +++++++------- src/compat/http-mock.ts | 8 +- src/compat/realtime-mock.ts | 4 +- src/compat/result.ts | 10 +- src/core/client.ts | 208 ++++----- src/core/pagination.ts | 8 +- src/core/schema.ts | 52 +-- src/generated/operations/alert-dashboards.ts | 26 +- src/generated/operations/alerts.ts | 10 +- src/generated/operations/api-keys.ts | 26 +- src/generated/operations/asset-categories.ts | 22 +- .../operations/asset-purchase-orders.ts | 22 +- src/generated/operations/asset-types.ts | 22 +- src/generated/operations/assets.ts | 16 +- src/generated/operations/brokers.ts | 10 +- src/generated/operations/build-monitor.ts | 10 +- src/generated/operations/chat-gpt-plugin.ts | 14 +- src/generated/operations/chat-gpt.ts | 14 +- src/generated/operations/cluster.ts | 8 +- src/generated/operations/domains.ts | 12 +- src/generated/operations/drivers.ts | 18 +- src/generated/operations/edges.ts | 34 +- src/generated/operations/flux.ts | 2 +- src/generated/operations/groups-history.ts | 10 +- .../operations/groups-invitations.ts | 22 +- src/generated/operations/groups-users.ts | 22 +- src/generated/operations/groups-zones.ts | 22 +- src/generated/operations/groups.ts | 16 +- src/generated/operations/history.ts | 6 +- src/generated/operations/index.ts | 62 +-- .../operations/ldap-authentications.ts | 22 +- src/generated/operations/map-ai.ts | 30 +- src/generated/operations/metadata.ts | 16 +- src/generated/operations/modules.ts | 32 +- src/generated/operations/mqtt.ts | 4 +- .../operations/oauth-applications.ts | 22 +- .../operations/oauth-authentications.ts | 22 +- src/generated/operations/pending-mails.ts | 26 +- src/generated/operations/playlist-media.ts | 46 +- src/generated/operations/playlist.ts | 30 +- src/generated/operations/public-events.ts | 14 +- .../operations/push-notifications.ts | 10 +- src/generated/operations/repositories.ts | 40 +- src/generated/operations/root.ts | 16 +- .../operations/saml-authentications.ts | 22 +- src/generated/operations/schema.ts | 10 +- src/generated/operations/settings.ts | 12 +- src/generated/operations/short-url.ts | 38 +- .../operations/signage-ai-providers.ts | 27 +- src/generated/operations/signage-ai.ts | 34 +- src/generated/operations/signage-plugins.ts | 22 +- .../operations/signage-template-mappings.ts | 22 +- src/generated/operations/signage-templates.ts | 42 +- src/generated/operations/signage.ts | 10 +- src/generated/operations/storages.ts | 10 +- src/generated/operations/system-triggers.ts | 22 +- src/generated/operations/systems.ts | 36 +- src/generated/operations/tenant-consent.ts | 14 +- src/generated/operations/triggers.ts | 12 +- src/generated/operations/uploads.ts | 24 +- src/generated/operations/url-proxy.ts | 6 +- src/generated/operations/users.ts | 26 +- src/generated/operations/web-rtc.ts | 34 +- src/generated/operations/webhook.ts | 2 +- src/generated/operations/zones.ts | 18 +- .../staff/operations/asset-categories.ts | 22 +- .../staff/operations/asset-purchase-orders.ts | 22 +- src/generated/staff/operations/asset-types.ts | 22 +- src/generated/staff/operations/assets.ts | 18 +- src/generated/staff/operations/bookings.ts | 56 +-- src/generated/staff/operations/calendars.ts | 8 +- src/generated/staff/operations/desks.ts | 8 +- src/generated/staff/operations/events.ts | 50 +- src/generated/staff/operations/groups.ts | 6 +- src/generated/staff/operations/guests.ts | 22 +- .../staff/operations/health-check.ts | 6 +- src/generated/staff/operations/index.ts | 14 +- src/generated/staff/operations/place.ts | 2 +- src/generated/staff/operations/spaces.ts | 14 +- src/generated/staff/operations/staff.ts | 14 +- .../staff/operations/surveys-answers.ts | 10 +- .../staff/operations/surveys-invitations.ts | 22 +- .../staff/operations/surveys-questions.ts | 22 +- src/generated/staff/operations/surveys.ts | 10 +- src/generated/staff/operations/teams.ts | 6 +- src/generated/staff/operations/tenants.ts | 20 +- src/generated/staff/operations/users.ts | 2 +- src/index.ts | 2 +- src/migrate/cli.ts | 12 +- src/migrate/migrate.ts | 191 ++++---- src/migrate/v1-map.ts | 294 ++++++------ src/mock/index.ts | 14 +- src/realtime/environment.ts | 6 +- src/realtime/realtime.ts | 189 ++++---- src/staff.ts | 2 +- test/auth.test.ts | 76 ++-- test/client.test.ts | 45 +- test/compat.test.ts | 16 +- test/migrate.test.ts | 8 +- test/mock.test.ts | 20 +- test/pagination.test.ts | 11 +- test/realtime.test.ts | 16 +- test/style.test.ts | 4 +- 108 files changed, 1871 insertions(+), 1837 deletions(-) diff --git a/README.md b/README.md index a809fa5cc..670af9329 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ import { configure, zones } from '@placeos/ts-client'; // Do this one time, when the application starts. configure({ - baseUrl: 'https://placeos.example.com', // Use '' for the origin of the page. + base_url: 'https://placeos.example.com', // Use '' for the origin of the page. auth: { kind: 'bearer', token: () => localStorage.getItem('token') }, }); @@ -36,9 +36,11 @@ if (result.ok) { ``` There is one namespace for each controller of the API, for example `zones`, `systems` and -`users`. Each function has the name of the server action: `show`, `create`, `update`, `destroy`, -or a custom action such as `systems.execute`. The `index` action is `query`, because a list -operation queries the items. The comment of each function gives the HTTP method and the path. +`alert_dashboards`. Namespaces, options and fields are snake_case, as the data of the server is. +Functions are camelCase. Each function has the name of the server action: `show`, `create`, +`update`, `destroy`, or a custom action such as `systems.execute`. The `index` action is `query`, +because a list operation queries the items. The comment of each function gives the HTTP method and +the path. The first argument has the path parameters, the query parameters and, for an operation with a body, `body`. The second argument has the options of the request: @@ -61,10 +63,10 @@ A function does not throw for an expected failure. It returns a `Result`. Examin | -------------------- | -------------------------------------------------------------------------- | | `http` | The server sent a status that is not 2xx. See `status`, `message`, `body`. | | `network` | The request got no response. For example, the network is down. | -| `timeout` | The request took more than `timeoutMs`. | +| `timeout` | The request took more than `timeout_ms`. | | `aborted` | The `signal` of the caller cancelled the request. | | `auth_missing` | The auth had no token or credential. | -| `response_too_large` | The body was more than `responseBytesMax`. | +| `response_too_large` | The body was more than `response_bytes_max`. | | `response_invalid` | The body does not match the API document. See `path` and `expected`. | A function throws only for a programmer error. For example, a parameter that the operation does @@ -79,7 +81,7 @@ In a project without `strictNullChecks`, `if (!result.ok)` does not narrow the ` with `createClient` and give it in the options. The configured client does not change: ```ts -const other = createClient({ baseUrl: 'https://other.example.com', auth: { kind: 'none' } }); +const other = createClient({ base_url: 'https://other.example.com', auth: { kind: 'none' } }); await zones.query({}, { client: other }); ``` @@ -89,9 +91,9 @@ Each request has a time limit. The default is 30 seconds. Set a different limit for one request: ```ts -configure({ baseUrl: '', auth: { kind: 'none' }, timeoutMs: 10_000 }); +configure({ base_url: '', auth: { kind: 'none' }, timeout_ms: 10_000 }); const controller = new AbortController(); -await zones.query({}, { signal: controller.signal, timeoutMs: 60_000 }); +await zones.query({}, { signal: controller.signal, timeout_ms: 60_000 }); ``` ### Pages @@ -103,7 +105,7 @@ import { pageInfo, zones } from '@placeos/ts-client'; const result = await zones.query({ limit: 100 }); if (result.ok) { - const { total, nextOffset } = pageInfo(result.value.headers); + const { total, next_offset } = pageInfo(result.value.headers); } ``` @@ -114,7 +116,7 @@ its own client in the options, so it does not change the configured client: ```ts const client = createClient({ - baseUrl: '', + base_url: '', auth: { kind: 'none' }, fetch: async (url, init) => new Response(JSON.stringify({ id: 'zone-1' })), }); @@ -129,11 +131,11 @@ the name of the endpoint, the input that the handler gets, and the data that it ```ts import { endpointMocks, httpError, mockEndpoint, respond } from '@placeos/ts-client/mock'; -configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); +configure({ base_url: '', auth: { kind: 'none' }, mock: endpointMocks }); mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 1 })); -mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delayMs: 300 }); +mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { delay_ms: 300 }); mockEndpoint('zones.destroy', () => { throw httpError(403); }); @@ -174,16 +176,16 @@ registerMockEndpoint({ }); registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); -configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch, missingFields: 'zero' }); +configure({ base_url: '', auth: { kind: 'none' }, fetch: mockFetch, missing_fields: 'zero' }); const realtime = createRealtime({ - baseUrl: '', + base_url: '', auth: { kind: 'none' }, environment: mockRealtimeEnvironment(), }); ``` - 7.x parses each mock response with the schema of the operation. Mock data often has only some - fields. `missingFields: 'zero'` gives each missing required field its empty value, such as `''`, + fields. `missing_fields: 'zero'` gives each missing required field its empty value, such as `''`, `0` or `[]`, as the 6.x classes did. A field with the wrong type is still an error, because the real server does not send it. - A mock endpoint that throws an error with a `status`, such as `404`, gives that HTTP status. @@ -216,12 +218,12 @@ const result = await bookings.query({ period_start: now, period_end: now + 86_40 import { configure, createAuthSession } from '@placeos/ts-client'; const session = createAuthSession({ - baseUrl: '', - redirectUri: `${location.origin}/oauth-resp.html`, + base_url: '', + redirect_uri: `${location.origin}/oauth-resp.html`, scope: 'public', grant: { kind: 'code' }, }); -configure({ baseUrl: '', auth: session.clientAuth, headers: { 'X-App-Id': session.clientId } }); +configure({ base_url: '', auth: session.client_auth, headers: { 'X-App-Id': session.client_id } }); const result = await session.start(); if (!result.ok && result.error.kind === 'redirecting') { @@ -229,8 +231,8 @@ if (!result.ok && result.error.kind === 'redirecting') { } ``` -Copy `oauth-resp.html` from the package to your application, and use its URL as `redirectUri`. The -client ID is the MD5 of `redirectUri`, as in 6.x. +Copy `oauth-resp.html` from the package to your application, and use its URL as `redirect_uri`. The +client ID is the MD5 of `redirect_uri`, as in 6.x. `session.start()` loads `/auth/authority`, and gets a credential in this order: @@ -238,9 +240,9 @@ client ID is the MD5 of `redirectUri`, as in 6.x. 2. A code or a token from the redirect. The `state` must be the nonce of this client. 3. The refresh token. 4. The `password` or `entra` grant. -5. If the user has a session: the authorize page, with a redirect or, with `useFrame`, in a +5. If the user has a session: the authorize page, with a redirect or, with `use_frame`, in a hidden frame. -6. Else the login page of the authority. With `handleLogin: false`, the result is a +6. Else the login page of the authority. With `handle_login: false`, the result is a `login_required` error, and the application shows its own login. The grants are `code` (with PKCE), `implicit`, `password` and `entra`. PlaceOS auth.cr refuses @@ -266,7 +268,7 @@ Other parts of the session: - The session keeps the storage keys of 6.x, so a user stays logged in after the change. - The default token path is `/auth/oauth/token`. PlaceOS auth.cr and the older Ruby auth service both serve it. The Ruby auth service does not serve `/auth/token`. -- A relative login or logout URL of the authority is on `baseUrl`. 6.x used the `domain` of the +- A relative login or logout URL of the authority is on `base_url`. 6.x used the `domain` of the authority, which has no port. - A refused code stops the login with `token_rejected`. A new redirect could loop. - The token requests send their parameters in the body, not in the URL. A password is not in the @@ -291,7 +293,7 @@ modules, calls their functions and gets their logs: ```ts import { createRealtime } from '@placeos/ts-client'; -const realtime = createRealtime({ baseUrl: '', auth: session.clientAuth }); +const realtime = createRealtime({ base_url: '', auth: session.client_auth }); const power = { sys: 'sys-1234', mod: 'Display', index: 1, name: 'power' }; const release = realtime.bind(power, (state) => { @@ -312,7 +314,7 @@ release(); - The client sends `ping` each 15 seconds. A socket without a message for 60 seconds closes, and the client connects again. It waits longer after each failure, to 5 seconds. After 40 attempts, the status is `failed`. Call `start` to try again. -- `realtime.debug({ sys, moduleId }, listener)` gets the logs of a module. +- `realtime.debug({ sys, module_id }, listener)` gets the logs of a module. - `splitModuleId('Display_2')` gives `{ mod: 'Display', index: 2 }`. - In a browser, the token goes in a cookie on the socket path. In a frame and on mobile Safari it goes in the query, as in 6.x. `createRealtime({ ..., environment })` replaces the socket, the @@ -456,7 +458,7 @@ The tool makes these changes: - A call of a 6.x REST function becomes the 7.x operation. `.then(orThrow)` gives the data, and an error rejects the promise, as in 6.x. A 6.x query function gets `.then(orThrowPage)`, which gives - `{ data, total, nextOffset }`. + `{ data, total, next_offset }`. ```ts // 6.x @@ -497,7 +499,7 @@ it keeps its 6.x import, so the compiler also shows it. These uses are: - the login and the realtime functions, such as `setup`, `token` and `getModule`; - `get`, `post` and the other HTTP functions; - `new` and `instanceof` on a 6.x class, because 7.x has plain objects; -- the `next` function of a 6.x page. 7.x gives `nextOffset`; +- the `next` function of a 6.x page. 7.x gives `next_offset`; - a function that is not called, out of a test; - a `vi.mock` without a factory or `{ spy: true }`: its 7.x functions give `undefined`, and `.then(orThrow)` fails; @@ -533,7 +535,7 @@ arguments, and it finds the 7.x operation with the same method and path. from 6.x. - The 6.x mock types of `@placeos/ts-client/compat` (`MockHttpRequest.body`, `metadata` and `MockModule`) keep `any`, so that the mocks of an app still compile. -- `missingFields: 'zero'` accepts data without its required fields. It is for mock data only. +- `missing_fields: 'zero'` accepts data without its required fields. It is for mock data only. - `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove that the parser output has the type of the schema. The tests check the parser. - `configure` keeps one client in module state, so a call does not need a client argument. A diff --git a/scripts/generate.ts b/scripts/generate.ts index 1f7d5bc1f..f6b906c6b 100644 --- a/scripts/generate.ts +++ b/scripts/generate.ts @@ -160,12 +160,12 @@ const VALUE_ENUM_FIELDS: ReadonlyMap> interface ValueEnum { /** The enum schema of the document that the field refers to now. */ - readonly specName: string; + readonly spec_name: string; readonly values: Readonly>; } -function valueEnum(specName: string, values: Readonly>): ValueEnum { - return { specName, values }; +function valueEnum(spec_name: string, values: Readonly>): ValueEnum { + return { spec_name, values }; } /** Operations that send JSON, but have no response schema in the document. */ @@ -311,21 +311,21 @@ type SpecNode = Readonly>; /** One endpoint, ready to write. */ interface OperationPlan { - readonly operationId: string; + readonly operation_id: string; readonly controller: string; readonly action: string; readonly method: (typeof METHODS)[number]; readonly path: string; - readonly pathKeys: readonly string[]; + readonly path_keys: readonly string[]; readonly summary: string; readonly description: string; /** Code of the expressions. */ readonly params: string; - readonly paramsRequired: boolean; + readonly params_required: boolean; readonly body: string | null; readonly response: string | null; /** Input key to query name, from `PARAMETER_KEYS`. */ - readonly wireNames: Readonly>; + readonly wire_names: Readonly>; readonly imports: Imports; } @@ -341,9 +341,9 @@ interface ApiSource { readonly repository: string; readonly dir: string; /** The part of each `operationId` before the controller, such as `PlaceOS::Api::`. */ - readonly idPrefix: string; + readonly id_prefix: string; /** The part of each operation name before the namespace, such as `staff.`. */ - readonly namePrefix: string; + readonly name_prefix: string; /** The path from `dir` to `src/core`. */ readonly core: string; readonly aliases: ReadonlyMap; @@ -353,16 +353,16 @@ const APIS: readonly ApiSource[] = [ { repository: 'PlaceOS/rest-api', dir: join(ROOT, 'src', 'generated'), - idPrefix: 'PlaceOS::Api::', - namePrefix: '', + id_prefix: 'PlaceOS::Api::', + name_prefix: '', core: '../core', aliases: TYPE_ALIASES, }, { repository: 'PlaceOS/staff-api', dir: join(ROOT, 'src', 'generated', 'staff'), - idPrefix: '', - namePrefix: 'staff.', + id_prefix: '', + name_prefix: 'staff.', core: '../../core', aliases: new Map(), }, @@ -387,9 +387,9 @@ function header(api: ApiSource): string { /** Generates the code of one API. Returns the files that changed, or that would change. */ async function generate(api: ApiSource, check: boolean): Promise { - const operationsDir = join(api.dir, 'operations'); - const specText = await downloadSpec(api); - const spec = asNode(Bun.YAML.parse(specText), 'the document'); + const operations_dir = join(api.dir, 'operations'); + const spec_text = await downloadSpec(api); + const spec = asNode(Bun.YAML.parse(spec_text), 'the document'); assert(asString(field(spec, 'openapi'), 'openapi').startsWith('3.'), 'the document is 3.x'); const components = asNode(field(spec, 'components'), 'components'); const schemas = asNode(field(components, 'schemas'), 'components.schemas'); @@ -398,16 +398,16 @@ async function generate(api: ApiSource, check: boolean): Promise { // Read each operation. The emit of its schemas collects the named schemas that it uses. const operations: OperationPlan[] = []; const skipped: string[] = []; - for (const [path, itemValue] of Object.entries(paths)) { - const item = asNode(itemValue, `paths.${path}`); + for (const [path, item_value] of Object.entries(paths)) { + const item = asNode(item_value, `paths.${path}`); for (const key of Object.keys(item)) { const known = PATH_ITEM_KEYS.has(key) || METHODS.some((method) => method === key); assert(known, `the key "${key}" of the path ${path} is supported`); } for (const method of METHODS) { - const operationValue = field(item, method); - if (operationValue === undefined) continue; - const plan = planOperation(api, schemas, path, method, asNode(operationValue, path)); + const operation_value = field(item, method); + if (operation_value === undefined) continue; + const plan = planOperation(api, schemas, path, method, asNode(operation_value, path)); if (plan === null) { skipped.push(`${method.toUpperCase()} ${path}`); } else { @@ -423,27 +423,27 @@ async function generate(api: ApiSource, check: boolean): Promise { const named = new Map(); const pending: string[] = []; for (const plan of kept) pending.push(...plan.imports.schemas); - const schemaNames = new Map(); - const generatedNames = new Set(); - for (const specName of Object.keys(schemas)) { - if (!isNamedSchema(specName)) continue; - const name = schemaTypeName(specName); + const schema_names = new Map(); + const generated_names = new Set(); + for (const spec_name of Object.keys(schemas)) { + if (!isNamedSchema(spec_name)) continue; + const name = schemaTypeName(spec_name); for (const generated of [name, `${name}Input`, `${name}Schema`]) { - assert(!generatedNames.has(generated), `the schema name ${generated} is unique`); + assert(!generated_names.has(generated), `the schema name ${generated} is unique`); assert(!CORE_NAMES.has(generated), `the schema name ${generated} is not a core name`); - generatedNames.add(generated); + generated_names.add(generated); } - schemaNames.set(name, specName); + schema_names.set(name, spec_name); } for (let index = 0; index < pending.length; index += 1) { - assert(index <= schemaNames.size * schemaNames.size, 'the schema queue is bounded'); + assert(index <= schema_names.size * schema_names.size, 'the schema queue is bounded'); const name = pending[index] ?? ''; if (named.has(name)) continue; - const specName = schemaNames.get(name); - assert(specName !== undefined, `the schema ${name} exists`); + const spec_name = schema_names.get(name); + assert(spec_name !== undefined, `the schema ${name} exists`); const imports: Imports = { combinators: new Set(), schemas: new Set() }; - const node = asNode(field(schemas, specName), specName); - const code = emitNamedSchema(schemas, specName, node, imports); + const node = asNode(field(schemas, spec_name), spec_name); + const code = emitNamedSchema(schemas, spec_name, node, imports); named.set(name, { code, imports }); pending.push(...imports.schemas); } @@ -459,45 +459,45 @@ async function generate(api: ApiSource, check: boolean): Promise { const namespaces: string[] = []; for (const controller of [...controllers.keys()].sort()) { const plans = controllers.get(controller) ?? []; - const fileName = kebabCase(controllerWords(controller)); + const file_name = kebabCase(controllerWords(controller)); files.set( - join(operationsDir, `${fileName}.ts`), + join(operations_dir, `${file_name}.ts`), writeOperationsFile(api, controller, plans), ); namespaces.push( - `export * as ${camelCase(controllerWords(controller))} from './${fileName}.ts';`, + `export * as ${snakeCase(controllerWords(controller))} from './${file_name}.ts';`, ); } - const indexIntro = '/** One namespace for each controller of the API. */'; + const index_intro = '/** One namespace for each controller of the API. */'; files.set( - join(operationsDir, 'index.ts'), - `${header(api)}\n${indexIntro}\n${namespaces.join('\n')}\n`, + join(operations_dir, 'index.ts'), + `${header(api)}\n${index_intro}\n${namespaces.join('\n')}\n`, ); // Format, then write or compare. const config = (await resolveConfig(join(ROOT, 'package.json'))) ?? {}; const stale: string[] = []; - for (const [filePath, code] of files) { + for (const [file_path, code] of files) { const annotated = markPure(code); const formatted = wrapLongComments( - await format(annotated, { ...config, filepath: filePath }), + await format(annotated, { ...config, filepath: file_path }), ); - const current = await readFile(filePath, 'utf8').catch(() => null); + const current = await readFile(file_path, 'utf8').catch(() => null); if (current === formatted) continue; - stale.push(filePath); + stale.push(file_path); if (!check) { - await mkdir(join(filePath, '..'), { recursive: true }); - await writeFile(filePath, formatted); + await mkdir(join(file_path, '..'), { recursive: true }); + await writeFile(file_path, formatted); } } // Remove generated files of controllers that the document does not have now. - for (const entry of await readdir(operationsDir).catch(() => [])) { - const filePath = join(operationsDir, entry); - if (files.has(filePath)) continue; - const text = await readFile(filePath, 'utf8'); - assert(text.startsWith(header(api)), `${filePath} is a generated file`); - stale.push(filePath); - if (!check) await rm(filePath); + for (const entry of await readdir(operations_dir).catch(() => [])) { + const file_path = join(operations_dir, entry); + if (files.has(file_path)) continue; + const text = await readFile(file_path, 'utf8'); + assert(text.startsWith(header(api)), `${file_path} is a generated file`); + stale.push(file_path); + if (!check) await rm(file_path); } console.log( @@ -515,9 +515,9 @@ async function downloadSpec(api: ApiSource): Promise { const url = `https://raw.githubusercontent.com/${api.repository}/refs/heads/master/OPENAPI_DOC.yml`; const response = await fetch(url, { signal: AbortSignal.timeout(SPEC_TIMEOUT_MS) }); assert(response.ok, `the download of ${url} succeeds (status ${response.status})`); - const lengthText = response.headers.get('content-length'); - if (lengthText !== null) { - assert(Number(lengthText) <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); + const length_text = response.headers.get('content-length'); + if (length_text !== null) { + assert(Number(length_text) <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); } const text = await response.text(); assert(text.length <= SPEC_BYTES_MAX, 'the document is less than SPEC_BYTES_MAX'); @@ -532,97 +532,99 @@ function planOperation( method: (typeof METHODS)[number], operation: SpecNode, ): OperationPlan | null { - const operationId = asString(field(operation, 'operationId'), `${path} operationId`); - const id = operationId.startsWith(api.idPrefix) ? operationId.slice(api.idPrefix.length) : ''; - const idMatch = /^([A-Za-z:]+)_([a-z0-9_]+)$/.exec(id); - assert(idMatch !== null, `${operationId} has the form ${api.idPrefix}Controller_action`); - const controller = idMatch[1] ?? ''; + const operation_id = asString(field(operation, 'operationId'), `${path} operationId`); + const id = operation_id.startsWith(api.id_prefix) + ? operation_id.slice(api.id_prefix.length) + : ''; + const id_match = /^([A-Za-z:]+)_([a-z0-9_]+)$/.exec(id); + assert(id_match !== null, `${operation_id} has the form ${api.id_prefix}Controller_action`); + const controller = id_match[1] ?? ''; // The list action of a controller is `index` in the server. The client calls it `query`. - const action = (idMatch[2] ?? '').replace(/^index(?=_\d+$|$)/, 'query'); + const action = (id_match[2] ?? '').replace(/^index(?=_\d+$|$)/, 'query'); // The success response. The API has one for each operation. - const responses = asNode(field(operation, 'responses'), `${operationId} responses`); + const responses = asNode(field(operation, 'responses'), `${operation_id} responses`); const successes = Object.keys(responses).filter((status) => /^[123]\d\d$/.test(status)); - assert(successes.length === 1, `${operationId} has one success response`); + assert(successes.length === 1, `${operation_id} has one success response`); const status = successes[0] ?? ''; if (status === '101') return null; const imports: Imports = { combinators: new Set(), schemas: new Set() }; let response: string | null = null; - const success = asNode(field(responses, status), `${operationId} ${status}`); + const success = asNode(field(responses, status), `${operation_id} ${status}`); const content = field(success, 'content'); - if (JSON_RESPONSE_OPERATIONS.has(operationId)) { - assert(content === undefined, `${operationId} has no response schema to replace`); + if (JSON_RESPONSE_OPERATIONS.has(operation_id)) { + assert(content === undefined, `${operation_id} has no response schema to replace`); imports.combinators.add('json'); response = 'json()'; } else if (content !== undefined) { - const schema = asNode(jsonContentSchema(content, operationId), `${operationId} schema`); + const schema = asNode(jsonContentSchema(content, operation_id), `${operation_id} schema`); response = emitSchema(schemas, schema, imports, 0); } // The parameters: one object schema with the path parameters and the query parameters. - const pathKeys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1] ?? ''); + const path_keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1] ?? ''); const fields: string[] = []; const required: string[] = []; - const parameterNames = new Set(); - const wireNames: Record = {}; - for (const parameterValue of asArray(field(operation, 'parameters') ?? [], operationId)) { - const parameter = asNode(parameterValue, `${operationId} parameter`); - const name = asString(field(parameter, 'name'), `${operationId} parameter name`); - const location = asString(field(parameter, 'in'), `${operationId} ${name} in`); - assert(location === 'path' || location === 'query', `${operationId} ${name} is supported`); - assert(!parameterNames.has(name), `${operationId} ${name} is unique`); - const key = PARAMETER_KEYS.get(operationId)?.[name] ?? name; - assert(key !== 'body', `${operationId} has no parameter named body, or a key for it`); + const parameter_names = new Set(); + const wire_names: Record = {}; + for (const parameter_value of asArray(field(operation, 'parameters') ?? [], operation_id)) { + const parameter = asNode(parameter_value, `${operation_id} parameter`); + const name = asString(field(parameter, 'name'), `${operation_id} parameter name`); + const location = asString(field(parameter, 'in'), `${operation_id} ${name} in`); + assert(location === 'path' || location === 'query', `${operation_id} ${name} is supported`); + assert(!parameter_names.has(name), `${operation_id} ${name} is unique`); + const key = PARAMETER_KEYS.get(operation_id)?.[name] ?? name; + assert(key !== 'body', `${operation_id} has no parameter named body, or a key for it`); if (key !== name) { - assert(location === 'query', `${operationId} renames only a query parameter`); - wireNames[key] = name; + assert(location === 'query', `${operation_id} renames only a query parameter`); + wire_names[key] = name; } - parameterNames.add(name); + parameter_names.add(name); if (location === 'path') { - assert(pathKeys.includes(name), `${operationId} ${name} is in the path`); + assert(path_keys.includes(name), `${operation_id} ${name} is in the path`); required.push(name); } else if (field(parameter, 'required') === true) { required.push(key); } - const schema = asNode(field(parameter, 'schema'), `${operationId} ${name} schema`); + const schema = asNode(field(parameter, 'schema'), `${operation_id} ${name} schema`); const expression = emitSchema(schemas, schema, imports, 0); const description = optionalString(field(parameter, 'description'), name) ?? ''; fields.push(`${docComment(description, 4)}${propertyKey(key)}: ${expression},`); } - for (const key of pathKeys) { - assert(parameterNames.has(key), `${operationId} has a path parameter ${key}`); + for (const key of path_keys) { + assert(parameter_names.has(key), `${operation_id} has a path parameter ${key}`); } imports.combinators.add('parameters'); - const requiredList = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; - const params = `parameters({\n${fields.join('\n')}\n}${requiredList})`; + const required_list = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; + const params = `parameters({\n${fields.join('\n')}\n}${required_list})`; let body: string | null = null; - const requestBody = field(operation, 'requestBody'); - if (requestBody !== undefined) { - const bodyNode = asNode(requestBody, `${operationId} requestBody`); - assert(field(bodyNode, 'required') === true, `${operationId} requires its body`); + const request_body = field(operation, 'requestBody'); + if (request_body !== undefined) { + const body_node = asNode(request_body, `${operation_id} requestBody`); + assert(field(body_node, 'required') === true, `${operation_id} requires its body`); const schema = asNode( - jsonContentSchema(field(bodyNode, 'content'), operationId), - `${operationId} body schema`, + jsonContentSchema(field(body_node, 'content'), operation_id), + `${operation_id} body schema`, ); body = emitSchema(schemas, schema, imports, 0); } return { - operationId, + operation_id, controller, action, method, path, - pathKeys, - summary: optionalString(field(operation, 'summary'), `${operationId} summary`) ?? '', - description: optionalString(field(operation, 'description'), operationId) ?? '', + path_keys, + summary: optionalString(field(operation, 'summary'), `${operation_id} summary`) ?? '', + description: optionalString(field(operation, 'description'), operation_id) ?? '', params, - paramsRequired: required.length > 0 || body !== null, + params_required: required.length > 0 || body !== null, body, response, - wireNames, + wire_names, imports, }; } @@ -646,23 +648,23 @@ function mergeRoutes(operations: readonly OperationPlan[]): OperationPlan[] { const kept: OperationPlan[] = []; for (const group of groups.values()) { const action = (group[0]?.action ?? '').replace(/_\d+$/, ''); - const byPath = new Map(); - for (const plan of group) byPath.set(plan.path, [...(byPath.get(plan.path) ?? []), plan]); + const by_path = new Map(); + for (const plan of group) by_path.set(plan.path, [...(by_path.get(plan.path) ?? []), plan]); const routes: OperationPlan[] = []; - for (const plans of byPath.values()) { + for (const plans of by_path.values()) { const [first, second] = plans; assert(first !== undefined, 'a path has a plan'); if (second === undefined) { routes.push(first); continue; } - assert(plans.length === 2, `${first.operationId} has at most two methods on its path`); + assert(plans.length === 2, `${first.operation_id} has at most two methods on its path`); assert( sameSignature(first, second), - `${first.operationId} has the same signature as ${second.operationId}`, + `${first.operation_id} has the same signature as ${second.operation_id}`, ); const methods = [first.method, second.method].sort().join(); - assert(methods === 'patch,put', `${first.operationId} is a PATCH and PUT pair`); + assert(methods === 'patch,put', `${first.operation_id} is a PATCH and PUT pair`); routes.push(first.method === 'patch' ? first : second); } const distinct: OperationPlan[] = []; @@ -676,14 +678,14 @@ function mergeRoutes(operations: readonly OperationPlan[]): OperationPlan[] { const [base, ...others] = distinct; assert(base !== undefined, 'an action has a route'); kept.push({ ...base, action }); - const baseSegments = new Set(base.path.split('/')); + const base_segments = new Set(base.path.split('/')); for (const other of others) { const extra = other.path .split('/') - .filter((segment) => !baseSegments.has(segment)) + .filter((segment) => !base_segments.has(segment)) .map((segment) => segment.replace(/[{}]/g, '')); const words = [...new Set(extra)]; - assert(words.length > 0, `${other.operationId} has a path with more segments`); + assert(words.length > 0, `${other.operation_id} has a path with more segments`); kept.push({ ...other, action: `${action}_${words.join('_')}` }); } } @@ -698,48 +700,48 @@ function sameSignature(a: OperationPlan, b: OperationPlan): boolean { /** The emit of a named schema. It applies the time field patches to its properties. */ function emitNamedSchema( schemas: SpecNode, - specName: string, + spec_name: string, node: SpecNode, imports: Imports, ): string { - const epochFields = new Set(EPOCH_FIELDS.get(specName) ?? []); - const stringFields = new Set(STRING_TIME_FIELDS.get(specName) ?? []); - const name = schemaTypeName(specName); - const description = optionalString(field(node, 'description'), specName) ?? ''; + const epoch_fields = new Set(EPOCH_FIELDS.get(spec_name) ?? []); + const string_fields = new Set(STRING_TIME_FIELDS.get(spec_name) ?? []); + const name = schemaTypeName(spec_name); + const description = optionalString(field(node, 'description'), spec_name) ?? ''; // The named interfaces make the declaration files and the editor hovers show `Zone`, not the // full shape at each use. The shape is in the schema only. - const schemaName = `${name}Schema`; + const schema_name = `${name}Schema`; const doc = docComment(description, 0); if (field(node, 'properties') === undefined) { - assert(epochFields.size === 0, `${specName} has the time fields of the patch`); + assert(epoch_fields.size === 0, `${spec_name} has the time fields of the patch`); imports.combinators.add('Output'); imports.combinators.add('Input'); imports.combinators.add('Schema'); return ( - `const ${schemaName} = ${emitSchema(schemas, node, imports, 0)};\n` + - `${doc}export type ${name} = Output;\n` + - `export type ${name}Input = Input;\n` + - `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schemaName};\n` + `const ${schema_name} = ${emitSchema(schemas, node, imports, 0)};\n` + + `${doc}export type ${name} = Output;\n` + + `export type ${name}Input = Input;\n` + + `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schema_name};\n` ); } - const timeFields = { specName, epochFields, stringFields }; - const expression = emitObject(schemas, node, imports, 0, timeFields); + const time_fields = { spec_name, epoch_fields, string_fields }; + const expression = emitObject(schemas, node, imports, 0, time_fields); imports.combinators.add('Output'); imports.combinators.add('Input'); imports.combinators.add('Schema'); return ( - `const ${schemaName} = ${expression};\n` + - `${doc}export interface ${name} extends Output {}\n` + - `export interface ${name}Input extends Input {}\n` + - `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schemaName};\n` + `const ${schema_name} = ${expression};\n` + + `${doc}export interface ${name} extends Output {}\n` + + `export interface ${name}Input extends Input {}\n` + + `${doc}export const ${name}: Schema<${name}, ${name}Input> = ${schema_name};\n` ); } /** The time field decisions of one named schema. */ interface TimeFields { - readonly specName: string; - readonly epochFields: ReadonlySet; - readonly stringFields: ReadonlySet; + readonly spec_name: string; + readonly epoch_fields: ReadonlySet; + readonly string_fields: ReadonlySet; } /** Returns the code of a schema expression, such as `nullable(string())`. */ @@ -749,21 +751,21 @@ function emitSchema(schemas: SpecNode, node: SpecNode, imports: Imports, depth: const ref = field(node, '$ref'); if (ref !== undefined) { - const specName = asString(ref, '$ref').replace('#/components/schemas/', ''); - assert(Object.hasOwn(schemas, specName), `the schema ${specName} exists`); - if (specName === 'JSON.Any') { + const spec_name = asString(ref, '$ref').replace('#/components/schemas/', ''); + assert(Object.hasOwn(schemas, spec_name), `the schema ${spec_name} exists`); + if (spec_name === 'JSON.Any') { imports.combinators.add('json'); return 'json()'; } - if (!isNamedSchema(specName)) { + if (!isNamedSchema(spec_name)) { return emitSchema( schemas, - asNode(field(schemas, specName), specName), + asNode(field(schemas, spec_name), spec_name), imports, depth + 1, ); } - const name = schemaTypeName(specName); + const name = schemaTypeName(spec_name); imports.schemas.add(name); return name; } @@ -784,9 +786,9 @@ function emitSchema(schemas: SpecNode, node: SpecNode, imports: Imports, depth: return `nullable(${inner})`; } - const enumValue = field(node, 'enum'); - if (enumValue !== undefined) { - const values = asArray(enumValue, 'enum'); + const enum_value = field(node, 'enum'); + if (enum_value !== undefined) { + const values = asArray(enum_value, 'enum'); const strings = values.every((value) => typeof value === 'string'); const integers = values.every((value) => Number.isSafeInteger(value)); assert(strings || integers, 'an enum has strings only or integers only'); @@ -795,28 +797,28 @@ function emitSchema(schemas: SpecNode, node: SpecNode, imports: Imports, depth: } const type = field(node, 'type'); - const formatValue = optionalString(field(node, 'format'), 'format'); + const format_value = optionalString(field(node, 'format'), 'format'); switch (type) { case 'string': assert( - formatValue === null || STRING_FORMATS.has(formatValue), - `format ${formatValue}`, + format_value === null || STRING_FORMATS.has(format_value), + `format ${format_value}`, ); imports.combinators.add('string'); return 'string()'; case 'integer': assert( - formatValue === null || INTEGER_FORMATS.has(formatValue), - `format ${formatValue}`, + format_value === null || INTEGER_FORMATS.has(format_value), + `format ${format_value}`, ); imports.combinators.add('integer'); - return formatValue === null || formatValue === 'Int64' + return format_value === null || format_value === 'Int64' ? 'integer()' - : `integer('${formatValue}')`; + : `integer('${format_value}')`; case 'number': assert( - formatValue === null || NUMBER_FORMATS.has(formatValue), - `format ${formatValue}`, + format_value === null || NUMBER_FORMATS.has(format_value), + `format ${format_value}`, ); imports.combinators.add('number'); return 'number()'; @@ -824,10 +826,10 @@ function emitSchema(schemas: SpecNode, node: SpecNode, imports: Imports, depth: imports.combinators.add('boolean'); return 'boolean()'; case 'array': { - const prefixItems = field(node, 'prefixItems'); - if (prefixItems !== undefined) { + const prefix_items = field(node, 'prefixItems'); + if (prefix_items !== undefined) { // A Crystal `Tuple`: a fixed length and no other items. - const list = asArray(prefixItems, 'prefixItems'); + const list = asArray(prefix_items, 'prefixItems'); assert(field(node, 'items') === false, 'a tuple has no other items'); assert(field(node, 'minItems') === list.length, 'a tuple has a fixed length'); assert(field(node, 'maxItems') === list.length, 'a tuple has a fixed length'); @@ -874,7 +876,7 @@ function emitObject( node: SpecNode, imports: Imports, depth: number, - timeFields: TimeFields | null, + time_fields: TimeFields | null, ): string { // A named schema comes here without `emitSchema`, so check its keys here too. An object // with properties cannot also be one of these: the output would ignore them. @@ -893,41 +895,46 @@ function emitObject( const property = asNode(value, `property ${key}`); let description = optionalString(field(property, 'description'), key) ?? ''; let expression: string; - const isTime = isDateTime(property); - const valueEnumField = - timeFields === null ? undefined : VALUE_ENUM_FIELDS.get(timeFields.specName)?.[key]; - if (timeFields === null) { + const is_time = isDateTime(property); + const value_enum_field = + time_fields === null ? undefined : VALUE_ENUM_FIELDS.get(time_fields.spec_name)?.[key]; + if (time_fields === null) { expression = emitSchema(schemas, property, imports, depth + 1); - } else if (valueEnumField !== undefined) { - const target = `#/components/schemas/${valueEnumField.specName}`; - const subject = `${timeFields.specName}.${key}`; + } else if (value_enum_field !== undefined) { + const target = `#/components/schemas/${value_enum_field.spec_name}`; + const subject = `${time_fields.spec_name}.${key}`; assertPatchedShape(property, (node) => isOnly(node, { $ref: target }), subject); // A new member of the enum needs its number in the patch. - const enumNode = asNode(field(schemas, valueEnumField.specName), 'the patched enum'); - assertSupportedKeys(enumNode); + const enum_node = asNode( + field(schemas, value_enum_field.spec_name), + 'the patched enum', + ); + assertSupportedKeys(enum_node); assert( - isOnly(enumNode, { type: 'string', enum: field(enumNode, 'enum') }), - `${valueEnumField.specName} is a string enum and nothing else`, + isOnly(enum_node, { type: 'string', enum: field(enum_node, 'enum') }), + `${value_enum_field.spec_name} is a string enum and nothing else`, + ); + const members = asArray(field(enum_node, 'enum'), 'the patched enum values').map( + String, ); - const members = asArray(field(enumNode, 'enum'), 'the patched enum values').map(String); - const mapped = Object.keys(valueEnumField.values); + const mapped = Object.keys(value_enum_field.values); assert( [...members].sort().join() === [...mapped].sort().join(), - `the numbers of ${valueEnumField.specName} cover each member of the enum`, + `the numbers of ${value_enum_field.spec_name} cover each member of the enum`, ); imports.combinators.add('literal'); - expression = `literal(${JSON.stringify(Object.values(valueEnumField.values))})`; + expression = `literal(${JSON.stringify(Object.values(value_enum_field.values))})`; if (isNullable(property)) { imports.combinators.add('nullable'); expression = `nullable(${expression})`; } - const names = Object.entries(valueEnumField.values).map(([n, v]) => `${v} ${n}`); + const names = Object.entries(value_enum_field.values).map(([n, v]) => `${v} ${n}`); const separator = description.length > 0 ? '\n\n' : ''; description = `${description}${separator}The number of the enum: ${names.join(', ')}.`; - } else if (timeFields.epochFields.has(key)) { - const subject = `${timeFields.specName}.${key}`; - const dateTime = { type: 'string', format: 'date-time' }; - assertPatchedShape(property, (node) => isOnly(node, dateTime), subject); + } else if (time_fields.epoch_fields.has(key)) { + const subject = `${time_fields.spec_name}.${key}`; + const date_time = { type: 'string', format: 'date-time' }; + assertPatchedShape(property, (node) => isOnly(node, date_time), subject); imports.combinators.add('integer'); expression = 'integer()'; if (isNullable(property)) { @@ -937,20 +944,20 @@ function emitObject( const separator = description.length > 0 ? '\n\n' : ''; description = `${description}${separator}Unix time in seconds.`; } else { - const known = timeFields.stringFields.has(key); - assert(isTime === known, `${timeFields.specName}.${key} has a time decision`); + const known = time_fields.string_fields.has(key); + assert(is_time === known, `${time_fields.spec_name}.${key} has a time decision`); expression = emitSchema(schemas, property, imports, depth + 1); } fields.push(`${docComment(description, 4)}${propertyKey(key)}: ${expression},`); } - if (timeFields !== null) { - const keys = [...timeFields.epochFields, ...timeFields.stringFields]; - keys.push(...Object.keys(VALUE_ENUM_FIELDS.get(timeFields.specName) ?? {})); + if (time_fields !== null) { + const keys = [...time_fields.epoch_fields, ...time_fields.string_fields]; + keys.push(...Object.keys(VALUE_ENUM_FIELDS.get(time_fields.spec_name) ?? {})); for (const key of keys) assert(Object.hasOwn(properties, key), `${key} is a property`); } imports.combinators.add('object'); - const requiredList = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; - return `object({\n${fields.join('\n')}\n}${requiredList})`; + const required_list = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; + return `object({\n${fields.join('\n')}\n}${required_list})`; } function assertSupportedKeys(node: SpecNode): void { @@ -1010,11 +1017,11 @@ function isNullable(node: SpecNode): boolean { ); } -function jsonContentSchema(content: unknown, operationId: string): unknown { - const contentNode = asNode(content, `${operationId} content`); - const types = Object.keys(contentNode); - assert(types.join() === 'application/json', `${operationId} has JSON content only`); - return field(asNode(field(contentNode, 'application/json'), operationId), 'schema'); +function jsonContentSchema(content: unknown, operation_id: string): unknown { + const content_node = asNode(content, `${operation_id} content`); + const types = Object.keys(content_node); + assert(types.join() === 'application/json', `${operation_id} has JSON content only`); + return field(asNode(field(content_node, 'application/json'), operation_id), 'schema'); } function writeSchemasFile( @@ -1071,56 +1078,56 @@ function writeOperationsFile( plans: readonly OperationPlan[], ): string { const combinators = new Set(); - const schemaImports = new Set(); - const functionNames = new Set(); + const schema_imports = new Set(); + const function_names = new Set(); const blocks: string[] = []; for (const plan of [...plans].sort((a, b) => a.action.localeCompare(b.action, 'en'))) { for (const name of plan.imports.combinators) combinators.add(name); - for (const name of plan.imports.schemas) schemaImports.add(name); - const functionName = camelCase(plan.action.split('_')); - assert(!RESERVED_WORDS.has(functionName), `${functionName} is not a reserved word`); - assert(!functionNames.has(functionName), `${controller}.${functionName} is unique`); - functionNames.add(functionName); + for (const name of plan.imports.schemas) schema_imports.add(name); + const function_name = camelCase(plan.action.split('_')); + assert(!RESERVED_WORDS.has(function_name), `${function_name} is not a reserved word`); + assert(!function_names.has(function_name), `${controller}.${function_name} is unique`); + function_names.add(function_name); const constant = plan.action.toUpperCase(); const method = plan.method.toUpperCase(); const text = [sentence(plan.summary), plan.description, `\`${method} ${plan.path}\``] .filter((part) => part.length > 0) .join('\n\n'); - const inputDefault = plan.paramsRequired ? '' : ' = {}'; + const input_default = plan.params_required ? '' : ' = {}'; blocks.push( - `${docComment(text, 0)}export function ${functionName}(\n` + - `input: OperationInput${inputDefault},\n` + + `${docComment(text, 0)}export function ${function_name}(\n` + + `input: OperationInput${input_default},\n` + `options?: CallOptions,\n` + `): Promise> {\n` + `return call(${constant}, input, options);\n}\n\n` + `const ${constant} = operation({\n` + `method: '${method}',\n` + `path: '${plan.path}',\n` + - `pathKeys: ${JSON.stringify(plan.pathKeys)},\n` + + `path_keys: ${JSON.stringify(plan.path_keys)},\n` + `params: ${plan.params},\n` + `body: ${plan.body ?? 'null'},\n` + `response: ${plan.response ?? 'null'},\n` + - `name: '${api.namePrefix}${camelCase(controllerWords(controller))}.${functionName}',\n` + - (Object.keys(plan.wireNames).length > 0 - ? `wireNames: ${JSON.stringify(plan.wireNames)},\n` + `name: '${api.name_prefix}${snakeCase(controllerWords(controller))}.${function_name}',\n` + + (Object.keys(plan.wire_names).length > 0 + ? `wire_names: ${JSON.stringify(plan.wire_names)},\n` : '') + `});\n`, ); } - const namespace = camelCase(controllerWords(controller)); + const namespace = snakeCase(controllerWords(controller)); const intro = `/**\n * The \`${controller}\` controller of the API. Import it as the \`${namespace}\` ` + `namespace.\n *\n * @module\n */\n`; - const schemaLine = - schemaImports.size > 0 - ? `import { ${[...schemaImports].sort().join(', ')} } from '../schemas.ts';\n` + const schema_line = + schema_imports.size > 0 + ? `import { ${[...schema_imports].sort().join(', ')} } from '../schemas.ts';\n` : ''; return ( `${header(api)}${intro}` + `import { call, operation, type CallOptions, type CallResult, ` + `type OperationInput } from '../${api.core}/client.ts';\n` + importLine([...combinators], `../${api.core}/schema.ts`) + - `${schemaLine}\n${blocks.join('\n')}` + `${schema_line}\n${blocks.join('\n')}` ); } @@ -1132,14 +1139,14 @@ function importLine(names: readonly string[], from: string): string { } /** True for a schema of the document that gets a name in the output. */ -function isNamedSchema(specName: string): boolean { - if (INLINE_SCHEMA_NAMES.has(specName)) return false; - return /^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)*$/.test(specName); +function isNamedSchema(spec_name: string): boolean { + if (INLINE_SCHEMA_NAMES.has(spec_name)) return false; + return /^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)*$/.test(spec_name); } /** `PlaceOS.Model.Playlist.Item` becomes `PlaylistItem`. Acronyms become words: `UserJwt`. */ -function schemaTypeName(specName: string): string { - let name = specName; +function schemaTypeName(spec_name: string): string { + let name = spec_name; for (const prefix of ['PlaceOS.Model.', 'PlaceOS.Api.', 'PlaceOS.Core.Client.', 'PlaceOS.']) { if (name.startsWith(prefix)) { name = name.slice(prefix.length); @@ -1174,6 +1181,11 @@ function camelCase(words: readonly string[]): string { return name.charAt(0).toLowerCase() + name.slice(1); } +/** The name of a namespace, such as `alert_dashboards`. */ +function snakeCase(words: readonly string[]): string { + return words.join('_'); +} + function kebabCase(words: readonly string[]): string { return words.join('-'); } diff --git a/scripts/v1-map.ts b/scripts/v1-map.ts index 161b35233..586ef1db9 100644 --- a/scripts/v1-map.ts +++ b/scripts/v1-map.ts @@ -68,7 +68,7 @@ interface V2Operation { readonly method: string; readonly segments: readonly string[]; readonly params: ReadonlySet; - readonly hasBody: boolean; + readonly has_body: boolean; /** `true` when the response is an array. */ readonly list: boolean; /** The named schema of the response data, or of its items, such as `Zone`. */ @@ -186,7 +186,7 @@ async function main(): Promise { * The exports of `src/compat` that 6.x also has, with `value` or `type`. The enums are generated * into `src/compat/enums.ts` by this script, so they count before the file exists. */ -function readCompatExports(v1Names: ReadonlySet): Record { +function readCompatExports(v1_names: ReadonlySet): Record { const program = ts.createProgram([COMPAT_INDEX], { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.Preserve, @@ -198,12 +198,12 @@ function readCompatExports(v1Names: ReadonlySet): Record = {}; - for (const exported of checker.getExportsOfModule(moduleSymbol)) { + for (const exported of checker.getExportsOfModule(module_symbol)) { const name = exported.getName(); - if (!v1Names.has(name)) continue; + if (!v1_names.has(name)) continue; const symbol = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; compat[name] = symbol.flags & ts.SymbolFlags.Value ? 'value' : 'type'; @@ -226,11 +226,11 @@ function readV1Enums(): Map { if (NOT_REST.test(relative(V1_SOURCE, declaration.getSourceFile().fileName))) continue; const members = declaration.members.map((member) => { const key = member.name.getText(); - const v1Value = checker.getConstantValue(member); - assert(v1Value !== undefined, `${name}.${key} has a constant value`); + const v1_value = checker.getConstantValue(member); + assert(v1_value !== undefined, `${name}.${key} has a constant value`); const numbers = NUMBER_ENUMS[name]; - if (numbers === undefined) return { key, value: v1Value }; - const value = numbers[String(v1Value)]; + if (numbers === undefined) return { key, value: v1_value }; + const value = numbers[String(v1_value)]; assert(value !== undefined, `${name}.${key} has a 7.x number`); return { key, value }; }); @@ -283,10 +283,10 @@ function readV1Functions(): V1Function[] { const data = page ? returned?.aliasTypeArguments?.[0] : returned && checker.getAwaitedType(returned); - const modelSymbol = data?.getSymbol(); + const model_symbol = data?.getSymbol(); const model = - modelSymbol !== undefined && modelSymbol.flags & ts.SymbolFlags.Class - ? modelSymbol.getName() + model_symbol !== undefined && model_symbol.flags & ts.SymbolFlags.Class + ? model_symbol.getName() : null; const list = !page && data !== undefined && data !== null && checker.isArrayType(data); functions.push({ name, file, parameters, page, list, model }); @@ -304,10 +304,10 @@ function readV1OtherExports(): string[] { return names; } -let cachedExports: { checker: ts.TypeChecker; exports: Map } | null = null; +let cached_exports: { checker: ts.TypeChecker; exports: Map } | null = null; function v1Exports(): { checker: ts.TypeChecker; exports: Map } { - if (cachedExports !== null) return cachedExports; + if (cached_exports !== null) return cached_exports; const program = ts.createProgram([V1_INDEX], { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, @@ -319,16 +319,16 @@ function v1Exports(): { checker: ts.TypeChecker; exports: Map const checker = program.getTypeChecker(); const source = program.getSourceFile(V1_INDEX); assert(source !== undefined, 'the 6.x index exists'); - const moduleSymbol = checker.getSymbolAtLocation(source); - assert(moduleSymbol !== undefined, 'the 6.x index is a module'); + const module_symbol = checker.getSymbolAtLocation(source); + assert(module_symbol !== undefined, 'the 6.x index is a module'); const exports = new Map(); - for (const exported of checker.getExportsOfModule(moduleSymbol)) { + for (const exported of checker.getExportsOfModule(module_symbol)) { const symbol = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; exports.set(exported.getName(), symbol); } - cachedExports = { checker, exports }; - return cachedExports; + cached_exports = { checker, exports }; + return cached_exports; } function parameterKind(checker: ts.TypeChecker, type: ts.Type): ParameterKind { @@ -368,11 +368,11 @@ async function readV2Operations(dir: string, module: 'staff' | null): Promise(); - for (const [, key = ''] of paramsText.matchAll(/^\s+(\w+): \/\* @__PURE__ \*\//gm)) + for (const [, key = ''] of params_text.matchAll(/^\s+(\w+): \/\* @__PURE__ \*\//gm)) params.add(key); - const hasBody = !/\n {4}body: null,/.test(block); + const has_body = !/\n {4}body: null,/.test(block); const response = (/\n {4}response: (.*),\n/.exec(block)?.[1] ?? '').replaceAll( '/* @__PURE__ */ ', '', @@ -385,7 +385,7 @@ async function readV2Operations(dir: string, module: 'staff' | null): Promise { Reflect.set(globalThis, 'location', location); Reflect.set(globalThis, 'localStorage', memoryStorage()); Reflect.set(globalThis, 'sessionStorage', memoryStorage()); - const httpModule = join(V1_SOURCE, 'http', 'functions.ts'); + const http_module = join(V1_SOURCE, 'http', 'functions.ts'); Bun.plugin({ name: '6.x HTTP recorder', setup(build) { build.onLoad({ filter: /\/src\/http\/functions\.ts$/ }, (args) => { assert( - args.path === httpModule, + args.path === http_module, `only the 6.x HTTP module is replaced: ${args.path}`, ); return { loader: 'js', contents: RECORDER_SOURCE }; @@ -607,7 +607,7 @@ async function mapFunction( } if (request.body !== undefined) { const body = valueTemplate(request.body); - if (operation.hasBody) { + if (operation.has_body) { entries.push({ kind: 'property', key: 'body', value: body }); } else if (body.kind === 'arg' && hasOpenQuery(operation, entries)) { // The API reads these values from the query. 6.x sent them in the body. @@ -644,11 +644,11 @@ async function mapFunction( const input: Template = { kind: 'object', entries }; const used = new Set(); collectArgs(input, used); - const pickIndex = first.reads + const pick_index = first.reads .map((key) => /^s(\d)zq$/.exec(key)?.[1]) .find((index) => index !== undefined); const pick: Template | null = - pickIndex === undefined ? null : { kind: 'arg', index: Number(pickIndex) }; + pick_index === undefined ? null : { kind: 'arg', index: Number(pick_index) }; if (pick !== null) collectArgs(pick, used); const parameters: V1Parameter[] = fn.parameters.map((parameter, index) => { const use = used.has(index) @@ -677,8 +677,8 @@ async function mapFunction( /** `true` when the operation has a query parameter that no other argument gives. */ function hasOpenQuery(operation: V2Operation, entries: readonly ObjectEntry[]): boolean { const given = new Set(entries.map((entry) => (entry.kind === 'property' ? entry.key : ''))); - const pathKeys = operation.segments.map((segment) => /^\{(\w+)\}$/.exec(segment)?.[1]); - return [...operation.params].some((key) => !pathKeys.includes(key) && !given.has(key)); + const path_keys = operation.segments.map((segment) => /^\{(\w+)\}$/.exec(segment)?.[1]); + return [...operation.params].some((key) => !path_keys.includes(key) && !given.has(key)); } /** The operation with this path. A fixed segment is a better match than a `{key}`. */ @@ -690,7 +690,7 @@ function findOperation( // 7.x merges the PUT and PATCH update of a resource into one operation. const methods = method === 'PUT' || method === 'PATCH' ? ['PUT', 'PATCH'] : [method]; let best: V2Operation | null = null; - let bestScore = -1; + let best_score = -1; for (const operation of operations) { if (!methods.includes(operation.method)) continue; if (operation.segments.length !== segments.length) continue; @@ -704,10 +704,10 @@ function findOperation( } score += 2; } - if (!matches || score < bestScore) continue; - assert(score !== bestScore, `one best 7.x operation for ${method} /${segments.join('/')}`); + if (!matches || score < best_score) continue; + assert(score !== best_score, `one best 7.x operation for ${method} /${segments.join('/')}`); best = operation; - bestScore = score; + best_score = score; } return best; } diff --git a/src/auth/environment.ts b/src/auth/environment.ts index c7d0c9e33..0a7a7238d 100644 --- a/src/auth/environment.ts +++ b/src/auth/environment.ts @@ -22,7 +22,7 @@ export interface AuthEnvironment { /** Keeps the tokens of a trusted application, the nonce and the device settings. */ readonly storage: KeyValueStore; /** Keeps values for one tab only: the PKCE verifier and the parameters of a deep link. */ - readonly sessionStorage: KeyValueStore; + readonly session_storage: KeyValueStore; /** The URL of the page now. */ readonly currentUrl: () => string; /** Changes the URL of the page without a navigation, to remove the parameters of a login. */ @@ -41,7 +41,7 @@ export interface AuthEnvironment { */ readonly authorizeInFrame: ( url: string, - timeoutMs: number, + timeout_ms: number, ) => Promise>; /** Calls `listener` when the application comes back to the foreground. Returns the remover. */ readonly onForeground: (listener: () => void) => () => void; @@ -58,11 +58,11 @@ export const FRAME_MESSAGE_TYPE = 'place-os'; */ export function browserEnvironment(storage: 'local' | 'session' = 'local'): AuthEnvironment { assert(typeof window !== 'undefined', 'browserEnvironment runs in a browser'); - const sessionStore = webStorageStore(() => window.sessionStorage); + const session_store = webStorageStore(() => window.sessionStorage); return { fetch: (url, init) => globalThis.fetch(url, init), - storage: storage === 'session' ? sessionStore : webStorageStore(() => window.localStorage), - sessionStorage: sessionStore, + storage: storage === 'session' ? session_store : webStorageStore(() => window.localStorage), + session_storage: session_store, currentUrl: () => window.location.href, replaceUrl: (url) => window.history.replaceState(window.history.state, '', url), navigate: (url) => window.location.assign(url), @@ -175,7 +175,7 @@ function trySetItem(store: Storage, key: string, value: string): boolean { * Opens a hidden frame on `url` and waits for the message of `oauth-resp.html`. The frame, the * listener and the timer are removed on each path. */ -function authorizeInFrame(url: string, timeoutMs: number): Promise> { +function authorizeInFrame(url: string, timeout_ms: number): Promise> { return new Promise((resolve) => { const frame = document.createElement('iframe'); frame.id = 'place-authorize'; @@ -193,7 +193,7 @@ function authorizeInFrame(url: string, timeoutMs: number): Promise finish({ ok: false, error: 'timeout' }), timeoutMs); + const timer = setTimeout(() => finish({ ok: false, error: 'timeout' }), timeout_ms); frame.addEventListener('error', () => finish({ ok: false, error: 'frame_error' })); window.addEventListener('message', onMessage); frame.src = url; diff --git a/src/auth/hash.ts b/src/auth/hash.ts index 8a09a56a6..cb7b3da1e 100644 --- a/src/auth/hash.ts +++ b/src/auth/hash.ts @@ -31,21 +31,21 @@ export function md5Hex(text: string): string { let d = state[3] ?? 0; for (let step = 0; step < 64; step += 1) { let mix: number; - let wordIndex: number; + let word_index: number; if (step < 16) { mix = (b & c) | (~b & d); - wordIndex = step; + word_index = step; } else if (step < 32) { mix = (d & b) | (~d & c); - wordIndex = (5 * step + 1) % 16; + word_index = (5 * step + 1) % 16; } else if (step < 48) { mix = b ^ c ^ d; - wordIndex = (3 * step + 5) % 16; + word_index = (3 * step + 5) % 16; } else { mix = c ^ (b | ~d); - wordIndex = (7 * step) % 16; + word_index = (7 * step) % 16; } - const sum = (a + mix + (MD5_CONSTANTS[step] ?? 0) + (words[wordIndex] ?? 0)) | 0; + const sum = (a + mix + (MD5_CONSTANTS[step] ?? 0) + (words[word_index] ?? 0)) | 0; a = d; d = c; c = b; @@ -139,18 +139,18 @@ type Endian = 'little' | 'big'; /** Adds the padding of MD5 and SHA-256: a 1 bit, zeros, and the bit length in 8 bytes. */ function padBlocks(input: Uint8Array, endian: Endian): Uint8Array { - const blockCount = Math.ceil((input.length + 9) / 64); - const blocks = new Uint8Array(blockCount * 64); + const block_count = Math.ceil((input.length + 9) / 64); + const blocks = new Uint8Array(block_count * 64); blocks.set(input); blocks[input.length] = 0x80; // The input is less than HASH_INPUT_BYTES_MAX, so the bit length fits in 32 bits. - const bitLength = input.length * 8; - assert(bitLength < 2 ** 32, 'the bit length fits in 32 bits'); - const lengthOffset = blocks.length - 8; + const bit_length = input.length * 8; + assert(bit_length < 2 ** 32, 'the bit length fits in 32 bits'); + const length_offset = blocks.length - 8; for (let byte = 0; byte < 4; byte += 1) { - const value = (bitLength >>> (byte * 8)) & 0xff; + const value = (bit_length >>> (byte * 8)) & 0xff; if (endian === 'little') { - blocks[lengthOffset + byte] = value; + blocks[length_offset + byte] = value; } else { blocks[blocks.length - 1 - byte] = value; } diff --git a/src/auth/session.ts b/src/auth/session.ts index 3295812ab..f69f48d0e 100644 --- a/src/auth/session.ts +++ b/src/auth/session.ts @@ -3,12 +3,12 @@ * * ```ts * const session = createAuthSession({ - * baseUrl: '', - * redirectUri: `${location.origin}/oauth-resp.html`, + * base_url: '', + * redirect_uri: `${location.origin}/oauth-resp.html`, * scope: 'public', * grant: { kind: 'code' }, * }); - * configure({ baseUrl: '', auth: session.clientAuth, headers: { 'X-App-Id': session.clientId } }); + * configure({ base_url: '', auth: session.client_auth, headers: { 'X-App-Id': session.client_id } }); * const result = await session.start(); * ``` * @@ -115,7 +115,7 @@ export type Grant = readonly kind: 'password'; readonly username: string; readonly password: string; - readonly clientSecret?: string; + readonly client_secret?: string; } /** * Exchanges a Microsoft Entra access token for PlaceOS tokens (RFC 8693), for applications @@ -124,29 +124,29 @@ export type Grant = | { readonly kind: 'entra'; readonly entraToken: () => Promise; - readonly clientSecret?: string; + readonly client_secret?: string; }; export interface AuthSessionConfig { /** The origin of the server, such as `https://placeos.example.com`. `''` is this origin. */ - readonly baseUrl: string; + readonly base_url: string; /** The redirect page, such as `https://app.example.com/oauth-resp.html`. */ - readonly redirectUri: string; + readonly redirect_uri: string; readonly scope: string; readonly grant: Grant; /** A path on the server, or a full URL. */ - readonly authorizePath?: string; + readonly authorize_path?: string; /** A path on the server, or a full URL. */ - readonly tokenPath?: string; + readonly token_path?: string; /** Opens the authorize page in a hidden frame, not with a redirect. */ - readonly useFrame?: boolean; + readonly use_frame?: boolean; /** * `true` (the default) sends a user without a session to the login page. With `false`, the * result is a `login_required` error, and the application shows its own login. */ - readonly handleLogin?: boolean; + readonly handle_login?: boolean; /** Ignores an API key in the URL or the storage. */ - readonly ignoreApiKey?: boolean; + readonly ignore_api_key?: boolean; /** Headers for each request of the session. The session adds `X-App-Id`. */ readonly headers?: Readonly>; readonly environment?: AuthEnvironment; @@ -212,7 +212,7 @@ export type AuthError = | { readonly kind: 'authority_invalid'; readonly path: string; readonly expected: string } /** The page goes to the login or the authorize page. The application waits. */ | { readonly kind: 'redirecting'; readonly url: string } - /** No session, and `handleLogin` is `false`. Show the login of the application. */ + /** No session, and `handle_login` is `false`. Show the login of the application. */ | { readonly kind: 'login_required' } /** The token endpoint refused the grant, for example a wrong password. */ | { readonly kind: 'token_rejected'; readonly status: number; readonly message: string | null } @@ -236,9 +236,9 @@ export type AuthError = export interface AuthSession { /** The OAuth client ID: the MD5 of the redirect URI, as PlaceOS registers it. */ - readonly clientId: string; + readonly client_id: string; /** Give this to `configure` or `createClient`. */ - readonly clientAuth: Auth; + readonly client_auth: Auth; /** Loads the authority, gets a credential, and watches for the foreground. */ start(): Promise>; /** Stops the watch for the foreground. */ @@ -258,7 +258,7 @@ export interface AuthSession { */ handleRedirect(url: string): Promise>; /** Uses a token from a different source. */ - useToken(token: string, expiresAtMs?: number): void; + useToken(token: string, expires_at_ms?: number): void; /** Uses an API key, for a fixed device. */ useApiKey(key: string, options?: { readonly trusted?: boolean }): void; /** Removes the access token, so the next request gets a new one. */ @@ -272,35 +272,35 @@ export interface AuthSession { } interface Tokens { - readonly accessToken: string | null; - readonly refreshToken: string | null; - readonly expiresAtMs: number; + readonly access_token: string | null; + readonly refresh_token: string | null; + readonly expires_at_ms: number; } -const NO_TOKENS: Tokens = { accessToken: null, refreshToken: null, expiresAtMs: 0 }; +const NO_TOKENS: Tokens = { access_token: null, refresh_token: null, expires_at_ms: 0 }; /** Makes a login session. It does no work until `start`, `authorize` or a request. */ export function createAuthSession(config: AuthSessionConfig): AuthSession { - assert(!config.baseUrl.endsWith('/'), 'the baseUrl has no trailing slash'); - assert(config.redirectUri.length > 0, 'the redirectUri is not empty'); + assert(!config.base_url.endsWith('/'), 'the base_url has no trailing slash'); + assert(config.redirect_uri.length > 0, 'the redirect_uri is not empty'); const environment = config.environment ?? browserEnvironment(); const storage = environment.storage; - const clientId = md5Hex(config.redirectUri); - const handleLogin = config.handleLogin ?? true; - const headers: Readonly> = { ...config.headers, 'X-App-Id': clientId }; - const limits = { timeoutMs: AUTH_TIMEOUT_MS, bytesMax: AUTH_RESPONSE_BYTES_MAX }; - const storageKey = (name: string) => `${clientId}_${name}`; + const client_id = md5Hex(config.redirect_uri); + const handle_login = config.handle_login ?? true; + const headers: Readonly> = { ...config.headers, 'X-App-Id': client_id }; + const limits = { timeout_ms: AUTH_TIMEOUT_MS, bytes_max: AUTH_RESPONSE_BYTES_MAX }; + const storageKey = (name: string) => `${client_id}_${name}`; let authority: DomainAuthority | null = null; let status: AuthStatus = { kind: 'stopped' }; /** The tokens of an application that is not trusted. A trusted one keeps them in storage. */ - let memoryTokens: Tokens = NO_TOKENS; + let memory_tokens: Tokens = NO_TOKENS; /** A code from a redirect. The next `authorize` exchanges it. */ - let pendingCode: string | null = null; + let pending_code: string | null = null; let authorizing: Promise> | null = null; - let loadingAuthority: Promise> | null = null; + let loading_authority: Promise> | null = null; let renewing: Promise | null = null; - let foregroundCheck: Promise | null = null; + let foreground_check: Promise | null = null; let removeForegroundListener: (() => void) | null = null; /** * A login that the user or the server refused: a consent denial or a refused code. Then @@ -313,8 +313,8 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const listeners = new Set<(status: AuthStatus) => void>(); const session: AuthSession = { - clientId, - clientAuth: { + client_id, + client_auth: { kind: 'credential', credential: credentialForRequest, rejected, @@ -365,55 +365,55 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { async function runAuthorize(): Promise> { // A logout during this attempt ends it. Each step checks the epoch after it waits. - const attemptEpoch = epoch; + const attempt_epoch = epoch; // Read the redirect first, before any wait, so its tokens leave the URL also when the // authority does not load. - const redirectOutcome = readRedirectParams(); - if (redirectOutcome.kind === 'denied') { - halted = redirectOutcome.error; - return failed(redirectOutcome.error); + const redirect_outcome = readRedirectParams(); + if (redirect_outcome.kind === 'denied') { + halted = redirect_outcome.error; + return failed(redirect_outcome.error); } if (authority === null) { const loaded = await loadAuthority(); - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (!loaded.ok) return failed(loaded.error); } - const known = await tokenFromKnownCredentials(attemptEpoch); + const known = await tokenFromKnownCredentials(attempt_epoch); // Check the epoch first: a logout during the wait makes even a known credential old. - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (known !== null) return known; const grant = config.grant; switch (grant.kind) { case 'password': { - const result = await requestTokens(attemptEpoch, { + const result = await requestTokens(attempt_epoch, { grant_type: 'password', - client_id: clientId, - redirect_uri: config.redirectUri, + client_id, + redirect_uri: config.redirect_uri, scope: config.scope, username: grant.username, password: grant.password, authority: authority?.id ?? '', - ...(grant.clientSecret === undefined + ...(grant.client_secret === undefined ? {} - : { client_secret: grant.clientSecret }), + : { client_secret: grant.client_secret }), }); return result.ok ? signedIn(result.value) : failed(result.error); } case 'entra': { - const subjectToken = await grant.entraToken(); - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); - if (subjectToken === null) return failed({ kind: 'entra_token_missing' }); - const result = await requestTokens(attemptEpoch, { + const subject_token = await grant.entraToken(); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); + if (subject_token === null) return failed({ kind: 'entra_token_missing' }); + const result = await requestTokens(attempt_epoch, { grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', - client_id: clientId, - subject_token: subjectToken, + client_id, + subject_token, subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', scope: config.scope, - ...(grant.clientSecret === undefined + ...(grant.client_secret === undefined ? {} - : { client_secret: grant.clientSecret }), + : { client_secret: grant.client_secret }), }); return result.ok ? signedIn(result.value) : failed(result.error); } @@ -431,9 +431,9 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { return failed(late.error); } if (late.kind === 'applied') { - const fromLink = await tokenFromKnownCredentials(attemptEpoch); - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); - if (fromLink !== null) return fromLink; + const from_link = await tokenFromKnownCredentials(attempt_epoch); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); + if (from_link !== null) return from_link; } // The user must act. Go to the server one time only, until a redirect comes back. @@ -443,9 +443,9 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { assert(current !== null, 'the authority is loaded'); if (current.session) { const url = createAuthorizeUrl(); - if (config.useFrame !== true) return redirect(url); + if (config.use_frame !== true) return redirect(url); const framed = await environment.authorizeInFrame(url, FRAME_TIMEOUT_MS); - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (!framed.ok) return failed({ kind: 'frame_failed', reason: framed.error }); const message = parseResponse(FrameMessage, framed.value); if (!message.ok) return failed({ kind: 'frame_failed', reason: 'message_invalid' }); @@ -463,12 +463,12 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { default: return unreachable(applied); } - const fromFrame = await tokenFromKnownCredentials(attemptEpoch); - if (epoch !== attemptEpoch) return failed({ kind: 'logged_out' }); - if (fromFrame !== null) return fromFrame; + const from_frame = await tokenFromKnownCredentials(attempt_epoch); + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); + if (from_frame !== null) return from_frame; return failed({ kind: 'frame_failed', reason: 'message_invalid' }); } - if (!handleLogin) return failed({ kind: 'login_required' }); + if (!handle_login) return failed({ kind: 'login_required' }); return redirect(loginUrl(current)); } @@ -477,20 +477,20 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { * a redirect, and the refresh token. Returns `null` if none gives a credential. */ async function tokenFromKnownCredentials( - attemptEpoch: number, + attempt_epoch: number, ): Promise | null> { const current = currentCredential(); if (current !== null) return signedIn(current); - if (pendingCode !== null) { - const code = pendingCode; - pendingCode = null; - const verifier = environment.sessionStorage.get(storageKey('code_verifier')); - environment.sessionStorage.remove(storageKey('code_verifier')); - const result = await requestTokens(attemptEpoch, { + if (pending_code !== null) { + const code = pending_code; + pending_code = null; + const verifier = environment.session_storage.get(storageKey('code_verifier')); + environment.session_storage.remove(storageKey('code_verifier')); + const result = await requestTokens(attempt_epoch, { grant_type: 'authorization_code', - client_id: clientId, - redirect_uri: config.redirectUri, + client_id, + redirect_uri: config.redirect_uri, code, ...(verifier === null ? {} : { code_verifier: verifier }), }); @@ -500,30 +500,30 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { return failed(result.error); } - const refreshToken = readTokens().refreshToken; - if (refreshToken !== null) { - const result = await requestTokens(attemptEpoch, { + const refresh_token = readTokens().refresh_token; + if (refresh_token !== null) { + const result = await requestTokens(attempt_epoch, { grant_type: 'refresh_token', - client_id: clientId, - redirect_uri: config.redirectUri, - refresh_token: refreshToken, + client_id, + redirect_uri: config.redirect_uri, + refresh_token, }); if (result.ok) return signedIn(result.value); if (!isRefusal(result.error)) return failed(result.error); // Keep a refresh token after a network error, but not after the server refused it. - writeTokens({ ...readTokens(), refreshToken: null }); + writeTokens({ ...readTokens(), refresh_token: null }); } return null; } /** Sends a grant to the token endpoint and keeps the tokens of the response. */ async function requestTokens( - attemptEpoch: number, + attempt_epoch: number, params: Readonly>, ): Promise> { const fetched = await fetchBody( environment.fetch, - serverUrl(config.tokenPath ?? TOKEN_PATH_DEFAULT), + serverUrl(config.token_path ?? TOKEN_PATH_DEFAULT), { method: 'POST', headers: { @@ -536,7 +536,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { limits, ); // A logout ran while the request waited. Its tokens must not log the user in again. - if (epoch !== attemptEpoch) return { ok: false, error: { kind: 'logged_out' } }; + if (epoch !== attempt_epoch) return { ok: false, error: { kind: 'logged_out' } }; if (!fetched.ok) { return { ok: false, error: { kind: 'token_unavailable', error: fetched.error } }; } @@ -556,40 +556,40 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const parsed = parseResponse(TokenResponse, decoded.value); if (!parsed.ok) return { ok: false, error: { kind: 'token_invalid', ...parsed.error } }; const tokens = parsed.value; - const expiresIn = + const expires_in = tokens.expires_in === null ? null : parseSeconds(String(tokens.expires_in)); - storeTokens(tokens.access_token, tokens.refresh_token, expiresIn); + storeTokens(tokens.access_token, tokens.refresh_token, expires_in); return { ok: true, value: { kind: 'bearer', token: tokens.access_token } }; } function storeTokens( - accessToken: string, - refreshToken: string | null, - expiresInSeconds: number | null, + access_token: string, + refresh_token: string | null, + expires_in_seconds: number | null, ): void { - const lifetimeSeconds = - expiresInSeconds === null + const lifetime_seconds = + expires_in_seconds === null ? TOKEN_LIFETIME_DEFAULT_SECONDS : Math.max( TOKEN_LIFETIME_MIN_SECONDS, - expiresInSeconds - TOKEN_EXPIRY_MARGIN_SECONDS, + expires_in_seconds - TOKEN_EXPIRY_MARGIN_SECONDS, ); writeTokens({ - accessToken, + access_token, // A refresh grant can answer without a new refresh token. Keep the one we have. - refreshToken: refreshToken ?? readTokens().refreshToken, - expiresAtMs: environment.now() + lifetimeSeconds * 1000, + refresh_token: refresh_token ?? readTokens().refresh_token, + expires_at_ms: environment.now() + lifetime_seconds * 1000, }); } /** The credential now, from the API key or a valid access token. It makes no requests. */ function currentCredential(): Credential | null { - const apiKey = config.ignoreApiKey === true ? null : deviceValue('x-api-key'); - if (apiKey !== null && apiKey.length > 0) return { kind: 'api_key', key: apiKey }; + const api_key = config.ignore_api_key === true ? null : deviceValue('x-api-key'); + if (api_key !== null && api_key.length > 0) return { kind: 'api_key', key: api_key }; const tokens = readTokens(); - if (tokens.accessToken === null) return null; - if (environment.now() >= tokens.expiresAtMs) return null; - return { kind: 'bearer', token: tokens.accessToken }; + if (tokens.access_token === null) return null; + if (environment.now() >= tokens.expires_at_ms) return null; + return { kind: 'bearer', token: tokens.access_token }; } async function credentialForRequest(): Promise { @@ -621,25 +621,25 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { invalidateToken(); if (status === 511) { // 511: the session on the server ended. The user must log in again. - if (handleLogin && authority !== null) redirect(loginUrl(authority)); + if (handle_login && authority !== null) redirect(loginUrl(authority)); return false; } // 401: the session can have changed, so load the authority again before the new attempt. - const renewEpoch = epoch; + const renew_epoch = epoch; const reloaded = await loadAuthority(); if (!reloaded.ok) return false; // A logout while the authority loaded ends the renewal. A new attempt would log in again. - if (epoch !== renewEpoch) return false; + if (epoch !== renew_epoch) return false; const result = await authorize(); return result.ok; } function loadAuthority(): Promise> { - if (loadingAuthority !== null) return loadingAuthority; + if (loading_authority !== null) return loading_authority; const attempt = runLoadAuthority().finally(() => { - loadingAuthority = null; + loading_authority = null; }); - loadingAuthority = attempt; + loading_authority = attempt; return attempt; } @@ -700,8 +700,8 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { /** Reads and removes the parameters that `handleRedirect` kept. */ function readDeepLink(): ReadonlyMap { - const text = environment.sessionStorage.get(DEEP_LINK_KEY); - environment.sessionStorage.remove(DEEP_LINK_KEY); + const text = environment.session_storage.get(DEEP_LINK_KEY); + environment.session_storage.remove(DEEP_LINK_KEY); if (text === null) return new Map(); const decoded = decodeJson(new TextEncoder().encode(text)); if (!decoded.ok) return new Map(); @@ -729,13 +729,17 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { }; } const code = params.get('code'); - if (code !== undefined) pendingCode = code; - const accessToken = params.get('access_token'); - const refreshToken = params.get('refresh_token') ?? null; - if (accessToken !== undefined) { - storeTokens(accessToken, refreshToken, parseSeconds(params.get('expires_in') ?? null)); - } else if (refreshToken !== null) { - writeTokens({ ...readTokens(), refreshToken }); + if (code !== undefined) pending_code = code; + const access_token = params.get('access_token'); + const refresh_token = params.get('refresh_token') ?? null; + if (access_token !== undefined) { + storeTokens( + access_token, + refresh_token, + parseSeconds(params.get('expires_in') ?? null), + ); + } else if (refresh_token !== null) { + writeTokens({ ...readTokens(), refresh_token }); } // The redirect came back, so the page is not on its way to the server now. if (status.kind === 'redirecting') setStatus({ kind: 'loading' }); @@ -746,22 +750,22 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { function createAuthorizeUrl(): string { const nonce = randomString(NONCE_LENGTH); storage.set(storageKey('nonce'), nonce); - const responseType = isTrusted() || config.grant.kind === 'code' ? 'code' : 'token'; + const response_type = isTrusted() || config.grant.kind === 'code' ? 'code' : 'token'; const params = new URLSearchParams({ - response_type: responseType, - client_id: clientId, + response_type, + client_id, state: nonce, - redirect_uri: config.redirectUri, + redirect_uri: config.redirect_uri, scope: config.scope, }); - if (responseType === 'code') { + if (response_type === 'code') { const verifier = randomString(VERIFIER_LENGTH); - environment.sessionStorage.set(storageKey('code_verifier'), verifier); + environment.session_storage.set(storageKey('code_verifier'), verifier); const challenge = base64Url(sha256(new TextEncoder().encode(verifier))); params.set('code_challenge_method', 'S256'); params.set('code_challenge', challenge); } - const base = serverUrl(config.authorizePath ?? AUTHORIZE_PATH_DEFAULT); + const base = serverUrl(config.authorize_path ?? AUTHORIZE_PATH_DEFAULT); return `${base}${base.includes('?') ? '&' : '?'}${params.toString()}`; } @@ -776,7 +780,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { */ function serverUrl(path: string): string { if (/^https?:\/\//.test(path)) return path; - return `${config.baseUrl}${path}`; + return `${config.base_url}${path}`; } function redirect(url: string): Result { @@ -799,18 +803,18 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { async function handleRedirect(url: string): Promise> { const params = urlParams(url); if (!hasLoginParams(params)) return { ok: false, error: { kind: 'redirect_invalid' } }; - environment.sessionStorage.set(DEEP_LINK_KEY, JSON.stringify(Object.fromEntries(params))); + environment.session_storage.set(DEEP_LINK_KEY, JSON.stringify(Object.fromEntries(params))); // An attempt that runs now reads the deep link before it redirects. Then its result is the // result of the link, and a second attempt would redirect after a denial. if (authorizing !== null) { - const linkEpoch = epoch; + const link_epoch = epoch; const running = await authorizing; // A logout while the link waited ends it. A new attempt would log in again. - if (epoch !== linkEpoch) { - environment.sessionStorage.remove(DEEP_LINK_KEY); + if (epoch !== link_epoch) { + environment.session_storage.remove(DEEP_LINK_KEY); return { ok: false, error: { kind: 'logged_out' } }; } - if (environment.sessionStorage.get(DEEP_LINK_KEY) === null) return running; + if (environment.session_storage.get(DEEP_LINK_KEY) === null) return running; } if (status.kind === 'redirecting') setStatus({ kind: 'loading' }); halted = null; @@ -820,9 +824,9 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { function onForeground(): void { // The handler only starts the check. Many events while a check runs give one check. A // rejection here is a bug, and the browser reports it as an unhandled rejection. - if (foregroundCheck !== null) return; - foregroundCheck = checkAfterForeground().finally(() => { - foregroundCheck = null; + if (foreground_check !== null) return; + foreground_check = checkAfterForeground().finally(() => { + foreground_check = null; }); } @@ -835,24 +839,25 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (authority.session) return; if (currentCredential() !== null) return; if (status.kind === 'redirecting') setStatus({ kind: 'loading' }); - const hasNewCredentials = - environment.sessionStorage.get(DEEP_LINK_KEY) !== null || - pendingCode !== null || - readTokens().refreshToken !== null; - if (!hasNewCredentials) { - const checkEpoch = epoch; + const has_new_credentials = + environment.session_storage.get(DEEP_LINK_KEY) !== null || + pending_code !== null || + readTokens().refresh_token !== null; + if (!has_new_credentials) { + const check_epoch = epoch; const reloaded = await loadAuthority(); if (!reloaded.ok) return; // A logout while the authority loaded ends the check. - if (epoch !== checkEpoch) return; + if (epoch !== check_epoch) return; } await authorize(); } - function useToken(token: string, expiresAtMs?: number): void { + function useToken(token: string, expires_at_ms?: number): void { assert(token.length > 0, 'the token is not empty'); - const expiresAt = expiresAtMs ?? environment.now() + TOKEN_LIFETIME_DEFAULT_SECONDS * 1000; - writeTokens({ ...readTokens(), accessToken: token, expiresAtMs: expiresAt }); + const expires_at = + expires_at_ms ?? environment.now() + TOKEN_LIFETIME_DEFAULT_SECONDS * 1000; + writeTokens({ ...readTokens(), access_token: token, expires_at_ms: expires_at }); halted = null; setStatus({ kind: 'signed_in', credential: 'bearer' }); } @@ -866,22 +871,22 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { } function invalidateToken(): void { - writeTokens({ ...readTokens(), accessToken: null, expiresAtMs: 0 }); + writeTokens({ ...readTokens(), access_token: null, expires_at_ms: 0 }); } async function logout(): Promise { const url = authority === null ? serverUrl(LOGOUT_PATH_DEFAULT) : serverUrl(authority.logout_url); epoch += 1; - const requestHeaders: Record = { ...headers }; + const request_headers: Record = { ...headers }; // Send the token also after its local expiry. That has a margin, so the server can still // accept the token, and the logout revokes it. - const accessToken = readTokens().accessToken; - if (accessToken !== null) requestHeaders['Authorization'] = `Bearer ${accessToken}`; + const access_token = readTokens().access_token; + if (access_token !== null) request_headers['Authorization'] = `Bearer ${access_token}`; const fetched = await fetchBody( environment.fetch, url, - { method: 'GET', headers: requestHeaders, redirect: 'manual' }, + { method: 'GET', headers: request_headers, redirect: 'manual' }, limits, ); // Remove the credentials also when the request fails. The navigation ends the session. @@ -893,15 +898,15 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { /** Removes each stored value of this client: each key that has the client ID, and the link. */ function clearCredentials(): void { - for (const store of [storage, environment.sessionStorage]) { + for (const store of [storage, environment.session_storage]) { for (const key of store.keys()) { - if (key.includes(clientId)) store.remove(key); + if (key.includes(client_id)) store.remove(key); } } // The deep link key has no client ID, so 6.x can read it. A logout also ends a waiting link. - environment.sessionStorage.remove(DEEP_LINK_KEY); - memoryTokens = NO_TOKENS; - pendingCode = null; + environment.session_storage.remove(DEEP_LINK_KEY); + memory_tokens = NO_TOKENS; + pending_code = null; } function isTrusted(): boolean { @@ -909,8 +914,8 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { } function isFixedDevice(): boolean { - const apiKey = deviceValue('x-api-key'); - if (config.ignoreApiKey !== true && apiKey !== null && apiKey.length > 0) return true; + const api_key = deviceValue('x-api-key'); + if (config.ignore_api_key !== true && api_key !== null && api_key.length > 0) return true; return deviceValue('fixed_device') === 'true'; } @@ -921,22 +926,22 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { /** The one place that reads the tokens: the storage if trusted, else memory. */ function readTokens(): Tokens { - if (!isTrusted()) return memoryTokens; + if (!isTrusted()) return memory_tokens; return { - accessToken: storage.get(storageKey('access_token')), - refreshToken: storage.get(storageKey('refresh_token')), - expiresAtMs: parseStoredMs(storage.get(storageKey('expires_at'))), + access_token: storage.get(storageKey('access_token')), + refresh_token: storage.get(storageKey('refresh_token')), + expires_at_ms: parseStoredMs(storage.get(storageKey('expires_at'))), }; } function writeTokens(tokens: Tokens): void { if (!isTrusted()) { - memoryTokens = tokens; + memory_tokens = tokens; return; } - writeStored(storageKey('access_token'), tokens.accessToken); - writeStored(storageKey('refresh_token'), tokens.refreshToken); - writeStored(storageKey('expires_at'), String(tokens.expiresAtMs)); + writeStored(storageKey('access_token'), tokens.access_token); + writeStored(storageKey('refresh_token'), tokens.refresh_token); + writeStored(storageKey('expires_at'), String(tokens.expires_at_ms)); } function writeStored(key: string, value: string | null): void { @@ -985,11 +990,11 @@ export function urlParams(url: string): ReadonlyMap { if (!URL.canParse(url)) return params; const parsed = new URL(url); const hash = parsed.hash.slice(1); - const queryStart = hash.indexOf('?'); - const hashMain = queryStart >= 0 ? hash.slice(0, queryStart) : hash; - const hashQuery = queryStart >= 0 ? hash.slice(queryStart + 1) : ''; + const query_start = hash.indexOf('?'); + const hash_main = query_start >= 0 ? hash.slice(0, query_start) : hash; + const hash_query = query_start >= 0 ? hash.slice(query_start + 1) : ''; // The query of the page wins over the hash, as in 6.x. - for (const part of [hashMain, hashQuery, parsed.search.slice(1)]) { + for (const part of [hash_main, hash_query, parsed.search.slice(1)]) { if (!part.includes('=')) continue; for (const [key, value] of new URLSearchParams(part)) { if (value.length > 0) params.set(key, value); @@ -1004,12 +1009,12 @@ export function withoutParams(url: string, names: ReadonlySet): string { const parsed = new URL(url); parsed.search = removeNames(parsed.search.slice(1), names); const hash = parsed.hash.slice(1); - const queryStart = hash.indexOf('?'); - let hashMain = queryStart >= 0 ? hash.slice(0, queryStart) : hash; - const hashQuery = removeNames(queryStart >= 0 ? hash.slice(queryStart + 1) : '', names); + const query_start = hash.indexOf('?'); + let hash_main = query_start >= 0 ? hash.slice(0, query_start) : hash; + const hash_query = removeNames(query_start >= 0 ? hash.slice(query_start + 1) : '', names); // A hash such as `#/rooms` is a route, not parameters. - if (hashMain.includes('=')) hashMain = removeNames(hashMain, names); - parsed.hash = hashQuery.length > 0 ? `${hashMain}?${hashQuery}` : hashMain; + if (hash_main.includes('=')) hash_main = removeNames(hash_main, names); + parsed.hash = hash_query.length > 0 ? `${hash_main}?${hash_query}` : hash_main; return parsed.toString(); } diff --git a/src/compat/http-mock.ts b/src/compat/http-mock.ts index 763b901a7..5b312b851 100644 --- a/src/compat/http-mock.ts +++ b/src/compat/http-mock.ts @@ -7,7 +7,7 @@ * id: request.route_params.id, * name: 'Zone', * }) }); - * configure({ baseUrl: '', auth: { kind: 'none' }, fetch: mockFetch }); + * configure({ base_url: '', auth: { kind: 'none' }, fetch: mockFetch }); * ``` * * The behavior is the same as 6.x: a path segment `:name` is a route parameter, the response comes @@ -145,12 +145,12 @@ export const mockFetch: FetchFunction = async (url, init) => { if (body === undefined) return new Response(null, { status: 204, headers }); // 6.x gave the value of the callback as it was, also a string. A JSON response has the string // as JSON. A handler with another `content-type`, such as `text/plain`, sends its text. - const contentType = headers['content-type'] ?? 'application/json'; + const content_type = headers['content-type'] ?? 'application/json'; const text = - typeof body === 'string' && !contentType.includes('json') ? body : JSON.stringify(body); + typeof body === 'string' && !content_type.includes('json') ? body : JSON.stringify(body); return new Response(text, { status: 200, - headers: { 'content-type': contentType, ...headers }, + headers: { 'content-type': content_type, ...headers }, }); }; diff --git a/src/compat/realtime-mock.ts b/src/compat/realtime-mock.ts index 8bdfc715c..539e009d7 100644 --- a/src/compat/realtime-mock.ts +++ b/src/compat/realtime-mock.ts @@ -4,7 +4,7 @@ * * ```ts * registerSystem('sys-1', { Display: [{ power: false, $power: (on: boolean) => on }] }); - * const realtime = createRealtime({ baseUrl: '', auth, environment: mockRealtimeEnvironment() }); + * const realtime = createRealtime({ base_url: '', auth, environment: mockRealtimeEnvironment() }); * const display = mockSystem('sys-1')?.['Display']?.[0]; * if (display !== undefined) display['power'] = true; // The bindings of `power` get `true`. * ``` @@ -115,7 +115,7 @@ export function mockRealtimeEnvironment(): RealtimeEnvironment { return { createSocket, currentUrl: () => (typeof location === 'undefined' ? 'http://localhost/' : location.href), - tokenTransport: 'query', + token_transport: 'query', setCookie: () => {}, now: () => Date.now(), setTimer: (milliseconds, callback) => { diff --git a/src/compat/result.ts b/src/compat/result.ts index ccb472fb0..e323128c9 100644 --- a/src/compat/result.ts +++ b/src/compat/result.ts @@ -35,13 +35,13 @@ export function orThrow(result: Result, CallError>): T { return result.value.data; } -/** The page of a 6.x query function. 6.x also gave `next`. 7.x gives `nextOffset`. */ +/** The page of a 6.x query function. 6.x also gave `next`. 7.x gives `next_offset`. */ export interface Page { readonly data: T; /** The `X-Total-Count` header, or `0` without it, as in 6.x. */ readonly total: number; /** Give it as the `offset` of the next call. `null` on the last page. */ - readonly nextOffset: number | null; + readonly next_offset: number | null; } /** The 6.x type of a query function, such as `QueryResponse`. */ @@ -51,7 +51,7 @@ export type QueryResponse = Promise>; export function orThrowPage(result: Result, CallError>): Page { if (!result.ok) throw new CallFailed(result.error); const page = pageInfo(result.value.headers); - return { data: result.value.data, total: page.total ?? 0, nextOffset: page.nextOffset }; + return { data: result.value.data, total: page.total ?? 0, next_offset: page.next_offset }; } /** @@ -142,11 +142,11 @@ function describe(error: CallError): string { case 'response_invalid': return `the response is not valid at ${error.path}: expected ${error.expected}`; case 'timeout': - return `no response in ${error.timeoutMs} ms`; + return `no response in ${error.timeout_ms} ms`; case 'network': return `network error: ${error.message}`; case 'response_too_large': - return `the response is larger than ${error.bytesMax} bytes`; + return `the response is larger than ${error.bytes_max} bytes`; case 'auth_missing': return 'no token or credential'; case 'aborted': diff --git a/src/core/client.ts b/src/core/client.ts index 9ae5aba18..8a9882b37 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -55,20 +55,20 @@ export type Auth = export interface ClientConfig { /** The origin of the server, for example `https://placeos.example.com`. `''` is this origin. */ - readonly baseUrl: string; + readonly base_url: string; readonly auth: Auth; /** Headers to add to each request. */ readonly headers?: Readonly>; /** The default time limit of a request, from the start to the end of the response body. */ - readonly timeoutMs?: number; + readonly timeout_ms?: number; /** The maximum size of a response body. A larger body gives a `response_too_large` error. */ - readonly responseBytesMax?: number; + readonly response_bytes_max?: number; readonly fetch?: FetchFunction; /** * `zero` fills a missing required field of a response with its empty value, such as `''`. * Only for mock data, such as the mock endpoints of `@placeos/ts-client/compat`. */ - readonly missingFields?: 'error' | 'zero'; + readonly missing_fields?: 'error' | 'zero'; /** * Answers calls without a request, for tests and a mock mode. `@placeos/ts-client/mock` has * one with a typed handler for each endpoint. @@ -95,13 +95,13 @@ export interface MockAnswer { /** The settings that each request uses. Make one with `createClient`. */ export interface Client { - readonly baseUrl: string; + readonly base_url: string; readonly auth: Auth; readonly headers: Readonly>; - readonly timeoutMs: number; - readonly responseBytesMax: number; + readonly timeout_ms: number; + readonly response_bytes_max: number; readonly fetch: FetchFunction; - readonly missingFields: 'error' | 'zero'; + readonly missing_fields: 'error' | 'zero'; readonly mock: CallMock | null; } @@ -110,8 +110,8 @@ export interface CallOptions { readonly client?: Client; /** Cancels the request. */ readonly signal?: AbortSignal; - /** Replaces the `timeoutMs` of the client for this request. */ - readonly timeoutMs?: number; + /** Replaces the `timeout_ms` of the client for this request. */ + readonly timeout_ms?: number; } /** A request that failed for an expected reason. Each kind is a different action for the caller. */ @@ -120,10 +120,10 @@ export type CallError = | { readonly kind: 'auth_missing' } /** The `signal` of the caller cancelled the request. */ | { readonly kind: 'aborted' } - | { readonly kind: 'timeout'; readonly timeoutMs: number } + | { readonly kind: 'timeout'; readonly timeout_ms: number } /** The request did not get a response, for example because the network is down. */ | { readonly kind: 'network'; readonly message: string } - | { readonly kind: 'response_too_large'; readonly bytesMax: number } + | { readonly kind: 'response_too_large'; readonly bytes_max: number } /** The server sent a status that is not 2xx. `message` is the `error` field of the body. */ | { readonly kind: 'http'; @@ -155,7 +155,7 @@ export interface Operation< readonly method: HttpMethod; /** The path template, for example `/api/engine/v2/zones/{id}`. */ readonly path: string; - readonly pathKeys: readonly string[]; + readonly path_keys: readonly string[]; readonly params: P; readonly body: B; readonly response: R; @@ -165,7 +165,7 @@ export interface Operation< * The query name of a parameter that has another key in the input. A query parameter named * `body` is an example, because `body` of the input is the request body. */ - readonly wireNames?: Readonly>; + readonly wire_names?: Readonly>; } export type AnyOperation = Operation; @@ -205,11 +205,11 @@ export type CallResult = Result>, CallError>; /** Checks the client settings once, so that each request can trust them. */ export function createClient(config: ClientConfig): Client { - assert(!config.baseUrl.endsWith('/'), 'the baseUrl has no trailing slash'); - const timeoutMs = config.timeoutMs ?? TIMEOUT_MS_DEFAULT; - assertPositiveInteger(timeoutMs, 'timeoutMs'); - const responseBytesMax = config.responseBytesMax ?? RESPONSE_BYTES_MAX_DEFAULT; - assertPositiveInteger(responseBytesMax, 'responseBytesMax'); + assert(!config.base_url.endsWith('/'), 'the base_url has no trailing slash'); + const timeout_ms = config.timeout_ms ?? TIMEOUT_MS_DEFAULT; + assertPositiveInteger(timeout_ms, 'timeout_ms'); + const response_bytes_max = config.response_bytes_max ?? RESPONSE_BYTES_MAX_DEFAULT; + assertPositiveInteger(response_bytes_max, 'response_bytes_max'); if (config.auth.kind === 'api_key') { assert(config.auth.key.length > 0, 'the API key is not empty'); } @@ -217,13 +217,13 @@ export function createClient(config: ClientConfig): Client { const fetchFunction: FetchFunction = config.fetch ?? ((url, init) => globalThis.fetch(url, init)); return Object.freeze({ - baseUrl: config.baseUrl, + base_url: config.base_url, auth: config.auth, headers: Object.freeze({ ...config.headers }), - timeoutMs, - responseBytesMax, + timeout_ms, + response_bytes_max, fetch: fetchFunction, - missingFields: config.missingFields ?? 'error', + missing_fields: config.missing_fields ?? 'error', mock: config.mock ?? null, }); } @@ -232,20 +232,20 @@ export function createClient(config: ClientConfig): Client { * The client of `configure`, so that an application does not give its client to each call. It is * the one module state of the core. The mock registries of `compat` and `mock` are the others. */ -let configuredClient: Client | null = null; +let configured_client: Client | null = null; /** * Makes the client that each call uses when its options have no `client`. Call it once, when the * application starts. A second call replaces the client. * * ```ts - * configure({ baseUrl: '', auth: { kind: 'bearer', token: () => getToken() } }); + * configure({ base_url: '', auth: { kind: 'bearer', token: () => getToken() } }); * const result = await zones.show({ id: 'zone-1234' }); * ``` */ export function configure(config: ClientConfig): Client { - configuredClient = createClient(config); - return configuredClient; + configured_client = createClient(config); + return configured_client; } /** Defines an operation. It checks the definition when the module loads. */ @@ -259,10 +259,10 @@ export function operation< assert(/^(staff\.)?\w+\.\w+$/.test(definition.name), 'the name is .'); assert(definition.params.node.kind === 'object', 'the params schema is an object'); // `[^{}]` cannot match a brace, so the match is linear also for a path with many braces. - const templateKeys = [...definition.path.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]); + const template_keys = [...definition.path.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]); assert( - templateKeys.join() === definition.pathKeys.join(), - `the path keys of ${definition.path} are in pathKeys`, + template_keys.join() === definition.path_keys.join(), + `the path keys of ${definition.path} are in path_keys`, ); return definition; } @@ -280,7 +280,7 @@ export async function call( options: CallOptions = {}, ): Promise> { // Read the client before the first `await`, so the whole request uses one client. - const client = options.client ?? configuredClient; + const client = options.client ?? configured_client; assert(client !== null, 'configure() ran before this call, or the options have a client'); const result = await send(client, operation, input, options); // `send` parsed the data with `operation.response`, which gives `OperationData` its type. @@ -297,24 +297,24 @@ async function send( const { body, ...params } = input; // Check the data immediately before it leaves the program, as a pair to the response parse. - const paramsChecked = checkRequest(operation.params, params); - assertValid(paramsChecked, `the parameters of ${operation.method} ${operation.path}`); - assert(isRecord(paramsChecked.value), 'the checked parameters are an object'); - const url = buildUrl(client.baseUrl, operation, paramsChecked.value); - let bodyText: string | null = null; + const params_checked = checkRequest(operation.params, params); + assertValid(params_checked, `the parameters of ${operation.method} ${operation.path}`); + assert(isRecord(params_checked.value), 'the checked parameters are an object'); + const url = buildUrl(client.base_url, operation, params_checked.value); + let body_text: string | null = null; if (operation.body === null) { assert(body === undefined, `${operation.method} ${operation.path} has no body`); } else { - const bodyChecked = checkRequest(operation.body, body); - assertValid(bodyChecked, `the body of ${operation.method} ${operation.path}`); - bodyText = JSON.stringify(bodyChecked.value); + const body_checked = checkRequest(operation.body, body); + assertValid(body_checked, `the body of ${operation.method} ${operation.path}`); + body_text = JSON.stringify(body_checked.value); } - const timeoutMs = options.timeoutMs ?? client.timeoutMs; - assertPositiveInteger(timeoutMs, 'timeoutMs'); + const timeout_ms = options.timeout_ms ?? client.timeout_ms; + assertPositiveInteger(timeout_ms, 'timeout_ms'); // One deadline for the call. The credential, a renewal and each fetch share it, so a slow - // login cannot make the call take longer than `timeoutMs`. - const deadlineMs = Date.now() + timeoutMs; + // login cannot make the call take longer than `timeout_ms`. + const deadline_ms = Date.now() + timeout_ms; const signal = options.signal; // A mock gets the input after the checks, so a test finds the same errors as the server. Its @@ -324,36 +324,36 @@ async function send( if (mock !== null) { const answered = await waitWithin( () => Promise.resolve(mock({ name: operation.name, input })), - deadlineMs, + deadline_ms, signal, ); - if (!answered.ok) return limitError(answered.error, timeoutMs); + if (!answered.ok) return limitError(answered.error, timeout_ms); // `null`: the mock does not answer this call, so the request goes to the server. if (answered.value !== null) { - return mockResult(operation, answered.value, client.responseBytesMax); + return mockResult(operation, answered.value, client.response_bytes_max); } } // Each attempt gets the credential again, because a `rejected` auth can renew it. let response: Fetched | null = null; for (let attempt = 0; attempt < AUTH_ATTEMPTS_MAX; attempt += 1) { const auth = client.auth; - const credential = await waitWithin(() => resolveCredential(auth), deadlineMs, signal); - if (!credential.ok) return limitError(credential.error, timeoutMs); + const credential = await waitWithin(() => resolveCredential(auth), deadline_ms, signal); + if (!credential.ok) return limitError(credential.error, timeout_ms); if (credential.value === null) return { ok: false, error: { kind: 'auth_missing' } }; const headers = new Headers(client.headers); headers.set('Accept', 'application/json'); - if (bodyText !== null) headers.set('Content-Type', 'application/json'); + if (body_text !== null) headers.set('Content-Type', 'application/json'); setCredentialHeader(headers, credential.value); - const init = { method: operation.method, headers, body: bodyText }; - const remainingMs = deadlineMs - Date.now(); - if (remainingMs <= 0) return { ok: false, error: { kind: 'timeout', timeoutMs } }; + const init = { method: operation.method, headers, body: body_text }; + const remaining_ms = deadline_ms - Date.now(); + if (remaining_ms <= 0) return { ok: false, error: { kind: 'timeout', timeout_ms } }; const limits = { - timeoutMs: remainingMs, - bytesMax: client.responseBytesMax, + timeout_ms: remaining_ms, + bytes_max: client.response_bytes_max, ...(signal === undefined ? {} : { signal }), }; const fetched = await fetchBody(client.fetch, url, init, limits); - if (!fetched.ok) return limitError(fetched.error, timeoutMs); + if (!fetched.ok) return limitError(fetched.error, timeout_ms); response = fetched.value; const status = response.status; @@ -362,26 +362,26 @@ async function send( if (attempt + 1 >= AUTH_ATTEMPTS_MAX) break; const rejected = client.auth.rejected; const used = credential.value; - const renewed = await waitWithin(() => rejected(status, used), deadlineMs, signal); - if (!renewed.ok) return limitError(renewed.error, timeoutMs); + const renewed = await waitWithin(() => rejected(status, used), deadline_ms, signal); + if (!renewed.ok) return limitError(renewed.error, timeout_ms); if (!renewed.value) break; } assert(response !== null, 'the request was sent'); if (!response.ok) { const parsed = decodeJson(response.bytes); - let errorBody: JsonValue | null = null; + let error_body: JsonValue | null = null; if (parsed.ok) { const body = parseResponse(json(), parsed.value); - if (body.ok) errorBody = body.value; + if (body.ok) error_body = body.value; } let message: string | null = null; - if (isRecord(errorBody) && typeof errorBody['error'] === 'string') { - message = errorBody['error']; + if (isRecord(error_body) && typeof error_body['error'] === 'string') { + message = error_body['error']; } return { ok: false, - error: { kind: 'http', status: response.status, message, body: errorBody }, + error: { kind: 'http', status: response.status, message, body: error_body }, }; } @@ -395,7 +395,7 @@ async function send( }; } const data = parseResponse(operation.response, parsed.value, { - missingFields: client.missingFields, + missing_fields: client.missing_fields, }); if (!data.ok) { return { @@ -410,7 +410,7 @@ async function send( function mockResult( operation: AnyOperation, answer: MockAnswer, - bytesMax: number, + bytes_max: number, ): Result, CallError> { const reply = { status: answer.status, headers: answer.headers }; const bytes = @@ -421,20 +421,20 @@ function mockResult( ? answer.data : (JSON.stringify(answer.data) ?? 'null'), ); - if (bytes.length > bytesMax) { - return { ok: false, error: { kind: 'response_too_large', bytesMax } }; + if (bytes.length > bytes_max) { + return { ok: false, error: { kind: 'response_too_large', bytes_max } }; } if (answer.status < 200 || answer.status > 299) { const parsed = decodeJson(bytes); const body = parsed.ok ? parseResponse(json(), parsed.value) : null; - const errorBody = body !== null && body.ok ? body.value : null; + const error_body = body !== null && body.ok ? body.value : null; const message = - isRecord(errorBody) && typeof errorBody['error'] === 'string' - ? errorBody['error'] + isRecord(error_body) && typeof error_body['error'] === 'string' + ? error_body['error'] : null; return { ok: false, - error: { kind: 'http', status: answer.status, message, body: errorBody }, + error: { kind: 'http', status: answer.status, message, body: error_body }, }; } if (operation.response === null) return { ok: true, value: { ...reply, data: bytes } }; @@ -445,7 +445,7 @@ function mockResult( error: { kind: 'response_invalid', status: reply.status, path: '$', expected: 'JSON' }, }; } - const data = parseResponse(operation.response, parsed.value, { missingFields: 'zero' }); + const data = parseResponse(operation.response, parsed.value, { missing_fields: 'zero' }); if (!data.ok) { return { ok: false, @@ -462,12 +462,12 @@ function mockResult( * commas. */ function buildUrl( - baseUrl: string, + base_url: string, operation: AnyOperation, params: Readonly>, ): string { let path = operation.path; - for (const key of operation.pathKeys) { + for (const key of operation.path_keys) { const text = queryScalar(params[key]); // An empty segment sends the request to a different endpoint, such as the collection. assert(text.length > 0, `the path parameter "${key}" is not empty`); @@ -478,10 +478,10 @@ function buildUrl( assert(node.kind === 'object', 'the params schema is an object'); const query = new URLSearchParams(); for (const field of node.fields) { - if (operation.pathKeys.includes(field.key)) continue; + if (operation.path_keys.includes(field.key)) continue; const value = params[field.key]; if (value === undefined || value === null) continue; - const name = operation.wireNames?.[field.key] ?? field.key; + const name = operation.wire_names?.[field.key] ?? field.key; if (Array.isArray(value)) { const items: readonly unknown[] = value; query.append(name, items.map(queryScalar).join(',')); @@ -489,9 +489,9 @@ function buildUrl( query.append(name, queryScalar(value)); } } - const queryText = query.toString(); - if (queryText.length === 0) return `${baseUrl}${path}`; - return `${baseUrl}${path}?${queryText}`; + const query_text = query.toString(); + if (query_text.length === 0) return `${base_url}${path}`; + return `${base_url}${path}?${query_text}`; } function queryScalar(value: unknown): string { @@ -518,8 +518,8 @@ export type FetchError = Extract< >; export interface FetchLimits { - readonly timeoutMs: number; - readonly bytesMax: number; + readonly timeout_ms: number; + readonly bytes_max: number; readonly signal?: AbortSignal; } @@ -535,30 +535,30 @@ export async function fetchBody( init: Omit, limits: FetchLimits, ): Promise> { - assertPositiveInteger(limits.timeoutMs, 'timeoutMs'); - assertPositiveInteger(limits.bytesMax, 'bytesMax'); + assertPositiveInteger(limits.timeout_ms, 'timeout_ms'); + assertPositiveInteger(limits.bytes_max, 'bytes_max'); // The caller can cancel while an earlier step waits, such as the credential of the auth. if (isAborted(limits.signal)) return { ok: false, error: { kind: 'aborted' } }; - const timeoutSignal = AbortSignal.timeout(limits.timeoutMs); + const timeout_signal = AbortSignal.timeout(limits.timeout_ms); const signal = limits.signal === undefined - ? timeoutSignal - : AbortSignal.any([limits.signal, timeoutSignal]); + ? timeout_signal + : AbortSignal.any([limits.signal, timeout_signal]); let response: Response; let bytes: Result; try { response = await fetchFunction(url, { ...init, signal }); - bytes = await readBody(response, limits.bytesMax); + bytes = await readBody(response, limits.bytes_max); } catch (error) { if (isAborted(limits.signal)) return { ok: false, error: { kind: 'aborted' } }; - if (timeoutSignal.aborted) { - return { ok: false, error: { kind: 'timeout', timeoutMs: limits.timeoutMs } }; + if (timeout_signal.aborted) { + return { ok: false, error: { kind: 'timeout', timeout_ms: limits.timeout_ms } }; } const message = error instanceof Error ? error.message : String(error); return { ok: false, error: { kind: 'network', message } }; } if (!bytes.ok) { - return { ok: false, error: { kind: 'response_too_large', bytesMax: limits.bytesMax } }; + return { ok: false, error: { kind: 'response_too_large', bytes_max: limits.bytes_max } }; } return { ok: true, @@ -572,7 +572,7 @@ export async function fetchBody( } /** - * Starts `work`, and waits for it until `deadlineMs` or until `signal` cancels. The work itself + * Starts `work`, and waits for it until `deadline_ms` or until `signal` cancels. The work itself * goes on, because it can be shared, such as one renewal of the auth for many calls. * * It starts the work only after the checks, so a cancelled call starts no work, and no promise is @@ -580,17 +580,17 @@ export async function fetchBody( */ async function waitWithin( work: () => Promise, - deadlineMs: number, + deadline_ms: number, signal: AbortSignal | undefined, ): Promise> { if (isAborted(signal)) return { ok: false, error: 'aborted' }; - const remainingMs = deadlineMs - Date.now(); - if (remainingMs <= 0) return { ok: false, error: 'timeout' }; + const remaining_ms = deadline_ms - Date.now(); + if (remaining_ms <= 0) return { ok: false, error: 'timeout' }; const promise = work(); let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; const stopped = new Promise>((resolve) => { - timer = setTimeout(() => resolve({ ok: false, error: 'timeout' }), remainingMs); + timer = setTimeout(() => resolve({ ok: false, error: 'timeout' }), remaining_ms); onAbort = () => resolve({ ok: false, error: 'aborted' }); signal?.addEventListener('abort', onAbort, { once: true }); // `work` can abort the signal before the listener exists, such as a mock of a test. @@ -611,11 +611,11 @@ async function waitWithin( /** A limit of the whole call. The error gives the time limit of the call, not of one step. */ function limitError( error: FetchError | 'aborted' | 'timeout', - timeoutMs: number, + timeout_ms: number, ): { readonly ok: false; readonly error: FetchError } { if (error === 'aborted') return { ok: false, error: { kind: 'aborted' } }; - if (error === 'timeout') return { ok: false, error: { kind: 'timeout', timeoutMs } }; - if (error.kind === 'timeout') return { ok: false, error: { kind: 'timeout', timeoutMs } }; + if (error === 'timeout') return { ok: false, error: { kind: 'timeout', timeout_ms } }; + if (error.kind === 'timeout') return { ok: false, error: { kind: 'timeout', timeout_ms } }; return { ok: false, error }; } @@ -660,15 +660,15 @@ function setCredentialHeader(headers: Headers, credential: Credential): void { } } -/** Reads the body, but stops at `bytesMax` bytes. The caller converts a throw to a value. */ +/** Reads the body, but stops at `bytes_max` bytes. The caller converts a throw to a value. */ async function readBody( response: Response, - bytesMax: number, + bytes_max: number, ): Promise> { - const lengthText = response.headers.get('content-length'); - if (lengthText !== null) { - const length = Number(lengthText); - if (Number.isSafeInteger(length) && length > bytesMax) { + const length_text = response.headers.get('content-length'); + if (length_text !== null) { + const length = Number(length_text); + if (Number.isSafeInteger(length) && length > bytes_max) { await response.body?.cancel(); return { ok: false, error: 'too_large' }; } @@ -691,7 +691,7 @@ async function readBody( return { ok: true, value: bytes }; } size += chunk.value.byteLength; - if (size > bytesMax) { + if (size > bytes_max) { await reader.cancel(); return { ok: false, error: 'too_large' }; } diff --git a/src/core/pagination.ts b/src/core/pagination.ts index 6a04ff15a..0d52079f8 100644 --- a/src/core/pagination.ts +++ b/src/core/pagination.ts @@ -6,7 +6,7 @@ export interface PageInfo { /** The `X-Total-Count` header: the number of results for all pages. */ readonly total: number | null; /** The `offset` of the next page, from the `Link` header. `null` on the last page. */ - readonly nextOffset: number | null; + readonly next_offset: number | null; } /** @@ -16,8 +16,8 @@ export interface PageInfo { * const first = await zones.query({ limit: 100 }); * if (first.ok) { * const page = pageInfo(first.value.headers); - * if (page.nextOffset !== null) { - * const second = await zones.query({ limit: 100, offset: page.nextOffset }); + * if (page.next_offset !== null) { + * const second = await zones.query({ limit: 100, offset: page.next_offset }); * } * } * ``` @@ -25,7 +25,7 @@ export interface PageInfo { export function pageInfo(headers: Headers): PageInfo { return { total: parseCount(headers.get('x-total-count')), - nextOffset: parseNextOffset(headers.get('link')), + next_offset: parseNextOffset(headers.get('link')), }; } diff --git a/src/core/schema.ts b/src/core/schema.ts index f1381f062..b3c59fad1 100644 --- a/src/core/schema.ts +++ b/src/core/schema.ts @@ -54,9 +54,9 @@ export interface ObjectField { readonly key: string; readonly node: SchemaNode; /** The parser fails on a response without this field. */ - readonly requiredInResponse: boolean; + readonly required_in_response: boolean; /** The check fails on a request without this field. */ - readonly requiredInRequest: boolean; + readonly required_in_request: boolean; } /** @@ -184,14 +184,14 @@ export function parameters, ObjectInput> { - const requiredKeys = new Set(required); - return { node: objectNode(fields, requiredKeys, requiredKeys) }; + const required_keys = new Set(required); + return { node: objectNode(fields, required_keys, required_keys) }; } function objectNode( fields: Fields, - requiredInResponse: ReadonlySet, - requiredInRequest: ReadonlySet, + required_in_response: ReadonlySet, + required_in_request: ReadonlySet, ): SchemaNode { const list: ObjectField[] = []; for (const [key, schema] of Object.entries(fields)) { @@ -200,11 +200,11 @@ function objectNode( list.push({ key, node: schema.node, - requiredInResponse: requiredInResponse.has(key), - requiredInRequest: requiredInRequest.has(key), + required_in_response: required_in_response.has(key), + required_in_request: required_in_request.has(key), }); } - for (const key of [...requiredInResponse, ...requiredInRequest]) { + for (const key of [...required_in_response, ...required_in_request]) { assert(Object.hasOwn(fields, key), `the required key "${key}" is a field`); } return { kind: 'object', fields: list, keys: new Set(Object.keys(fields)) }; @@ -233,7 +233,7 @@ export function parseResponse( options: ParseOptions = {}, ): Result { const failure: Failure = { expected: '', segments: [] }; - const direction = options.missingFields === 'zero' ? 'response_zero' : 'response'; + const direction = options.missing_fields === 'zero' ? 'response_zero' : 'response'; const parsed = walk(schema.node, value, direction, failure, 0); if (parsed === FAIL) return { ok: false, error: describeFailure(failure) }; // The walk built `parsed` from the same nodes that give `O` its shape. This is one of the two @@ -266,7 +266,7 @@ export interface ParseOptions { * of its type, such as `''`, `0` or `[]`, as the 6.x classes did. Only for mock data, which * often has only some of the fields. */ - readonly missingFields?: 'error' | 'zero'; + readonly missing_fields?: 'error' | 'zero'; } /** `response_zero` is a `response` that fills the missing required fields. */ @@ -342,9 +342,9 @@ function walk( } const output: unknown[] = []; for (let index = 0; index < node.items.length; index += 1) { - const itemNode = node.items[index]; - assert(itemNode !== undefined, 'the index is in the tuple'); - const item = walk(itemNode, items[index], direction, failure, depth + 1); + const item_node = node.items[index]; + assert(item_node !== undefined, 'the index is in the tuple'); + const item = walk(item_node, items[index], direction, failure, depth + 1); if (item === FAIL) { failure.segments.push(`[${index}]`); return FAIL; @@ -357,12 +357,12 @@ function walk( if (!isRecord(value)) return fail(failure, 'object'); const entries: [string, unknown][] = []; for (const key of Object.keys(value)) { - const entryValue = value[key]; - if (entryValue === undefined) { + const entry_value = value[key]; + if (entry_value === undefined) { assert(direction === 'request', 'JSON has no undefined values'); continue; } - const entry = walk(node.values, entryValue, direction, failure, depth + 1); + const entry = walk(node.values, entry_value, direction, failure, depth + 1); if (entry === FAIL) { failure.segments.push(`.${key}`); return FAIL; @@ -376,12 +376,12 @@ function walk( if (!isRecord(value)) return fail(failure, 'object'); const output: Record = {}; for (const field of node.fields) { - const fieldValue = Object.hasOwn(value, field.key) ? value[field.key] : undefined; - if (fieldValue === undefined) { + const field_value = Object.hasOwn(value, field.key) ? value[field.key] : undefined; + if (field_value === undefined) { const required = direction === 'request' - ? field.requiredInRequest - : field.requiredInResponse; + ? field.required_in_request + : field.required_in_response; if (required && direction === 'response_zero') { output[field.key] = zeroValue(field.node, depth + 1); continue; @@ -395,7 +395,7 @@ function walk( if (direction !== 'request') output[field.key] = null; continue; } - const parsed = walk(field.node, fieldValue, direction, failure, depth + 1); + const parsed = walk(field.node, field_value, direction, failure, depth + 1); if (parsed === FAIL) { failure.segments.push(`.${field.key}`); return FAIL; @@ -425,7 +425,7 @@ function walk( // fields wins, so that the fill does not drop them. In a tie, a variant that matches // without the fill wins, then the first. let best: unknown = FAIL; - let bestScore = -1; + let best_score = -1; for (const variant of node.variants) { const parsed = walk(variant, value, direction, failure, depth + 1); failure.segments.length = 0; @@ -433,9 +433,9 @@ function walk( const strict = walk(variant, value, 'response', failure, depth + 1) !== FAIL; failure.segments.length = 0; const score = knownKeys(variant, value) * 2 + (strict ? 1 : 0); - if (score > bestScore) { + if (score > best_score) { best = parsed; - bestScore = score; + best_score = score; } } if (best !== FAIL) return best; @@ -478,7 +478,7 @@ function zeroValue(node: SchemaNode, depth: number): unknown { case 'object': { const output: Record = {}; for (const field of node.fields) { - output[field.key] = field.requiredInResponse + output[field.key] = field.required_in_response ? zeroValue(field.node, depth + 1) : null; } diff --git a/src/generated/operations/alert-dashboards.ts b/src/generated/operations/alert-dashboards.ts index 8d4578266..0a162f4d1 100644 --- a/src/generated/operations/alert-dashboards.ts +++ b/src/generated/operations/alert-dashboards.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `AlertDashboards` controller of the API. Import it as the `alertDashboards` namespace. + * The `AlertDashboards` controller of the API. Import it as the `alert_dashboards` namespace. * * @module */ @@ -29,7 +29,7 @@ export function alerts( const ALERTS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alert_dashboards/{id}/alerts', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -38,7 +38,7 @@ const ALERTS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(Alert), - name: 'alertDashboards.alerts', + name: 'alert_dashboards.alerts', }); /** @@ -56,11 +56,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/alert_dashboards', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AlertDashboard, response: AlertDashboard, - name: 'alertDashboards.create', + name: 'alert_dashboards.create', }); /** @@ -78,7 +78,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/alert_dashboards/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -87,7 +87,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'alertDashboards.destroy', + name: 'alert_dashboards.destroy', }); /** @@ -105,7 +105,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alert_dashboards', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return dashboards for a specific authority */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -125,7 +125,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AlertDashboard), - name: 'alertDashboards.query', + name: 'alert_dashboards.query', }); /** @@ -143,7 +143,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alert_dashboards/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -152,7 +152,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AlertDashboard, - name: 'alertDashboards.show', + name: 'alert_dashboards.show', }); /** @@ -170,7 +170,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/alert_dashboards/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -179,5 +179,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AlertDashboard, response: AlertDashboard, - name: 'alertDashboards.update', + name: 'alert_dashboards.update', }); diff --git a/src/generated/operations/alerts.ts b/src/generated/operations/alerts.ts index 654676e7c..865616753 100644 --- a/src/generated/operations/alerts.ts +++ b/src/generated/operations/alerts.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/alerts', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Alert, response: Alert, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/alerts/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alerts', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return alerts for a specific dashboard */ alert_dashboard_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -122,7 +122,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/alerts/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -151,7 +151,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/alerts/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/api-keys.ts b/src/generated/operations/api-keys.ts index fe2cde44f..185a7618c 100644 --- a/src/generated/operations/api-keys.ts +++ b/src/generated/operations/api-keys.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `ApiKeys` controller of the API. Import it as the `apiKeys` namespace. + * The `ApiKeys` controller of the API. Import it as the `api_keys` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/api_keys', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: ApiKey, response: ApiKeysResponse, - name: 'apiKeys.create', + name: 'api_keys.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/api_keys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'apiKeys.destroy', + name: 'api_keys.destroy', }); /** @@ -78,11 +78,11 @@ export function inspectKey( const INSPECT_KEY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/api_keys/inspect', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: UserJwt, - name: 'apiKeys.inspectKey', + name: 'api_keys.inspectKey', }); /** @@ -100,7 +100,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/api_keys', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** the ID of the domain to be listed */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -120,7 +120,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ApiKeysResponse), - name: 'apiKeys.query', + name: 'api_keys.query', }); /** @@ -138,7 +138,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/api_keys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -147,7 +147,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: ApiKeysResponse, - name: 'apiKeys.show', + name: 'api_keys.show', }); /** @@ -165,7 +165,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/api_keys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -174,5 +174,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: ApiKey, response: ApiKeysResponse, - name: 'apiKeys.update', + name: 'api_keys.update', }); diff --git a/src/generated/operations/asset-categories.ts b/src/generated/operations/asset-categories.ts index 3bdfbd000..dd88d27b3 100644 --- a/src/generated/operations/asset-categories.ts +++ b/src/generated/operations/asset-categories.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `AssetCategories` controller of the API. Import it as the `assetCategories` namespace. + * The `AssetCategories` controller of the API. Import it as the `asset_categories` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/asset_categories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetCategory, response: AssetCategory, - name: 'assetCategories.create', + name: 'asset_categories.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'assetCategories.destroy', + name: 'asset_categories.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_categories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * true returns only hidden categories, false only non-hidden categories; omit to return all @@ -101,7 +101,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetCategory), - name: 'assetCategories.query', + name: 'asset_categories.query', }); /** @@ -119,7 +119,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -128,7 +128,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetCategory, - name: 'assetCategories.show', + name: 'asset_categories.show', }); /** @@ -146,7 +146,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -155,5 +155,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetCategory, response: AssetCategory, - name: 'assetCategories.update', + name: 'asset_categories.update', }); diff --git a/src/generated/operations/asset-purchase-orders.ts b/src/generated/operations/asset-purchase-orders.ts index df5e2cfc4..ca893d1b8 100644 --- a/src/generated/operations/asset-purchase-orders.ts +++ b/src/generated/operations/asset-purchase-orders.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `AssetPurchaseOrders` controller of the API. Import it as the `assetPurchaseOrders` + * The `AssetPurchaseOrders` controller of the API. Import it as the `asset_purchase_orders` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/asset_purchase_orders', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetPurchaseOrder, response: AssetPurchaseOrder, - name: 'assetPurchaseOrders.create', + name: 'asset_purchase_orders.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -61,7 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'assetPurchaseOrders.destroy', + name: 'asset_purchase_orders.destroy', }); /** @@ -79,7 +79,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_purchase_orders', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -97,7 +97,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetPurchaseOrder), - name: 'assetPurchaseOrders.query', + name: 'asset_purchase_orders.query', }); /** @@ -115,7 +115,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -124,7 +124,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetPurchaseOrder, - name: 'assetPurchaseOrders.show', + name: 'asset_purchase_orders.show', }); /** @@ -143,7 +143,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -152,5 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetPurchaseOrder, response: AssetPurchaseOrder, - name: 'assetPurchaseOrders.update', + name: 'asset_purchase_orders.update', }); diff --git a/src/generated/operations/asset-types.ts b/src/generated/operations/asset-types.ts index dcd633df5..89f32126f 100644 --- a/src/generated/operations/asset-types.ts +++ b/src/generated/operations/asset-types.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `AssetTypes` controller of the API. Import it as the `assetTypes` namespace. + * The `AssetTypes` controller of the API. Import it as the `asset_types` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/asset_types', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetType, response: AssetType, - name: 'assetTypes.create', + name: 'asset_types.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'assetTypes.destroy', + name: 'asset_types.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_types', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return asset types with exactly this brand */ brand: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -108,7 +108,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetType), - name: 'assetTypes.query', + name: 'asset_types.query', }); /** @@ -126,7 +126,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -135,7 +135,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetType, - name: 'assetTypes.show', + name: 'asset_types.show', }); /** @@ -153,7 +153,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -162,5 +162,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetType, response: AssetType, - name: 'assetTypes.update', + name: 'asset_types.update', }); diff --git a/src/generated/operations/assets.ts b/src/generated/operations/assets.ts index 202696bfc..b1044a99f 100644 --- a/src/generated/operations/assets.ts +++ b/src/generated/operations/assets.ts @@ -29,7 +29,7 @@ export function bulkCreate( const BULK_CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), @@ -51,7 +51,7 @@ export function bulkDestroy( const BULK_DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(/* @__PURE__ */ string()), response: null, @@ -73,7 +73,7 @@ export function bulkUpdate( const BULK_UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), @@ -95,7 +95,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Asset, response: Asset, @@ -117,7 +117,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -144,7 +144,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return assets whose zone_id field is this zone id */ zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -200,7 +200,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -227,7 +227,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/brokers.ts b/src/generated/operations/brokers.ts index 3244895f8..63e63d153 100644 --- a/src/generated/operations/brokers.ts +++ b/src/generated/operations/brokers.ts @@ -29,7 +29,7 @@ export function collection( const COLLECTION = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/brokers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(Broker), @@ -51,7 +51,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/brokers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Broker, response: Broker, @@ -73,7 +73,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/brokers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -100,7 +100,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/brokers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -127,7 +127,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/brokers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/build-monitor.ts b/src/generated/operations/build-monitor.ts index 3f009da83..87e7828e2 100644 --- a/src/generated/operations/build-monitor.ts +++ b/src/generated/operations/build-monitor.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `BuildMonitor` controller of the API. Import it as the `buildMonitor` namespace. + * The `BuildMonitor` controller of the API. Import it as the `build_monitor` namespace. * * @module */ @@ -25,7 +25,7 @@ export function cancel( const CANCEL = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/build/cancel/{job}', - pathKeys: ['job'], + path_keys: ['job'], params: /* @__PURE__ */ parameters( { /** ID of previously submitted compilation job */ @@ -35,7 +35,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: BuildMonitorCancelStatus, - name: 'buildMonitor.cancel', + name: 'build_monitor.cancel', }); /** `GET /api/engine/v2/build/monitor` */ @@ -49,7 +49,7 @@ export function monitor( const MONITOR = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/build/monitor', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * state of job to return. One of [pending,running,cancelled error,done]. Defaults to @@ -62,5 +62,5 @@ const MONITOR = /* @__PURE__ */ operation({ /* @__PURE__ */ array(BuildMonitorTaskStatus), /* @__PURE__ */ string(), ]), - name: 'buildMonitor.monitor', + name: 'build_monitor.monitor', }); diff --git a/src/generated/operations/chat-gpt-plugin.ts b/src/generated/operations/chat-gpt-plugin.ts index b4424c6dd..a64db452a 100644 --- a/src/generated/operations/chat-gpt-plugin.ts +++ b/src/generated/operations/chat-gpt-plugin.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `ChatGPT::Plugin` controller of the API. Import it as the `chatGptPlugin` namespace. + * The `ChatGPT::Plugin` controller of the API. Import it as the `chat_gpt_plugin` namespace. * * @module */ @@ -31,7 +31,7 @@ export function callFunction( const CALL_FUNCTION = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/chatgpt/plugin/{system_id}/call_function/{capability_id}/{function_name}', - pathKeys: ['system_id', 'capability_id', 'function_name'], + path_keys: ['system_id', 'capability_id', 'function_name'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -57,7 +57,7 @@ const CALL_FUNCTION = /* @__PURE__ */ operation({ }, ['response'], ), - name: 'chatGptPlugin.callFunction', + name: 'chat_gpt_plugin.callFunction', }); /** @@ -77,7 +77,7 @@ export function capabilities( const CAPABILITIES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/chatgpt/plugin/{system_id}/capabilities', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -86,7 +86,7 @@ const CAPABILITIES = /* @__PURE__ */ operation({ ), body: null, response: ChatGptPluginDetails, - name: 'chatGptPlugin.capabilities', + name: 'chat_gpt_plugin.capabilities', }); /** @@ -105,7 +105,7 @@ export function functionSchema( const FUNCTION_SCHEMA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/chatgpt/plugin/{system_id}/function_schema/{capability_id}', - pathKeys: ['system_id', 'capability_id'], + path_keys: ['system_id', 'capability_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -125,5 +125,5 @@ const FUNCTION_SCHEMA = /* @__PURE__ */ operation({ ['function', 'description', 'parameters'], ), ), - name: 'chatGptPlugin.functionSchema', + name: 'chat_gpt_plugin.functionSchema', }); diff --git a/src/generated/operations/chat-gpt.ts b/src/generated/operations/chat-gpt.ts index 71c46c0d5..b3974b817 100644 --- a/src/generated/operations/chat-gpt.ts +++ b/src/generated/operations/chat-gpt.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `ChatGPT` controller of the API. Import it as the `chatGpt` namespace. + * The `ChatGPT` controller of the API. Import it as the `chat_gpt` namespace. * * @module */ @@ -29,7 +29,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/chatgpt/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the chat to delete */ @@ -39,7 +39,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'chatGpt.destroy', + name: 'chat_gpt.destroy', }); /** @@ -57,7 +57,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/chatgpt', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -75,7 +75,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Chat), - name: 'chatGpt.query', + name: 'chat_gpt.query', }); /** @@ -93,7 +93,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/chatgpt/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** return the chat messages associated with this chat id */ @@ -112,5 +112,5 @@ const SHOW = /* @__PURE__ */ operation({ ['role', 'timestamp'], ), ), - name: 'chatGpt.show', + name: 'chat_gpt.show', }); diff --git a/src/generated/operations/cluster.ts b/src/generated/operations/cluster.ts index f530edd5a..e09666efa 100644 --- a/src/generated/operations/cluster.ts +++ b/src/generated/operations/cluster.ts @@ -29,7 +29,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/cluster/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** specifies the core node we want to send the request to */ @@ -59,7 +59,7 @@ export function nodes( const NODES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/cluster', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return the detailed status of the node including memory and CPU usage? */ include_status: /* @__PURE__ */ boolean(), @@ -87,7 +87,7 @@ export function rebalance( const REBALANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/cluster/rebalance', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: ClusterVersions, @@ -109,7 +109,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/cluster/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** specifies the core node we want to send the request to */ diff --git a/src/generated/operations/domains.ts b/src/generated/operations/domains.ts index e9af82b53..a4b39827b 100644 --- a/src/generated/operations/domains.ts +++ b/src/generated/operations/domains.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/domains', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Authority, response: Authority, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/domains/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -78,7 +78,7 @@ export function lookup( const LOOKUP = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/domains/lookup/{email}', - pathKeys: ['email'], + path_keys: ['email'], params: /* @__PURE__ */ parameters( { /** User email to lookup domain for */ @@ -106,7 +106,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/domains', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -142,7 +142,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/domains/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -169,7 +169,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/domains/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/drivers.ts b/src/generated/operations/drivers.ts index 4bbf010b6..50b68272b 100644 --- a/src/generated/operations/drivers.ts +++ b/src/generated/operations/drivers.ts @@ -29,7 +29,7 @@ export function compiled( const COMPILED = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/drivers/{id}/compiled', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -56,7 +56,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/drivers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Driver, response: Driver, @@ -78,7 +78,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/drivers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -105,7 +105,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/drivers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter by the type of driver */ role: /* @__PURE__ */ nullable(DriverRole), @@ -145,7 +145,7 @@ export function readme( const README = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/drivers/{id}/readme', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -172,7 +172,7 @@ export function recompile( const RECOMPILE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/drivers/{id}/recompile', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -199,7 +199,7 @@ export function reload( const RELOAD = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/drivers/{id}/reload', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -226,7 +226,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/drivers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -255,7 +255,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/drivers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/edges.ts b/src/generated/operations/edges.ts index 33fd3346d..d075e7852 100644 --- a/src/generated/operations/edges.ts +++ b/src/generated/operations/edges.ts @@ -47,7 +47,7 @@ export function cleanupErrors( const CLEANUP_ERRORS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/edges/monitoring/cleanup', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** Hours of error history to retain */ hours: /* @__PURE__ */ integer('Int32'), @@ -72,7 +72,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/edges', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: EdgeCreateBody, response: EdgeKeyResponse, @@ -94,7 +94,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/edges/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -121,7 +121,7 @@ export function edgeConnections( const EDGE_CONNECTIONS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}/connections', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -148,7 +148,7 @@ export function edgeErrors( const EDGE_ERRORS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}/errors', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -179,7 +179,7 @@ export function edgeHealth( const EDGE_HEALTH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}/health', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -206,7 +206,7 @@ export function edgeModuleStatus( const EDGE_MODULE_STATUS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}/modules/status', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -233,7 +233,7 @@ export function edgesConnections( const EDGES_CONNECTIONS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/connections', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(ConnectionMetrics), @@ -255,7 +255,7 @@ export function edgesErrors( const EDGES_ERRORS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/errors', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** Number of recent errors to return */ limit: /* @__PURE__ */ integer('Int32'), @@ -282,7 +282,7 @@ export function edgesHealth( const EDGES_HEALTH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/health', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(EdgeHealth), @@ -304,7 +304,7 @@ export function edgesModuleFailures( const EDGES_MODULE_FAILURES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/modules/failures', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record( @@ -328,7 +328,7 @@ export function edgesStatistics( const EDGES_STATISTICS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/statistics', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: EdgeStatistics, @@ -350,7 +350,7 @@ export function monitoringSummary( const MONITORING_SUMMARY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/monitoring/summary', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ record(/* @__PURE__ */ json())), @@ -375,7 +375,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -411,7 +411,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -438,7 +438,7 @@ export function token( const TOKEN = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/edges/{id}/token', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -470,7 +470,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/edges/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/flux.ts b/src/generated/operations/flux.ts index 4d07a8d96..c64f60f69 100644 --- a/src/generated/operations/flux.ts +++ b/src/generated/operations/flux.ts @@ -28,7 +28,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'POST', path: '/api/v2/query', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ string(), response: null, diff --git a/src/generated/operations/groups-history.ts b/src/generated/operations/groups-history.ts index 4726fbf17..a0b57bfc9 100644 --- a/src/generated/operations/groups-history.ts +++ b/src/generated/operations/groups-history.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `Groups::History` controller of the API. Import it as the `groupsHistory` namespace. + * The `Groups::History` controller of the API. Import it as the `groups_history` namespace. * * @module */ @@ -32,7 +32,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_history', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return changes to this group and its memberships */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -52,7 +52,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(History), - name: 'groupsHistory.query', + name: 'groups_history.query', }); /** `GET /api/engine/v2/group_history/{id}` */ @@ -66,7 +66,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_history/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -75,5 +75,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: History, - name: 'groupsHistory.show', + name: 'groups_history.show', }); diff --git a/src/generated/operations/groups-invitations.ts b/src/generated/operations/groups-invitations.ts index ad3d93724..d00ebceb9 100644 --- a/src/generated/operations/groups-invitations.ts +++ b/src/generated/operations/groups-invitations.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `Groups::Invitations` controller of the API. Import it as the `groupsInvitations` namespace. + * The `Groups::Invitations` controller of the API. Import it as the `groups_invitations` namespace. * * @module */ @@ -37,7 +37,7 @@ export function accept( const ACCEPT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/group_invitations/{id}/accept', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -46,7 +46,7 @@ const ACCEPT = /* @__PURE__ */ operation({ ), body: null, response: GroupUser, - name: 'groupsInvitations.accept', + name: 'groups_invitations.accept', }); /** @@ -67,11 +67,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/group_invitations', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: GroupsInvitationsInvitationCreatePayload, response: GroupsInvitationsInvitationCreatedResponse, - name: 'groupsInvitations.create', + name: 'groups_invitations.create', }); /** `DELETE /api/engine/v2/group_invitations/{id}` */ @@ -85,7 +85,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/group_invitations/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -94,7 +94,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'groupsInvitations.destroy', + name: 'groups_invitations.destroy', }); /** @@ -115,7 +115,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_invitations', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), limit: /* @__PURE__ */ integer('Int32'), @@ -132,7 +132,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupInvitation), - name: 'groupsInvitations.query', + name: 'groups_invitations.query', }); /** `GET /api/engine/v2/group_invitations/{id}` */ @@ -146,7 +146,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_invitations/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -155,5 +155,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupInvitation, - name: 'groupsInvitations.show', + name: 'groups_invitations.show', }); diff --git a/src/generated/operations/groups-users.ts b/src/generated/operations/groups-users.ts index 48564c0d5..2ea6c2d4c 100644 --- a/src/generated/operations/groups-users.ts +++ b/src/generated/operations/groups-users.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `Groups::Users` controller of the API. Import it as the `groupsUsers` namespace. + * The `Groups::Users` controller of the API. Import it as the `groups_users` namespace. * * @module */ @@ -25,11 +25,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/group_users', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: GroupUser, response: GroupUser, - name: 'groupsUsers.create', + name: 'groups_users.create', }); /** `DELETE /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -43,7 +43,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/group_users/{user_id}/{group_id}', - pathKeys: ['user_id', 'group_id'], + path_keys: ['user_id', 'group_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -53,7 +53,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'groupsUsers.destroy', + name: 'groups_users.destroy', }); /** @@ -74,7 +74,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_users', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -92,7 +92,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupUser), - name: 'groupsUsers.query', + name: 'groups_users.query', }); /** `GET /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -106,7 +106,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_users/{user_id}/{group_id}', - pathKeys: ['user_id', 'group_id'], + path_keys: ['user_id', 'group_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -116,7 +116,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupUser, - name: 'groupsUsers.show', + name: 'groups_users.show', }); /** `PATCH /api/engine/v2/group_users/{user_id}/{group_id}` */ @@ -130,7 +130,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/group_users/{user_id}/{group_id}', - pathKeys: ['user_id', 'group_id'], + path_keys: ['user_id', 'group_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -140,5 +140,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: GroupUser, response: GroupUser, - name: 'groupsUsers.update', + name: 'groups_users.update', }); diff --git a/src/generated/operations/groups-zones.ts b/src/generated/operations/groups-zones.ts index 9efe7e7b6..80e9f926b 100644 --- a/src/generated/operations/groups-zones.ts +++ b/src/generated/operations/groups-zones.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `Groups::Zones` controller of the API. Import it as the `groupsZones` namespace. + * The `Groups::Zones` controller of the API. Import it as the `groups_zones` namespace. * * @module */ @@ -25,11 +25,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/group_zones', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: GroupZone, response: GroupZone, - name: 'groupsZones.create', + name: 'groups_zones.create', }); /** `DELETE /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -43,7 +43,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', - pathKeys: ['group_id', 'zone_id'], + path_keys: ['group_id', 'zone_id'], params: /* @__PURE__ */ parameters( { group_id: /* @__PURE__ */ string(), @@ -53,7 +53,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'groupsZones.destroy', + name: 'groups_zones.destroy', }); /** @@ -71,7 +71,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_zones', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -89,7 +89,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(GroupZone), - name: 'groupsZones.query', + name: 'groups_zones.query', }); /** `GET /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -103,7 +103,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', - pathKeys: ['group_id', 'zone_id'], + path_keys: ['group_id', 'zone_id'], params: /* @__PURE__ */ parameters( { group_id: /* @__PURE__ */ string(), @@ -113,7 +113,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: GroupZone, - name: 'groupsZones.show', + name: 'groups_zones.show', }); /** `PATCH /api/engine/v2/group_zones/{group_id}/{zone_id}` */ @@ -127,7 +127,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/group_zones/{group_id}/{zone_id}', - pathKeys: ['group_id', 'zone_id'], + path_keys: ['group_id', 'zone_id'], params: /* @__PURE__ */ parameters( { group_id: /* @__PURE__ */ string(), @@ -137,5 +137,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: GroupZone, response: GroupZone, - name: 'groupsZones.update', + name: 'groups_zones.update', }); diff --git a/src/generated/operations/groups.ts b/src/generated/operations/groups.ts index 78cf182b2..11a2df6ef 100644 --- a/src/generated/operations/groups.ts +++ b/src/generated/operations/groups.ts @@ -41,7 +41,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/groups', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Group, response: Group, @@ -59,7 +59,7 @@ export function current( const CURRENT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/groups/current', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter to groups participating in this subsystem (e.g. 'signage') */ subsystem: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -84,7 +84,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/groups/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -114,7 +114,7 @@ export function features( const FEATURES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/groups/{id}/features', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -148,7 +148,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/groups', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter by parent group id; pass 'root' for root-level groups */ parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -183,7 +183,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/groups/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -215,7 +215,7 @@ export function syncAdGroups( const SYNC_AD_GROUPS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/groups/ad_groups/sync', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: GroupsAdGroupSync, response: /* @__PURE__ */ array(GroupUser), @@ -240,7 +240,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/groups/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/history.ts b/src/generated/operations/history.ts index b3051ceb1..75a804186 100644 --- a/src/generated/operations/history.ts +++ b/src/generated/operations/history.ts @@ -29,7 +29,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/history', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return changes to these resource types (table names) */ resource_types: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), @@ -79,7 +79,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/history/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -109,7 +109,7 @@ export function undelete( const UNDELETE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/history/undelete', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the type (table name) of the deleted resource */ diff --git a/src/generated/operations/index.ts b/src/generated/operations/index.ts index 2a8dd1ae4..aa4223db4 100644 --- a/src/generated/operations/index.ts +++ b/src/generated/operations/index.ts @@ -1,60 +1,60 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** One namespace for each controller of the API. */ -export * as alertDashboards from './alert-dashboards.ts'; +export * as alert_dashboards from './alert-dashboards.ts'; export * as alerts from './alerts.ts'; -export * as apiKeys from './api-keys.ts'; -export * as assetCategories from './asset-categories.ts'; -export * as assetPurchaseOrders from './asset-purchase-orders.ts'; -export * as assetTypes from './asset-types.ts'; +export * as api_keys from './api-keys.ts'; +export * as asset_categories from './asset-categories.ts'; +export * as asset_purchase_orders from './asset-purchase-orders.ts'; +export * as asset_types from './asset-types.ts'; export * as assets from './assets.ts'; export * as brokers from './brokers.ts'; -export * as buildMonitor from './build-monitor.ts'; -export * as chatGpt from './chat-gpt.ts'; -export * as chatGptPlugin from './chat-gpt-plugin.ts'; +export * as build_monitor from './build-monitor.ts'; +export * as chat_gpt from './chat-gpt.ts'; +export * as chat_gpt_plugin from './chat-gpt-plugin.ts'; export * as cluster from './cluster.ts'; export * as domains from './domains.ts'; export * as drivers from './drivers.ts'; export * as edges from './edges.ts'; export * as flux from './flux.ts'; export * as groups from './groups.ts'; -export * as groupsHistory from './groups-history.ts'; -export * as groupsInvitations from './groups-invitations.ts'; -export * as groupsUsers from './groups-users.ts'; -export * as groupsZones from './groups-zones.ts'; +export * as groups_history from './groups-history.ts'; +export * as groups_invitations from './groups-invitations.ts'; +export * as groups_users from './groups-users.ts'; +export * as groups_zones from './groups-zones.ts'; export * as history from './history.ts'; -export * as ldapAuthentications from './ldap-authentications.ts'; +export * as ldap_authentications from './ldap-authentications.ts'; export * as mqtt from './mqtt.ts'; -export * as mapAi from './map-ai.ts'; +export * as map_ai from './map-ai.ts'; export * as metadata from './metadata.ts'; export * as modules from './modules.ts'; -export * as oauthApplications from './oauth-applications.ts'; -export * as oauthAuthentications from './oauth-authentications.ts'; -export * as pendingMails from './pending-mails.ts'; +export * as oauth_applications from './oauth-applications.ts'; +export * as oauth_authentications from './oauth-authentications.ts'; +export * as pending_mails from './pending-mails.ts'; export * as playlist from './playlist.ts'; -export * as playlistMedia from './playlist-media.ts'; -export * as publicEvents from './public-events.ts'; -export * as pushNotifications from './push-notifications.ts'; +export * as playlist_media from './playlist-media.ts'; +export * as public_events from './public-events.ts'; +export * as push_notifications from './push-notifications.ts'; export * as repositories from './repositories.ts'; export * as root from './root.ts'; -export * as samlAuthentications from './saml-authentications.ts'; +export * as saml_authentications from './saml-authentications.ts'; export * as schema from './schema.ts'; export * as settings from './settings.ts'; -export * as shortUrl from './short-url.ts'; +export * as short_url from './short-url.ts'; export * as signage from './signage.ts'; -export * as signageAi from './signage-ai.ts'; -export * as signageAiProviders from './signage-ai-providers.ts'; -export * as signagePlugins from './signage-plugins.ts'; -export * as signageTemplateMappings from './signage-template-mappings.ts'; -export * as signageTemplates from './signage-templates.ts'; +export * as signage_ai from './signage-ai.ts'; +export * as signage_ai_providers from './signage-ai-providers.ts'; +export * as signage_plugins from './signage-plugins.ts'; +export * as signage_template_mappings from './signage-template-mappings.ts'; +export * as signage_templates from './signage-templates.ts'; export * as storages from './storages.ts'; -export * as systemTriggers from './system-triggers.ts'; +export * as system_triggers from './system-triggers.ts'; export * as systems from './systems.ts'; -export * as tenantConsent from './tenant-consent.ts'; +export * as tenant_consent from './tenant-consent.ts'; export * as triggers from './triggers.ts'; export * as uploads from './uploads.ts'; -export * as urlProxy from './url-proxy.ts'; +export * as url_proxy from './url-proxy.ts'; export * as users from './users.ts'; -export * as webRtc from './web-rtc.ts'; +export * as web_rtc from './web-rtc.ts'; export * as webhook from './webhook.ts'; export * as zones from './zones.ts'; diff --git a/src/generated/operations/ldap-authentications.ts b/src/generated/operations/ldap-authentications.ts index 519efd49a..724ea59ab 100644 --- a/src/generated/operations/ldap-authentications.ts +++ b/src/generated/operations/ldap-authentications.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `LdapAuthentications` controller of the API. Import it as the `ldapAuthentications` + * The `LdapAuthentications` controller of the API. Import it as the `ldap_authentications` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/ldap_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: LdapAuthentication, response: LdapAuthentication, - name: 'ldapAuthentications.create', + name: 'ldap_authentications.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/ldap_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -61,7 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'ldapAuthentications.destroy', + name: 'ldap_authentications.destroy', }); /** @@ -79,7 +79,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/ldap_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return authentications that belong to the provided domain */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -99,7 +99,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(LdapAuthentication), - name: 'ldapAuthentications.query', + name: 'ldap_authentications.query', }); /** @@ -117,7 +117,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/ldap_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -126,7 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: LdapAuthentication, - name: 'ldapAuthentications.show', + name: 'ldap_authentications.show', }); /** @@ -144,7 +144,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/ldap_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -153,5 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: LdapAuthentication, response: LdapAuthentication, - name: 'ldapAuthentications.update', + name: 'ldap_authentications.update', }); diff --git a/src/generated/operations/map-ai.ts b/src/generated/operations/map-ai.ts index 2c42a1a55..4cbbf631d 100644 --- a/src/generated/operations/map-ai.ts +++ b/src/generated/operations/map-ai.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `MapAI` controller of the API. Import it as the `mapAi` namespace. + * The `MapAI` controller of the API. Import it as the `map_ai` namespace. * * @module */ @@ -35,7 +35,7 @@ export function cancel( const CANCEL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/maps/ai/jobs/{id}/cancel', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -44,7 +44,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: MapAiJobResponse, - name: 'mapAi.cancel', + name: 'map_ai.cancel', }); /** @@ -62,11 +62,11 @@ export function capabilities( const CAPABILITIES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/maps/ai/capabilities', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: MapAiCapabilities, - name: 'mapAi.capabilities', + name: 'map_ai.capabilities', }); /** @@ -84,11 +84,11 @@ export function edit( const EDIT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/maps/ai/edit', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: MapAiEditParams, response: MapAiJobResponse, - name: 'mapAi.edit', + name: 'map_ai.edit', }); /** @@ -106,7 +106,7 @@ export function indexJobs( const INDEX_JOBS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/maps/ai/jobs', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only the caller's own jobs */ mine: /* @__PURE__ */ boolean(), @@ -118,7 +118,7 @@ const INDEX_JOBS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(MapAiJobResponse), - name: 'mapAi.indexJobs', + name: 'map_ai.indexJobs', }); /** @@ -139,7 +139,7 @@ export function resolve( const RESOLVE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/maps/ai/jobs/{id}/resolve', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -148,7 +148,7 @@ const RESOLVE = /* @__PURE__ */ operation({ ), body: MapAiResolveParams, response: MapAiJobResponse, - name: 'mapAi.resolve', + name: 'map_ai.resolve', }); /** @@ -166,7 +166,7 @@ export function showJob( const SHOW_JOB = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/maps/ai/jobs/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -179,7 +179,7 @@ const SHOW_JOB = /* @__PURE__ */ operation({ ), body: null, response: MapAiJobResponse, - name: 'mapAi.showJob', + name: 'map_ai.showJob', }); /** @@ -197,7 +197,7 @@ export function usage( const USAGE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/maps/ai/usage', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** unix seconds, defaults to 30 days ago */ from: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -206,5 +206,5 @@ const USAGE = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobUsageRow), - name: 'mapAi.usage', + name: 'map_ai.usage', }); diff --git a/src/generated/operations/metadata.ts b/src/generated/operations/metadata.ts index 1bb2338fb..ef470d013 100644 --- a/src/generated/operations/metadata.ts +++ b/src/generated/operations/metadata.ts @@ -41,7 +41,7 @@ export function bulkFetch( const BULK_FETCH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/metadata/{name}/bulk', - pathKeys: ['name'], + path_keys: ['name'], params: /* @__PURE__ */ parameters( { /** the name of the metadata key to fetch */ @@ -76,7 +76,7 @@ export function childrenMetadata( const CHILDREN_METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/metadata/{id}/children', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be returned */ @@ -108,7 +108,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/metadata/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be returned */ @@ -138,7 +138,7 @@ export function history( const HISTORY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/metadata/{id}/history', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be returned */ @@ -175,7 +175,7 @@ export function merge( const MERGE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/metadata/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be updated */ @@ -205,7 +205,7 @@ export function rename( const RENAME = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/metadata/{id}/name', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be renamed */ @@ -237,7 +237,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/metadata/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be returned */ @@ -270,7 +270,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PUT', path: '/api/engine/v2/metadata/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the parent id of the metadata to be replaced */ diff --git a/src/generated/operations/modules.ts b/src/generated/operations/modules.ts index 58f2e6485..3948d24b9 100644 --- a/src/generated/operations/modules.ts +++ b/src/generated/operations/modules.ts @@ -38,7 +38,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** add the new module to this control system */ system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -63,7 +63,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/modules/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -93,7 +93,7 @@ export function execute( const EXECUTE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules/{id}/exec/{method}', - pathKeys: ['id', 'method'], + path_keys: ['id', 'method'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -125,7 +125,7 @@ export function load( const LOAD = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules/{id}/load', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -157,7 +157,7 @@ export function logs( const LOGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/logs', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -191,7 +191,7 @@ export function ping( const PING = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules/{id}/ping', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -218,7 +218,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return modules updated before this time (unix epoch) */ as_of: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -266,7 +266,7 @@ export function settings( const SETTINGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/settings', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -293,7 +293,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -322,7 +322,7 @@ export function showError( const SHOW_ERROR = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/error', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -349,7 +349,7 @@ export function start( const START = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules/{id}/start', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -376,7 +376,7 @@ export function state( const STATE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/state', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -403,7 +403,7 @@ export function stateLookup( const STATE_LOOKUP = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/state/{key}', - pathKeys: ['id', 'key'], + path_keys: ['id', 'key'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -435,7 +435,7 @@ export function stateValue( const STATE_VALUE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/modules/{id}/state/{key}/value', - pathKeys: ['id', 'key'], + path_keys: ['id', 'key'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -464,7 +464,7 @@ export function stop( const STOP = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/modules/{id}/stop', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -491,7 +491,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/modules/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/mqtt.ts b/src/generated/operations/mqtt.ts index f6c3709f4..8a7d2e73f 100644 --- a/src/generated/operations/mqtt.ts +++ b/src/generated/operations/mqtt.ts @@ -33,7 +33,7 @@ export function mqttAccess( const MQTT_ACCESS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/mqtt/access', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { topic: /* @__PURE__ */ string(), @@ -66,7 +66,7 @@ export function mqttUser( const MQTT_USER = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/mqtt/user', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: null, diff --git a/src/generated/operations/oauth-applications.ts b/src/generated/operations/oauth-applications.ts index 9990d59dd..94a7bea34 100644 --- a/src/generated/operations/oauth-applications.ts +++ b/src/generated/operations/oauth-applications.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `OAuthApplications` controller of the API. Import it as the `oauthApplications` namespace. + * The `OAuthApplications` controller of the API. Import it as the `oauth_applications` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/oauth_apps', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: DoorkeeperApplication, response: DoorkeeperApplication, - name: 'oauthApplications.create', + name: 'oauth_applications.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/oauth_apps/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'oauthApplications.destroy', + name: 'oauth_applications.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_apps', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * the ID of the domain to be listed; ignored for non-admin/support callers (forced to their @@ -102,7 +102,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), - name: 'oauthApplications.query', + name: 'oauth_applications.query', }); /** @@ -120,7 +120,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_apps/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -129,7 +129,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: DoorkeeperApplication, - name: 'oauthApplications.show', + name: 'oauth_applications.show', }); /** @@ -147,7 +147,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/oauth_apps/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -156,5 +156,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: DoorkeeperApplication, response: DoorkeeperApplication, - name: 'oauthApplications.update', + name: 'oauth_applications.update', }); diff --git a/src/generated/operations/oauth-authentications.ts b/src/generated/operations/oauth-authentications.ts index a72d2d171..517079e0c 100644 --- a/src/generated/operations/oauth-authentications.ts +++ b/src/generated/operations/oauth-authentications.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `OAuthAuthentications` controller of the API. Import it as the `oauthAuthentications` + * The `OAuthAuthentications` controller of the API. Import it as the `oauth_authentications` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/oauth_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: OauthAuthentication, response: OauthAuthentication, - name: 'oauthAuthentications.create', + name: 'oauth_authentications.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/oauth_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -61,7 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'oauthAuthentications.destroy', + name: 'oauth_authentications.destroy', }); /** @@ -79,7 +79,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return authentications that belong to the provided domain */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -99,7 +99,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(OauthAuthentication), - name: 'oauthAuthentications.query', + name: 'oauth_authentications.query', }); /** @@ -117,7 +117,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/oauth_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -126,7 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: OauthAuthentication, - name: 'oauthAuthentications.show', + name: 'oauth_authentications.show', }); /** @@ -144,7 +144,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/oauth_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -153,5 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: OauthAuthentication, response: OauthAuthentication, - name: 'oauthAuthentications.update', + name: 'oauth_authentications.update', }); diff --git a/src/generated/operations/pending-mails.ts b/src/generated/operations/pending-mails.ts index 6b67c993b..ec4f3520e 100644 --- a/src/generated/operations/pending-mails.ts +++ b/src/generated/operations/pending-mails.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `PendingMails` controller of the API. Import it as the `pendingMails` namespace. + * The `PendingMails` controller of the API. Import it as the `pending_mails` namespace. * * @module */ @@ -29,14 +29,14 @@ export function cleanup( const CLEANUP = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/emails/cleanup', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** authority to clean up (defaults to the caller's authority) */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), }), body: null, response: null, - name: 'pendingMails.cleanup', + name: 'pending_mails.cleanup', }); /** @@ -54,7 +54,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/emails/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -63,7 +63,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'pendingMails.destroy', + name: 'pending_mails.destroy', }); /** @@ -81,7 +81,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/emails', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only mail whose zones are anchored to this group */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -127,7 +127,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PendingMail), - name: 'pendingMails.query', + name: 'pending_mails.query', }); /** @@ -145,7 +145,7 @@ export function reject( const REJECT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/emails/{id}/reject', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -156,7 +156,7 @@ const REJECT = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, - name: 'pendingMails.reject', + name: 'pending_mails.reject', }); /** @@ -174,7 +174,7 @@ export function sent( const SENT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/emails/{id}/sent', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -185,7 +185,7 @@ const SENT = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, - name: 'pendingMails.sent', + name: 'pending_mails.sent', }); /** @@ -203,7 +203,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/emails/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -212,5 +212,5 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: PendingMail, - name: 'pendingMails.show', + name: 'pending_mails.show', }); diff --git a/src/generated/operations/playlist-media.ts b/src/generated/operations/playlist-media.ts index b83ebeaf2..ce33ecf0e 100644 --- a/src/generated/operations/playlist-media.ts +++ b/src/generated/operations/playlist-media.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `PlaylistMedia` controller of the API. Import it as the `playlistMedia` namespace. + * The `PlaylistMedia` controller of the API. Import it as the `playlist_media` namespace. * * @module */ @@ -42,14 +42,14 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/media', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** group id to auto-link the new item to (required for non-admin callers) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), }), body: PlaylistItem, response: PlaylistItem, - name: 'playlistMedia.create', + name: 'playlist_media.create', }); /** @@ -71,7 +71,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/media/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -86,7 +86,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'playlistMedia.destroy', + name: 'playlist_media.destroy', }); /** @@ -110,7 +110,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter to items linked to this group (caller must have Read on the group) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -127,7 +127,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(PlaylistItem), - name: 'playlistMedia.query', + name: 'playlist_media.query', }); /** @@ -151,7 +151,7 @@ export function removeTag( const REMOVE_TAG = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/media/tags', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the tag to be removed */ @@ -169,7 +169,7 @@ const REMOVE_TAG = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'playlistMedia.removeTag', + name: 'playlist_media.removeTag', }); /** @@ -191,7 +191,7 @@ export function renameTag( const RENAME_TAG = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/media/tags', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the existing tag to be renamed */ @@ -207,7 +207,7 @@ const RENAME_TAG = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'playlistMedia.renameTag', + name: 'playlist_media.renameTag', }); /** @@ -235,7 +235,7 @@ export function share( const SHARE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/media/share', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** comma-separated item ids to share into the target group */ @@ -253,7 +253,7 @@ const SHARE = /* @__PURE__ */ operation({ }, ['linked', 'already_present'], ), - name: 'playlistMedia.share', + name: 'playlist_media.share', }); /** @@ -274,7 +274,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -283,7 +283,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: PlaylistItem, - name: 'playlistMedia.show', + name: 'playlist_media.show', }); /** @@ -306,14 +306,14 @@ export function tagCounts( const TAG_COUNTS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media/tag_counts', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** limit to media linked to this group (caller must have Read on the group) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), }), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), - name: 'playlistMedia.tagCounts', + name: 'playlist_media.tagCounts', }); /** @@ -336,14 +336,14 @@ export function tags( const TAGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media/tags', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** limit to media linked to this group (caller must have Read on the group) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), }), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), - name: 'playlistMedia.tags', + name: 'playlist_media.tags', }); /** @@ -361,7 +361,7 @@ export function thumbnail( const THUMBNAIL = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/media/{id}/thumbnail', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -370,7 +370,7 @@ const THUMBNAIL = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'playlistMedia.thumbnail', + name: 'playlist_media.thumbnail', }); /** @@ -388,7 +388,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/media/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -397,5 +397,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: PlaylistItem, response: PlaylistItem, - name: 'playlistMedia.update', + name: 'playlist_media.update', }); diff --git a/src/generated/operations/playlist.ts b/src/generated/operations/playlist.ts index 0f1794363..332d5ae6b 100644 --- a/src/generated/operations/playlist.ts +++ b/src/generated/operations/playlist.ts @@ -44,7 +44,7 @@ export function approveMedia( const APPROVE_MEDIA = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists/{id}/media/approve', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -74,7 +74,7 @@ export function approvers( const APPROVERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists/approvers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** group to find approvers for */ @@ -107,7 +107,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** group id to auto-link the new playlist to (required for non-admin callers) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -136,7 +136,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/playlists/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -175,7 +175,7 @@ export function history( const HISTORY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists/{id}/history', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -224,7 +224,7 @@ export function media( const MEDIA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists/{id}/media', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -251,7 +251,7 @@ export function mediaRevisions( const MEDIA_REVISIONS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists/{id}/media/revisions', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -285,7 +285,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter to playlists linked to this group (caller must have Read on the group) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -322,7 +322,7 @@ export function requestApproval( const REQUEST_APPROVAL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists/{id}/media/request_approval', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -353,7 +353,7 @@ export function scheduleMedia( const SCHEDULE_MEDIA = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists/{id}/media/schedule', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -390,7 +390,7 @@ export function share( const SHARE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists/share', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** comma-separated playlist ids to share into the target group */ @@ -428,7 +428,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/playlists/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -455,7 +455,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/playlists/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -482,7 +482,7 @@ export function updateMedia( const UPDATE_MEDIA = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/playlists/{id}/media', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -505,7 +505,7 @@ export function updateSchedule( const UPDATE_SCHEDULE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/playlists/{id}/media/schedule/{item_id}', - pathKeys: ['id', 'item_id'], + path_keys: ['id', 'item_id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/public-events.ts b/src/generated/operations/public-events.ts index 4b91077c6..fb593c858 100644 --- a/src/generated/operations/public-events.ts +++ b/src/generated/operations/public-events.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `PublicEvents` controller of the API. Import it as the `publicEvents` namespace. + * The `PublicEvents` controller of the API. Import it as the `public_events` namespace. * * @module */ @@ -38,7 +38,7 @@ export function guestToken( const GUEST_TOKEN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/public_events/guest_token/{system_id}', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -47,7 +47,7 @@ const GUEST_TOKEN = /* @__PURE__ */ operation({ ), body: PublicEventsTokenRequest, response: /* @__PURE__ */ string(), - name: 'publicEvents.guestToken', + name: 'public_events.guestToken', }); /** @@ -73,7 +73,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/public_events/{system_id}/events', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -97,7 +97,7 @@ const QUERY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ json()), - name: 'publicEvents.query', + name: 'public_events.query', }); /** @@ -122,7 +122,7 @@ export function register( const REGISTER = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/public_events/{system_id}/register', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -131,5 +131,5 @@ const REGISTER = /* @__PURE__ */ operation({ ), body: PublicEventsRegistrationRequest, response: null, - name: 'publicEvents.register', + name: 'public_events.register', }); diff --git a/src/generated/operations/push-notifications.ts b/src/generated/operations/push-notifications.ts index f679b242f..cef936440 100644 --- a/src/generated/operations/push-notifications.ts +++ b/src/generated/operations/push-notifications.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `PushNotifications` controller of the API. Import it as the `pushNotifications` namespace. + * The `PushNotifications` controller of the API. Import it as the `push_notifications` namespace. * * @module */ @@ -25,11 +25,11 @@ export function google( const GOOGLE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/notifications/google', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: null, - name: 'pushNotifications.google', + name: 'push_notifications.google', }); /** `POST /api/engine/v2/notifications/office365` */ @@ -43,9 +43,9 @@ export function microsoft( const MICROSOFT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/notifications/office365', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: MicrosoftNotification, response: null, - name: 'pushNotifications.microsoft', + name: 'push_notifications.microsoft', }); diff --git a/src/generated/operations/repositories.ts b/src/generated/operations/repositories.ts index 0448d5feb..0204fa444 100644 --- a/src/generated/operations/repositories.ts +++ b/src/generated/operations/repositories.ts @@ -38,7 +38,7 @@ export function branches( const BRANCHES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/branches', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -65,7 +65,7 @@ export function commits( const COMMITS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/commits', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -98,7 +98,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/repositories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Repository, response: Repository, @@ -120,7 +120,7 @@ export function defaultBranch( const DEFAULT_BRANCH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/default_branch', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -147,7 +147,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/repositories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -178,7 +178,7 @@ export function details( const DETAILS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/details', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -209,7 +209,7 @@ export function drivers( const DRIVERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/drivers', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -239,7 +239,7 @@ export function files( const FILES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/files', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -272,7 +272,7 @@ export function folders( const FOLDERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/folders', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -305,7 +305,7 @@ export function loadedInterfaces( const LOADED_INTERFACES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/interfaces', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ string()), @@ -327,7 +327,7 @@ export function pull( const PULL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/repositories/{id}/pull', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -359,7 +359,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -395,7 +395,7 @@ export function releases( const RELEASES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/releases', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -422,7 +422,7 @@ export function remoteBranches( const REMOTE_BRANCHES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/remote_branches', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the git url that represents the repository */ @@ -454,7 +454,7 @@ export function remoteCommits( const REMOTE_COMMITS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/remote_commits', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the branch to grab commits from */ @@ -490,7 +490,7 @@ export function remoteDefaultBranch( const REMOTE_DEFAULT_BRANCH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/remote_default_branch', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the git url that represents the repository */ @@ -522,7 +522,7 @@ export function remoteTags( const REMOTE_TAGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/remote_tags', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the git url that represents the repository */ @@ -554,7 +554,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -581,7 +581,7 @@ export function tags( const TAGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/repositories/{id}/tags', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -608,7 +608,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/repositories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/root.ts b/src/generated/operations/root.ts index 46c56cf97..4b3e1537e 100644 --- a/src/generated/operations/root.ts +++ b/src/generated/operations/root.ts @@ -29,7 +29,7 @@ export function clusterVersion( const CLUSTER_VERSION = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/cluster/versions', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(Version), @@ -51,7 +51,7 @@ export function platformInfo( const PLATFORM_INFO = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/platform', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: RootPlatformInfo, @@ -73,7 +73,7 @@ export function root( const ROOT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: null, @@ -95,7 +95,7 @@ export function scopes( const SCOPES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/scopes', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), @@ -120,7 +120,7 @@ export function signal( const SIGNAL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signal', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the path we would like to send data to */ @@ -153,7 +153,7 @@ export function sourceResync( const SOURCE_RESYNC = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/source/resync', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** remove everything source publishes from the brokers first */ clear: /* @__PURE__ */ boolean(), @@ -178,7 +178,7 @@ export function sourceResyncStatus( const SOURCE_RESYNC_STATUS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/source/resync', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: RootSourceResyncStatus, @@ -200,7 +200,7 @@ export function version( const VERSION = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/version', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: Version, diff --git a/src/generated/operations/saml-authentications.ts b/src/generated/operations/saml-authentications.ts index f003e3f17..b1d7318b1 100644 --- a/src/generated/operations/saml-authentications.ts +++ b/src/generated/operations/saml-authentications.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SamlAuthentications` controller of the API. Import it as the `samlAuthentications` + * The `SamlAuthentications` controller of the API. Import it as the `saml_authentications` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/saml_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SamlAuthentication, response: SamlAuthentication, - name: 'samlAuthentications.create', + name: 'saml_authentications.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/saml_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -61,7 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'samlAuthentications.destroy', + name: 'saml_authentications.destroy', }); /** @@ -79,7 +79,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/saml_auths', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return authentications that belong to the provided domain */ authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -99,7 +99,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SamlAuthentication), - name: 'samlAuthentications.query', + name: 'saml_authentications.query', }); /** @@ -117,7 +117,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/saml_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -126,7 +126,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SamlAuthentication, - name: 'samlAuthentications.show', + name: 'saml_authentications.show', }); /** @@ -144,7 +144,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/saml_auths/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -153,5 +153,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SamlAuthentication, response: SamlAuthentication, - name: 'samlAuthentications.update', + name: 'saml_authentications.update', }); diff --git a/src/generated/operations/schema.ts b/src/generated/operations/schema.ts index 038092d95..64a8b0623 100644 --- a/src/generated/operations/schema.ts +++ b/src/generated/operations/schema.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/schema', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: JsonSchema, response: JsonSchema, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/schema/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -80,7 +80,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/schema', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -116,7 +116,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/schema/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -143,7 +143,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/schema/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/settings.ts b/src/generated/operations/settings.ts index 38a1bdc22..f06e5e788 100644 --- a/src/generated/operations/settings.ts +++ b/src/generated/operations/settings.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/settings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Settings, response: Settings, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/settings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -78,7 +78,7 @@ export function history( const HISTORY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/settings/{id}/history', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -109,7 +109,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/settings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ parent_id: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), /** @@ -146,7 +146,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/settings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -173,7 +173,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/settings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/short-url.ts b/src/generated/operations/short-url.ts index 5c190b944..5a0bc4003 100644 --- a/src/generated/operations/short-url.ts +++ b/src/generated/operations/short-url.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `ShortURL` controller of the API. Import it as the `shortUrl` namespace. + * The `ShortURL` controller of the API. Import it as the `short_url` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/short_url', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Shortener, response: Shortener, - name: 'shortUrl.create', + name: 'short_url.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/short_url/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'shortUrl.destroy', + name: 'short_url.destroy', }); /** @@ -78,7 +78,7 @@ export function generateQrCode( const GENERATE_QR_CODE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url/qr_code', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the contents of the QR code */ @@ -93,7 +93,7 @@ const GENERATE_QR_CODE = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'shortUrl.generateQrCode', + name: 'short_url.generateQrCode', }); /** @@ -111,7 +111,7 @@ export function pngQr( const PNG_QR = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url/{id}/qr_code.png', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -122,7 +122,7 @@ const PNG_QR = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'shortUrl.pngQr', + name: 'short_url.pngQr', }); /** @@ -140,7 +140,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -158,7 +158,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(Shortener), - name: 'shortUrl.query', + name: 'short_url.query', }); /** @@ -176,7 +176,7 @@ export function redirect( const REDIRECT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url/{id}/redirect', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -185,7 +185,7 @@ const REDIRECT = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'shortUrl.redirect', + name: 'short_url.redirect', }); /** @@ -203,7 +203,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -212,7 +212,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: Shortener, - name: 'shortUrl.show', + name: 'short_url.show', }); /** @@ -230,7 +230,7 @@ export function svgQr( const SVG_QR = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/short_url/{id}/qr_code.svg', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -239,7 +239,7 @@ const SVG_QR = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'shortUrl.svgQr', + name: 'short_url.svgQr', }); /** @@ -257,7 +257,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/short_url/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -266,5 +266,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: Shortener, response: Shortener, - name: 'shortUrl.update', + name: 'short_url.update', }); diff --git a/src/generated/operations/signage-ai-providers.ts b/src/generated/operations/signage-ai-providers.ts index f9fed9b4c..2807420d6 100644 --- a/src/generated/operations/signage-ai-providers.ts +++ b/src/generated/operations/signage-ai-providers.ts @@ -1,6 +1,7 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SignageAIProviders` controller of the API. Import it as the `signageAiProviders` namespace. + * The `SignageAIProviders` controller of the API. Import it as the `signage_ai_providers` + * namespace. * * @module */ @@ -34,7 +35,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/providers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SignageAiProvidersProviderParams, response: /* @__PURE__ */ object( @@ -66,7 +67,7 @@ const CREATE = /* @__PURE__ */ operation({ 'updated_at', ], ), - name: 'signageAiProviders.create', + name: 'signage_ai_providers.create', }); /** `DELETE /api/engine/v2/signage/ai/providers/{id}` */ @@ -80,7 +81,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/ai/providers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -89,7 +90,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'signageAiProviders.destroy', + name: 'signage_ai_providers.destroy', }); /** @@ -113,7 +114,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/providers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** include the shared fallback row */ include_shared: /* @__PURE__ */ boolean(), @@ -163,7 +164,7 @@ const QUERY = /* @__PURE__ */ operation({ ], ), ), - name: 'signageAiProviders.query', + name: 'signage_ai_providers.query', }); /** `GET /api/engine/v2/signage/ai/providers/{id}` */ @@ -177,7 +178,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/providers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -214,7 +215,7 @@ const SHOW = /* @__PURE__ */ operation({ 'updated_at', ], ), - name: 'signageAiProviders.show', + name: 'signage_ai_providers.show', }); /** @@ -235,7 +236,7 @@ export function test( const TEST = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/providers/{id}/test', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -246,7 +247,7 @@ const TEST = /* @__PURE__ */ operation({ ), body: null, response: SignageAiProvidersTestResult, - name: 'signageAiProviders.test', + name: 'signage_ai_providers.test', }); /** `PATCH /api/engine/v2/signage/ai/providers/{id}` */ @@ -260,7 +261,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/ai/providers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -297,5 +298,5 @@ const UPDATE = /* @__PURE__ */ operation({ 'updated_at', ], ), - name: 'signageAiProviders.update', + name: 'signage_ai_providers.update', }); diff --git a/src/generated/operations/signage-ai.ts b/src/generated/operations/signage-ai.ts index 5d5e98563..165e0ff8a 100644 --- a/src/generated/operations/signage-ai.ts +++ b/src/generated/operations/signage-ai.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SignageAI` controller of the API. Import it as the `signageAi` namespace. + * The `SignageAI` controller of the API. Import it as the `signage_ai` namespace. * * @module */ @@ -36,7 +36,7 @@ export function cancel( const CANCEL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/jobs/{id}/cancel', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -45,7 +45,7 @@ const CANCEL = /* @__PURE__ */ operation({ ), body: null, response: SignageAiJobResponse, - name: 'signageAi.cancel', + name: 'signage_ai.cancel', }); /** @@ -63,11 +63,11 @@ export function capabilities( const CAPABILITIES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/capabilities', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: SignageAiCapabilities, - name: 'signageAi.capabilities', + name: 'signage_ai.capabilities', }); /** @@ -85,7 +85,7 @@ export function claim( const CLAIM = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/jobs/{id}/claim', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -94,7 +94,7 @@ const CLAIM = /* @__PURE__ */ operation({ ), body: SignageAiClaimParams, response: SignageAiJobResponse, - name: 'signageAi.claim', + name: 'signage_ai.claim', }); /** @@ -112,11 +112,11 @@ export function edit( const EDIT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/edit', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SignageAiEditParams, response: SignageAiJobResponse, - name: 'signageAi.edit', + name: 'signage_ai.edit', }); /** @@ -134,11 +134,11 @@ export function generate( const GENERATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/ai/generate', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SignageAiGenerateParams, response: SignageAiJobResponse, - name: 'signageAi.generate', + name: 'signage_ai.generate', }); /** @@ -156,7 +156,7 @@ export function indexJobs( const INDEX_JOBS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/jobs', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only the caller's own jobs */ mine: /* @__PURE__ */ boolean(), @@ -166,7 +166,7 @@ const INDEX_JOBS = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobResponse), - name: 'signageAi.indexJobs', + name: 'signage_ai.indexJobs', }); /** @@ -184,7 +184,7 @@ export function showJob( const SHOW_JOB = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/jobs/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -197,7 +197,7 @@ const SHOW_JOB = /* @__PURE__ */ operation({ ), body: null, response: SignageAiJobResponse, - name: 'signageAi.showJob', + name: 'signage_ai.showJob', }); /** @@ -215,7 +215,7 @@ export function usage( const USAGE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/ai/usage', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** unix seconds, defaults to 30 days ago */ from: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -224,5 +224,5 @@ const USAGE = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageAiJobUsageRow), - name: 'signageAi.usage', + name: 'signage_ai.usage', }); diff --git a/src/generated/operations/signage-plugins.ts b/src/generated/operations/signage-plugins.ts index 5906f717c..66e5b512e 100644 --- a/src/generated/operations/signage-plugins.ts +++ b/src/generated/operations/signage-plugins.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SignagePlugins` controller of the API. Import it as the `signagePlugins` namespace. + * The `SignagePlugins` controller of the API. Import it as the `signage_plugins` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/plugins', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SignagePlugin, response: SignagePlugin, - name: 'signagePlugins.create', + name: 'signage_plugins.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/plugins/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'signagePlugins.destroy', + name: 'signage_plugins.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/plugins', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return plugins that are enabled */ enabled: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), @@ -100,7 +100,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignagePlugin), - name: 'signagePlugins.query', + name: 'signage_plugins.query', }); /** @@ -118,7 +118,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/plugins/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -127,7 +127,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignagePlugin, - name: 'signagePlugins.show', + name: 'signage_plugins.show', }); /** @@ -145,7 +145,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/plugins/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -154,5 +154,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignagePlugin, response: SignagePlugin, - name: 'signagePlugins.update', + name: 'signage_plugins.update', }); diff --git a/src/generated/operations/signage-template-mappings.ts b/src/generated/operations/signage-template-mappings.ts index 549652c76..e539b1d29 100644 --- a/src/generated/operations/signage-template-mappings.ts +++ b/src/generated/operations/signage-template-mappings.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SignageTemplateMappings` controller of the API. Import it as the `signageTemplateMappings` + * The `SignageTemplateMappings` controller of the API. Import it as the `signage_template_mappings` * namespace. * * @module @@ -34,11 +34,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/template_mappings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SignageTemplateSystemTemplate, response: SignageTemplateSystemTemplate, - name: 'signageTemplateMappings.create', + name: 'signage_template_mappings.create', }); /** @@ -56,7 +56,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/template_mappings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -65,7 +65,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'signageTemplateMappings.destroy', + name: 'signage_template_mappings.destroy', }); /** @@ -88,7 +88,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/template_mappings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filter to mappings applied to this display (control system id), including those applied @@ -114,7 +114,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplateSystemTemplate), - name: 'signageTemplateMappings.query', + name: 'signage_template_mappings.query', }); /** @@ -134,7 +134,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/template_mappings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -143,7 +143,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplateSystemTemplate, - name: 'signageTemplateMappings.show', + name: 'signage_template_mappings.show', }); /** @@ -165,7 +165,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/template_mappings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -174,5 +174,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignageTemplateSystemTemplate, response: SignageTemplateSystemTemplate, - name: 'signageTemplateMappings.update', + name: 'signage_template_mappings.update', }); diff --git a/src/generated/operations/signage-templates.ts b/src/generated/operations/signage-templates.ts index 7ab4dc85b..135840e8c 100644 --- a/src/generated/operations/signage-templates.ts +++ b/src/generated/operations/signage-templates.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SignageTemplates` controller of the API. Import it as the `signageTemplates` namespace. + * The `SignageTemplates` controller of the API. Import it as the `signage_templates` namespace. * * @module */ @@ -44,7 +44,7 @@ export function approve( const APPROVE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/templates/{id}/approve', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -53,7 +53,7 @@ const APPROVE = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplate, - name: 'signageTemplates.approve', + name: 'signage_templates.approve', }); /** @@ -74,7 +74,7 @@ export function approvers( const APPROVERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/templates/approvers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** group to find approvers for */ @@ -84,7 +84,7 @@ const APPROVERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(SignageTemplatesApprover), - name: 'signageTemplates.approvers', + name: 'signage_templates.approvers', }); /** @@ -107,14 +107,14 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/templates', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** group id to auto-link the new template to (required for non-admin callers) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), }), body: SignageTemplate, response: SignageTemplate, - name: 'signageTemplates.create', + name: 'signage_templates.create', }); /** @@ -137,7 +137,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/templates/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -152,7 +152,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'signageTemplates.destroy', + name: 'signage_templates.destroy', }); /** @@ -170,7 +170,7 @@ export function destroyDraft( const DESTROY_DRAFT = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/signage/templates/{id}/draft', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -179,7 +179,7 @@ const DESTROY_DRAFT = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'signageTemplates.destroyDraft', + name: 'signage_templates.destroyDraft', }); /** @@ -205,7 +205,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/templates', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filter to templates linked to this group (caller must have Read on the group) */ group_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -222,7 +222,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SignageTemplate), - name: 'signageTemplates.query', + name: 'signage_templates.query', }); /** @@ -244,7 +244,7 @@ export function requestApproval( const REQUEST_APPROVAL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/templates/{id}/request_approval', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -257,7 +257,7 @@ const REQUEST_APPROVAL = /* @__PURE__ */ operation({ ), body: SignageTemplatesApprovalMessage, response: null, - name: 'signageTemplates.requestApproval', + name: 'signage_templates.requestApproval', }); /** @@ -285,7 +285,7 @@ export function share( const SHARE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/templates/share', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** comma-separated template ids to share into the target group */ @@ -303,7 +303,7 @@ const SHARE = /* @__PURE__ */ operation({ }, ['linked', 'already_present'], ), - name: 'signageTemplates.share', + name: 'signage_templates.share', }); /** @@ -325,7 +325,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/templates/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -336,7 +336,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SignageTemplate, - name: 'signageTemplates.show', + name: 'signage_templates.show', }); /** @@ -359,7 +359,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/signage/templates/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -368,5 +368,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SignageTemplate, response: SignageTemplate, - name: 'signageTemplates.update', + name: 'signage_templates.update', }); diff --git a/src/generated/operations/signage.ts b/src/generated/operations/signage.ts index 1b48509f6..cb83d85ee 100644 --- a/src/generated/operations/signage.ts +++ b/src/generated/operations/signage.ts @@ -29,7 +29,7 @@ export function display( const DISPLAY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/{system_id}', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), @@ -63,7 +63,7 @@ export function fetchStaticMedia( const FETCH_STATIC_MEDIA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/{system_id}/static/{item_id}', - pathKeys: ['system_id', 'item_id'], + path_keys: ['system_id', 'item_id'], params: /* @__PURE__ */ parameters( { /** the display showing the media, sizes web page captures */ @@ -98,7 +98,7 @@ export function samsungEinkManifest( const SAMSUNG_EINK_MANIFEST = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/{system_id}/samsung/eink/{item_id}/{expires_after}', - pathKeys: ['system_id', 'item_id', 'expires_after'], + path_keys: ['system_id', 'item_id', 'expires_after'], params: /* @__PURE__ */ parameters( { /** the display showing the media, sizes web page captures */ @@ -133,7 +133,7 @@ export function samsungEinkManifestWithoutExpiresAfter( const SAMSUNG_EINK_MANIFEST_WITHOUT_EXPIRES_AFTER = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/signage/{system_id}/samsung/eink/{item_id}', - pathKeys: ['system_id', 'item_id'], + path_keys: ['system_id', 'item_id'], params: /* @__PURE__ */ parameters( { /** the display showing the media, sizes web page captures */ @@ -163,7 +163,7 @@ export function updateMetrics( const UPDATE_METRICS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/signage/{system_id}/metrics', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { system_id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/storages.ts b/src/generated/operations/storages.ts index 4c9674eb4..c282ee398 100644 --- a/src/generated/operations/storages.ts +++ b/src/generated/operations/storages.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/storages', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Storage, response: Storage, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/storages/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/storages', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return storages which are in the authority provided */ auth_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -116,7 +116,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/storages/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -143,7 +143,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/storages/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/system-triggers.ts b/src/generated/operations/system-triggers.ts index fb003b3da..ef5db83b4 100644 --- a/src/generated/operations/system-triggers.ts +++ b/src/generated/operations/system-triggers.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `SystemTriggers` controller of the API. Import it as the `systemTriggers` namespace. + * The `SystemTriggers` controller of the API. Import it as the `system_triggers` namespace. * * @module */ @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/systems/{sys_id}/triggers', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { /** the id of the system */ @@ -39,7 +39,7 @@ const CREATE = /* @__PURE__ */ operation({ ), body: TriggerInstance, response: TriggerInstance, - name: 'systemTriggers.create', + name: 'system_triggers.create', }); /** @@ -57,7 +57,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/systems/{sys_id}/triggers/{trig_id}', - pathKeys: ['sys_id', 'trig_id'], + path_keys: ['sys_id', 'trig_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -68,7 +68,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'systemTriggers.destroy', + name: 'system_triggers.destroy', }); /** @@ -86,7 +86,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/triggers', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { /** the system to filter on */ @@ -121,7 +121,7 @@ const QUERY = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(TriggerInstance), - name: 'systemTriggers.query', + name: 'system_triggers.query', }); /** @@ -139,7 +139,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/triggers/{trig_id}', - pathKeys: ['sys_id', 'trig_id'], + path_keys: ['sys_id', 'trig_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -151,7 +151,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: TriggerInstance, - name: 'systemTriggers.show', + name: 'system_triggers.show', }); /** @@ -169,7 +169,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/systems/{sys_id}/triggers/{trig_id}', - pathKeys: ['sys_id', 'trig_id'], + path_keys: ['sys_id', 'trig_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -180,5 +180,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SystemTriggersUpdateParams, response: TriggerInstance, - name: 'systemTriggers.update', + name: 'system_triggers.update', }); diff --git a/src/generated/operations/systems.ts b/src/generated/operations/systems.ts index 38d7a771e..1aa7efdfa 100644 --- a/src/generated/operations/systems.ts +++ b/src/generated/operations/systems.ts @@ -44,7 +44,7 @@ export function addModule( const ADD_MODULE = /* @__PURE__ */ operation({ method: 'PUT', path: '/api/engine/v2/systems/{sys_id}/module/{module_id}', - pathKeys: ['sys_id', 'module_id'], + path_keys: ['sys_id', 'module_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -72,7 +72,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/systems', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: ControlSystem, response: ControlSystem, @@ -94,7 +94,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/systems/{sys_id}', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -121,7 +121,7 @@ export function execute( const EXECUTE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/systems/{sys_id}/{module_slug}/{method}', - pathKeys: ['sys_id', 'module_slug', 'method'], + path_keys: ['sys_id', 'module_slug', 'method'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -152,7 +152,7 @@ export function findByEmail( const FIND_BY_EMAIL = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/with_emails', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** comma seperated list of emails */ @@ -182,7 +182,7 @@ export function functions( const FUNCTIONS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/functions/{module_slug}', - pathKeys: ['sys_id', 'module_slug'], + path_keys: ['sys_id', 'module_slug'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -211,7 +211,7 @@ export function metadata( const METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/metadata', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -239,7 +239,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** return only bookable or non-bookable rooms (returns both when not specified) */ bookable: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), @@ -304,7 +304,7 @@ export function removeModule( const REMOVE_MODULE = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/systems/{sys_id}/module/{module_id}', - pathKeys: ['sys_id', 'module_id'], + path_keys: ['sys_id', 'module_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -332,7 +332,7 @@ export function settings( const SETTINGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/settings', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -359,7 +359,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -388,7 +388,7 @@ export function start( const START = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/systems/{sys_id}/start', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -417,7 +417,7 @@ export function state( const STATE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/{module_slug}', - pathKeys: ['sys_id', 'module_slug'], + path_keys: ['sys_id', 'module_slug'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -449,7 +449,7 @@ export function stateLookup( const STATE_LOOKUP = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/{module_slug}/{key}', - pathKeys: ['sys_id', 'module_slug', 'key'], + path_keys: ['sys_id', 'module_slug', 'key'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -480,7 +480,7 @@ export function stop( const STOP = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/systems/{sys_id}/stop', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -509,7 +509,7 @@ export function sysZones( const SYS_ZONES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/zones', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -536,7 +536,7 @@ export function types( const TYPES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/systems/{sys_id}/types', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), @@ -563,7 +563,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/systems/{sys_id}', - pathKeys: ['sys_id'], + path_keys: ['sys_id'], params: /* @__PURE__ */ parameters( { sys_id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/tenant-consent.ts b/src/generated/operations/tenant-consent.ts index 902f5f1cd..7ab6d458d 100644 --- a/src/generated/operations/tenant-consent.ts +++ b/src/generated/operations/tenant-consent.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `TenantConsent` controller of the API. Import it as the `tenantConsent` namespace. + * The `TenantConsent` controller of the API. Import it as the `tenant_consent` namespace. * * @module */ @@ -33,7 +33,7 @@ export function azureAdminConsentCallback( const AZURE_ADMIN_CONSENT_CALLBACK = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/admin_consent/callback', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** Azure AD tenant identifier */ tenant: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -48,7 +48,7 @@ const AZURE_ADMIN_CONSENT_CALLBACK = /* @__PURE__ */ operation({ }), body: null, response: null, - name: 'tenantConsent.azureAdminConsentCallback', + name: 'tenant_consent.azureAdminConsentCallback', }); /** @@ -69,7 +69,7 @@ export function flowStatus( const FLOW_STATUS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/admin_consent/flow/{flow_id}', - pathKeys: ['flow_id'], + path_keys: ['flow_id'], params: /* @__PURE__ */ parameters( { /** Flow identifier issued by the consent callback */ @@ -79,7 +79,7 @@ const FLOW_STATUS = /* @__PURE__ */ operation({ ), body: null, response: AdminConsentFlow, - name: 'tenantConsent.flowStatus', + name: 'tenant_consent.flowStatus', }); /** `GET /api/engine/v2/admin_consent/{id}` */ @@ -93,7 +93,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/admin_consent/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -122,5 +122,5 @@ const QUERY = /* @__PURE__ */ operation({ }, ['url'], ), - name: 'tenantConsent.query', + name: 'tenant_consent.query', }); diff --git a/src/generated/operations/triggers.ts b/src/generated/operations/triggers.ts index 960b78643..615d1535f 100644 --- a/src/generated/operations/triggers.ts +++ b/src/generated/operations/triggers.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/triggers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Trigger, response: Trigger, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/triggers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -78,7 +78,7 @@ export function instances( const INSTANCES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/triggers/{id}/instances', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -105,7 +105,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/triggers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -141,7 +141,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/triggers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -170,7 +170,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/triggers/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/uploads.ts b/src/generated/operations/uploads.ts index 740cd87d6..75a65a76d 100644 --- a/src/generated/operations/uploads.ts +++ b/src/generated/operations/uploads.ts @@ -40,7 +40,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/uploads', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: UploadsUploadInfo, response: /* @__PURE__ */ union([ @@ -97,7 +97,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/uploads/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -129,7 +129,7 @@ export function downloadProxyFileContents( const DOWNLOAD_PROXY_FILE_CONTENTS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/{id}/download', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -161,7 +161,7 @@ export function downloadSimpleRoute( const DOWNLOAD_SIMPLE_ROUTE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/{id}/download/{api_key}/{inline}/{file_name}', - pathKeys: ['id', 'api_key', 'inline', 'file_name'], + path_keys: ['id', 'api_key', 'inline', 'file_name'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -196,7 +196,7 @@ export function downloadSimpleRouteWithoutFileName( const DOWNLOAD_SIMPLE_ROUTE_WITHOUT_FILE_NAME = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/{id}/download/{api_key}/{inline}', - pathKeys: ['id', 'api_key', 'inline'], + path_keys: ['id', 'api_key', 'inline'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -231,7 +231,7 @@ export function edit( const EDIT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/{id}/edit', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -278,7 +278,7 @@ export function finished( const FINISHED = /* @__PURE__ */ operation({ method: 'PUT', path: '/api/engine/v2/uploads/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -311,7 +311,7 @@ export function getLink( const GET_LINK = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/{id}/url', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ @@ -341,7 +341,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** filters results to returns ones where file_name contains this search string */ file_search: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -389,7 +389,7 @@ export function screenshot( const SCREENSHOT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/uploads/screenshot', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: UploadsScreenshotInfo, response: Upload, @@ -411,7 +411,7 @@ export function storageName( const STORAGE_NAME = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/uploads/new', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** Name of file which will be uploaded to cloud storage */ @@ -448,7 +448,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/uploads/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** upload id of the upload */ diff --git a/src/generated/operations/url-proxy.ts b/src/generated/operations/url-proxy.ts index fff3e730a..b337d567c 100644 --- a/src/generated/operations/url-proxy.ts +++ b/src/generated/operations/url-proxy.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `UrlProxy` controller of the API. Import it as the `urlProxy` namespace. + * The `UrlProxy` controller of the API. Import it as the `url_proxy` namespace. * * @module */ @@ -31,7 +31,7 @@ export function proxy( const PROXY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/proxy', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the fully qualified URL to be proxied */ @@ -41,5 +41,5 @@ const PROXY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'urlProxy.proxy', + name: 'url_proxy.proxy', }); diff --git a/src/generated/operations/users.ts b/src/generated/operations/users.ts index a9a17d4a5..e13306762 100644 --- a/src/generated/operations/users.ts +++ b/src/generated/operations/users.ts @@ -47,7 +47,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/users', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ json(), response: /* @__PURE__ */ union([ @@ -74,7 +74,7 @@ export function current( const CURRENT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users/current', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: UserAdminMetadataResponse, @@ -98,7 +98,7 @@ export function deleteResourceToken( const DELETE_RESOURCE_TOKEN = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/users/{id}/resource_token', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -126,7 +126,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/users/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -155,7 +155,7 @@ export function groups( const GROUPS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users/groups', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the user emails whos group membership we are interested */ @@ -183,7 +183,7 @@ export function metadata( const METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users/{id}/metadata', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -213,7 +213,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** include soft deleted users in the results */ include_deleted: /* @__PURE__ */ boolean(), @@ -266,7 +266,7 @@ export function resourceToken( const RESOURCE_TOKEN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/users/resource_token', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: UserResourceToken, @@ -288,7 +288,7 @@ export function revive( const REVIVE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/users/{id}/revive', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -319,7 +319,7 @@ export function search( const SEARCH = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users/metadata/search', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** filter expression in JSONPath format */ @@ -358,7 +358,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/users/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -393,7 +393,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/users/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ @@ -429,7 +429,7 @@ export function userResourceToken( const USER_RESOURCE_TOKEN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/users/{id}/resource_token', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the id of the user */ diff --git a/src/generated/operations/web-rtc.ts b/src/generated/operations/web-rtc.ts index 8b01d33b5..96b903e30 100644 --- a/src/generated/operations/web-rtc.ts +++ b/src/generated/operations/web-rtc.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/rest-api OpenAPI document. Do not edit. /** - * The `WebRTC` controller of the API. Import it as the `webRtc` namespace. + * The `WebRTC` controller of the API. Import it as the `web_rtc` namespace. * * @module */ @@ -33,7 +33,7 @@ export function guestEntry( const GUEST_ENTRY = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/webrtc/guest_entry/{system_id}', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { /** either a system id or a unique permalink */ @@ -43,7 +43,7 @@ const GUEST_ENTRY = /* @__PURE__ */ operation({ ), body: GuestParticipant, response: null, - name: 'webRtc.guestEntry', + name: 'web_rtc.guestEntry', }); /** @@ -64,11 +64,11 @@ export function guestExit( const GUEST_EXIT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/webrtc/guest/exit', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: null, - name: 'webRtc.guestExit', + name: 'web_rtc.guestExit', }); /** @@ -89,7 +89,7 @@ export function kickUser( const KICK_USER = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/webrtc/kick/{user_id}/{session_id}', - pathKeys: ['user_id', 'session_id'], + path_keys: ['user_id', 'session_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -99,7 +99,7 @@ const KICK_USER = /* @__PURE__ */ operation({ ), body: KickReason, response: null, - name: 'webRtc.kickUser', + name: 'web_rtc.kickUser', }); /** @@ -117,7 +117,7 @@ export function members( const MEMBERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/webrtc/members/{session_id}', - pathKeys: ['session_id'], + path_keys: ['session_id'], params: /* @__PURE__ */ parameters( { session_id: /* @__PURE__ */ string(), @@ -126,7 +126,7 @@ const MEMBERS = /* @__PURE__ */ operation({ ), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), - name: 'webRtc.members', + name: 'web_rtc.members', }); /** @@ -147,7 +147,7 @@ export function publicRoom( const PUBLIC_ROOM = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/webrtc/room/{system_id}', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { /** either a system id or a unique permalink */ @@ -157,7 +157,7 @@ const PUBLIC_ROOM = /* @__PURE__ */ operation({ ), body: null, response: WebRtcRoomDetails, - name: 'webRtc.publicRoom', + name: 'web_rtc.publicRoom', }); /** @@ -175,7 +175,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/webrtc/rooms', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -193,7 +193,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(ControlSystem), - name: 'webRtc.query', + name: 'web_rtc.query', }); /** @@ -214,7 +214,7 @@ export function transferGuest( const TRANSFER_GUEST = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/webrtc/transfer/{user_id}/{session_id}', - pathKeys: ['user_id', 'session_id'], + path_keys: ['user_id', 'session_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -224,7 +224,7 @@ const TRANSFER_GUEST = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), response: null, - name: 'webRtc.transferGuest', + name: 'web_rtc.transferGuest', }); /** @@ -245,7 +245,7 @@ export function transferGuestWithoutSessionId( const TRANSFER_GUEST_WITHOUT_SESSION_ID = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/webrtc/transfer/{user_id}', - pathKeys: ['user_id'], + path_keys: ['user_id'], params: /* @__PURE__ */ parameters( { user_id: /* @__PURE__ */ string(), @@ -254,5 +254,5 @@ const TRANSFER_GUEST_WITHOUT_SESSION_ID = /* @__PURE__ */ operation({ ), body: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), response: null, - name: 'webRtc.transferGuestWithoutSessionId', + name: 'web_rtc.transferGuestWithoutSessionId', }); diff --git a/src/generated/operations/webhook.ts b/src/generated/operations/webhook.ts index fb4a8cd4a..0176020e0 100644 --- a/src/generated/operations/webhook.ts +++ b/src/generated/operations/webhook.ts @@ -29,7 +29,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/webhook/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/operations/zones.ts b/src/generated/operations/zones.ts index 835a7aa12..2c096eb5c 100644 --- a/src/generated/operations/zones.ts +++ b/src/generated/operations/zones.ts @@ -38,7 +38,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/zones', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Zone, response: Zone, @@ -60,7 +60,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/engine/v2/zones/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -87,7 +87,7 @@ export function metadata( const METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones/{id}/metadata', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -116,7 +116,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * only return zones who have this zone as a parent (supports comma-separated list). Use @@ -170,7 +170,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -199,7 +199,7 @@ export function tags( const TAGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones/tags', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(/* @__PURE__ */ string()), @@ -221,7 +221,7 @@ export function triggerInstances( const TRIGGER_INSTANCES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/engine/v2/zones/{id}/triggers', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -248,7 +248,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/engine/v2/zones/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -275,7 +275,7 @@ export function zoneExecute( const ZONE_EXECUTE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/engine/v2/zones/{id}/exec/{module_slug}/{method}', - pathKeys: ['id', 'module_slug', 'method'], + path_keys: ['id', 'module_slug', 'method'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/staff/operations/asset-categories.ts b/src/generated/staff/operations/asset-categories.ts index 578b21f82..e7bce2ac7 100644 --- a/src/generated/staff/operations/asset-categories.ts +++ b/src/generated/staff/operations/asset-categories.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `AssetCategories` controller of the API. Import it as the `assetCategories` namespace. + * The `AssetCategories` controller of the API. Import it as the `asset_categories` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/asset_categories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetCategory, response: AssetCategory, - name: 'staff.assetCategories.create', + name: 'staff.asset_categories.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'staff.assetCategories.destroy', + name: 'staff.asset_categories.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_categories', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * true returns only hidden categories, false only non-hidden categories; omit to return all @@ -101,7 +101,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetCategory), - name: 'staff.assetCategories.query', + name: 'staff.asset_categories.query', }); /** @@ -119,7 +119,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -128,7 +128,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetCategory, - name: 'staff.assetCategories.show', + name: 'staff.asset_categories.show', }); /** @@ -146,7 +146,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/asset_categories/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -155,5 +155,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetCategory, response: AssetCategory, - name: 'staff.assetCategories.update', + name: 'staff.asset_categories.update', }); diff --git a/src/generated/staff/operations/asset-purchase-orders.ts b/src/generated/staff/operations/asset-purchase-orders.ts index 8f7a48b5a..b3f0c7cff 100644 --- a/src/generated/staff/operations/asset-purchase-orders.ts +++ b/src/generated/staff/operations/asset-purchase-orders.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `AssetPurchaseOrders` controller of the API. Import it as the `assetPurchaseOrders` + * The `AssetPurchaseOrders` controller of the API. Import it as the `asset_purchase_orders` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/asset_purchase_orders', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetPurchaseOrder, response: AssetPurchaseOrder, - name: 'staff.assetPurchaseOrders.create', + name: 'staff.asset_purchase_orders.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -61,7 +61,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'staff.assetPurchaseOrders.destroy', + name: 'staff.asset_purchase_orders.destroy', }); /** @@ -79,7 +79,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_purchase_orders', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * filters results by the given text: a record matches when any word matches its searchable @@ -97,7 +97,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetPurchaseOrder), - name: 'staff.assetPurchaseOrders.query', + name: 'staff.asset_purchase_orders.query', }); /** @@ -115,7 +115,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -124,7 +124,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetPurchaseOrder, - name: 'staff.assetPurchaseOrders.show', + name: 'staff.asset_purchase_orders.show', }); /** @@ -143,7 +143,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/asset_purchase_orders/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -152,5 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetPurchaseOrder, response: AssetPurchaseOrder, - name: 'staff.assetPurchaseOrders.update', + name: 'staff.asset_purchase_orders.update', }); diff --git a/src/generated/staff/operations/asset-types.ts b/src/generated/staff/operations/asset-types.ts index 615490df5..896407133 100644 --- a/src/generated/staff/operations/asset-types.ts +++ b/src/generated/staff/operations/asset-types.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `AssetTypes` controller of the API. Import it as the `assetTypes` namespace. + * The `AssetTypes` controller of the API. Import it as the `asset_types` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/asset_types', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: AssetType, response: AssetType, - name: 'staff.assetTypes.create', + name: 'staff.asset_types.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'staff.assetTypes.destroy', + name: 'staff.asset_types.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_types', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return asset types with exactly this brand */ brand: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -95,7 +95,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(AssetType), - name: 'staff.assetTypes.query', + name: 'staff.asset_types.query', }); /** @@ -113,7 +113,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -122,7 +122,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: AssetType, - name: 'staff.assetTypes.show', + name: 'staff.asset_types.show', }); /** @@ -140,7 +140,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/asset_types/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -149,5 +149,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: AssetType, response: AssetType, - name: 'staff.assetTypes.update', + name: 'staff.asset_types.update', }); diff --git a/src/generated/staff/operations/assets.ts b/src/generated/staff/operations/assets.ts index a022d0af5..5fcefbd43 100644 --- a/src/generated/staff/operations/assets.ts +++ b/src/generated/staff/operations/assets.ts @@ -29,7 +29,7 @@ export function bulkCreate( const BULK_CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), @@ -51,7 +51,7 @@ export function bulkDestroy( const BULK_DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(/* @__PURE__ */ string()), response: null, @@ -73,7 +73,7 @@ export function bulkUpdate( const BULK_UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/assets/bulk', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(Asset), response: /* @__PURE__ */ array(Asset), @@ -95,7 +95,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Asset, response: Asset, @@ -117,7 +117,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -144,7 +144,7 @@ export function map( const MAP = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/assets/{id}/map', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -171,7 +171,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return assets whose zone_id field is this zone id */ zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -227,7 +227,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -254,7 +254,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/assets/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), diff --git a/src/generated/staff/operations/bookings.ts b/src/generated/staff/operations/bookings.ts index 2017651f3..0f73acf1d 100644 --- a/src/generated/staff/operations/bookings.ts +++ b/src/generated/staff/operations/bookings.ts @@ -44,7 +44,7 @@ export function addAttendee( const ADD_ATTENDEE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/attendee', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -79,7 +79,7 @@ export function approve( const APPROVE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/approve', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -116,7 +116,7 @@ export function approveInstance( const APPROVE_INSTANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/approve/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -153,7 +153,7 @@ export function book( const BOOK = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/book', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the asset id to book, i.e. a desk id from desks_index */ @@ -195,7 +195,7 @@ export function booked( const BOOKED = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/bookings/booked', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** start of the period to search, unix epoch in seconds. Defaults to now */ period_start: /* @__PURE__ */ integer(), @@ -295,7 +295,7 @@ export function checkIn( const CHECK_IN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/check_in', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -334,7 +334,7 @@ export function checkInInstance( const CHECK_IN_INSTANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/check_in/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -373,7 +373,7 @@ export function clashingAssets( const CLASHING_ASSETS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/clashing-assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * when true, return the assets from the booking's asset_ids that are NOT booked, so @@ -408,7 +408,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** the client or channel making the change, recorded for analytics */ utm_source: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -449,7 +449,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/bookings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -486,7 +486,7 @@ export function destroyAttendee( const DESTROY_ATTENDEE = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/bookings/{id}/attendee/{attendee_id}', - pathKeys: ['id', 'attendee_id'], + path_keys: ['id', 'attendee_id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -523,7 +523,7 @@ export function destroyInstance( const DESTROY_INSTANCE = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/bookings/{id}/instance/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -560,7 +560,7 @@ export function edit( const EDIT = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/bookings/{id}/edit', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -603,7 +603,7 @@ export function guestCheckin( const GUEST_CHECKIN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/guests/{guest_id}/check_in', - pathKeys: ['id', 'guest_id'], + path_keys: ['id', 'guest_id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -642,7 +642,7 @@ export function guestList( const GUEST_LIST = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/bookings/{id}/guests', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -683,7 +683,7 @@ export function patchExtdata( const PATCH_EXTDATA = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/bookings/{id}/ext_data', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -723,7 +723,7 @@ export function patchExtdataInstance( const PATCH_EXTDATA_INSTANCE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/bookings/{id}/ext_data/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -763,7 +763,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/bookings', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** start of the period to search, unix epoch in seconds. Defaults to now */ period_start: /* @__PURE__ */ integer(), @@ -887,7 +887,7 @@ export function reject( const REJECT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/reject', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -924,7 +924,7 @@ export function rejectInstance( const REJECT_INSTANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/reject/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -961,7 +961,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/bookings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -996,7 +996,7 @@ export function showInstance( const SHOW_INSTANCE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/bookings/{id}/instance/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1031,7 +1031,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/bookings/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1072,7 +1072,7 @@ export function updateInduction( const UPDATE_INDUCTION = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/update_induction', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1111,7 +1111,7 @@ export function updateInductionInstance( const UPDATE_INDUCTION_INSTANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/update_induction/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1150,7 +1150,7 @@ export function updateInstance( const UPDATE_INSTANCE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/bookings/{id}/instance/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1191,7 +1191,7 @@ export function updateState( const UPDATE_STATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/update_state', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -1230,7 +1230,7 @@ export function updateStateInstance( const UPDATE_STATE_INSTANCE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/bookings/{id}/update_state/{instance}', - pathKeys: ['id', 'instance'], + path_keys: ['id', 'instance'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), diff --git a/src/generated/staff/operations/calendars.ts b/src/generated/staff/operations/calendars.ts index 6808abf40..eaef088ea 100644 --- a/src/generated/staff/operations/calendars.ts +++ b/src/generated/staff/operations/calendars.ts @@ -37,7 +37,7 @@ export function availability( const AVAILABILITY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/calendars/availability', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** search period start as a unix epoch in seconds */ @@ -89,7 +89,7 @@ export function checkPermission( const CHECK_PERMISSION = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/calendars/{user_email}/permission', - pathKeys: ['user_email'], + path_keys: ['user_email'], params: /* @__PURE__ */ parameters( { /** email or UPN of the calendar owner */ @@ -122,7 +122,7 @@ export function freeBusy( const FREE_BUSY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/calendars/free_busy', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** search period start as a unix epoch in seconds */ @@ -177,7 +177,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/calendars', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(PlaceCalendarCalendar), diff --git a/src/generated/staff/operations/desks.ts b/src/generated/staff/operations/desks.ts index 2fd5d54df..0cb950759 100644 --- a/src/generated/staff/operations/desks.ts +++ b/src/generated/staff/operations/desks.ts @@ -29,7 +29,7 @@ export function features( const FEATURES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/desks/features', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only desks in this zone, a building or level */ zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -55,7 +55,7 @@ export function nearColleagues( const NEAR_COLLEAGUES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/desks/near_colleagues', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** comma separated colleague emails, defaults to your saved contacts */ emails: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), @@ -86,7 +86,7 @@ export function nearby( const NEARBY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/desks/nearby', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** the desk (asset id) to search near, required unless email is provided */ asset_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -127,7 +127,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/desks', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the level zone id */ diff --git a/src/generated/staff/operations/events.ts b/src/generated/staff/operations/events.ts index d46f6638e..9db8ca872 100644 --- a/src/generated/staff/operations/events.ts +++ b/src/generated/staff/operations/events.ts @@ -48,7 +48,7 @@ export function addAttendee( const ADD_ATTENDEE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/attendee', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -89,7 +89,7 @@ export function approve( const APPROVE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/approve', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id on the room's resource calendar */ @@ -119,7 +119,7 @@ export function approveAll( const APPROVE_ALL = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/approve_all', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** period start as a unix epoch in seconds */ @@ -163,7 +163,7 @@ export function book( const BOOK = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/book', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** the meeting title */ @@ -186,7 +186,7 @@ const BOOK = /* @__PURE__ */ operation({ body: null, response: PlaceCalendarEvent, name: 'staff.events.book', - wireNames: { body_text: 'body' }, + wire_names: { body_text: 'body' }, }); /** @@ -204,7 +204,7 @@ export function clashingAssets( const CLASHING_ASSETS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/clashing-assets', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * return the system if it is available instead of clashes, requires `system_id` on the @@ -238,7 +238,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: PlaceCalendarEvent, response: PlaceCalendarEvent, @@ -260,7 +260,7 @@ export function decline( const DECLINE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/decline', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -301,7 +301,7 @@ export function deleteAttendee( const DELETE_ATTENDEE = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/events/{id}/attendee/{email}', - pathKeys: ['id', 'email'], + path_keys: ['id', 'email'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -338,7 +338,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/events/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -379,7 +379,7 @@ export function edit( const EDIT = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/events/{id}/edit', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -422,7 +422,7 @@ export function extensionMetadata( const EXTENSION_METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/extension_metadata/{system_id}', - pathKeys: ['system_id'], + path_keys: ['system_id'], params: /* @__PURE__ */ parameters( { /** only return metadata for this room (system) */ @@ -460,7 +460,7 @@ export function extensionMetadataWithoutSystemId( const EXTENSION_METADATA_WITHOUT_SYSTEM_ID = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/extension_metadata', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return metadata for this room (system) */ system_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -495,7 +495,7 @@ export function getMetadata( const GET_METADATA = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/{id}/metadata/{system_id}', - pathKeys: ['id', 'system_id'], + path_keys: ['id', 'system_id'], params: /* @__PURE__ */ parameters( { /** the event id, on the host's or the room's calendar */ @@ -527,7 +527,7 @@ export function guestCheckin( const GUEST_CHECKIN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/guests/{guest_id}/check_in', - pathKeys: ['id', 'guest_id'], + path_keys: ['id', 'guest_id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -567,7 +567,7 @@ export function guestList( const GUEST_LIST = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/{id}/guests', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id on the room's resource calendar */ @@ -602,7 +602,7 @@ export function history( const HISTORY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/history', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** period start as a unix epoch in seconds */ @@ -646,7 +646,7 @@ export function linkMasterMetadata( const LINK_MASTER_METADATA = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/metadata/{system_id}/link/{ical_uid}', - pathKeys: ['id', 'system_id', 'ical_uid'], + path_keys: ['id', 'system_id', 'ical_uid'], params: /* @__PURE__ */ parameters( { /** the event id to link */ @@ -678,7 +678,7 @@ export function notifyChange( const NOTIFY_CHANGE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/notify/{change}/{system_id}/{event_id}', - pathKeys: ['change', 'system_id', 'event_id'], + path_keys: ['change', 'system_id', 'event_id'], params: /* @__PURE__ */ parameters( { /** the type of change that has occured */ @@ -710,7 +710,7 @@ export function patchMetadata( const PATCH_METADATA = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/events/{id}/metadata/{system_id}', - pathKeys: ['id', 'system_id'], + path_keys: ['id', 'system_id'], params: /* @__PURE__ */ parameters( { /** the event id, on the host's or the room's calendar */ @@ -756,7 +756,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** period start as a unix epoch in seconds */ @@ -820,7 +820,7 @@ export function reject( const REJECT = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/events/{id}/reject', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id on the room's resource calendar */ @@ -850,7 +850,7 @@ export function replaceMetadata( const REPLACE_METADATA = /* @__PURE__ */ operation({ method: 'PUT', path: '/api/staff/v1/events/{id}/metadata/{system_id}', - pathKeys: ['id', 'system_id'], + path_keys: ['id', 'system_id'], params: /* @__PURE__ */ parameters( { /** the event id, on the host's or the room's calendar */ @@ -896,7 +896,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/events/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ @@ -928,7 +928,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/events/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the event id, as found on the calendar being searched */ diff --git a/src/generated/staff/operations/groups.ts b/src/generated/staff/operations/groups.ts index b5ebf3faa..c31daca18 100644 --- a/src/generated/staff/operations/groups.ts +++ b/src/generated/staff/operations/groups.ts @@ -29,7 +29,7 @@ export function members( const MEMBERS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/groups/{id}/members', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the directory group id */ @@ -57,7 +57,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/groups', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** optional search query, matches groups whose display name starts with this text */ q: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -82,7 +82,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/groups/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the directory group id */ diff --git a/src/generated/staff/operations/guests.ts b/src/generated/staff/operations/guests.ts index 3e24b72eb..d12cd2e66 100644 --- a/src/generated/staff/operations/guests.ts +++ b/src/generated/staff/operations/guests.ts @@ -39,7 +39,7 @@ export function bookings( const BOOKINGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests/{id}/bookings', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -71,7 +71,7 @@ export function catering( const CATERING = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests/{id}/catering', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -105,7 +105,7 @@ export function cateringDestroy( const CATERING_DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/guests/{id}/catering', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -139,7 +139,7 @@ export function cateringMenu( const CATERING_MENU = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests/{id}/catering/menu', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -173,7 +173,7 @@ export function cateringUpdate( const CATERING_UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/guests/{id}/catering', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -207,7 +207,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/guests', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Guest, response: Guest, @@ -229,7 +229,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/guests/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -257,7 +257,7 @@ export function meetings( const MEETINGS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests/{id}/meetings', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -289,7 +289,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * space separated search query matching guest name, email etc, ignored when a period is @@ -336,7 +336,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/guests/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ @@ -364,7 +364,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/guests/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** looks up a guest using either their id or email */ diff --git a/src/generated/staff/operations/health-check.ts b/src/generated/staff/operations/health-check.ts index 207566eeb..219718891 100644 --- a/src/generated/staff/operations/health-check.ts +++ b/src/generated/staff/operations/health-check.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `HealthCheck` controller of the API. Import it as the `healthCheck` namespace. + * The `HealthCheck` controller of the API. Import it as the `health_check` namespace. * * @module */ @@ -29,9 +29,9 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: HealthCheckBuildInfo, - name: 'staff.healthCheck.query', + name: 'staff.health_check.query', }); diff --git a/src/generated/staff/operations/index.ts b/src/generated/staff/operations/index.ts index 0de6e537e..d527376e0 100644 --- a/src/generated/staff/operations/index.ts +++ b/src/generated/staff/operations/index.ts @@ -1,9 +1,9 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** One namespace for each controller of the API. */ -export * as assetCategories from './asset-categories.ts'; -export * as assetPurchaseOrders from './asset-purchase-orders.ts'; -export * as assetTypes from './asset-types.ts'; +export * as asset_categories from './asset-categories.ts'; +export * as asset_purchase_orders from './asset-purchase-orders.ts'; +export * as asset_types from './asset-types.ts'; export * as assets from './assets.ts'; export * as bookings from './bookings.ts'; export * as calendars from './calendars.ts'; @@ -11,14 +11,14 @@ export * as desks from './desks.ts'; export * as events from './events.ts'; export * as groups from './groups.ts'; export * as guests from './guests.ts'; -export * as healthCheck from './health-check.ts'; +export * as health_check from './health-check.ts'; export * as place from './place.ts'; export * as spaces from './spaces.ts'; export * as staff from './staff.ts'; export * as surveys from './surveys.ts'; -export * as surveysAnswers from './surveys-answers.ts'; -export * as surveysInvitations from './surveys-invitations.ts'; -export * as surveysQuestions from './surveys-questions.ts'; +export * as surveys_answers from './surveys-answers.ts'; +export * as surveys_invitations from './surveys-invitations.ts'; +export * as surveys_questions from './surveys-questions.ts'; export * as teams from './teams.ts'; export * as tenants from './tenants.ts'; export * as users from './users.ts'; diff --git a/src/generated/staff/operations/place.ts b/src/generated/staff/operations/place.ts index 60f90923f..ed272e0c6 100644 --- a/src/generated/staff/operations/place.ts +++ b/src/generated/staff/operations/place.ts @@ -29,7 +29,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/place', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * optional comma separated list of room properties to return (maps to the graph `$select` diff --git a/src/generated/staff/operations/spaces.ts b/src/generated/staff/operations/spaces.ts index 2aa3da360..b6723e400 100644 --- a/src/generated/staff/operations/spaces.ts +++ b/src/generated/staff/operations/spaces.ts @@ -29,7 +29,7 @@ export function features( const FEATURES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/features', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** comma separated zone ids, only features of spaces in every zone */ zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), @@ -54,7 +54,7 @@ export function free( const FREE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/free', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters( { /** meeting start as a unix epoch in seconds */ @@ -88,7 +88,7 @@ export function image( const IMAGE = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/{id}/images/{index}', - pathKeys: ['id', 'index'], + path_keys: ['id', 'index'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -117,7 +117,7 @@ export function map( const MAP = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/{id}/map', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -144,7 +144,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** comma separated zone ids, spaces must be in every zone, i.e. a building and a level */ zone_ids: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), @@ -186,7 +186,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ string(), @@ -223,7 +223,7 @@ export function zones( const ZONES = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/spaces/zones', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** comma separated tags, zones must have every tag, i.e. building or level */ tags: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), diff --git a/src/generated/staff/operations/staff.ts b/src/generated/staff/operations/staff.ts index 2e604ca11..6c9ef5b2d 100644 --- a/src/generated/staff/operations/staff.ts +++ b/src/generated/staff/operations/staff.ts @@ -34,7 +34,7 @@ export function calendars( const CALENDARS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}/calendars', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the user's email address */ @@ -62,7 +62,7 @@ export function freeBusy( const FREE_BUSY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}/free_busy', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the person's email address */ @@ -94,7 +94,7 @@ export function groups( const GROUPS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}/groups', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** a user id OR user email address */ @@ -122,7 +122,7 @@ export function manager( const MANAGER = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}/manager', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** a user id OR user email address */ @@ -150,7 +150,7 @@ export function photo( const PHOTO = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}/photo', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** a user id OR user email address */ @@ -178,7 +178,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** * An optional search query to filter users by name or email. If both 'q' and 'filter' @@ -223,7 +223,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/people/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** a user id OR user email address */ diff --git a/src/generated/staff/operations/surveys-answers.ts b/src/generated/staff/operations/surveys-answers.ts index 1b131eadc..b7a72f2ad 100644 --- a/src/generated/staff/operations/surveys-answers.ts +++ b/src/generated/staff/operations/surveys-answers.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `Surveys::Answers` controller of the API. Import it as the `surveysAnswers` namespace. + * The `Surveys::Answers` controller of the API. Import it as the `surveys_answers` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/surveys/answers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: /* @__PURE__ */ array(SurveyAnswer), response: /* @__PURE__ */ array(SurveyAnswer), - name: 'staff.surveysAnswers.create', + name: 'staff.surveys_answers.create', }); /** @@ -51,7 +51,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/answers', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return answers submitted for this survey id */ survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -70,5 +70,5 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SurveyAnswer), - name: 'staff.surveysAnswers.query', + name: 'staff.surveys_answers.query', }); diff --git a/src/generated/staff/operations/surveys-invitations.ts b/src/generated/staff/operations/surveys-invitations.ts index df40b9f8d..e718f51ea 100644 --- a/src/generated/staff/operations/surveys-invitations.ts +++ b/src/generated/staff/operations/surveys-invitations.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `Surveys::Invitations` controller of the API. Import it as the `surveysInvitations` + * The `Surveys::Invitations` controller of the API. Import it as the `surveys_invitations` * namespace. * * @module @@ -30,11 +30,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/surveys/invitations', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SurveyInvitation, response: SurveyInvitation, - name: 'staff.surveysInvitations.create', + name: 'staff.surveys_invitations.create', }); /** @@ -52,7 +52,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/surveys/invitations/{token}', - pathKeys: ['token'], + path_keys: ['token'], params: /* @__PURE__ */ parameters( { /** the unique invitation token (a ULID) */ @@ -62,7 +62,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'staff.surveysInvitations.destroy', + name: 'staff.surveys_invitations.destroy', }); /** @@ -80,7 +80,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/invitations', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return invitations for this survey id */ survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -92,7 +92,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SurveyInvitation), - name: 'staff.surveysInvitations.query', + name: 'staff.surveys_invitations.query', }); /** @@ -110,7 +110,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/invitations/{token}', - pathKeys: ['token'], + path_keys: ['token'], params: /* @__PURE__ */ parameters( { /** the unique invitation token (a ULID) */ @@ -120,7 +120,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SurveyInvitation, - name: 'staff.surveysInvitations.show', + name: 'staff.surveys_invitations.show', }); /** @@ -138,7 +138,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/surveys/invitations/{token}', - pathKeys: ['token'], + path_keys: ['token'], params: /* @__PURE__ */ parameters( { token: /* @__PURE__ */ string(), @@ -147,5 +147,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SurveyInvitation, response: SurveyInvitation, - name: 'staff.surveysInvitations.update', + name: 'staff.surveys_invitations.update', }); diff --git a/src/generated/staff/operations/surveys-questions.ts b/src/generated/staff/operations/surveys-questions.ts index c26e2925c..1985dc8c5 100644 --- a/src/generated/staff/operations/surveys-questions.ts +++ b/src/generated/staff/operations/surveys-questions.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate.ts from the PlaceOS/staff-api OpenAPI document. Do not edit. /** - * The `Surveys::Questions` controller of the API. Import it as the `surveysQuestions` namespace. + * The `Surveys::Questions` controller of the API. Import it as the `surveys_questions` namespace. * * @module */ @@ -29,11 +29,11 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/surveys/questions', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: SurveyQuestion, response: SurveyQuestion, - name: 'staff.surveysQuestions.create', + name: 'staff.surveys_questions.create', }); /** @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/surveys/questions/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -60,7 +60,7 @@ const DESTROY = /* @__PURE__ */ operation({ ), body: null, response: null, - name: 'staff.surveysQuestions.destroy', + name: 'staff.surveys_questions.destroy', }); /** @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/questions', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return questions referenced by this survey's pages */ survey_id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -90,7 +90,7 @@ const QUERY = /* @__PURE__ */ operation({ }), body: null, response: /* @__PURE__ */ array(SurveyQuestion), - name: 'staff.surveysQuestions.query', + name: 'staff.surveys_questions.query', }); /** @@ -108,7 +108,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/questions/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the numeric id of the question */ @@ -118,7 +118,7 @@ const SHOW = /* @__PURE__ */ operation({ ), body: null, response: SurveyQuestion, - name: 'staff.surveysQuestions.show', + name: 'staff.surveys_questions.show', }); /** @@ -137,7 +137,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/surveys/questions/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -152,5 +152,5 @@ const UPDATE = /* @__PURE__ */ operation({ ), body: SurveyQuestion, response: SurveyQuestion, - name: 'staff.surveysQuestions.update', + name: 'staff.surveys_questions.update', }); diff --git a/src/generated/staff/operations/surveys.ts b/src/generated/staff/operations/surveys.ts index d3af6afdd..33ad31112 100644 --- a/src/generated/staff/operations/surveys.ts +++ b/src/generated/staff/operations/surveys.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/surveys', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: Survey, response: Survey, @@ -51,7 +51,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/surveys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -78,7 +78,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({ /** only return surveys whose zone_id matches this zone id exactly */ zone_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -105,7 +105,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/surveys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { /** the numeric id of the survey */ @@ -133,7 +133,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/surveys/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), diff --git a/src/generated/staff/operations/teams.ts b/src/generated/staff/operations/teams.ts index 008ece5ed..7f3711f8f 100644 --- a/src/generated/staff/operations/teams.ts +++ b/src/generated/staff/operations/teams.ts @@ -29,7 +29,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/teams/{teams_id}/{channel_id}', - pathKeys: ['teams_id', 'channel_id'], + path_keys: ['teams_id', 'channel_id'], params: /* @__PURE__ */ parameters( { /** the Microsoft Teams team id */ @@ -61,7 +61,7 @@ export function sendChannelMessage( const SEND_CHANNEL_MESSAGE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/teams/{teams_id}/{channel_id}', - pathKeys: ['teams_id', 'channel_id'], + path_keys: ['teams_id', 'channel_id'], params: /* @__PURE__ */ parameters( { /** the Microsoft Teams team id */ @@ -93,7 +93,7 @@ export function show( const SHOW = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/teams/{teams_id}/{channel_id}/{message_id}', - pathKeys: ['teams_id', 'channel_id', 'message_id'], + path_keys: ['teams_id', 'channel_id', 'message_id'], params: /* @__PURE__ */ parameters( { /** the Microsoft Teams team id */ diff --git a/src/generated/staff/operations/tenants.ts b/src/generated/staff/operations/tenants.ts index b237ea8ed..fdc732e34 100644 --- a/src/generated/staff/operations/tenants.ts +++ b/src/generated/staff/operations/tenants.ts @@ -29,7 +29,7 @@ export function create( const CREATE = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/tenants', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: TenantResponder, response: TenantResponder, @@ -51,7 +51,7 @@ export function currentEarlyCheckin( const CURRENT_EARLY_CHECKIN = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/tenants/current_early_checkin', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: Int64, @@ -73,7 +73,7 @@ export function currentLimits( const CURRENT_LIMITS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/tenants/current_limits', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ record(/* @__PURE__ */ integer('Int32')), @@ -95,7 +95,7 @@ export function destroy( const DESTROY = /* @__PURE__ */ operation({ method: 'DELETE', path: '/api/staff/v1/tenants/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -122,7 +122,7 @@ export function query( const QUERY = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/tenants', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: /* @__PURE__ */ array(TenantResponder), @@ -144,7 +144,7 @@ export function showEarlyCheckin( const SHOW_EARLY_CHECKIN = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/tenants/{id}/early_checkin', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -171,7 +171,7 @@ export function showLimits( const SHOW_LIMITS = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/tenants/{id}/limits', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -198,7 +198,7 @@ export function update( const UPDATE = /* @__PURE__ */ operation({ method: 'PATCH', path: '/api/staff/v1/tenants/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -225,7 +225,7 @@ export function updateEarlyCheckin( const UPDATE_EARLY_CHECKIN = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/tenants/{id}/early_checkin', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), @@ -252,7 +252,7 @@ export function updateLimits( const UPDATE_LIMITS = /* @__PURE__ */ operation({ method: 'POST', path: '/api/staff/v1/tenants/{id}/limits', - pathKeys: ['id'], + path_keys: ['id'], params: /* @__PURE__ */ parameters( { id: /* @__PURE__ */ integer(), diff --git a/src/generated/staff/operations/users.ts b/src/generated/staff/operations/users.ts index 7686877e6..1cedfe156 100644 --- a/src/generated/staff/operations/users.ts +++ b/src/generated/staff/operations/users.ts @@ -29,7 +29,7 @@ export function current( const CURRENT = /* @__PURE__ */ operation({ method: 'GET', path: '/api/staff/v1/users/current', - pathKeys: [], + path_keys: [], params: /* @__PURE__ */ parameters({}), body: null, response: UserAdminResponse, diff --git a/src/index.ts b/src/index.ts index 4a6af26b8..3be8e3500 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ * ```ts * import { configure, zones } from '@placeos/ts-client'; * - * configure({ baseUrl: '', auth: { kind: 'bearer', token: () => token } }); + * configure({ base_url: '', auth: { kind: 'bearer', token: () => token } }); * const result = await zones.show({ id: 'zone-1234' }); * if (result.ok) console.log(result.value.data.name); * ``` diff --git a/src/migrate/cli.ts b/src/migrate/cli.ts index fe077280a..6e0ccff24 100644 --- a/src/migrate/cli.ts +++ b/src/migrate/cli.ts @@ -76,7 +76,7 @@ async function main(argv: readonly string[]): Promise { const files = await sourceFiles(paths.map((path) => resolve(path))); const findings: { file: string; finding: Finding }[] = []; const migrated = new Set(); - let changedFiles = 0; + let changed_files = 0; let changes = 0; for (const file of files) { const text = await readFile(file, 'utf8'); @@ -85,7 +85,7 @@ async function main(argv: readonly string[]): Promise { for (const finding of result.findings) findings.push({ file: name, finding }); for (const fn of result.migrated) migrated.add(fn); if (result.text === text) continue; - changedFiles += 1; + changed_files += 1; changes += result.changes; console.log(`${write ? 'changed' : 'would change'} ${name} (${result.changes})`); if (write) await writeFile(file, result.text); @@ -105,16 +105,16 @@ async function main(argv: readonly string[]): Promise { if (notes.length > 0) console.log(`\nDifferences of the changed calls:\n${notes.join('\n')}`); console.log( - `\n${files.length} files read. ${changedFiles} files ${write ? 'changed' : 'to change'}, ` + + `\n${files.length} files read. ${changed_files} files ${write ? 'changed' : 'to change'}, ` + `${changes} changes, ${findings.length} uses to change by hand.`, ); - if (!write && changedFiles > 0) console.log('Run again with --write to write the changes.'); - if (write && changedFiles > 0) { + if (!write && changed_files > 0) console.log('Run again with --write to write the changes.'); + if (write && changed_files > 0) { console.log( `\nNext:\n` + ` 1. Install 7.x: npm install @placeos/ts-client@7\n` + ` 2. Call configure() once, before the first call (README: Log in). For a mock mode,\n` + - ` give fetch: mockFetch and missingFields: 'zero' (README: Mock mode).\n` + + ` give fetch: mockFetch and missing_fields: 'zero' (README: Mock mode).\n` + ` 3. Run the compiler. It shows the changes to the data, such as a field that can be null.\n` + ` 4. orThrow from ${COMPAT_MODULE} keeps the 6.x errors. Check the Result in new code.`, ); diff --git a/src/migrate/migrate.ts b/src/migrate/migrate.ts index 4028d2c9b..43a383be7 100644 --- a/src/migrate/migrate.ts +++ b/src/migrate/migrate.ts @@ -102,12 +102,12 @@ interface Edit { /** Rewrites the 6.x calls of one file. The text is the same when the file does not import 6.x. */ export function migrateSource( ts: typeof TS, - fileName: string, + file_name: string, text: string, tables: MigrateTables, ): MigrateResult { - const kind = /\.[cm]?tsx$/.test(fileName) ? ts.ScriptKind.TSX : ts.ScriptKind.TS; - const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind); + const kind = /\.[cm]?tsx$/.test(file_name) ? ts.ScriptKind.TSX : ts.ScriptKind.TS; + const source = ts.createSourceFile(file_name, text, ts.ScriptTarget.Latest, true, kind); const imports = readImports(ts, source); if (imports.declarations.length === 0) { @@ -129,13 +129,13 @@ export function migrateSource( /** The uses of each local name of a named import, and how many the tool changed. */ const uses = new Map(); /** The 7.x namespaces that the new imports give, by module and name, with the local name. */ - const namespaceNames = new Map< + const namespace_names = new Map< string, { module: 'staff' | null; name: string; local: string } >(); /** The 7.x types that the new imports give, by local name. */ - const typeNames = new Map(); - const compatNames = new Set(); + const type_names = new Map(); + const compat_names = new Set(); /** The local names of the 6.x imports that move to the compat module. */ const moved = new Set(); for (const [local, imported] of imports.named) { @@ -143,13 +143,13 @@ export function migrateSource( if (kind === undefined) continue; moved.add(local); const name = local === imported ? imported : `${imported} as ${local}`; - compatNames.add(kind === 'type' ? `type ${name}` : name); + compat_names.add(kind === 'type' ? `type ${name}` : name); } let changes = 0; let deep = false; // The helpers that a file already imports from the compat module, by name. - const compatImported = new Map(); + const compat_imported = new Map(); for (const statement of source.statements) { if (!ts.isImportDeclaration(statement)) continue; const specifier = statement.moduleSpecifier; @@ -160,10 +160,10 @@ export function migrateSource( if (bindings === undefined || !ts.isNamedImports(bindings)) continue; for (const element of bindings.elements) { if (element.isTypeOnly) continue; - compatImported.set((element.propertyName ?? element.name).text, element.name.text); + compat_imported.set((element.propertyName ?? element.name).text, element.name.text); } } - const helperLocals = new Map(); + const helper_locals = new Map(); /** * The local name of a compat helper, such as `orThrow`: the name of an import that the file @@ -173,28 +173,28 @@ export function migrateSource( name: string, options: { readonly register: boolean } = { register: true }, ): string { - const imported = compatImported.get(name); + const imported = compat_imported.get(name); if (imported !== undefined) return imported; - let local = helperLocals.get(name); + let local = helper_locals.get(name); if (local === undefined) { local = localName(name); - helperLocals.set(name, local); + helper_locals.set(name, local); } - if (options.register) compatNames.add(local === name ? name : `${name} as ${local}`); + if (options.register) compat_names.add(local === name ? name : `${name} as ${local}`); return local; } /** The name of `vi.hoisted` for `fromV1Mock`, when the file also imports `fromV1Mock`. */ - let hoistedLocal: string | null = null; + let hoisted_local: string | null = null; /** * The local name of `fromV1Mock`. A `vi.mock` factory runs before the imports, so it uses the * name of `vi.hoisted`. That name is not the name of an import that the file has. */ - function fromV1MockLocal(options: { readonly inFactory: boolean }): string { - if (options.inFactory && compatImported.has('fromV1Mock')) { - hoistedLocal ??= localName('fromV1Mock'); - return hoistedLocal; + function fromV1MockLocal(options: { readonly in_factory: boolean }): string { + if (options.in_factory && compat_imported.has('fromV1Mock')) { + hoisted_local ??= localName('fromV1Mock'); + return hoisted_local; } return helperLocal('fromV1Mock', { register: false }); } @@ -221,15 +221,15 @@ export function migrateSource( function namespaceLocal(namespace: string, module: 'staff' | null = null): string { const key = `${module ?? ''}|${namespace}`; - const known = namespaceNames.get(key); + const known = namespace_names.get(key); if (known !== undefined) return known.local; // A staff namespace, such as `assets`, can have the name of a REST API namespace. - const staffName = `staff${namespace.charAt(0).toUpperCase()}${namespace.slice(1)}`; + const staff_name = `staff${namespace.charAt(0).toUpperCase()}${namespace.slice(1)}`; const local = - module === 'staff' && taken.has(namespace) && !taken.has(staffName) - ? localName(staffName) + module === 'staff' && taken.has(namespace) && !taken.has(staff_name) + ? localName(staff_name) : localName(namespace); - namespaceNames.set(key, { module, name: namespace, local }); + namespace_names.set(key, { module, name: namespace, local }); return local; } @@ -242,24 +242,24 @@ export function migrateSource( } /** The local name of a compat export that a namespace import used, such as `PlaceDriverRole`. */ - const compatLocals = new Map(); + const compat_locals = new Map(); function compatLocal(name: string): string { - const known = compatLocals.get(name); + const known = compat_locals.get(name); if (known !== undefined) return known; const local = localName(name); - compatLocals.set(name, local); + compat_locals.set(name, local); const specifier = local === name ? name : `${name} as ${local}`; - compatNames.add(tables.compat[name] === 'type' ? `type ${specifier}` : specifier); + compat_names.add(tables.compat[name] === 'type' ? `type ${specifier}` : specifier); return local; } function typeLocal(type: TypeMapping): string { const module = type.module ?? null; - for (const [local, known] of typeNames) { + for (const [local, known] of type_names) { if (known.name === type.name && known.module === module) return local; } const local = localName(type.name); - typeNames.set(local, { module, name: type.name }); + type_names.set(local, { module, name: type.name }); return local; } @@ -300,7 +300,7 @@ export function migrateSource( const pick = rendered.pick === null ? '' - : `.then((${rendered.pickParameter}) => ${rendered.pickParameter}[${rendered.pick}])`; + : `.then((${rendered.pick_parameter}) => ${rendered.pick_parameter}[${rendered.pick}])`; replace( call, `${namespace}.${mapping.operation}(${rendered.input}).then(${helper})${pick}`, @@ -313,9 +313,9 @@ export function migrateSource( /** The test doubles that the tool changed, by the call that holds the 7.x function. */ const doubles = new Map(); /** A spec file. There a reference to a 6.x function that is not a call is a test double. */ - const testFile = /\.(spec|test)\.[cm]?[jt]sx?$/.test(fileName); + const test_file = /\.(spec|test)\.[cm]?[jt]sx?$/.test(file_name); /** `true` when a call on a test double uses `fromV1Mock`, out of a `vi.mock` factory. */ - let importsFromV1Mock = false; + let imports_from_v1_mock = false; /** * Changes the function of a test double, such as `vi.mocked(showZone)` to @@ -389,11 +389,11 @@ export function migrateSource( const v1 = method.startsWith('mockImplementation') ? textOf(value) : `() => (${textOf(value)})`; - importsFromV1Mock = true; - const fromV1Mock = fromV1MockLocal({ inFactory: false }); + imports_from_v1_mock = true; + const from_v1_mock = fromV1MockLocal({ in_factory: false }); replace( call, - `${textOf(callee.expression)}.${implementation}(${fromV1Mock}(${v1}, ${fromV1MockArgs(mapping)}))`, + `${textOf(callee.expression)}.${implementation}(${from_v1_mock}(${v1}, ${fromV1MockArgs(mapping)}))`, ); return; } @@ -409,7 +409,7 @@ export function migrateSource( } /** `true` when a `vi.mock` factory uses `fromV1Mock`. The file then imports it. */ - let usesFromV1Mock = false; + let uses_from_v1_mock = false; /** * Changes the 6.x functions of a `vi.mock` factory to 7.x namespaces. `fromV1Mock` keeps the @@ -494,7 +494,7 @@ export function migrateSource( changes += 1; } if (groups.size === 0) return; - usesFromV1Mock = true; + uses_from_v1_mock = true; for (const [namespace, entries] of groups) { const base = spread === null ? '' : `...${spread}.${namespace}, `; kept.push(`${namespace}: { ${base}${entries.join(', ')} }`); @@ -505,7 +505,7 @@ export function migrateSource( /** The 7.x value of one 6.x function of a factory. `null` is a shorthand property. */ function mockValue(value: TS.Expression | null, name: string, mapping: CallMapping): string { const extra = fromV1MockArgs(mapping); - const fromV1Mock = fromV1MockLocal({ inFactory: true }); + const from_v1_mock = fromV1MockLocal({ in_factory: true }); if ( value !== null && ts.isCallExpression(value) && @@ -513,11 +513,11 @@ export function migrateSource( ) { const [implementation] = value.arguments; const text = implementation === undefined ? 'undefined' : textOf(implementation); - return `${textOf(value.expression)}(${fromV1Mock}(${text}, ${extra}))`; + return `${textOf(value.expression)}(${from_v1_mock}(${text}, ${extra}))`; } // Another value, such as `vi.fn().mockResolvedValue(zone)` or a hoisted mock, is the 6.x // implementation of a new mock, so the 7.x function is still a mock that tests can change. - return `vi.fn(${fromV1Mock}(${value === null ? name : textOf(value)}, ${extra}))`; + return `vi.fn(${from_v1_mock}(${value === null ? name : textOf(value)}, ${extra}))`; } /** `vi.mocked(f)`, `jest.mocked(f)` or `expect(f)`, with `f` as the first argument. */ @@ -526,12 +526,12 @@ export function migrateSource( if (!ts.isCallExpression(parent) || parent.arguments[0] !== node) return null; const callee = parent.expression; if (ts.isIdentifier(callee) && callee.text === 'expect') return parent; - const isMocked = + const is_mocked = ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && TEST_GLOBALS.has(callee.expression.text) && callee.name.text === 'mocked'; - return isMocked ? parent : null; + return is_mocked ? parent : null; } function visit(node: TS.Node, depth: number): void { @@ -615,31 +615,31 @@ export function migrateSource( } if (ts.isTypeReferenceNode(node)) { - const typeName = node.typeName; - if (ts.isIdentifier(typeName)) { - const imported = imports.named.get(typeName.text); - if (imported === undefined || moved.has(typeName.text)) return; - const v2Name = tables.types[imported]; - if (v2Name !== undefined) { - replace(typeName, typeLocal(v2Name)); - countUse(typeName.text, true); + const type_name = node.typeName; + if (ts.isIdentifier(type_name)) { + const imported = imports.named.get(type_name.text); + if (imported === undefined || moved.has(type_name.text)) return; + const v2_name = tables.types[imported]; + if (v2_name !== undefined) { + replace(type_name, typeLocal(v2_name)); + countUse(type_name.text, true); changes += 1; } return; } - const left = typeName.left; - const right = typeName.right.text; + const left = type_name.left; + const right = type_name.right.text; const type = tables.types[right]; if (!ts.isIdentifier(left) || !imports.namespaces.has(left.text)) return; if (type !== undefined && type.module === undefined) { - replace(typeName.right, type.name); + replace(type_name.right, type.name); changes += 1; } else if (type !== undefined) { // A staff type is not in the namespace of 6.x. It gets its own import. - replace(typeName, typeLocal(type)); + replace(type_name, typeLocal(type)); changes += 1; } else if (right in tables.compat) { - replace(typeName, compatLocal(right)); + replace(type_name, compatLocal(right)); changes += 1; } return; @@ -653,11 +653,11 @@ export function migrateSource( if (!isV1Name(tables, imported)) return; if (isCountedAtParent(ts, node, imported, tables)) return; const wrapper = doubleWrapper(node); - const doubleMapping = tables.calls[imported]; - const isDouble = - wrapper !== null || (testFile && !ts.isShorthandPropertyAssignment(node.parent)); + const double_mapping = tables.calls[imported]; + const is_double = + wrapper !== null || (test_file && !ts.isShorthandPropertyAssignment(node.parent)); // A test double of a function whose 6.x arguments the tool cannot rebuild stays 6.x. - if (isDouble && doubleMapping !== undefined && !invertible(doubleMapping)) { + if (is_double && double_mapping !== undefined && !invertible(double_mapping)) { countUse(node.text, false); find(node, imported, NOT_INVERTIBLE); return; @@ -668,7 +668,7 @@ export function migrateSource( return; } if ( - testFile && + test_file && imported in tables.calls && !ts.isShorthandPropertyAssignment(node.parent) ) { @@ -689,11 +689,11 @@ export function migrateSource( ) { const name = node.name.text; const wrapper = doubleWrapper(node); - const doubleMapping = tables.calls[name]; + const double_mapping = tables.calls[name]; if ( - (wrapper !== null || testFile) && - doubleMapping !== undefined && - !invertible(doubleMapping) + (wrapper !== null || test_file) && + double_mapping !== undefined && + !invertible(double_mapping) ) { find(node, name, NOT_INVERTIBLE); return; @@ -702,7 +702,7 @@ export function migrateSource( rewriteDouble(node, wrapper, name, node.expression.text); return; } - if (testFile && name in tables.calls) { + if (test_file && name in tables.calls) { rewriteDouble(node, node, name, node.expression.text); return; } @@ -727,11 +727,11 @@ export function migrateSource( // The tool changes `vi.spyOn(client, 'showZone')` on a namespace import above. if (ts.isStringLiteral(node) && imports.namespaces.size > 0 && node.text in tables.calls) { const parent = node.parent; - const spyOnNamespace = + const spy_on_namespace = ts.isCallExpression(parent) && isTestCall(ts, parent.expression, 'spyOn') && parent.arguments[1] === node; - if (spyOnNamespace) return; + if (spy_on_namespace) return; const mapping = tables.calls[node.text]; const target = mapping === undefined ? '' : ` (${mapping.namespace}.${mapping.operation})`; @@ -742,22 +742,22 @@ export function migrateSource( if (deep) return tooDeep(text); // The hoisted `fromV1Mock` of a factory is also there for the tests. - if (importsFromV1Mock && !usesFromV1Mock) helperLocal('fromV1Mock'); + if (imports_from_v1_mock && !uses_from_v1_mock) helperLocal('fromV1Mock'); // The new imports of the 7.x namespaces and types, and of the helpers. const specifiers = (module: 'staff' | null): string[] => [ - ...[...namespaceNames.values()] + ...[...namespace_names.values()] .filter((entry) => entry.module === module) .map(({ name, local }) => (name === local ? name : `${name} as ${local}`)), - ...[...typeNames] + ...[...type_names] .filter(([, entry]) => entry.module === module) .map(([local, { name }]) => name === local ? `type ${name}` : `type ${name} as ${local}`, ), ].sort(compareSpecifiers); const added = specifiers(null); - const staffAdded = specifiers('staff'); + const staff_added = specifiers('staff'); const changed = importEdits(ts, source, imports.declarations, uses, tables, added, moved); edits.push(...changed.edits); // The new imports go after the last 6.x import, or in its place when the tool removes it. @@ -765,16 +765,16 @@ export function migrateSource( if (changed.pending.length > 0) { lines.push(`import { ${changed.pending.join(', ')} } from '${V1_MODULE}';`); } - if (staffAdded.length > 0) { - lines.push(`import { ${staffAdded.join(', ')} } from '${STAFF_MODULE}';`); + if (staff_added.length > 0) { + lines.push(`import { ${staff_added.join(', ')} } from '${STAFF_MODULE}';`); } - if (compatNames.size > 0) { - const names = [...compatNames].sort(compareSpecifiers).join(', '); + if (compat_names.size > 0) { + const names = [...compat_names].sort(compareSpecifiers).join(', '); lines.push(`import { ${names} } from '${COMPAT_MODULE}';`); } - if (usesFromV1Mock) { + if (uses_from_v1_mock) { // `vi.mock` runs before the imports, so its factory gets the helper from `vi.hoisted`. - const local = hoistedLocal ?? fromV1MockLocal({ inFactory: true }); + const local = hoisted_local ?? fromV1MockLocal({ in_factory: true }); const binding = local === 'fromV1Mock' ? local : `fromV1Mock: ${local}`; lines.push(`const { ${binding} } = await vi.hoisted(() => import('${COMPAT_MODULE}'));`); } @@ -854,8 +854,8 @@ function declaredNames( } if (ts.isIdentifier(node) && isReference(ts, node)) { const parent = node.parent; - const typeName = ts.isTypeReferenceNode(parent) && parent.typeName === node; - if (!typeName || !replacedType(node.text)) names.add(node.text); + const type_name = ts.isTypeReferenceNode(parent) && parent.typeName === node; + if (!type_name || !replacedType(node.text)) names.add(node.text); } // An import of another module, such as `import { orThrow } from './utils'`, has a name. if (ts.isImportDeclaration(node)) { @@ -943,11 +943,11 @@ function fromV1MockArgs(mapping: CallMapping): string { const keys = mapping.parameters.map((_parameter, index) => inputKey(mapping, index)); while (keys.at(-1) === null) keys.pop(); const list = `[${keys.map((key) => (key === null ? 'null' : quote(key))).join(', ')}]`; - const pickKey = mapping.pick?.kind === 'arg' ? inputKey(mapping, mapping.pick.index) : null; + const pick_key = mapping.pick?.kind === 'arg' ? inputKey(mapping, mapping.pick.index) : null; return [ list, - ...(mapping.result === 'page' || pickKey !== null ? [`'${mapping.result}'`] : []), - ...(pickKey === null ? [] : [quote(pickKey)]), + ...(mapping.result === 'page' || pick_key !== null ? [`'${mapping.result}'`] : []), + ...(pick_key === null ? [] : [quote(pick_key)]), ].join(', '); } @@ -1027,7 +1027,7 @@ function hint(tables: MigrateTables, name: string): string { interface RenderedCall { readonly input: string; readonly pick: string | null; - readonly pickParameter: string; + readonly pick_parameter: string; } /** The 7.x input of a 6.x call, or the reason that the tool cannot make it. */ @@ -1041,10 +1041,10 @@ function renderCall( // A check does not know the `version` that 7.x reads from the data, so it checks the rest. const isMember = (entry: ObjectEntry) => entry.kind === 'property' && entry.value.kind === 'member'; - const entriesOf = mapping.input.kind === 'object' ? mapping.input.entries : []; - const loose = expectation && entriesOf.some(isMember); + const entries_of = mapping.input.kind === 'object' ? mapping.input.entries : []; + const loose = expectation && entries_of.some(isMember); const template: Template = loose - ? { kind: 'object', entries: entriesOf.filter((entry) => !isMember(entry)) } + ? { kind: 'object', entries: entries_of.filter((entry) => !isMember(entry)) } : mapping.input; if (args.some((arg) => ts.isSpreadElement(arg))) return 'a spread argument: change the call by hand'; @@ -1100,12 +1100,13 @@ function renderCall( ? whole.text : (renderTemplate(ts, template, value, textOf) ?? '{}'); const pick = mapping.pick === null ? null : renderTemplate(ts, mapping.pick, value, textOf); - const pickText = pick ?? ''; - const pickParameter = - ['data', 'value', 'response'].find((name) => !new RegExp(`\\b${name}\\b`).test(pickText)) ?? - 'v2Data'; - if (loose) return { input: `expect.objectContaining(${input})`, pick, pickParameter }; - return { input, pick, pickParameter }; + const pick_text = pick ?? ''; + const pick_parameter = + ['data', 'value', 'response'].find( + (name) => !new RegExp(`\\b${name}\\b`).test(pick_text), + ) ?? 'v2Data'; + if (loose) return { input: `expect.objectContaining(${input})`, pick, pick_parameter }; + return { input, pick, pick_parameter }; } interface Value { @@ -1287,12 +1288,12 @@ function importEdits( removed.add(declaration); continue; } - const typeOnly = clause.isTypeOnly ? 'type ' : ''; + const type_only = clause.isTypeOnly ? 'type ' : ''; const from = declaration.moduleSpecifier.getText(source); edits.push({ start, end: declaration.end, - text: `import ${typeOnly}{ ${specifiers.join(', ')} } from ${from};`, + text: `import ${type_only}{ ${specifiers.join(', ')} } from ${from};`, }); } return { edits, pending, removed }; diff --git a/src/migrate/v1-map.ts b/src/migrate/v1-map.ts index b06174561..97349bf7c 100644 --- a/src/migrate/v1-map.ts +++ b/src/migrate/v1-map.ts @@ -4,7 +4,7 @@ import type { CallMap, TypeMapping } from './map.ts'; /** The 7.x call for each 6.x REST function. */ export const V1_CALLS: CallMap = { acceptGroupInvitation: { - namespace: 'groupsInvitations', + namespace: 'groups_invitations', operation: 'accept', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -28,7 +28,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addAlertDashboard: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -41,7 +41,7 @@ export const V1_CALLS: CallMap = { }, addAnswer: { module: 'staff', - namespace: 'surveysAnswers', + namespace: 'surveys_answers', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -53,7 +53,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addApiKey: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -65,7 +65,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addApplication: { - namespace: 'oauthApplications', + namespace: 'oauth_applications', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -89,7 +89,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addAssetCategory: { - namespace: 'assetCategories', + namespace: 'asset_categories', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -101,7 +101,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addAssetPurchaseOrder: { - namespace: 'assetPurchaseOrders', + namespace: 'asset_purchase_orders', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -125,7 +125,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addAssetType: { - namespace: 'assetTypes', + namespace: 'asset_types', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -197,7 +197,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addGroupInvitation: { - namespace: 'groupsInvitations', + namespace: 'groups_invitations', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -209,7 +209,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addGroupUser: { - namespace: 'groupsUsers', + namespace: 'groups_users', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -221,7 +221,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addGroupZone: { - namespace: 'groupsZones', + namespace: 'groups_zones', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -234,7 +234,7 @@ export const V1_CALLS: CallMap = { }, addInvitation: { module: 'staff', - namespace: 'surveysInvitations', + namespace: 'surveys_invitations', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -246,7 +246,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addLDAPSource: { - namespace: 'ldapAuthentications', + namespace: 'ldap_authentications', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -270,7 +270,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addOAuthSource: { - namespace: 'oauthAuthentications', + namespace: 'oauth_authentications', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -283,7 +283,7 @@ export const V1_CALLS: CallMap = { }, addQuestion: { module: 'staff', - namespace: 'surveysQuestions', + namespace: 'surveys_questions', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -307,7 +307,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSAMLSource: { - namespace: 'samlAuthentications', + namespace: 'saml_authentications', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -337,7 +337,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addShortUrl: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -349,7 +349,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSignageAIProvider: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -361,7 +361,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'create', parameters: [ { name: 'form_data', initializer: null, use: 'mapped' }, @@ -397,7 +397,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSignagePlugin: { - namespace: 'signagePlugins', + namespace: 'signage_plugins', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -409,7 +409,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'create', parameters: [ { name: 'form_data', initializer: null, use: 'mapped' }, @@ -427,7 +427,7 @@ export const V1_CALLS: CallMap = { notes: [], }, addSignageTemplateMapping: { - namespace: 'signageTemplateMappings', + namespace: 'signage_template_mappings', operation: 'create', parameters: [{ name: 'form_data', initializer: null, use: 'mapped' }], input: { @@ -495,7 +495,7 @@ export const V1_CALLS: CallMap = { notes: ['7.x has no body for data'], }, addSystemTrigger: { - namespace: 'systemTriggers', + namespace: 'system_triggers', operation: 'create', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -570,7 +570,7 @@ export const V1_CALLS: CallMap = { notes: [], }, approveSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'approve', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -582,7 +582,7 @@ export const V1_CALLS: CallMap = { notes: [], }, buildMonitor: { - namespace: 'buildMonitor', + namespace: 'build_monitor', operation: 'monitor', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -609,7 +609,7 @@ export const V1_CALLS: CallMap = { notes: [], }, cancelBuildJob: { - namespace: 'buildMonitor', + namespace: 'build_monitor', operation: 'cancel', parameters: [{ name: 'job', initializer: null, use: 'mapped' }], input: { @@ -621,7 +621,7 @@ export const V1_CALLS: CallMap = { notes: [], }, cancelSignageAIJob: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'cancel', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -633,7 +633,7 @@ export const V1_CALLS: CallMap = { notes: [], }, claimSignageAIImage: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'claim', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -834,7 +834,7 @@ export const V1_CALLS: CallMap = { notes: [], }, editSignageImage: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'edit', parameters: [{ name: 'request', initializer: null, use: 'mapped' }], input: { @@ -943,7 +943,7 @@ export const V1_CALLS: CallMap = { notes: [], }, generateQrCode: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'generateQrCode', parameters: [{ name: 'options', initializer: null, use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -952,7 +952,7 @@ export const V1_CALLS: CallMap = { notes: ['6.x sent format=svg, and 7.x has no format parameter'], }, generateSignageImage: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'generate', parameters: [{ name: 'request', initializer: null, use: 'mapped' }], input: { @@ -964,7 +964,7 @@ export const V1_CALLS: CallMap = { notes: [], }, getShortUrlQrCodeSvg: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'svgQr', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -976,7 +976,7 @@ export const V1_CALLS: CallMap = { notes: [], }, googleNotification: { - namespace: 'pushNotifications', + namespace: 'push_notifications', operation: 'google', parameters: [{ name: 'body', initializer: '{}', use: 'unsupported' }], input: { kind: 'object', entries: [] }, @@ -994,7 +994,7 @@ export const V1_CALLS: CallMap = { notes: [], }, inspectApiKey: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'inspectKey', parameters: [], input: { kind: 'object', entries: [] }, @@ -1033,7 +1033,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listDashboardAlerts: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'alerts', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -1045,7 +1045,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listPublicEvents: { - namespace: 'publicEvents', + namespace: 'public_events', operation: 'query', parameters: [ { name: 'system_id', initializer: null, use: 'mapped' }, @@ -1204,7 +1204,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listSignageMediaTagCounts: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'tagCounts', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1213,7 +1213,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listSignageMediaTags: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'tags', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1264,7 +1264,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listSignageTemplateApprovers: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'approvers', parameters: [{ name: 'group_id', initializer: null, use: 'mapped' }], input: { @@ -1276,7 +1276,7 @@ export const V1_CALLS: CallMap = { notes: [], }, listSystemTriggers: { - namespace: 'systemTriggers', + namespace: 'system_triggers', operation: 'query', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -1466,7 +1466,7 @@ export const V1_CALLS: CallMap = { notes: [], }, office365Notification: { - namespace: 'pushNotifications', + namespace: 'push_notifications', operation: 'microsoft', parameters: [{ name: 'body', initializer: null, use: 'mapped' }], input: { @@ -1487,7 +1487,7 @@ export const V1_CALLS: CallMap = { notes: [], }, proxyUrl: { - namespace: 'urlProxy', + namespace: 'url_proxy', operation: 'proxy', parameters: [ { name: 'url', initializer: null, use: 'mapped' }, @@ -1502,7 +1502,7 @@ export const V1_CALLS: CallMap = { notes: [], }, publicEventGuestToken: { - namespace: 'publicEvents', + namespace: 'public_events', operation: 'guestToken', parameters: [ { name: 'system_id', initializer: null, use: 'mapped' }, @@ -1535,7 +1535,7 @@ export const V1_CALLS: CallMap = { notes: ['7.x has no body for query_params'], }, queryAlertDashboards: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1554,7 +1554,7 @@ export const V1_CALLS: CallMap = { }, queryAnswers: { module: 'staff', - namespace: 'surveysAnswers', + namespace: 'surveys_answers', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1563,7 +1563,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryApiKeys: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1572,7 +1572,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryApplications: { - namespace: 'oauthApplications', + namespace: 'oauth_applications', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1581,7 +1581,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryAssetCategories: { - namespace: 'assetCategories', + namespace: 'asset_categories', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1590,7 +1590,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryAssetPurchaseOrders: { - namespace: 'assetPurchaseOrders', + namespace: 'asset_purchase_orders', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1608,7 +1608,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryAssetTypes: { - namespace: 'assetTypes', + namespace: 'asset_types', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1662,7 +1662,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryGroupHistory: { - namespace: 'groupsHistory', + namespace: 'groups_history', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1671,7 +1671,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryGroupInvitations: { - namespace: 'groupsInvitations', + namespace: 'groups_invitations', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1689,7 +1689,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryGroupUsers: { - namespace: 'groupsUsers', + namespace: 'groups_users', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1698,7 +1698,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryGroupZones: { - namespace: 'groupsZones', + namespace: 'groups_zones', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1717,7 +1717,7 @@ export const V1_CALLS: CallMap = { }, queryInvitations: { module: 'staff', - namespace: 'surveysInvitations', + namespace: 'surveys_invitations', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1726,7 +1726,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryLDAPSources: { - namespace: 'ldapAuthentications', + namespace: 'ldap_authentications', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1744,7 +1744,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryOAuthSources: { - namespace: 'oauthAuthentications', + namespace: 'oauth_authentications', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1772,7 +1772,7 @@ export const V1_CALLS: CallMap = { }, queryQuestions: { module: 'staff', - namespace: 'surveysQuestions', + namespace: 'surveys_questions', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1790,7 +1790,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySAMLSources: { - namespace: 'samlAuthentications', + namespace: 'saml_authentications', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1808,7 +1808,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryShortUrls: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1817,7 +1817,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignageAIJobs: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'indexJobs', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1826,7 +1826,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignageAIProviders: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1835,7 +1835,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1853,7 +1853,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignagePlugins: { - namespace: 'signagePlugins', + namespace: 'signage_plugins', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1862,7 +1862,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignageTemplateMappings: { - namespace: 'signageTemplateMappings', + namespace: 'signage_template_mappings', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1871,7 +1871,7 @@ export const V1_CALLS: CallMap = { notes: [], }, querySignageTemplates: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1944,7 +1944,7 @@ export const V1_CALLS: CallMap = { notes: [], }, queryWebrtcRooms: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'query', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -1974,7 +1974,7 @@ export const V1_CALLS: CallMap = { notes: [], }, registerPublicEvent: { - namespace: 'publicEvents', + namespace: 'public_events', operation: 'register', parameters: [ { name: 'system_id', initializer: null, use: 'mapped' }, @@ -2016,7 +2016,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeAlertDashboard: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2028,7 +2028,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeApiKey: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2040,7 +2040,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeApplication: { - namespace: 'oauthApplications', + namespace: 'oauth_applications', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2070,7 +2070,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeAssetCategory: { - namespace: 'assetCategories', + namespace: 'asset_categories', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2088,7 +2088,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeAssetPurchaseOrder: { - namespace: 'assetPurchaseOrders', + namespace: 'asset_purchase_orders', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2124,7 +2124,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeAssetType: { - namespace: 'assetTypes', + namespace: 'asset_types', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2208,7 +2208,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeGroupInvitation: { - namespace: 'groupsInvitations', + namespace: 'groups_invitations', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2220,7 +2220,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeGroupUser: { - namespace: 'groupsUsers', + namespace: 'groups_users', operation: 'destroy', parameters: [ { name: 'user_id', initializer: null, use: 'mapped' }, @@ -2238,7 +2238,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeGroupZone: { - namespace: 'groupsZones', + namespace: 'groups_zones', operation: 'destroy', parameters: [ { name: 'group_id', initializer: null, use: 'mapped' }, @@ -2257,7 +2257,7 @@ export const V1_CALLS: CallMap = { }, removeInvitation: { module: 'staff', - namespace: 'surveysInvitations', + namespace: 'surveys_invitations', operation: 'destroy', parameters: [ { name: 'token', initializer: null, use: 'mapped' }, @@ -2275,7 +2275,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeLDAPSource: { - namespace: 'ldapAuthentications', + namespace: 'ldap_authentications', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2317,7 +2317,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeOAuthSource: { - namespace: 'oauthAuthentications', + namespace: 'oauth_authentications', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2330,7 +2330,7 @@ export const V1_CALLS: CallMap = { }, removeQuestion: { module: 'staff', - namespace: 'surveysQuestions', + namespace: 'surveys_questions', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2360,7 +2360,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSAMLSource: { - namespace: 'samlAuthentications', + namespace: 'saml_authentications', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2384,7 +2384,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeShortUrl: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2402,7 +2402,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageAIProvider: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2414,7 +2414,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2432,7 +2432,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageMediaTag: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'removeTag', parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -2459,7 +2459,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignagePlugin: { - namespace: 'signagePlugins', + namespace: 'signage_plugins', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2477,7 +2477,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2495,7 +2495,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageTemplateDraft: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'destroyDraft', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2507,7 +2507,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSignageTemplateMapping: { - namespace: 'signageTemplateMappings', + namespace: 'signage_template_mappings', operation: 'destroy', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2586,7 +2586,7 @@ export const V1_CALLS: CallMap = { notes: [], }, removeSystemTrigger: { - namespace: 'systemTriggers', + namespace: 'system_triggers', operation: 'destroy', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2676,7 +2676,7 @@ export const V1_CALLS: CallMap = { notes: [], }, renameSignageMediaTag: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'renameTag', parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -2716,7 +2716,7 @@ export const V1_CALLS: CallMap = { notes: [], }, requestApprovalSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'requestApproval', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2825,7 +2825,7 @@ export const V1_CALLS: CallMap = { notes: [], }, shareSignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'share', parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -2843,7 +2843,7 @@ export const V1_CALLS: CallMap = { notes: [], }, shareSignageTemplates: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'share', parameters: [{ name: 'query_params', initializer: null, use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -2870,7 +2870,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showAlertDashboard: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2882,7 +2882,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showApiKey: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2894,7 +2894,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showApplication: { - namespace: 'oauthApplications', + namespace: 'oauth_applications', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -2924,7 +2924,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showAssetCategory: { - namespace: 'assetCategories', + namespace: 'asset_categories', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2942,7 +2942,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showAssetPurchaseOrder: { - namespace: 'assetPurchaseOrders', + namespace: 'asset_purchase_orders', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -2960,7 +2960,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showAssetType: { - namespace: 'assetTypes', + namespace: 'asset_types', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3086,7 +3086,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showGroupHistory: { - namespace: 'groupsHistory', + namespace: 'groups_history', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3098,7 +3098,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showGroupInvitation: { - namespace: 'groupsInvitations', + namespace: 'groups_invitations', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3110,7 +3110,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showGroupUser: { - namespace: 'groupsUsers', + namespace: 'groups_users', operation: 'show', parameters: [ { name: 'user_id', initializer: null, use: 'mapped' }, @@ -3128,7 +3128,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showGroupZone: { - namespace: 'groupsZones', + namespace: 'groups_zones', operation: 'show', parameters: [ { name: 'group_id', initializer: null, use: 'mapped' }, @@ -3159,7 +3159,7 @@ export const V1_CALLS: CallMap = { }, showInvitation: { module: 'staff', - namespace: 'surveysInvitations', + namespace: 'surveys_invitations', operation: 'show', parameters: [ { name: 'token', initializer: null, use: 'mapped' }, @@ -3177,7 +3177,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showLDAPSource: { - namespace: 'ldapAuthentications', + namespace: 'ldap_authentications', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3225,7 +3225,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showOAuthSource: { - namespace: 'oauthAuthentications', + namespace: 'oauth_authentications', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3238,7 +3238,7 @@ export const V1_CALLS: CallMap = { }, showQuestion: { module: 'staff', - namespace: 'surveysQuestions', + namespace: 'surveys_questions', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3268,7 +3268,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSAMLSource: { - namespace: 'samlAuthentications', + namespace: 'saml_authentications', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3292,7 +3292,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showShortUrl: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3329,7 +3329,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignageAIJob: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'showJob', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3348,7 +3348,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignageAIProvider: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3360,7 +3360,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3396,7 +3396,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignagePlugin: { - namespace: 'signagePlugins', + namespace: 'signage_plugins', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3414,7 +3414,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'show', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3432,7 +3432,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSignageTemplateMapping: { - namespace: 'signageTemplateMappings', + namespace: 'signage_template_mappings', operation: 'show', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3499,7 +3499,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showSystemTrigger: { - namespace: 'systemTriggers', + namespace: 'system_triggers', operation: 'show', parameters: [ { name: 'sys_id', initializer: null, use: 'mapped' }, @@ -3573,7 +3573,7 @@ export const V1_CALLS: CallMap = { notes: [], }, showWebrtcRoom: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'publicRoom', parameters: [{ name: 'system_id', initializer: null, use: 'mapped' }], input: { @@ -3603,7 +3603,7 @@ export const V1_CALLS: CallMap = { notes: [], }, signageAICapabilities: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'capabilities', parameters: [], input: { kind: 'object', entries: [] }, @@ -3612,7 +3612,7 @@ export const V1_CALLS: CallMap = { notes: [], }, signageAIUsage: { - namespace: 'signageAi', + namespace: 'signage_ai', operation: 'usage', parameters: [{ name: 'query_params', initializer: '{}', use: 'mapped' }], input: { kind: 'object', entries: [{ kind: 'spread', index: 0 }] }, @@ -3800,7 +3800,7 @@ export const V1_CALLS: CallMap = { notes: [], }, testSignageAIProvider: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'test', parameters: [{ name: 'id', initializer: null, use: 'mapped' }], input: { @@ -3831,7 +3831,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateAlertDashboard: { - namespace: 'alertDashboards', + namespace: 'alert_dashboards', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3850,7 +3850,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateApiKey: { - namespace: 'apiKeys', + namespace: 'api_keys', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3869,7 +3869,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateApplication: { - namespace: 'oauthApplications', + namespace: 'oauth_applications', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3907,7 +3907,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateAssetCategory: { - namespace: 'assetCategories', + namespace: 'asset_categories', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3926,7 +3926,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateAssetPurchaseOrder: { - namespace: 'assetPurchaseOrders', + namespace: 'asset_purchase_orders', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -3960,7 +3960,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateAssetType: { - namespace: 'assetTypes', + namespace: 'asset_types', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4074,7 +4074,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateGroupUser: { - namespace: 'groupsUsers', + namespace: 'groups_users', operation: 'update', parameters: [ { name: 'user_id', initializer: null, use: 'mapped' }, @@ -4095,7 +4095,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateGroupZone: { - namespace: 'groupsZones', + namespace: 'groups_zones', operation: 'update', parameters: [ { name: 'group_id', initializer: null, use: 'mapped' }, @@ -4117,7 +4117,7 @@ export const V1_CALLS: CallMap = { }, updateInvitation: { module: 'staff', - namespace: 'surveysInvitations', + namespace: 'surveys_invitations', operation: 'update', parameters: [ { name: 'token', initializer: null, use: 'mapped' }, @@ -4136,7 +4136,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateLDAPSource: { - namespace: 'ldapAuthentications', + namespace: 'ldap_authentications', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4193,7 +4193,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateOAuthSource: { - namespace: 'oauthAuthentications', + namespace: 'oauth_authentications', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4213,7 +4213,7 @@ export const V1_CALLS: CallMap = { }, updateQuestion: { module: 'staff', - namespace: 'surveysQuestions', + namespace: 'surveys_questions', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4251,7 +4251,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSAMLSource: { - namespace: 'samlAuthentications', + namespace: 'saml_authentications', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4291,7 +4291,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateShortUrl: { - namespace: 'shortUrl', + namespace: 'short_url', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4310,7 +4310,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSignageAIProvider: { - namespace: 'signageAiProviders', + namespace: 'signage_ai_providers', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4329,7 +4329,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSignageMedia: { - namespace: 'playlistMedia', + namespace: 'playlist_media', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4423,7 +4423,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSignagePlugin: { - namespace: 'signagePlugins', + namespace: 'signage_plugins', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4442,7 +4442,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSignageTemplate: { - namespace: 'signageTemplates', + namespace: 'signage_templates', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4461,7 +4461,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSignageTemplateMapping: { - namespace: 'signageTemplateMappings', + namespace: 'signage_template_mappings', operation: 'update', parameters: [ { name: 'id', initializer: null, use: 'mapped' }, @@ -4543,7 +4543,7 @@ export const V1_CALLS: CallMap = { notes: [], }, updateSystemTrigger: { - namespace: 'systemTriggers', + namespace: 'system_triggers', operation: 'show', parameters: [ { name: 'sys_id', initializer: null, use: 'mapped' }, @@ -4651,7 +4651,7 @@ export const V1_CALLS: CallMap = { notes: [], }, webrtcGuestEntry: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'guestEntry', parameters: [ { name: 'system_id', initializer: null, use: 'mapped' }, @@ -4669,7 +4669,7 @@ export const V1_CALLS: CallMap = { notes: [], }, webrtcGuestExit: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'guestExit', parameters: [], input: { kind: 'object', entries: [] }, @@ -4678,7 +4678,7 @@ export const V1_CALLS: CallMap = { notes: [], }, webrtcKickUser: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'kickUser', parameters: [ { name: 'user_id', initializer: null, use: 'mapped' }, @@ -4698,7 +4698,7 @@ export const V1_CALLS: CallMap = { notes: [], }, webrtcSessionMembers: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'members', parameters: [{ name: 'session_id', initializer: null, use: 'mapped' }], input: { @@ -4710,7 +4710,7 @@ export const V1_CALLS: CallMap = { notes: [], }, webrtcTransferUser: { - namespace: 'webRtc', + namespace: 'web_rtc', operation: 'transferGuest', parameters: [ { name: 'user_id', initializer: null, use: 'mapped' }, diff --git a/src/mock/index.ts b/src/mock/index.ts index 1002a41a3..07b8912b1 100644 --- a/src/mock/index.ts +++ b/src/mock/index.ts @@ -7,7 +7,7 @@ * import { configure, zones } from '@placeos/ts-client'; * import { endpointMocks, mockEndpoint, respond } from '@placeos/ts-client/mock'; * - * configure({ baseUrl: '', auth: { kind: 'none' }, mock: endpointMocks }); + * configure({ base_url: '', auth: { kind: 'none' }, mock: endpointMocks }); * mockEndpoint('zones.show', (input) => ({ id: input.id, name: 'Level 1' })); * mockEndpoint('zones.query', (input) => respond([{ id: 'zone-1' }], { total: 1 })); * @@ -97,7 +97,7 @@ type MockResult = export interface MockOptions { /** Milliseconds before the answer, to show the loading state of an app. The default is 0. */ - readonly delayMs?: number; + readonly delay_ms?: number; } /** More mocks is a leak, such as a test that adds mocks in a loop and never removes them. */ @@ -105,7 +105,7 @@ export const ENDPOINT_MOCKS_MAX = 10_000; interface Entry { readonly handler: (input: Readonly>) => unknown; - readonly delayMs: number; + readonly delay_ms: number; } const mocks = new Map(); @@ -120,12 +120,12 @@ export function mockEndpoint( options: MockOptions = {}, ): () => void { assert(mocks.has(name) || mocks.size < ENDPOINT_MOCKS_MAX, 'fewer endpoint mocks'); - const delayMs = options.delayMs ?? 0; - assert(Number.isSafeInteger(delayMs) && delayMs >= 0, 'delayMs is a whole number'); + const delay_ms = options.delay_ms ?? 0; + assert(Number.isSafeInteger(delay_ms) && delay_ms >= 0, 'delay_ms is a whole number'); // The client gives the input of this endpoint, which the type of `handler` describes. const entry: Entry = { handler: (input) => Reflect.apply(handler, undefined, [input]), - delayMs, + delay_ms, }; mocks.set(name, entry); return () => { @@ -167,7 +167,7 @@ export const endpointMocks: CallMock = ({ name, input }) => { }; async function answer(entry: Entry, input: Readonly>): Promise { - if (entry.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, entry.delayMs)); + if (entry.delay_ms > 0) await new Promise((resolve) => setTimeout(resolve, entry.delay_ms)); let value: unknown; try { value = await entry.handler(input); diff --git a/src/realtime/environment.ts b/src/realtime/environment.ts index 1d4a5c128..03d03ca26 100644 --- a/src/realtime/environment.ts +++ b/src/realtime/environment.ts @@ -28,9 +28,9 @@ export type TokenTransport = export interface RealtimeEnvironment { readonly createSocket: (url: string, handlers: SocketHandlers) => RealtimeSocket; - /** The URL of the page now. A `baseUrl` of `''` uses its origin. */ + /** The URL of the page now. A `base_url` of `''` uses its origin. */ readonly currentUrl: () => string; - readonly tokenTransport: TokenTransport; + readonly token_transport: TokenTransport; /** Sets a cookie, as `document.cookie = cookie` does. */ readonly setCookie: (cookie: string) => void; /** Milliseconds since the Unix epoch. */ @@ -48,7 +48,7 @@ export function browserRealtimeEnvironment(): RealtimeEnvironment { return { createSocket, currentUrl: () => window.location.href, - tokenTransport: isNestedFrame() || isMobileSafari() ? 'query' : 'cookie', + token_transport: isNestedFrame() || isMobileSafari() ? 'query' : 'cookie', setCookie: (cookie) => { document.cookie = cookie; }, diff --git a/src/realtime/realtime.ts b/src/realtime/realtime.ts index 87a1731b5..221122129 100644 --- a/src/realtime/realtime.ts +++ b/src/realtime/realtime.ts @@ -3,7 +3,7 @@ * variables of modules, function calls and module logs. * * ```ts - * const realtime = createRealtime({ baseUrl: '', auth: session.clientAuth }); + * const realtime = createRealtime({ base_url: '', auth: session.client_auth }); * const release = realtime.bind({ sys: 'sys-1', mod: 'Display', name: 'power' }, (state) => { * if (state.kind === 'value') console.log(state.value); * }); @@ -93,18 +93,18 @@ export interface RealtimeTarget { /** A module to get the logs of. The server needs the module ID, not its name. */ export interface DebugTarget { readonly sys: string; - readonly moduleId: string; + readonly module_id: string; } export type RealtimeError = - | { readonly kind: 'timeout'; readonly timeoutMs: number } + | { readonly kind: 'timeout'; readonly timeout_ms: number } /** The socket closed after the server got the request. The result is not known. */ | { readonly kind: 'disconnected' } /** `stop` ran before the response. */ | { readonly kind: 'stopped' } /** The client could not connect `RECONNECT_ATTEMPTS_MAX` times. */ | { readonly kind: 'unavailable' } - | { readonly kind: 'too_many_requests'; readonly pendingMax: number } + | { readonly kind: 'too_many_requests'; readonly pending_max: number } /** The server refused the request. `status` is the HTTP style code, such as 404. */ | { readonly kind: 'server'; @@ -123,24 +123,24 @@ export interface DebugMessage { readonly level: string | null; readonly message: string; /** When the client got the message, in milliseconds since the Unix epoch. */ - readonly receivedAtMs: number; + readonly received_at_ms: number; } export type RealtimeStatus = | { readonly kind: 'idle' } | { readonly kind: 'connecting'; readonly attempt: number } - | { readonly kind: 'open'; readonly sinceMs: number } - | { readonly kind: 'waiting'; readonly attempt: number; readonly delayMs: number } + | { readonly kind: 'open'; readonly since_ms: number } + | { readonly kind: 'waiting'; readonly attempt: number; readonly delay_ms: number } /** `RECONNECT_ATTEMPTS_MAX` attempts failed. `start` tries again. */ | { readonly kind: 'failed' } | { readonly kind: 'stopped' }; export interface RealtimeConfig { /** The origin of the server, such as `https://placeos.example.com`. `''` is this origin. */ - readonly baseUrl: string; + readonly base_url: string; readonly auth: Auth; /** Tells the server that this is a device in a fixed location. */ - readonly fixedDevice?: boolean; + readonly fixed_device?: boolean; readonly environment?: RealtimeEnvironment; } @@ -156,7 +156,7 @@ export interface Realtime { exec( target: RealtimeTarget, args?: readonly JsonValue[], - options?: { readonly timeoutMs?: number }, + options?: { readonly timeout_ms?: number }, ): Promise>; /** * Binds to a status variable. `listener` gets each new state, and the current one at once if @@ -172,14 +172,14 @@ export interface Realtime { } /** `Display_2` is the module `Display` with index 2. A name without an index has index 1. */ -export function splitModuleId(moduleId: string): { readonly mod: string; readonly index: number } { +export function splitModuleId(module_id: string): { readonly mod: string; readonly index: number } { // `lastIndexOf` is linear. A regular expression such as `^(.+)_(\d+)$` backtracks. - const separator = moduleId.lastIndexOf('_'); - const digits = moduleId.slice(separator + 1); - if (separator <= 0 || !/^\d+$/.test(digits)) return { mod: moduleId, index: 1 }; + const separator = module_id.lastIndexOf('_'); + const digits = module_id.slice(separator + 1); + if (separator <= 0 || !/^\d+$/.test(digits)) return { mod: module_id, index: 1 }; const index = Number(digits); assert(Number.isSafeInteger(index), 'the module index is an integer'); - return { mod: moduleId.slice(0, separator), index: Math.max(1, index) }; + return { mod: module_id.slice(0, separator), index: Math.max(1, index) }; } const Meta = object({ sys: string(), mod: string(), index: integer('Int32'), name: string() }, [ @@ -232,7 +232,7 @@ interface Debugger { /** Makes a realtime client. It connects when it first needs to. */ export function createRealtime(config: RealtimeConfig): Realtime { - assert(!config.baseUrl.endsWith('/'), 'the baseUrl has no trailing slash'); + assert(!config.base_url.endsWith('/'), 'the base_url has no trailing slash'); const environment = config.environment ?? browserRealtimeEnvironment(); let status: RealtimeStatus = { kind: 'idle' }; @@ -240,27 +240,27 @@ export function createRealtime(config: RealtimeConfig): Realtime { /** Each socket has a generation. The client ignores the events of an old socket. */ let generation = 0; /** Each connect attempt has an ID. `stop` and a new attempt make an older one stop. */ - let connectAttempt = 0; - let callsPending = 0; + let connect_attempt = 0; + let calls_pending = 0; /** The connect attempts since the last open. */ let attempt = 0; - let failuresBeforeOpen = 0; - let renewBeforeConnect = false; - let lastCredential: Credential | null = null; - let lastMessageAtMs = 0; + let failures_before_open = 0; + let renew_before_connect = false; + let last_credential: Credential | null = null; + let last_message_at_ms = 0; let cancelConnectTimer: (() => void) | null = null; let cancelKeepAlive: (() => void) | null = null; let cancelReconnect: (() => void) | null = null; - let drainScheduled = false; - let statusNotifyScheduled = false; - let nextId = 1; + let drain_scheduled = false; + let status_notify_scheduled = false; + let next_id = 1; const pending = new Map(); /** The pending requests that wait for a socket, in the order of the calls. */ const queue: number[] = []; const bindings = new Map(); const debuggers = new Map(); const inbox: unknown[] = []; - const statusListeners = new Set<(status: RealtimeStatus) => void>(); + const status_listeners = new Set<(status: RealtimeStatus) => void>(); return { start, @@ -277,13 +277,13 @@ export function createRealtime(config: RealtimeConfig): Realtime { const kind = status.kind; if (kind === 'open' || kind === 'connecting' || kind === 'waiting') return; attempt = 0; - failuresBeforeOpen = 0; + failures_before_open = 0; // A rejection of `connect` is a bug, and the platform reports it as unhandled. void connect(); } function stop(): void { - connectAttempt += 1; + connect_attempt += 1; setStatus({ kind: 'stopped' }); cancelTimers(); cancelReconnect?.(); @@ -296,11 +296,14 @@ export function createRealtime(config: RealtimeConfig): Realtime { function exec( target: RealtimeTarget, args: readonly JsonValue[] = [], - options: { readonly timeoutMs?: number } = {}, + options: { readonly timeout_ms?: number } = {}, ): Promise> { - const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS; - assert(Number.isSafeInteger(timeoutMs) && timeoutMs > 0, 'timeoutMs is a positive integer'); - return request('exec', normalize(target), args, timeoutMs); + const timeout_ms = options.timeout_ms ?? REQUEST_TIMEOUT_MS; + assert( + Number.isSafeInteger(timeout_ms) && timeout_ms > 0, + 'timeout_ms is a positive integer', + ); + return request('exec', normalize(target), args, timeout_ms); } function bind(target: RealtimeTarget, listener: (state: BindingState) => void): () => void { @@ -343,8 +346,8 @@ export function createRealtime(config: RealtimeConfig): Realtime { function debug(target: DebugTarget, listener: (message: DebugMessage) => void): () => void { assert(target.sys.length > 0, 'the system ID is not empty'); - assert(target.moduleId.length > 0, 'the module ID is not empty'); - const key = debugKey(target.sys, target.moduleId); + assert(target.module_id.length > 0, 'the module ID is not empty'); + const key = debugKey(target.sys, target.module_id); let entry = debuggers.get(key); if (entry === undefined) { assert( @@ -376,18 +379,18 @@ export function createRealtime(config: RealtimeConfig): Realtime { command: Command, target: Required, args: readonly JsonValue[] | null, - timeoutMs: number, + timeout_ms: number, ): Promise> { if (status.kind === 'stopped') return Promise.resolve(failure({ kind: 'stopped' })); if (status.kind === 'failed') return Promise.resolve(failure({ kind: 'unavailable' })); const call = command === 'exec'; const limit = call ? PENDING_MAX : BINDING_REQUESTS_MAX; - const count = call ? callsPending : pending.size - callsPending; + const count = call ? calls_pending : pending.size - calls_pending; if (count >= limit) { - return Promise.resolve(failure({ kind: 'too_many_requests', pendingMax: limit })); + return Promise.resolve(failure({ kind: 'too_many_requests', pending_max: limit })); } - const id = nextId; - nextId += 1; + const id = next_id; + next_id += 1; assert(Number.isSafeInteger(id), 'the request ID is a safe integer'); // The server parses the request strictly, so send only the fields that it knows. const text = JSON.stringify({ @@ -401,12 +404,12 @@ export function createRealtime(config: RealtimeConfig): Realtime { ...(target.iface ? { iface: true } : {}), }); return new Promise((resolve) => { - const cancelTimer = environment.setTimer(timeoutMs, () => - settle(id, failure({ kind: 'timeout', timeoutMs })), + const cancelTimer = environment.setTimer(timeout_ms, () => + settle(id, failure({ kind: 'timeout', timeout_ms })), ); const entry: Pending = { text, call, sent: false, resolve, cancelTimer }; pending.set(id, entry); - if (call) callsPending += 1; + if (call) calls_pending += 1; if (socket !== null && status.kind === 'open') { socket.send(text); entry.sent = true; @@ -421,8 +424,8 @@ export function createRealtime(config: RealtimeConfig): Realtime { const entry = pending.get(id); if (entry === undefined) return; pending.delete(id); - if (entry.call) callsPending -= 1; - assert(callsPending >= 0, 'the count of calls is not negative'); + if (entry.call) calls_pending -= 1; + assert(calls_pending >= 0, 'the count of calls is not negative'); // A request that times out before the socket opens leaves the queue, so it stays bounded. if (!entry.sent) { const queued = queue.indexOf(id); @@ -453,33 +456,33 @@ export function createRealtime(config: RealtimeConfig): Realtime { return; } // The server reads the module ID from `mod` for logs. It does not use `index` or `name`. - const target = { sys: entry.target.sys, mod: entry.target.moduleId, index: 1, name: '' }; + const target = { sys: entry.target.sys, mod: entry.target.module_id, index: 1, name: '' }; void request(command, { ...target, iface: false }, null, REQUEST_TIMEOUT_MS); } async function connect(): Promise { - connectAttempt += 1; - const thisAttempt = connectAttempt; + connect_attempt += 1; + const this_attempt = connect_attempt; attempt += 1; setStatus({ kind: 'connecting', attempt }); - if (renewBeforeConnect && config.auth.kind === 'credential' && lastCredential !== null) { - renewBeforeConnect = false; - await config.auth.rejected(401, lastCredential); - if (thisAttempt !== connectAttempt) return; + if (renew_before_connect && config.auth.kind === 'credential' && last_credential !== null) { + renew_before_connect = false; + await config.auth.rejected(401, last_credential); + if (this_attempt !== connect_attempt) return; } const credential = await resolveCredential(config.auth); // `stop`, or `stop` then `start`, can run while the credential is pending. - if (thisAttempt !== connectAttempt) return; + if (this_attempt !== connect_attempt) return; if (status.kind !== 'connecting') return; if (credential === null) { scheduleReconnect(); return; } - lastCredential = credential; + last_credential = credential; const url = socketUrl(credential); generation += 1; - const socketGeneration = generation; - const current = () => socketGeneration === generation; + const socket_generation = generation; + const current = () => socket_generation === generation; socket = environment.createSocket(url, { open: () => { if (current()) onOpen(); @@ -501,9 +504,9 @@ export function createRealtime(config: RealtimeConfig): Realtime { cancelConnectTimer?.(); cancelConnectTimer = null; attempt = 0; - failuresBeforeOpen = 0; - lastMessageAtMs = environment.now(); - setStatus({ kind: 'open', sinceMs: lastMessageAtMs }); + failures_before_open = 0; + last_message_at_ms = environment.now(); + setStatus({ kind: 'open', since_ms: last_message_at_ms }); const opened = socket; assert(opened !== null, 'an open socket exists'); opened.send('ping'); @@ -520,25 +523,25 @@ export function createRealtime(config: RealtimeConfig): Realtime { } function onMessage(data: unknown): void { - lastMessageAtMs = environment.now(); + last_message_at_ms = environment.now(); if (inbox.length >= INBOX_MAX) { // The listeners are slower than the server. A new socket resyncs each binding. dropSocket(); return; } inbox.push(data); - if (drainScheduled) return; - drainScheduled = true; + if (drain_scheduled) return; + drain_scheduled = true; environment.setTimer(0, drain); } /** Handles the inbox in one batch. Notifications for one variable give one update. */ function drain(): void { - drainScheduled = false; + drain_scheduled = false; const messages = inbox.splice(0, inbox.length); const changed = new Map(); const logs: [Debugger, DebugMessage][] = []; - const receivedAtMs = environment.now(); + const received_at_ms = environment.now(); for (const data of messages) { if (typeof data !== 'string') continue; // The server sends `pong` as an answer and also as its own keep-alive. @@ -562,7 +565,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { const entry = debuggers.get(debugKey(message.meta.sys, message.meta.mod)); if (entry === undefined) break; const text = message.msg ?? ''; - logs.push([entry, { level: message.level, message: text, receivedAtMs }]); + logs.push([entry, { level: message.level, message: text, received_at_ms }]); break; } default: @@ -570,10 +573,10 @@ export function createRealtime(config: RealtimeConfig): Realtime { } } // Update the state first, then call the listeners. - for (const [key, changedValue] of changed) { + for (const [key, changed_value] of changed) { const binding = bindings.get(key); if (binding !== undefined) { - setBindingState(binding, { kind: 'value', value: changedValue }); + setBindingState(binding, { kind: 'value', value: changed_value }); } } for (const [entry, log] of logs) { @@ -586,7 +589,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { if (inbox.length > 0) drain(); cancelTimers(); socket = null; - if (status.kind !== 'open') failuresBeforeOpen += 1; + if (status.kind !== 'open') failures_before_open += 1; // The result of a request that the server got is not known now. for (const [id, entry] of [...pending]) { if (entry.sent) settle(id, failure({ kind: 'disconnected' })); @@ -602,17 +605,17 @@ export function createRealtime(config: RealtimeConfig): Realtime { queue.length = 0; return; } - if (failuresBeforeOpen >= RENEW_AFTER_FAILURES) { + if (failures_before_open >= RENEW_AFTER_FAILURES) { // The credential can be the reason. The next attempt asks the auth for a new one. - failuresBeforeOpen = 0; - renewBeforeConnect = true; + failures_before_open = 0; + renew_before_connect = true; } - const delayMs = Math.min( + const delay_ms = Math.min( RECONNECT_DELAY_MAX_MS, Math.max(1, attempt) * RECONNECT_DELAY_STEP_MS, ); - setStatus({ kind: 'waiting', attempt, delayMs }); - cancelReconnect = environment.setTimer(delayMs, () => { + setStatus({ kind: 'waiting', attempt, delay_ms }); + cancelReconnect = environment.setTimer(delay_ms, () => { cancelReconnect = null; void connect(); }); @@ -622,7 +625,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { cancelKeepAlive = environment.setTimer(KEEP_ALIVE_MS, () => { cancelKeepAlive = null; if (status.kind !== 'open' || socket === null) return; - if (environment.now() - lastMessageAtMs > STALE_MS) { + if (environment.now() - last_message_at_ms > STALE_MS) { dropSocket(); return; } @@ -654,11 +657,11 @@ export function createRealtime(config: RealtimeConfig): Realtime { /** The URL of the socket. It puts the token in the query or in a cookie. */ function socketUrl(credential: Credential): string { const origin = - config.baseUrl.length > 0 ? config.baseUrl : new URL(environment.currentUrl()).origin; + config.base_url.length > 0 ? config.base_url : new URL(environment.currentUrl()).origin; const url = new URL(CONTROL_PATH, origin); const secure = url.protocol === 'https:'; url.protocol = secure ? 'wss:' : 'ws:'; - if (config.fixedDevice === true) url.searchParams.set('fixed_device', 'true'); + if (config.fixed_device === true) url.searchParams.set('fixed_device', 'true'); let token: readonly [string, string] | null = null; switch (credential.kind) { case 'none': @@ -673,19 +676,19 @@ export function createRealtime(config: RealtimeConfig): Realtime { unreachable(credential); } if (token !== null) { - const [name, tokenValue] = token; + const [name, token_value] = token; // A cookie reaches only the host of the page. A socket to a different host gets the token // in the query. - const pageHost = new URL(environment.currentUrl()).hostname; - if (environment.tokenTransport === 'query' || url.hostname !== pageHost) { - url.searchParams.set(name, tokenValue); + const page_host = new URL(environment.currentUrl()).hostname; + if (environment.token_transport === 'query' || url.hostname !== page_host) { + url.searchParams.set(name, token_value); } else { // The server reads the cookie value as it is, so the value must be cookie safe. - assert(/^[^;\s]+$/.test(tokenValue), 'the token has no semicolons or spaces'); - const secureFlag = secure ? '; secure' : ''; + assert(/^[^;\s]+$/.test(token_value), 'the token has no semicolons or spaces'); + const secure_flag = secure ? '; secure' : ''; environment.setCookie( - `${name}=${tokenValue}; max-age=${COOKIE_MAX_AGE_SECONDS}; ` + - `path=${CONTROL_PATH}; samesite=strict${secureFlag}`, + `${name}=${token_value}; max-age=${COOKIE_MAX_AGE_SECONDS}; ` + + `path=${CONTROL_PATH}; samesite=strict${secure_flag}`, ); } } @@ -704,20 +707,20 @@ export function createRealtime(config: RealtimeConfig): Realtime { */ function setStatus(next: RealtimeStatus): void { status = next; - if (statusNotifyScheduled) return; - statusNotifyScheduled = true; + if (status_notify_scheduled) return; + status_notify_scheduled = true; environment.setTimer(0, () => { - statusNotifyScheduled = false; + status_notify_scheduled = false; const current = status; - for (const listener of [...statusListeners]) listener(current); + for (const listener of [...status_listeners]) listener(current); }); } function subscribe(listener: (status: RealtimeStatus) => void): () => void { - assert(statusListeners.size < STATUS_LISTENERS_MAX, 'the client has room for a listener'); - statusListeners.add(listener); + assert(status_listeners.size < STATUS_LISTENERS_MAX, 'the client has room for a listener'); + status_listeners.add(listener); return () => { - statusListeners.delete(listener); + status_listeners.delete(listener); }; } } @@ -748,8 +751,8 @@ function variableKey(target: { return JSON.stringify([target.sys, target.mod, target.index, target.name]); } -function debugKey(sys: string, moduleId: string): string { - return JSON.stringify([sys, moduleId]); +function debugKey(sys: string, module_id: string): string { + return JSON.stringify([sys, module_id]); } /** Parses one text frame. A frame that is not a message of the server gives `null`. */ diff --git a/src/staff.ts b/src/staff.ts index 2cb1fe154..f487337ab 100644 --- a/src/staff.ts +++ b/src/staff.ts @@ -6,7 +6,7 @@ * import { configure } from '@placeos/ts-client'; * import { bookings } from '@placeos/ts-client/staff'; * - * configure({ baseUrl: '', auth: session.clientAuth }); + * configure({ base_url: '', auth: session.client_auth }); * const result = await bookings.query({ period_start, period_end, type: 'desk' }); * ``` * diff --git a/test/auth.test.ts b/test/auth.test.ts index a56470cb1..bee7790cd 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -39,13 +39,13 @@ interface FakeOptions { /** A fake browser and server. The returned object records what the session did. */ function fake(options: FakeOptions = {}) { - let currentUrl = options.url ?? 'http://localhost:4200/rooms?level=2#/map'; - let tokenCount = 0; + let current_url = options.url ?? 'http://localhost:4200/rooms?level=2#/map'; + let token_count = 0; let foreground: (() => void) | null = null; const sent: Sent[] = []; const navigations: string[] = []; const storage = memoryStore(); - const sessionStorage = memoryStore(); + const session_storage = memoryStore(); const authority = { id: 'authority-1', name: 'PlaceOS', @@ -76,10 +76,10 @@ function fake(options: FakeOptions = {}) { const answer = await options.token?.(form); if (answer === 'network_error') throw new TypeError('Failed to fetch'); if (answer !== undefined) return answer; - tokenCount += 1; + token_count += 1; return Response.json({ - access_token: `token-${tokenCount}`, - refresh_token: `refresh-${tokenCount}`, + access_token: `token-${token_count}`, + refresh_token: `refresh-${token_count}`, expires_in: 3600, }); } @@ -87,10 +87,10 @@ function fake(options: FakeOptions = {}) { return options.api?.(record) ?? new Response('{}'); }, storage, - sessionStorage, - currentUrl: () => currentUrl, + session_storage, + currentUrl: () => current_url, replaceUrl: (url) => { - currentUrl = url; + current_url = url; }, navigate: (url) => { navigations.push(url); @@ -113,11 +113,11 @@ function fake(options: FakeOptions = {}) { sent, navigations, storage, - sessionStorage, + session_storage, authority, - url: () => currentUrl, + url: () => current_url, setUrl: (url: string) => { - currentUrl = url; + current_url = url; }, foreground: () => foreground?.(), tokenRequests: () => sent.filter((request) => request.url.endsWith('/auth/oauth/token')), @@ -126,8 +126,8 @@ function fake(options: FakeOptions = {}) { function session(world: ReturnType, config: Partial = {}) { return createAuthSession({ - baseUrl: '', - redirectUri: REDIRECT_URI, + base_url: '', + redirect_uri: REDIRECT_URI, scope: 'public', grant: { kind: 'code' }, environment: world.environment, @@ -144,7 +144,7 @@ async function startLogin(world: ReturnType, config: Partial { test('the client ID is the MD5 of the redirect URI, as in 6.x', () => { - expect(session(fake()).clientId).toBe(CLIENT_ID); + expect(session(fake()).client_id).toBe(CLIENT_ID); }); test('sends a user with a session to authorize, with a nonce and a challenge', async () => { @@ -157,7 +157,7 @@ describe('authorization code with PKCE', () => { expect(target.searchParams.get('response_type')).toBe('code'); expect(target.searchParams.get('client_id')).toBe(CLIENT_ID); expect(target.searchParams.get('state')).toBe(world.storage.get(`${CLIENT_ID}_nonce`)); - const verifier = world.sessionStorage.get(`${CLIENT_ID}_code_verifier`) ?? ''; + const verifier = world.session_storage.get(`${CLIENT_ID}_code_verifier`) ?? ''; const challenge = base64Url(sha256(new TextEncoder().encode(verifier))); expect(target.searchParams.get('code_challenge')).toBe(challenge); expect(target.searchParams.get('code_challenge_method')).toBe('S256'); @@ -166,7 +166,7 @@ describe('authorization code with PKCE', () => { test('exchanges the code of the redirect, then removes it from the URL', async () => { const world = fake(); const state = (await startLogin(world)).get('state') ?? ''; - const verifier = world.sessionStorage.get(`${CLIENT_ID}_code_verifier`); + const verifier = world.session_storage.get(`${CLIENT_ID}_code_verifier`); world.setUrl(`http://localhost:4200/rooms?level=2&code=abc&state=${state}#/map`); const result = await session(world).start(); expect(result).toEqual({ ok: true, value: { kind: 'bearer', token: 'token-1' } }); @@ -301,9 +301,9 @@ describe('login page', () => { expect(world.navigations).toEqual([`/login?continue=${back}`]); }); - test('gives login_required and does not navigate when handleLogin is false', async () => { + test('gives login_required and does not navigate when handle_login is false', async () => { const world = fake({ session: false }); - const auth = session(world, { handleLogin: false }); + const auth = session(world, { handle_login: false }); expect(await auth.start()).toEqual({ ok: false, error: { kind: 'login_required' } }); expect(world.navigations).toEqual([]); expect(auth.status()).toEqual({ kind: 'signed_out', error: { kind: 'login_required' } }); @@ -356,8 +356,8 @@ describe('trusted applications and refresh tokens', () => { await session(world).start(); expect(world.storage.get(`${CLIENT_ID}_access_token`)).toBe('token-1'); expect(world.storage.get(`${CLIENT_ID}_refresh_token`)).toBe('refresh-1'); - const lifetimeMs = (3600 - 300) * 1000; - expect(world.storage.get(`${CLIENT_ID}_expires_at`)).toBe(String(NOW_MS + lifetimeMs)); + const lifetime_ms = (3600 - 300) * 1000; + expect(world.storage.get(`${CLIENT_ID}_expires_at`)).toBe(String(NOW_MS + lifetime_ms)); // A new page load uses the stored token without a token request. world.setUrl('http://localhost:4200/'); expect(await session(world).start()).toEqual({ @@ -447,7 +447,7 @@ describe('frames, deep links and fixed devices', () => { }; }, }); - const result = await session(world, { useFrame: true }).start(); + const result = await session(world, { use_frame: true }).start(); expect(result).toEqual({ ok: true, value: { kind: 'bearer', token: 'token-1' } }); expect(world.navigations).toHaveLength(0); }); @@ -459,7 +459,7 @@ describe('frames, deep links and fixed devices', () => { value: { type: 'place-os', params: { code: 'abc', state: 'x' } }, }), }); - const result = await session(world, { useFrame: true }).start(); + const result = await session(world, { use_frame: true }).start(); expect(result).toEqual({ ok: false, error: { kind: 'frame_failed', reason: 'state_mismatch' }, @@ -485,12 +485,12 @@ describe('frames, deep links and fixed devices', () => { expect(await auth.start()).toEqual({ ok: true, value: { kind: 'api_key', key: 'key-1' } }); expect(auth.isFixedDevice()).toBe(true); expect(world.url()).toBe('http://localhost:4200/?fixed_device=true'); - const ignoring = session(world, { ignoreApiKey: true }); + const ignoring = session(world, { ignore_api_key: true }); expect(ignoring.credential()).toBeNull(); }); test('the foreground loads the authority again when there was no session', async () => { - let hasSession = false; + let has_session = false; const world = fake({ authority: () => Response.json({ @@ -499,14 +499,14 @@ describe('frames, deep links and fixed devices', () => { domain: 'placeos.test', login_url: '/login', logout_url: '/logout', - session: hasSession, + session: has_session, }), }); const auth = session(world); await auth.start(); expect(world.navigations).toEqual(['/login']); // The user logs in with a different tab, then this one comes back. - hasSession = true; + has_session = true; world.foreground(); await Bun.sleep(0); expect(world.navigations.at(-1)).toStartWith('/auth/oauth/authorize?'); @@ -518,7 +518,7 @@ describe('the session with the client', () => { const SHOW = operation({ method: 'GET', path: '/api/engine/v2/zones/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: parameters({ id: string() }, ['id']), body: null, response: object({ id: string() }, ['id']), @@ -538,8 +538,8 @@ describe('the session with the client', () => { world.storage.set(`${CLIENT_ID}_expires_at`, String(NOW_MS + 60_000)); const auth = session(world); const client = createClient({ - baseUrl: '', - auth: auth.clientAuth, + base_url: '', + auth: auth.client_auth, fetch: world.environment.fetch, }); const results = await Promise.all([ @@ -648,9 +648,9 @@ describe('the session with the client', () => { world.storage.set(`${CLIENT_ID}_expires_at`, String(NOW_MS + 60_000)); const auth = session(world); await auth.start(); - if (auth.clientAuth.kind !== 'credential') throw new Error('a credential auth'); + if (auth.client_auth.kind !== 'credential') throw new Error('a credential auth'); slow = true; - const renewing = auth.clientAuth.rejected(401, { kind: 'bearer', token: 'stale' }); + const renewing = auth.client_auth.rejected(401, { kind: 'bearer', token: 'stale' }); await Bun.sleep(0); await auth.logout(); release(); @@ -708,17 +708,17 @@ describe('web storage', () => { } test('a removal in a different tab is seen here, so a logout there logs out here', () => { - const fakeWeb = fakeStorage(); - const store = webStorageStore(() => fakeWeb.storage); + const fake_web = fakeStorage(); + const store = webStorageStore(() => fake_web.storage); store.set('token', 'abc'); - fakeWeb.values.delete('token'); + fake_web.values.delete('token'); expect(store.get('token')).toBeNull(); }); test('a value that the storage refuses stays in memory', () => { - const fakeWeb = fakeStorage(); - const store = webStorageStore(() => fakeWeb.storage); - fakeWeb.fill(); + const fake_web = fakeStorage(); + const store = webStorageStore(() => fake_web.storage); + fake_web.fill(); store.set('token', 'abc'); expect(store.get('token')).toBe('abc'); expect(store.keys()).toEqual(['token']); diff --git a/test/client.test.ts b/test/client.test.ts index 478d847e0..174717212 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -47,7 +47,7 @@ function jsonResponse(value: unknown, status = 200): Response { function clientWith(fetch: FetchFunction, config: Partial = {}) { return createClient({ - baseUrl: 'https://placeos.test', + base_url: 'https://placeos.test', auth: { kind: 'none' }, fetch, ...config, @@ -59,7 +59,7 @@ const Item = object({ id: string(), name: nullable(string()) }, ['id']); const UPDATE = operation({ method: 'PATCH', path: '/api/items/{id}', - pathKeys: ['id'], + path_keys: ['id'], params: parameters( { id: string(), @@ -78,7 +78,7 @@ const UPDATE = operation({ const DOWNLOAD = operation({ method: 'GET', path: '/api/download', - pathKeys: [], + path_keys: [], params: parameters({}), body: null, response: null, @@ -151,10 +151,10 @@ describe('call', () => { const client = clientWith(fetch); // A variable with an extra field passes the type check. Only the run time check sees it. const typo = { id: 'item-1', limt: 5, body: {} }; - await expect(call(UPDATE, typo, { client: client })).rejects.toThrow( + await expect(call(UPDATE, typo, { client })).rejects.toThrow( 'At $.limt: no field with this name', ); - await expect(call(UPDATE, { id: '', body: {} }, { client: client })).rejects.toThrow( + await expect(call(UPDATE, { id: '', body: {} }, { client })).rejects.toThrow( 'the path parameter "id" is not empty', ); expect(sent).toHaveLength(0); @@ -210,16 +210,16 @@ describe('call errors', () => { new Promise((_resolve, reject) => { init.signal?.addEventListener('abort', () => reject(init.signal?.reason)); }); - const client = clientWith(hang, { timeoutMs: 20 }); - expect(await call(DOWNLOAD, {}, { client: client })).toEqual({ + const client = clientWith(hang, { timeout_ms: 20 }); + expect(await call(DOWNLOAD, {}, { client })).toEqual({ ok: false, - error: { kind: 'timeout', timeoutMs: 20 }, + error: { kind: 'timeout', timeout_ms: 20 }, }); const controller = new AbortController(); const pending = call( DOWNLOAD, {}, - { client: client, signal: controller.signal, timeoutMs: 5_000 }, + { client, signal: controller.signal, timeout_ms: 5_000 }, ); controller.abort(); expect(await pending).toEqual({ ok: false, error: { kind: 'aborted' } }); @@ -230,12 +230,16 @@ describe('call errors', () => { // A credential that is slow, such as a login that renews the token. const slow = new Promise((resolve) => setTimeout(() => resolve('abc'), 200)); const client = clientWith(fetch, { auth: { kind: 'bearer', token: () => slow } }); - expect(await call(DOWNLOAD, {}, { client, timeoutMs: 20 })).toEqual({ + expect(await call(DOWNLOAD, {}, { client, timeout_ms: 20 })).toEqual({ ok: false, - error: { kind: 'timeout', timeoutMs: 20 }, + error: { kind: 'timeout', timeout_ms: 20 }, }); const controller = new AbortController(); - const pending = call(DOWNLOAD, {}, { client, signal: controller.signal, timeoutMs: 5_000 }); + const pending = call( + DOWNLOAD, + {}, + { client, signal: controller.signal, timeout_ms: 5_000 }, + ); controller.abort(); expect(await pending).toEqual({ ok: false, error: { kind: 'aborted' } }); expect(sent).toHaveLength(0); @@ -259,16 +263,19 @@ describe('call errors', () => { expect(started).toBe(false); }); - test('stops at responseBytesMax, with or without a content-length', async () => { - const tooLarge = { ok: false, error: { kind: 'response_too_large', bytesMax: 8 } } as const; + test('stops at response_bytes_max, with or without a content-length', async () => { + const too_large = { + ok: false, + error: { kind: 'response_too_large', bytes_max: 8 }, + } as const; const declared = fakeFetch(() => new Response('0123456789')); expect( await call( DOWNLOAD, {}, - { client: clientWith(declared.fetch, { responseBytesMax: 8 }) }, + { client: clientWith(declared.fetch, { response_bytes_max: 8 }) }, ), - ).toEqual(tooLarge); + ).toEqual(too_large); // A stream has no content-length, so the reader must count the bytes. const streamed = fakeFetch(() => { const stream = new ReadableStream({ @@ -282,9 +289,9 @@ describe('call errors', () => { await call( DOWNLOAD, {}, - { client: clientWith(streamed.fetch, { responseBytesMax: 8 }) }, + { client: clientWith(streamed.fetch, { response_bytes_max: 8 }) }, ), - ).toEqual(tooLarge); + ).toEqual(too_large); }); }); @@ -315,7 +322,7 @@ describe('configure', () => { test('gives the client to each call without a client in its options', async () => { const configured = fakeFetch(() => jsonResponse({ id: 'zone-1', update_systems: false })); configure({ - baseUrl: 'https://configured.test', + base_url: 'https://configured.test', auth: { kind: 'none' }, fetch: configured.fetch, }); diff --git a/test/compat.test.ts b/test/compat.test.ts index c435d2dd1..ffbdb604c 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -22,13 +22,13 @@ import { createClient } from '../src/core/client.ts'; import { createRealtime, type BindingState } from '../src/realtime/realtime.ts'; import { zones } from '../src/generated/operations/index.ts'; -// An app gives `baseUrl: ''`. Outside a browser, a URL needs an origin. 6.x mock data often has -// only some fields. `missingFields: 'zero'` fills the others, as the 6.x classes did. +// An app gives `base_url: ''`. Outside a browser, a URL needs an origin. 6.x mock data often has +// only some fields. `missing_fields: 'zero'` fills the others, as the 6.x classes did. const client = createClient({ - baseUrl: 'http://mock.invalid', + base_url: 'http://mock.invalid', auth: { kind: 'none' }, fetch: mockFetch, - missingFields: 'zero', + missing_fields: 'zero', }); const options = { client }; @@ -94,14 +94,14 @@ test('a missing endpoint is a 404, and a thrown status is that status', async () expect(refused.ok === false && refused.error.kind === 'http' && refused.error.status).toBe(403); }); -test('without missingFields: zero, partial mock data is not valid', async () => { +test('without missing_fields: zero, partial mock data is not valid', async () => { registerMockEndpoint({ path: '/api/engine/v2/zones/:id', method: 'GET', metadata: { id: 'z' }, }); const strict = createClient({ - baseUrl: 'http://mock.invalid', + base_url: 'http://mock.invalid', auth: { kind: 'none' }, fetch: mockFetch, }); @@ -115,7 +115,7 @@ test('mockReply and mockPage make the results of test doubles', () => { expect(orThrowPage(mockPage({ data: [zone], total: 3 }))).toEqual({ data: [zone], total: 3, - nextOffset: null, + next_offset: null, }); }); @@ -132,7 +132,7 @@ test('a 7.x binding and call use a 6.x mock system', async () => { ], }); const realtime = createRealtime({ - baseUrl: 'http://mock.invalid', + base_url: 'http://mock.invalid', auth: { kind: 'none' }, environment: mockRealtimeEnvironment(), }); diff --git a/test/migrate.test.ts b/test/migrate.test.ts index a8d0d24f7..cba139660 100644 --- a/test/migrate.test.ts +++ b/test/migrate.test.ts @@ -15,8 +15,8 @@ const TABLES: MigrateTables = { unmapped: V1_UNMAPPED, }; -function migrate(text: string, fileName = 'file.ts') { - return migrateSource(ts, fileName, text, TABLES); +function migrate(text: string, file_name = 'file.ts') { + return migrateSource(ts, file_name, text, TABLES); } test('rewrites calls, types and imports', () => { @@ -321,14 +321,14 @@ test('a helper reuses the compat import of the file, and gets an alias when the 'await zones.show({ id }).then(orThrow);', ]); // A type-only import has no value, so the call gets a value import. - const typeOnly = migrate( + const type_only = migrate( [ "import { showZone } from '@placeos/ts-client';", "import type { orThrow } from '@placeos/ts-client/compat';", 'await showZone(id);', ].join('\n'), ); - expect(typeOnly.text).toContain('.then(orThrowV2)'); + expect(type_only.text).toContain('.then(orThrowV2)'); const local = migrate( [ "import { showZone } from '@placeos/ts-client';", diff --git a/test/mock.test.ts b/test/mock.test.ts index e6452f2a5..ebb3699a3 100644 --- a/test/mock.test.ts +++ b/test/mock.test.ts @@ -17,7 +17,7 @@ import { // No `fetch` can answer: a call that a mock does not answer fails as a network error. const client = createClient({ - baseUrl: 'http://mock.invalid', + base_url: 'http://mock.invalid', auth: { kind: 'none' }, mock: endpointMocks, fetch: () => Promise.reject(new Error('no server')), @@ -44,7 +44,7 @@ test('a mock gets the typed input and gives the parsed data', async () => { test('respond sets the status and the page total, and the body reaches the mock', async () => { mockEndpoint('zones.query', () => respond([{ id: 'zone-1' }], { total: 25 })); mockEndpoint('systems.update', (input) => ({ id: input.sys_id, ...input.body }), { - delayMs: 1, + delay_ms: 1, }); const page = await zones.query({ limit: 1 }, options); expect(page.ok && pageInfo(page.value.headers).total).toBe(25); @@ -107,7 +107,7 @@ test('a staff API endpoint has a typed mock too', async () => { test('a mock answer has the deadline, the signal and the size limit of a response', async () => { mockEndpoint('zones.show', () => new Promise(() => {})); - const late = await zones.show({ id: 'zone-1' }, { client, timeoutMs: 5 }); + const late = await zones.show({ id: 'zone-1' }, { client, timeout_ms: 5 }); expect(late.ok === false && late.error.kind).toBe('timeout'); const controller = new AbortController(); const pending = zones.show({ id: 'zone-1' }, { client, signal: controller.signal }); @@ -115,10 +115,10 @@ test('a mock answer has the deadline, the signal and the size limit of a respons const aborted = await pending; expect(aborted.ok === false && aborted.error.kind).toBe('aborted'); const small = createClient({ - baseUrl: 'http://mock.invalid', + base_url: 'http://mock.invalid', auth: { kind: 'none' }, mock: endpointMocks, - responseBytesMax: 16, + response_bytes_max: 16, }); mockEndpoint('zones.show', () => ({ id: 'zone-1', name: 'a name longer than the limit' })); const large = await zones.show({ id: 'zone-1' }, { client: small }); @@ -130,12 +130,12 @@ test('zero-fill keeps the union variant that knows the given fields', async () = const input = { id: 'event-1', body: { email: 'a@example.com' } } as never; // `PlaceCalendarEventAttendee` is first, and has no `id`. mockEndpoint('staff.events.addAttendee', () => ({ id: 7 }) as never); - const byId = await events.addAttendee(input, options); - expect(byId.ok && Reflect.get(Object(byId.value.data), 'id')).toBe(7); + const by_id = await events.addAttendee(input, options); + expect(by_id.ok && Reflect.get(Object(by_id.value.data), 'id')).toBe(7); // `Attendee` matches without the fill, and has no `resource`. mockEndpoint('staff.events.addAttendee', () => ({ resource: true }) as never); - const byResource = await events.addAttendee(input, options); - expect(byResource.ok && Reflect.get(Object(byResource.value.data), 'resource')).toBe(true); + const by_resource = await events.addAttendee(input, options); + expect(by_resource.ok && Reflect.get(Object(by_resource.value.data), 'resource')).toBe(true); }); test('an aborted call does not leave the promise of a mock without a handler', async () => { @@ -163,7 +163,7 @@ test('a mock that aborts its own call gives aborted, not timeout', async () => { }); const result = await zones.show( { id: 'zone-1' }, - { client, signal: controller.signal, timeoutMs: 50 }, + { client, signal: controller.signal, timeout_ms: 50 }, ); expect(result.ok === false && result.error.kind).toBe('aborted'); }); diff --git a/test/pagination.test.ts b/test/pagination.test.ts index 2ada5fb21..a2f8e8cf4 100644 --- a/test/pagination.test.ts +++ b/test/pagination.test.ts @@ -10,13 +10,16 @@ test('reads the total and the offset of the next page', () => { 'X-Total-Count': '250', Link: '; rel="next"', }); - expect(pageInfo(headers)).toEqual({ total: 250, nextOffset: 100 }); + expect(pageInfo(headers)).toEqual({ total: 250, next_offset: 100 }); }); test('gives null on the last page and for values that are not counts', () => { - expect(pageInfo(new Headers({ 'X-Total-Count': '3' }))).toEqual({ total: 3, nextOffset: null }); + expect(pageInfo(new Headers({ 'X-Total-Count': '3' }))).toEqual({ + total: 3, + next_offset: null, + }); const bad = new Headers({ 'X-Total-Count': '-1', Link: '; rel="next"' }); - expect(pageInfo(bad)).toEqual({ total: null, nextOffset: null }); + expect(pageInfo(bad)).toEqual({ total: null, next_offset: null }); const other = new Headers({ Link: '; rel="prev"' }); - expect(pageInfo(other)).toEqual({ total: null, nextOffset: null }); + expect(pageInfo(other)).toEqual({ total: null, next_offset: null }); }); diff --git a/test/realtime.test.ts b/test/realtime.test.ts index c91c12d05..629356178 100644 --- a/test/realtime.test.ts +++ b/test/realtime.test.ts @@ -47,7 +47,7 @@ function fakePlatform(transport: 'query' | 'cookie' = 'query') { }; }, currentUrl: () => 'https://app.test/rooms', - tokenTransport: transport, + token_transport: transport, setCookie: (cookie) => cookies.push(cookie), now: () => now, setTimer: (milliseconds, callback) => { @@ -105,7 +105,7 @@ function settled(): Promise { function realtime(platform: ReturnType, config: Partial = {}) { const auth: Auth = { kind: 'bearer', token: () => 'abc' }; return createRealtime({ - baseUrl: 'https://placeos.test', + base_url: 'https://placeos.test', auth, environment: platform.environment, ...config, @@ -118,7 +118,7 @@ const META = { sys: 'sys-1', mod: 'Display', index: 1, name: 'power' }; describe('connection', () => { test('connects on the first binding, with the token in the query', async () => { const platform = fakePlatform(); - const client = realtime(platform, { fixedDevice: true }); + const client = realtime(platform, { fixed_device: true }); expect(client.status().kind).toBe('idle'); client.bind(POWER, () => {}); await settled(); @@ -130,7 +130,7 @@ describe('connection', () => { test('puts the token in a cookie on the socket path, not in the URL', async () => { const platform = fakePlatform('cookie'); const auth: Auth = { kind: 'api_key', key: 'key-1' }; - realtime(platform, { auth, baseUrl: '' }).start(); + realtime(platform, { auth, base_url: '' }).start(); await settled(); expect(platform.latest().url).toBe('wss://app.test/api/engine/v2/systems/control'); expect(platform.cookies).toEqual([ @@ -142,7 +142,7 @@ describe('connection', () => { test('a socket to a different host gets the token in the query, not a cookie', async () => { // A cookie set by the page reaches only the host of the page, app.test. const platform = fakePlatform('cookie'); - realtime(platform, { baseUrl: 'https://placeos.test' }).start(); + realtime(platform, { base_url: 'https://placeos.test' }).start(); await settled(); expect(platform.latest().url).toBe( 'wss://placeos.test/api/engine/v2/systems/control?bearer_token=abc', @@ -232,7 +232,7 @@ describe('connection', () => { test('gives up after RECONNECT_ATTEMPTS_MAX attempts, and start tries again', async () => { const platform = fakePlatform(); const client = realtime(platform); - const result = client.exec(POWER, [true], { timeoutMs: 10 * 60_000 }); + const result = client.exec(POWER, [true], { timeout_ms: 10 * 60_000 }); for (let failure = 0; failure < RECONNECT_ATTEMPTS_MAX; failure += 1) { await settled(); platform.latest().handlers.close(); @@ -401,7 +401,7 @@ describe('exec', () => { await platform.advance(REQUEST_TIMEOUT_MS); expect(await result).toEqual({ ok: false, - error: { kind: 'timeout', timeoutMs: REQUEST_TIMEOUT_MS }, + error: { kind: 'timeout', timeout_ms: REQUEST_TIMEOUT_MS }, }); }); @@ -435,7 +435,7 @@ describe('debug', () => { const platform = fakePlatform(); const client = realtime(platform); const messages: string[] = []; - const release = client.debug({ sys: 'sys-1', moduleId: 'mod-1' }, (log) => + const release = client.debug({ sys: 'sys-1', module_id: 'mod-1' }, (log) => messages.push(`${log.level}: ${log.message}`), ); await platform.open(); diff --git a/test/style.test.ts b/test/style.test.ts index 21acd55f7..b1e256742 100644 --- a/test/style.test.ts +++ b/test/style.test.ts @@ -25,8 +25,8 @@ test('the source has no escape from the type checks', async () => { // Comments and strings are text, not code. const code = line.replace(/\/\*.*?\*\/|\/\/.*$|^\s*\/?\*.*$|'[^']*'|`[^`]*`/g, ''); const where = `${file}:${index + 1}: ${line.trim()}`; - const allowedAny = ALLOWED_ANY.includes(`${file}: ${line.trim()}`); - if (/(? Date: Wed, 18 Nov 2026 15:42:47 +1100 Subject: [PATCH 15/29] feat: next() on the reply of a page requests the next page A paged call needed the offset from `pageInfo` and a second call with the same input. The reply of each operation with an `offset` parameter now has `next()`: the same input at the offset of the `Link` header, through the same client. It gives `null` on the last page, and when the offset does not move forward, so a loop over the pages ends. `respond` of the typed mocks takes `next_offset`, and `mockPage` gives a reply whose `next()` gives `null`. Co-Authored-By: Claude Opus 5.5 --- README.md | 29 +++++++++++----- src/compat/result.ts | 7 ++-- src/core/client.ts | 77 ++++++++++++++++++++++++++++++++++++++++-- src/core/pagination.ts | 8 ++--- src/index.ts | 2 ++ src/mock/index.ts | 8 ++++- test/client.test.ts | 60 ++++++++++++++++++++++++++++++++ test/mock.test.ts | 13 +++++++ 8 files changed, 184 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 670af9329..39874cbd7 100644 --- a/README.md +++ b/README.md @@ -98,17 +98,27 @@ await zones.query({}, { signal: controller.signal, timeout_ms: 60_000 }); ### Pages -A `query` operation returns one page. Use `pageInfo` to get the total and the next offset: +A `query` operation returns one page. `next()` of the reply requests the next page: the same +input with the offset of the `Link` header, through the same client. It gives `null` on the last +page: ```ts -import { pageInfo, zones } from '@placeos/ts-client'; - -const result = await zones.query({ limit: 100 }); -if (result.ok) { - const { total, next_offset } = pageInfo(result.value.headers); +let result = await zones.query({ limit: 100 }); +while (result.ok) { + show(result.value.data); + const next = result.value.next(); + if (next === null) break; + result = await next; } ``` +- Each operation with an `offset` parameter has `next()`, such as `zones.query`, `history.query` + and `staff.bookings.query`. The compiler knows which ones do. +- `next(options)` replaces the options of the first call, such as `signal` or `timeout_ms`. +- `next()` also gives `null` when the offset of the link does not move forward, so that a loop over + the pages always ends. +- `pageInfo(result.value.headers)` gives the `total` (`X-Total-Count`) and the `next_offset`. + ### Tests and mocks Give the client a `fetch` function. The client sends each request through it. A test can give @@ -145,8 +155,9 @@ mockEndpoint('zones.destroy', () => { the response schema of the endpoint, as it parses a response. The data can leave out fields: a missing required field gets its empty value, such as `''`, `0` or `[]`. A field with the wrong type is a `response_invalid` error. -- `respond(data, { status, headers, total })` sets the status and the headers. `total` is the - `X-Total-Count` that `pageInfo` and `orThrowPage` read. +- `respond(data, { status, headers, total, next_offset })` sets the status and the headers. + `total` is the `X-Total-Count` that `pageInfo` and `orThrowPage` read. `next_offset` goes in + the `Link` header, so `next()` of the reply asks the mock for that page. - `mockEndpoint` returns the function that removes the mock. `clearEndpointMocks()` removes all. - A call to an endpoint without a mock goes to the `fetch` of the client. Give `mockFetch` of `@placeos/ts-client/compat` to answer it from the 6.x mock endpoints. @@ -499,7 +510,7 @@ it keeps its 6.x import, so the compiler also shows it. These uses are: - the login and the realtime functions, such as `setup`, `token` and `getModule`; - `get`, `post` and the other HTTP functions; - `new` and `instanceof` on a 6.x class, because 7.x has plain objects; -- the `next` function of a 6.x page. 7.x gives `next_offset`; +- the `next` function of a 6.x page. In 7.x, `next()` is on the reply of the call; - a function that is not called, out of a test; - a `vi.mock` without a factory or `{ spy: true }`: its 7.x functions give `undefined`, and `.then(orThrow)` fails; diff --git a/src/compat/result.ts b/src/compat/result.ts index e323128c9..0668ee27b 100644 --- a/src/compat/result.ts +++ b/src/compat/result.ts @@ -67,7 +67,8 @@ export function mockReply(data: T, status = 200): Result, CallError> /** * The 7.x result for a 6.x page, for a test double of a `query` call. `total` goes in the - * `X-Total-Count` header, so `orThrowPage` gives it back. + * `X-Total-Count` header, so `orThrowPage` gives it back. The page is the last one: `next()` gives + * `null`. * * ```ts * vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); @@ -78,10 +79,10 @@ export function mockPage(page: { readonly total?: number; /** The `next` of a 6.x page. 7.x has no use for it. */ readonly next?: unknown; -}): Result, CallError> { +}): Result & { next(): null }, CallError> { const headers = new Headers(); if (page.total !== undefined) headers.set('x-total-count', String(page.total)); - return { ok: true, value: { status: 200, headers, data: page.data } }; + return { ok: true, value: { status: 200, headers, data: page.data, next: () => null } }; } /** In the arguments of `fromV1Mock`, the input values that no other argument has. */ diff --git a/src/core/client.ts b/src/core/client.ts index 8a9882b37..cc3abf3a0 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -1,4 +1,5 @@ import { assert, unreachable } from './assert.ts'; +import { pageInfo } from './pagination.ts'; import type { Result } from './result.ts'; import { checkRequest, @@ -201,7 +202,34 @@ export interface Reply { readonly data: T; } -export type CallResult = Result>, CallError>; +/** + * The reply of an operation with an `offset` parameter, such as `zones.query`: one page of a list. + * + * ```ts + * let result = await zones.query({ limit: 100 }); + * while (result.ok) { + * show(result.value.data); + * const next = result.value.next(); + * if (next === null) break; + * result = await next; + * } + * ``` + */ +export interface PageReply extends Reply { + /** + * Requests the next page: the same input with the `offset` of the `Link` header, through the + * same client. `options` replace the options of the first call. `null` on the last page, and + * when the offset does not move forward, so that a loop over the pages ends. + */ + next(options?: CallOptions): Promise> | null; +} + +/** The reply of an operation: a `PageReply` when the operation has an `offset` parameter. */ +export type OperationReply = 'offset' extends keyof OperationInput + ? PageReply> + : Reply>; + +export type CallResult = Result, CallError>; /** Checks the client settings once, so that each request can trust them. */ export function createClient(config: ClientConfig): Client { @@ -282,11 +310,56 @@ export async function call( // Read the client before the first `await`, so the whole request uses one client. const client = options.client ?? configured_client; assert(client !== null, 'configure() ran before this call, or the options have a client'); - const result = await send(client, operation, input, options); + const result = await request(client, operation, input, options); // `send` parsed the data with `operation.response`, which gives `OperationData` its type. + // `paged` gives the reply a `next` when `OperationReply` is a `PageReply`. return result as CallResult; } +/** A reply before `call` gives it the types of its operation. */ +interface RawPage extends Reply { + next(options?: CallOptions): Promise | null; +} +type RawResult = Result | RawPage, CallError>; + +/** Sends the request. The reply of an operation with an `offset` parameter gets `next`. */ +async function request( + client: Client, + operation: AnyOperation, + input: unknown, + options: CallOptions, +): Promise { + const sent = await send(client, operation, input, options); + if (!sent.ok || !paged(operation)) return sent; + const reply = sent.value; + const next = (next_options: CallOptions = {}) => + nextPage(client, operation, input, reply.headers, { ...options, ...next_options }); + return { ok: true, value: { ...reply, next } }; +} + +/** `true` when the operation has an `offset` parameter, so that its reply is a page. */ +function paged(operation: AnyOperation): boolean { + const node = operation.params.node; + return node.kind === 'object' && node.keys.has('offset'); +} + +/** The request of the next page, or `null` when the `Link` header has no offset after this one. */ +function nextPage( + client: Client, + operation: AnyOperation, + input: unknown, + headers: Headers, + options: CallOptions, +): Promise | null { + assert(isRecord(input), 'the input is an object'); + const next_offset = pageInfo(headers).next_offset; + if (next_offset === null) return null; + const offset = typeof input['offset'] === 'number' ? input['offset'] : 0; + // A link back to this page or an earlier one would make a loop over the pages endless. + if (next_offset <= offset) return null; + return request(options.client ?? client, operation, { ...input, offset: next_offset }, options); +} + async function send( client: Client, operation: AnyOperation, diff --git a/src/core/pagination.ts b/src/core/pagination.ts index 0d52079f8..ec24d21b6 100644 --- a/src/core/pagination.ts +++ b/src/core/pagination.ts @@ -10,15 +10,13 @@ export interface PageInfo { } /** - * Reads the pagination headers of a `query` response. + * Reads the pagination headers of a `query` response. `next()` of the reply uses `next_offset` + * to request the next page. * * ```ts * const first = await zones.query({ limit: 100 }); * if (first.ok) { - * const page = pageInfo(first.value.headers); - * if (page.next_offset !== null) { - * const second = await zones.query({ limit: 100, offset: page.next_offset }); - * } + * const { total, next_offset } = pageInfo(first.value.headers); * } * ``` */ diff --git a/src/index.ts b/src/index.ts index 3be8e3500..a635bb7b9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -69,6 +69,8 @@ export { type Operation, type OperationData, type OperationInput, + type OperationReply, + type PageReply, type Reply, } from './core/client.ts'; export { pageInfo, type PageInfo } from './core/pagination.ts'; diff --git a/src/mock/index.ts b/src/mock/index.ts index 07b8912b1..993656812 100644 --- a/src/mock/index.ts +++ b/src/mock/index.ts @@ -138,7 +138,7 @@ export function clearEndpointMocks(): void { mocks.clear(); } -/** Data with a status, headers, or the `X-Total-Count` of a page. */ +/** Data with a status, headers, or the `X-Total-Count` and the next offset of a page. */ export function respond( data: T, options: { @@ -146,10 +146,16 @@ export function respond( readonly headers?: Readonly>; /** The number of items on all pages. `pageInfo` reads it. */ readonly total?: number; + /** The `offset` of the next page, in the `Link` header. `next()` of the reply uses it. */ + readonly next_offset?: number; } = {}, ): MockResponse { const headers: Record = { ...options.headers }; if (options.total !== undefined) headers['x-total-count'] = String(options.total); + if (options.next_offset !== undefined) { + assert(Number.isSafeInteger(options.next_offset) && options.next_offset > 0, 'an offset'); + headers['link'] = `; rel="next"`; + } return { [RESPONSE]: true, data, status: options.status ?? 200, headers }; } diff --git a/test/client.test.ts b/test/client.test.ts index 174717212..ae3c05877 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -161,6 +161,66 @@ describe('call', () => { }); }); +const LIST = operation({ + method: 'GET', + path: '/api/items', + path_keys: [], + params: parameters({ q: string(), limit: integer('UInt32'), offset: integer('UInt32') }), + body: null, + response: array(Item), + name: 'items.query', +}); + +/** A page of the list. `next` is the offset of the `Link` header, or no header. */ +function pageResponse(ids: readonly string[], next: number | null): Response { + const response = jsonResponse(ids.map((id) => ({ id }))); + if (next !== null) response.headers.set('link', `; rel="next"`); + return response; +} + +describe('pages', () => { + test('next() asks for the next offset with the same input and client, to the last page', async () => { + const pages = new Map([ + [0, pageResponse(['a', 'b'], 2)], + [2, pageResponse(['c'], null)], + ]); + const urls: string[] = []; + const client = clientWith(async (url) => { + urls.push(url); + const offset = Number(new URL(url).searchParams.get('offset') ?? 0); + return pages.get(offset) ?? jsonResponse([], 404); + }); + const first = await call(LIST, { q: 'lobby', limit: 2 }, { client }); + if (!first.ok) throw new Error('the first page is ok'); + const second = await first.value.next(); + expect(second?.ok && second.value.data.map((item) => item.id)).toEqual(['c']); + expect(urls).toEqual([ + 'https://placeos.test/api/items?q=lobby&limit=2', + 'https://placeos.test/api/items?q=lobby&limit=2&offset=2', + ]); + expect(second?.ok && second.value.next()).toBeNull(); + }); + + test('a link to this offset or an earlier one ends the pages, so a loop ends', async () => { + const back = clientWith(async () => pageResponse(['a'], 4)); + const page = await call(LIST, { offset: 4 }, { client: back }); + expect(page.ok && page.value.next()).toBeNull(); + }); + + test('an operation without an offset has no next()', async () => { + const { fetch } = fakeFetch(() => jsonResponse({ id: 'item-1' })); + const result = await call( + UPDATE, + { id: 'item-1', body: {} }, + { client: clientWith(fetch) }, + ); + if (!result.ok) throw new Error('the call is ok'); + expect('next' in result.value).toBe(false); + // @ts-expect-error `UPDATE` has no `offset`, so its reply is not a page. + expect(result.value.next).toBeUndefined(); + }); +}); + describe('call errors', () => { test('gives the status, the message and the body of an HTTP error', async () => { const { fetch } = fakeFetch(() => jsonResponse({ error: 'not found' }, 404)); diff --git a/test/mock.test.ts b/test/mock.test.ts index ebb3699a3..a4b91f6f6 100644 --- a/test/mock.test.ts +++ b/test/mock.test.ts @@ -55,6 +55,19 @@ test('respond sets the status and the page total, and the body reaches the mock' expect(updated.ok && updated.value.data.name).toBe('Room'); }); +test('respond gives the next offset, and next() asks the mock for that page', async () => { + mockEndpoint('zones.query', (input) => + input.offset === undefined + ? respond([{ id: 'zone-1' }], { next_offset: 1 }) + : respond([{ id: `zone-${input.offset + 1}` }]), + ); + const first = await zones.query({ limit: 1 }, options); + if (!first.ok) throw new Error('the first page is ok'); + const second = await first.value.next(); + expect(second?.ok && second.value.data.map((zone) => zone.id)).toEqual(['zone-2']); + expect(second?.ok && second.value.next()).toBeNull(); +}); + test('httpError gives an http error, and data with a wrong type is invalid', async () => { mockEndpoint('zones.show', () => { throw httpError(404, 'zone not found'); From ba4b95f5d8b1d51961cc7cf498761da059847873 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 15:55:52 +1100 Subject: [PATCH 16/29] fix: the migration tool follows the 7.x names and the prerelease install - A new import that clashes with a name of the file gets a suffix in the style of the name: `zones_v7`, `orThrowV7` and `SignagePluginV7`. It was `V2`. - The CLI tells the project to install the version that made the changes, from its own package.json. `@7` does not install a prerelease, so the README uses `@next` until 7.0.0 is out. - `fromV1Mock` takes its result type from the test double that holds it, so `vi.mocked(zones.show).mockImplementation(fromV1Mock(...))` type-checks. It also takes no input, as `zones.query()` does. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +++++++++---- src/compat/result.ts | 20 ++++++++++++++++---- src/migrate/cli.ts | 16 +++++++++++++++- src/migrate/migrate.ts | 10 ++++++++-- test/compat.test.ts | 13 +++++++++++++ test/migrate.test.ts | 18 +++++++++--------- test/style.test.ts | 2 +- 7 files changed, 71 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 39874cbd7..a9bb53f4b 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,12 @@ Version 7 is a new client, with a different API from 6.x. To move an application [`6.x` branch](https://github.com/PlaceOS/ts-client/tree/6.x), which gets the 6.x fixes. ```sh -npm install @placeos/ts-client@7 +npm install @placeos/ts-client@next ``` +Version 7 is a prerelease on the npm tag `next` until 7.0.0 is out. `@7` does not install a +prerelease. + ## Use the client ```ts @@ -461,8 +464,8 @@ can examine and undo the changes. Run it in the folder of the project, because i `typescript` package of the project: ```sh -npx -p @placeos/ts-client@7 placeos-migrate src # Shows the changes. Writes no file. -npx -p @placeos/ts-client@7 placeos-migrate --write src # Writes the changes. +npx -p @placeos/ts-client@next placeos-migrate src # Shows the changes. Writes no file. +npx -p @placeos/ts-client@next placeos-migrate --write src # Writes the changes. ``` The tool makes these changes: @@ -485,7 +488,7 @@ The tool makes these changes: `@placeos/ts-client/compat`. The enums have the 7.x values, so they fit the 7.x fields of the data. A query parameter takes the name: the `role` of `drivers.query` is `'logic'`, not `99`. - A new import gets another name when the file has the name. For example, a file with a - `zones` variable gets `zones as zonesV2`. + `zones` variable gets `zones as zones_v7`. The tool also changes the test doubles, so that the tests of the app still work: @@ -549,6 +552,8 @@ arguments, and it finds the 7.x operation with the same method and path. - `missing_fields: 'zero'` accepts data without its required fields. It is for mock data only. - `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove that the parser output has the type of the schema. The tests check the parser. +- `fromV1Mock` of `@placeos/ts-client/compat` has one `as` cast. It gives the result of a 6.x mock + implementation, which has no types, the type of the test double that holds it. - `configure` keeps one client in module state, so a call does not need a client argument. A call before `configure` is a run-time assertion, not a compile error. - The mocks keep their registries in module state, as 6.x did: the endpoints of diff --git a/src/compat/result.ts b/src/compat/result.ts index 0668ee27b..8cf2ff24f 100644 --- a/src/compat/result.ts +++ b/src/compat/result.ts @@ -104,15 +104,27 @@ export const REST = '...'; * `name` of `showMetadata`. * * Without an implementation, the data is `undefined`, as the value of a 6.x `vi.fn()` was. + * + * `R` is the result of the operation, from the place of the double, such as the + * `mockImplementation` of `vi.mocked(zones.show)`. The 6.x implementation has no types, so the + * data is what it gives, as with other mock data. */ -export function fromV1Mock( +export function fromV1Mock, CallError>>( implementation: ((...args: never[]) => unknown) | undefined, args: readonly (string | null)[], result: 'data' | 'page' = 'data', key?: string, -): (input: Readonly>) => Promise, CallError>> { +): (input?: Readonly>) => Promise { const named = new Set(args.filter((arg) => arg !== null && arg !== REST)); - return async (input) => { + // An operation without a required parameter, such as `zones.query`, can have no input. + return async (input = {}) => { + const reply = await answer(input); + return reply as R; + }; + + async function answer( + input: Readonly>, + ): Promise, CallError>> { const values = args.map((arg) => { if (arg === null) return undefined; if (arg !== REST) return input[arg]; @@ -133,7 +145,7 @@ export function fromV1Mock( const total: unknown = Reflect.get(page, 'total'); const data: unknown = Reflect.get(page, 'data'); return mockPage(typeof total === 'number' ? { data, total } : { data }); - }; + } } function describe(error: CallError): string { diff --git a/src/migrate/cli.ts b/src/migrate/cli.ts index 6e0ccff24..5cd80b3f8 100644 --- a/src/migrate/cli.ts +++ b/src/migrate/cli.ts @@ -13,6 +13,7 @@ import { readdir, readFile, stat, writeFile } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { join, relative, resolve } from 'node:path'; import type * as TS from 'typescript-5'; +import { assert } from '../core/assert.ts'; import { COMPAT_MODULE, migrateSource, type Finding, type MigrateTables } from './migrate.ts'; import { V1_CALLS, V1_COMPAT, V1_TYPES, V1_UNMAPPED } from './v1-map.ts'; @@ -110,9 +111,10 @@ async function main(argv: readonly string[]): Promise { ); if (!write && changed_files > 0) console.log('Run again with --write to write the changes.'); if (write && changed_files > 0) { + const version = await ownVersion(); console.log( `\nNext:\n` + - ` 1. Install 7.x: npm install @placeos/ts-client@7\n` + + ` 1. Install 7.x: npm install @placeos/ts-client@${version}\n` + ` 2. Call configure() once, before the first call (README: Log in). For a mock mode,\n` + ` give fetch: mockFetch and missing_fields: 'zero' (README: Mock mode).\n` + ` 3. Run the compiler. It shows the changes to the data, such as a field that can be null.\n` + @@ -121,6 +123,18 @@ async function main(argv: readonly string[]): Promise { } } +/** + * The version of this package, such as `7.0.0-next.1`. The tool tells the project to install the + * version that made its changes. `@7` does not install a prerelease. + */ +async function ownVersion(): Promise { + // The same path from `src/migrate/cli.ts` and from `dist/migrate/cli.js`. + const text = await readFile(new URL('../../package.json', import.meta.url), 'utf8'); + const version: unknown = Reflect.get(Object(JSON.parse(text)), 'version'); + assert(typeof version === 'string' && version.length > 0, 'the package has a version'); + return version; +} + /** The `typescript` package of the project, or `null`. */ function loadTypeScript(): typeof TS | null { const require = createRequire(join(process.cwd(), 'package.json')); diff --git a/src/migrate/migrate.ts b/src/migrate/migrate.ts index 43a383be7..2237c094a 100644 --- a/src/migrate/migrate.ts +++ b/src/migrate/migrate.ts @@ -204,14 +204,20 @@ export function migrateSource( findings.push({ line: at.line + 1, column: at.character + 1, name, message }); } - /** A local name for a new import: the name, or the name with a suffix if the file has it. */ + /** + * A local name for a new import: the name, or the name with a suffix if the file has it. The + * suffix keeps the style of the name: `zones_v7` for a namespace, `orThrowV7` for a function + * and `SignagePluginV7` for a type. + */ function localName(name: string): string { if (!taken.has(name)) { taken.add(name); return name; } + const snake_case = /^[a-z][a-z0-9_]*$/.test(name); for (let index = 1; index <= ALIASES_MAX; index += 1) { - const alias = `${name}V2${index === 1 ? '' : index}`; + const count = index === 1 ? '' : snake_case ? `_${index}` : String(index); + const alias = snake_case ? `${name}_v7${count}` : `${name}V7${count}`; if (taken.has(alias)) continue; taken.add(alias); return alias; diff --git a/test/compat.test.ts b/test/compat.test.ts index ffbdb604c..179908541 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -7,6 +7,7 @@ import { afterEach, expect, test } from 'bun:test'; import { clearMockEndpoints, deregisterSystem, + fromV1Mock, mockFetch, mockPage, mockRealtimeEnvironment, @@ -109,6 +110,18 @@ test('without missing_fields: zero, partial mock data is not valid', async () => expect(result.ok === false && result.error.kind).toBe('response_invalid'); }); +test('fromV1Mock fits the mockImplementation of an operation, with and without an input', async () => { + // `vi.mocked(zones.show).mockImplementation(...)` asks for these types. + const show: (...args: Parameters) => ReturnType = + fromV1Mock((id: string) => Promise.resolve({ id, name: 'Level 1' }), ['id']); + const query: (...args: Parameters) => ReturnType = + fromV1Mock(() => Promise.resolve({ data: [{ id: 'zone-1' }], total: 1 }), ['...'], 'page'); + expect(orThrow(await show({ id: 'zone-1' })).name).toBe('Level 1'); + const page = await query(); + expect(orThrowPage(page).total).toBe(1); + expect(page.ok && page.value.next()).toBeNull(); +}); + test('mockReply and mockPage make the results of test doubles', () => { const zone = { id: 'zone-1' }; expect(orThrow(mockReply(zone))).toBe(zone); diff --git a/test/migrate.test.ts b/test/migrate.test.ts index cba139660..f4bc96143 100644 --- a/test/migrate.test.ts +++ b/test/migrate.test.ts @@ -90,9 +90,9 @@ test('gives a new import another name when the file has the name', () => { ); expect(result.text).toBe( [ - "import { zones as zonesV2 } from '@placeos/ts-client';", + "import { zones as zones_v7 } from '@placeos/ts-client';", "import { orThrowPage } from '@placeos/ts-client/compat';", - 'const zones = await zonesV2.query({}).then(orThrowPage);', + 'const zones = await zones_v7.query({}).then(orThrowPage);', ].join('\n'), ); }); @@ -263,8 +263,8 @@ test('a 7.x type gets an alias when the 6.x class stays for a value use', () => ].join('\n'), ); expect(result.text.split('\n')).toEqual([ - "import { SignagePlugin, type SignagePlugin as SignagePluginV2 } from '@placeos/ts-client';", - 'const plugin: SignagePluginV2 = new SignagePlugin();', + "import { SignagePlugin, type SignagePlugin as SignagePluginV7 } from '@placeos/ts-client';", + 'const plugin: SignagePluginV7 = new SignagePlugin();', ]); }); @@ -328,7 +328,7 @@ test('a helper reuses the compat import of the file, and gets an alias when the 'await showZone(id);', ].join('\n'), ); - expect(type_only.text).toContain('.then(orThrowV2)'); + expect(type_only.text).toContain('.then(orThrowV7)'); const local = migrate( [ "import { showZone } from '@placeos/ts-client';", @@ -337,9 +337,9 @@ test('a helper reuses the compat import of the file, and gets an alias when the ].join('\n'), ); expect(local.text.split('\n').slice(1)).toEqual([ - "import { orThrow as orThrowV2 } from '@placeos/ts-client/compat';", + "import { orThrow as orThrowV7 } from '@placeos/ts-client/compat';", 'const orThrow = 1;', - 'await zones.show({ id }).then(orThrowV2);', + 'await zones.show({ id }).then(orThrowV7);', ]); }); @@ -397,8 +397,8 @@ test('the hoisted helper gets its own name when the file imports fromV1Mock', () ].join('\n'), ); expect(result.text.split('\n')).toEqual([ - "const { fromV1Mock: fromV1MockV2 } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", + "const { fromV1Mock: fromV1MockV7 } = await vi.hoisted(() => import('@placeos/ts-client/compat'));", "import { fromV1Mock } from '@placeos/ts-client/compat';", - "vi.mock('@placeos/ts-client', () => ({ zones: { show: vi.fn(fromV1MockV2(undefined, ['id', '...'])) } }));", + "vi.mock('@placeos/ts-client', () => ({ zones: { show: vi.fn(fromV1MockV7(undefined, ['id', '...'])) } }));", ]); }); diff --git a/test/style.test.ts b/test/style.test.ts index b1e256742..c164d0c0a 100644 --- a/test/style.test.ts +++ b/test/style.test.ts @@ -8,7 +8,7 @@ import { Glob } from 'bun'; import { join } from 'node:path'; const SOURCE_DIR = join(import.meta.dir, '..', 'src'); -const ALLOWED_CASTS = ['parsed as O', 'checked as I', 'result as CallResult']; +const ALLOWED_CASTS = ['parsed as O', 'checked as I', 'result as CallResult', 'reply as R']; /** The 6.x mock types of the compat module keep `any`, so that the mocks of an app still compile. */ const ALLOWED_ANY = [ 'compat/http-mock.ts: readonly metadata: any;', From aea8081ab6ad1fba686b45fd91c27a4c15e5c3ad Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 16:28:04 +1100 Subject: [PATCH 17/29] feat: debug logs for the client, the login and the realtime client 6.x wrote debug logs to the console when `window.debug` was set. 7.x wrote nothing, so a login or a binding could not be traced. - `configure`, `createAuthSession` and `createRealtime` take a `log` function. Without it, nothing is logged. - Each part logs through a scoped logger, as `std.log.scoped` does in Zig. Its methods have the arguments of the console methods: error, warn, info, debug, print (`console.log`), group and groupEnd. An entry is `{ scope, level, args }`. - `consoleLog` and `createConsoleLog({ colors })` of the compat module write the 6.x format, `[PlaceOS][Auth] the authority is loaded`, with the console method of the level, when `window.debug` is set. A string first argument joins the prefix. The 6.x mock endpoints log through it, as in 6.x. - An entry has no tokens, API keys, cookies, request bodies or input values. 6.x logged the socket cookie with the token in it. A log function that throws does not change the caller. Co-Authored-By: Claude Opus 5.5 --- README.md | 54 +++++++++++++++++++++++++ src/auth/session.ts | 66 +++++++++++++++++++++++++++++-- src/compat/http-mock.ts | 9 ++++- src/compat/index.ts | 3 ++ src/compat/log.ts | 65 ++++++++++++++++++++++++++++++ src/core/client.ts | 35 +++++++++++++++++ src/core/log.ts | 85 ++++++++++++++++++++++++++++++++++++++++ src/index.ts | 1 + src/realtime/realtime.ts | 37 +++++++++++++++-- test/auth.test.ts | 29 ++++++++++++++ test/client.test.ts | 25 ++++++++++++ test/compat.test.ts | 36 ++++++++++++++++- test/log.test.ts | 42 ++++++++++++++++++++ test/realtime.test.ts | 28 +++++++++++++ 14 files changed, 506 insertions(+), 9 deletions(-) create mode 100644 src/compat/log.ts create mode 100644 src/core/log.ts create mode 100644 test/log.test.ts diff --git a/README.md b/README.md index a9bb53f4b..197e2aadd 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,9 @@ Other parts of the session: login with `authorization_denied`. 6.x sent the user to the authorize page again. - `/auth/authority` gets `AUTHORITY_ATTEMPTS_MAX` attempts, not an unlimited number. Then `start` gives `authority_unavailable`. Call `start` again to try again. +- The debug logs need a `log` function, such as `consoleLog` (see [Debug logs](#debug-logs)). + `window.debug` alone does not turn them on. The logs do not have the cookie of the socket, which + 6.x logged with the token in it. - Not ported: `revokeToken`, the state of the application in `authorise(state)`, and the ACA Engine API path. The mock mode is in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). It does not need a login: give `auth: { kind: 'none' }`. @@ -345,6 +348,57 @@ release(); - Not ported: the `connectionState` signal and the `/control/websocket` path of ACA Engine. The mock systems are in `@placeos/ts-client/compat` (see [Mock mode](#mock-mode)). +## Debug logs + +The client, the login and the realtime client log nothing by default. Give each one a `log` +function to get an entry for each step: `{ scope, level, args }`. `args` are the arguments of the +call, as a console method gets them: a message, then values such as a status. `consoleLog` of +`@placeos/ts-client/compat` writes the entries in the console format of 6.x, and only when +`window.debug` is set: + +```ts +import { consoleLog } from '@placeos/ts-client/compat'; + +const session = createAuthSession({ ..., log: consoleLog }); +configure({ base_url: '', auth: session.client_auth, log: consoleLog }); +const realtime = createRealtime({ base_url: '', auth: session.client_auth, log: consoleLog }); +// In the console of the browser: +window.debug = true; +// [PlaceOS][Auth] the authority is loaded {id: 'authority-1'} +// [PlaceOS][Auth] name: PlaceOS +// [PlaceOS][Auth] domain: placeos.example.com +// [PlaceOS][HTTP] zones.query: 200 in 41 ms {name: 'zones.query', method: 'GET', ...} +// [PlaceOS][WS] sys-1 Display_1 power changed {sys: 'sys-1', ..., value: true} +``` + +| `scope` | Entries | +| ---------- | ------------------------------------------------------------------------------- | +| `auth` | The steps of the login: the authority, each grant, redirects, renewals, logout. | +| `http` | Each call: the name, the status or the error, and the time. | +| `realtime` | The socket: connect, close and reconnect, value changes, server errors, logs. | +| `mock` | The 6.x mock endpoints of `compat`: added, matched and not found. | + +| `level` | Use | Console method | +| ----------- | --------------------------------------------------------- | ------------------ | +| `error` | A failure without an answer, such as a timeout. | `console.error` | +| `warn` | A refusal or a drop, such as a 404 or a closed socket. | `console.warn` | +| `info` | A step, such as a new token or a connected socket. | `console.info` | +| `debug` | A detail, such as each call or each value change. | `console.debug` | +| `print` | A line without a level, such as a field of the authority. | `console.log` | +| `group` | Starts a group of the entries that follow. | `console.group` | +| `group_end` | Ends the group. | `console.groupEnd` | + +- `createConsoleLog({ colors: false })` writes the same text without the `%c` colors. +- An entry has no tokens, API keys, cookies, request bodies or input values. A redirect gives its + path only, because the query has the state of the login. +- A log function that throws does not change the call, the login or the socket. +- The `mock` entries of the 6.x mock endpoints always go to `consoleLog`, as in 6.x. +- In the library, each part logs through a scoped logger, as `std.log.scoped` does in Zig: + `const log = scopedLog('auth', { sink: config.log ?? null })`. Its methods have the arguments + of the console methods: `log.error(...data)`, `log.warn(...data)`, `log.info(...data)`, + `log.debug(...data)`, `log.print(...data)` (`console.log`), `log.group(...label)` and + `log.groupEnd()`. The `log` function of the application is the sink, as `logFn` is in Zig. + ## Types Each schema of the API document has a value and two types with the same base name: diff --git a/src/auth/session.ts b/src/auth/session.ts index f69f48d0e..c6515dd5a 100644 --- a/src/auth/session.ts +++ b/src/auth/session.ts @@ -32,6 +32,7 @@ import { type Credential, type FetchError, } from '../core/client.ts'; +import { scopedLog, type LogFunction } from '../core/log.ts'; import type { Result } from '../core/result.ts'; import { array, @@ -150,6 +151,8 @@ export interface AuthSessionConfig { /** Headers for each request of the session. The session adds `X-App-Id`. */ readonly headers?: Readonly>; readonly environment?: AuthEnvironment; + /** Gets the debug log entries of the login. See `LogFunction`. */ + readonly log?: LogFunction; } const DomainAuthoritySchema = object( @@ -290,6 +293,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const headers: Readonly> = { ...config.headers, 'X-App-Id': client_id }; const limits = { timeout_ms: AUTH_TIMEOUT_MS, bytes_max: AUTH_RESPONSE_BYTES_MAX }; const storageKey = (name: string) => `${client_id}_${name}`; + const log = scopedLog('auth', { sink: config.log ?? null }); let authority: DomainAuthority | null = null; let status: AuthStatus = { kind: 'stopped' }; @@ -342,6 +346,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { removeForegroundListener = environment.onForeground(onForeground); } if (status.kind === 'stopped') setStatus({ kind: 'loading' }); + log.info('start', { fixed_device: isFixedDevice(), trusted: isTrusted() }); // `start` is the explicit retry of a login that was refused. halted = null; return authorize(); @@ -387,6 +392,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const grant = config.grant; switch (grant.kind) { case 'password': { + log.debug('logging in with the password grant'); const result = await requestTokens(attempt_epoch, { grant_type: 'password', client_id, @@ -402,6 +408,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { return result.ok ? signedIn(result.value) : failed(result.error); } case 'entra': { + log.debug('exchanging the Entra token'); const subject_token = await grant.entraToken(); if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (subject_token === null) return failed({ kind: 'entra_token_missing' }); @@ -431,6 +438,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { return failed(late.error); } if (late.kind === 'applied') { + log.debug('using the parameters of a deep link'); const from_link = await tokenFromKnownCredentials(attempt_epoch); if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (from_link !== null) return from_link; @@ -444,6 +452,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (current.session) { const url = createAuthorizeUrl(); if (config.use_frame !== true) return redirect(url); + log.debug('authorizing in a hidden frame'); const framed = await environment.authorizeInFrame(url, FRAME_TIMEOUT_MS); if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); if (!framed.ok) return failed({ kind: 'frame_failed', reason: framed.error }); @@ -468,7 +477,10 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (from_frame !== null) return from_frame; return failed({ kind: 'frame_failed', reason: 'message_invalid' }); } - if (!handle_login) return failed({ kind: 'login_required' }); + if (!handle_login) { + log.info('no session: the application shows its login'); + return failed({ kind: 'login_required' }); + } return redirect(loginUrl(current)); } @@ -480,9 +492,13 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { attempt_epoch: number, ): Promise | null> { const current = currentCredential(); - if (current !== null) return signedIn(current); + if (current !== null) { + log.debug('a valid credential is found', { credential: current.kind }); + return signedIn(current); + } if (pending_code !== null) { + log.debug('exchanging the code of the redirect'); const code = pending_code; pending_code = null; const verifier = environment.session_storage.get(storageKey('code_verifier')); @@ -502,6 +518,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const refresh_token = readTokens().refresh_token; if (refresh_token !== null) { + log.debug('refreshing the access token'); const result = await requestTokens(attempt_epoch, { grant_type: 'refresh_token', client_id, @@ -511,6 +528,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (result.ok) return signedIn(result.value); if (!isRefusal(result.error)) return failed(result.error); // Keep a refresh token after a network error, but not after the server refused it. + log.warn('the server refused the refresh token'); writeTokens({ ...readTokens(), refresh_token: null }); } return null; @@ -537,7 +555,9 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { ); // A logout ran while the request waited. Its tokens must not log the user in again. if (epoch !== attempt_epoch) return { ok: false, error: { kind: 'logged_out' } }; + const grant = params['grant_type'] ?? ''; if (!fetched.ok) { + log.error('the token request failed', { grant, error: fetched.error.kind }); return { ok: false, error: { kind: 'token_unavailable', error: fetched.error } }; } const decoded = decodeJson(fetched.value.bytes); @@ -548,6 +568,11 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { status: fetched.value.status, message, } as const; + log.warn('the server refused the token request', { + grant, + status: error.status, + message, + }); return { ok: false, error }; } if (!decoded.ok) { @@ -559,6 +584,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const expires_in = tokens.expires_in === null ? null : parseSeconds(String(tokens.expires_in)); storeTokens(tokens.access_token, tokens.refresh_token, expires_in); + log.info('got new tokens', { grant, expires_in_seconds: expires_in }); return { ok: true, value: { kind: 'bearer', token: tokens.access_token } }; } @@ -618,6 +644,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { async function renew(status: 401 | 511, used: Credential): Promise { // The server does not accept an API key, and a new attempt cannot change that. if (used.kind === 'api_key') return false; + log.warn('the server refused the credential', { status }); invalidateToken(); if (status === 511) { // 511: the session on the server ended. The user must log in again. @@ -645,9 +672,13 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { async function runLoadAuthority(): Promise> { if (authority === null && status.kind !== 'redirecting') setStatus({ kind: 'loading' }); + log.debug('loading the authority'); let reason = ''; for (let attempt = 0; attempt < AUTHORITY_ATTEMPTS_MAX; attempt += 1) { - if (attempt > 0) await environment.wait(AUTHORITY_RETRY_MS * attempt); + if (attempt > 0) { + log.warn('the authority did not load: trying again', { attempt, reason }); + await environment.wait(AUTHORITY_RETRY_MS * attempt); + } const fetched = await fetchBody( environment.fetch, serverUrl(AUTHORITY_PATH), @@ -674,8 +705,17 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const parsed = parseResponse(DomainAuthority, decoded.value); if (!parsed.ok) return failed({ kind: 'authority_invalid', ...parsed.error }); authority = parsed.value; + const { id, name, version, domain, session, production } = parsed.value; + log.group('the authority is loaded', { id }); + log.print(`name: ${name}`); + log.print(`version: ${version ?? 'unknown'}`); + log.print(`domain: ${domain}`); + log.print(`session: ${session}`); + log.print(`production: ${production ?? 'unknown'}`); + log.groupEnd(); return { ok: true, value: parsed.value }; } + log.error('the authority is unavailable', { attempts: AUTHORITY_ATTEMPTS_MAX, reason }); return failed({ kind: 'authority_unavailable', reason }); } @@ -716,13 +756,17 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { // The state is `` or `;`. const nonce = (params.get('state') ?? '').split(';')[0] ?? ''; const saved = storage.get(storageKey('nonce')); - if (saved === null || saved !== nonce) return { kind: 'state_mismatch' }; + if (saved === null || saved !== nonce) { + log.warn('the state of the login parameters is not the nonce of this client'); + return { kind: 'state_mismatch' }; + } // Only a login that this client started gives credentials, and only one time. storage.remove(storageKey('nonce')); const denial = params.get('error'); if (denial !== undefined) { // RFC 6749 §4.1.2.1: the server refused. A new redirect shows the same refusal. const description = params.get('error_description') ?? null; + log.warn('the server refused the login', { error: denial, description }); return { kind: 'denied', error: { kind: 'authorization_denied', error: denial, description }, @@ -732,6 +776,10 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (code !== undefined) pending_code = code; const access_token = params.get('access_token'); const refresh_token = params.get('refresh_token') ?? null; + log.debug('got the login parameters', { + code: code !== undefined, + access_token: access_token !== undefined, + }); if (access_token !== undefined) { storeTokens( access_token, @@ -784,6 +832,8 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { } function redirect(url: string): Result { + // The path only: the query has the state of the login. + log.info('redirecting', { path: new URL(url, 'http://base.invalid').pathname }); setStatus({ kind: 'redirecting', url }); environment.navigate(url); return { ok: false, error: { kind: 'redirecting', url } }; @@ -791,11 +841,13 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { function signedIn(credential: Credential): Result { assert(credential.kind !== 'none', 'a session credential is a token or a key'); + if (status.kind !== 'signed_in') log.info('signed in', { credential: credential.kind }); setStatus({ kind: 'signed_in', credential: credential.kind }); return { ok: true, value: credential }; } function failed(error: AuthError): Result { + log.warn('not signed in', { error }); if (status.kind !== 'redirecting') setStatus({ kind: 'signed_out', error }); return { ok: false, error }; } @@ -803,6 +855,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { async function handleRedirect(url: string): Promise> { const params = urlParams(url); if (!hasLoginParams(params)) return { ok: false, error: { kind: 'redirect_invalid' } }; + log.debug('got a deep link'); environment.session_storage.set(DEEP_LINK_KEY, JSON.stringify(Object.fromEntries(params))); // An attempt that runs now reads the deep link before it redirects. Then its result is the // result of the link, and a second attempt would redirect after a denial. @@ -838,6 +891,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (authority === null) return; if (authority.session) return; if (currentCredential() !== null) return; + log.debug('the application is in the foreground without a session'); if (status.kind === 'redirecting') setStatus({ kind: 'loading' }); const has_new_credentials = environment.session_storage.get(DEEP_LINK_KEY) !== null || @@ -859,6 +913,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { expires_at_ms ?? environment.now() + TOKEN_LIFETIME_DEFAULT_SECONDS * 1000; writeTokens({ ...readTokens(), access_token: token, expires_at_ms: expires_at }); halted = null; + log.info('using a token of the application'); setStatus({ kind: 'signed_in', credential: 'bearer' }); } @@ -867,16 +922,19 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { storage.set(storageKey('x-api-key'), key); storage.set(storageKey('trusted'), String(options.trusted ?? true)); halted = null; + log.info('using an API key of the application'); setStatus({ kind: 'signed_in', credential: 'api_key' }); } function invalidateToken(): void { + log.debug('invalidating the access token'); writeTokens({ ...readTokens(), access_token: null, expires_at_ms: 0 }); } async function logout(): Promise { const url = authority === null ? serverUrl(LOGOUT_PATH_DEFAULT) : serverUrl(authority.logout_url); + log.info('logging out'); epoch += 1; const request_headers: Record = { ...headers }; // Send the token also after its local expiry. That has a margin, so the server can still diff --git a/src/compat/http-mock.ts b/src/compat/http-mock.ts index 5b312b851..42a496e8c 100644 --- a/src/compat/http-mock.ts +++ b/src/compat/http-mock.ts @@ -19,6 +19,8 @@ */ import { assert } from '../core/assert.ts'; import type { FetchFunction } from '../core/client.ts'; +import { scopedLog } from '../core/log.ts'; +import { consoleLog } from './log.ts'; /** More endpoints is a leak, such as a test that registers in a loop and never removes them. */ export const MOCK_ENDPOINTS_MAX = 10_000; @@ -78,6 +80,8 @@ export interface MockHttpResponse { type NotFoundHandler = (method: HttpVerb, url: string) => Promise | null; const handlers = new Map(); +/** The logs of the mock endpoints. As in 6.x, they go to the console when `window.debug` is set. */ +const log = scopedLog('mock', { sink: consoleLog }); let notFound: NotFoundHandler = (method, url) => Promise.reject( @@ -93,10 +97,11 @@ export function registerMockEndpoint(options: MockHttpRequestHandlerOptions { const method = verb(init.method); const handler = findHandler(method, url); if (handler === null) { + log.warn(`404 ${method} ${url}`); const fallback = notFound(method, url); if (fallback === null) return fetch(url, init); return fallback.then( @@ -129,6 +135,7 @@ export const mockFetch: FetchFunction = async (url, init) => { ); } const request = makeRequest(url, handler, method, init.body); + log.debug(`MATCHED ${method} ${handler.path}`, { url }); let body: unknown; let headers: Record; try { diff --git a/src/compat/index.ts b/src/compat/index.ts index 1f267dbd3..56c6ae3d2 100644 --- a/src/compat/index.ts +++ b/src/compat/index.ts @@ -6,11 +6,14 @@ * - `mockReply` and `mockPage` make 7.x results for the test doubles of 7.x calls. * - `registerMockEndpoint` and `mockFetch` are the 6.x mock endpoints, for the 7.x client. * - `registerSystem` and `mockRealtimeEnvironment` are the 6.x mock systems, for `createRealtime`. + * - `consoleLog` and `createConsoleLog` write the debug logs in the console format of 6.x, when + * `window.debug` is set. * - The 6.x enums, with the values of 7.x. * * @module */ export * from './enums.ts'; export * from './http-mock.ts'; +export { consoleLog, createConsoleLog } from './log.ts'; export * from './realtime-mock.ts'; export * from './result.ts'; diff --git a/src/compat/log.ts b/src/compat/log.ts new file mode 100644 index 000000000..4dfa7cb3c --- /dev/null +++ b/src/compat/log.ts @@ -0,0 +1,65 @@ +import type { LogEntry, LogFunction, LogLevel, LogScope } from '../core/log.ts'; + +/** The scope names of the 6.x console logs. */ +const SCOPE_NAMES: Readonly> = { + http: 'HTTP', + auth: 'Auth', + realtime: 'WS', + mock: 'HTTP(M)', +}; +const COLORS = ['color: #0288D1', 'color: #009688', 'color: default'] as const; + +/** The console method of each level. */ +const METHODS = { + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug', + print: 'log', + group: 'group', + group_end: 'groupEnd', +} as const satisfies Readonly>; + +/** + * A log function that writes `[PlaceOS][Auth] the authority is loaded` to the console, with the + * console method of the level, such as `console.warn` for `warn`, and the arguments of the call. + * As in 6.x, it writes only when `window.debug` is set, so an application can turn it on in the + * console of the browser. + * + * A first argument that is a string joins the prefix, as in `[PlaceOS][Auth] loading`. `colors` + * colors the prefix with `%c`, as 6.x did. Without colors, the text is plain. + */ +export function createConsoleLog(options: { readonly colors?: boolean } = {}): LogFunction { + const colors = options.colors ?? true; + return (entry: LogEntry) => { + if (!Boolean(Reflect.get(globalThis, 'debug'))) return; + const method = METHODS[entry.level]; + if (method === 'groupEnd') { + console.groupEnd(); + return; + } + const scope = SCOPE_NAMES[entry.scope]; + const [first, ...rest] = entry.args; + // A message joins the prefix: `[PlaceOS][WS] the socket closed`. The prefix is the format + // string of the console, so a message with a `%` goes in with `%s`, and stays text. + const message = typeof first === 'string' ? first : null; + const literal = message !== null && !message.includes('%'); + const text = message === null ? '' : literal ? ` ${message}` : ' %s'; + const format = colors ? `%c[PlaceOS]%c[${scope}]%c${text}` : `[PlaceOS][${scope}]${text}`; + const substituted = message !== null && !literal ? [message] : []; + const values = message === null ? entry.args : rest; + console[method](format, ...(colors ? COLORS : []), ...substituted, ...values); + }; +} + +/** + * The log function with the console format of 6.x, with colors: + * + * ```ts + * configure({ base_url: '', auth: session.client_auth, log: consoleLog }); + * const session = createAuthSession({ ..., log: consoleLog }); + * const realtime = createRealtime({ ..., log: consoleLog }); + * // In the console of the browser: window.debug = true + * ``` + */ +export const consoleLog: LogFunction = createConsoleLog({ colors: true }); diff --git a/src/core/client.ts b/src/core/client.ts index cc3abf3a0..0cfe7db4d 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -1,4 +1,5 @@ import { assert, unreachable } from './assert.ts'; +import { scopedLog, type LogFunction } from './log.ts'; import { pageInfo } from './pagination.ts'; import type { Result } from './result.ts'; import { @@ -75,6 +76,8 @@ export interface ClientConfig { * one with a typed handler for each endpoint. */ readonly mock?: CallMock; + /** Gets a debug log entry for each call. See `LogFunction`. */ + readonly log?: LogFunction; } /** @@ -104,6 +107,7 @@ export interface Client { readonly fetch: FetchFunction; readonly missing_fields: 'error' | 'zero'; readonly mock: CallMock | null; + readonly log: LogFunction | null; } export interface CallOptions { @@ -253,6 +257,7 @@ export function createClient(config: ClientConfig): Client { fetch: fetchFunction, missing_fields: config.missing_fields ?? 'error', mock: config.mock ?? null, + log: config.log ?? null, }); } @@ -329,7 +334,9 @@ async function request( input: unknown, options: CallOptions, ): Promise { + const started_ms = Date.now(); const sent = await send(client, operation, input, options); + logOutcome(client, operation, sent, Date.now() - started_ms); if (!sent.ok || !paged(operation)) return sent; const reply = sent.value; const next = (next_options: CallOptions = {}) => @@ -337,6 +344,29 @@ async function request( return { ok: true, value: { ...reply, next } }; } +/** The status or the error of a call, without its input or data. */ +function logOutcome( + client: Client, + operation: AnyOperation, + result: Result, CallError>, + duration_ms: number, +): void { + if (client.log === null) return; + const log = scopedLog('http', { sink: client.log }); + const call_data = { name: operation.name, method: operation.method, duration_ms }; + if (result.ok) { + const status = result.value.status; + log.debug(`${operation.name}: ${status} in ${duration_ms} ms`, { ...call_data, status }); + return; + } + const error = result.error; + const status = error.kind === 'http' ? ` ${error.status}` : ''; + const message = `${operation.name}: ${error.kind}${status} in ${duration_ms} ms`; + // The server answered: a warning. No answer, such as a timeout: an error. + if (error.kind === 'http') log.warn(message, { ...call_data, error }); + else log.error(message, { ...call_data, error }); +} + /** `true` when the operation has an `offset` parameter, so that its reply is a page. */ function paged(operation: AnyOperation): boolean { const node = operation.params.node; @@ -403,6 +433,9 @@ async function send( if (!answered.ok) return limitError(answered.error, timeout_ms); // `null`: the mock does not answer this call, so the request goes to the server. if (answered.value !== null) { + scopedLog('http', { sink: client.log }).debug( + `${operation.name}: answered by the mock`, + ); return mockResult(operation, answered.value, client.response_bytes_max); } } @@ -435,6 +468,8 @@ async function send( if (attempt + 1 >= AUTH_ATTEMPTS_MAX) break; const rejected = client.auth.rejected; const used = credential.value; + const log = scopedLog('http', { sink: client.log }); + log.info(`${operation.name}: ${status}, renewing the credential`); const renewed = await waitWithin(() => rejected(status, used), deadline_ms, signal); if (!renewed.ok) return limitError(renewed.error, timeout_ms); if (!renewed.value) break; diff --git a/src/core/log.ts b/src/core/log.ts new file mode 100644 index 000000000..9f453cdbf --- /dev/null +++ b/src/core/log.ts @@ -0,0 +1,85 @@ +/** + * Optional debug logs of the client, the login and the realtime client. Without a `log` function + * they log nothing. Give `consoleLog` of `@placeos/ts-client/compat` for the console format of + * 6.x, or a function of your own: + * + * ```ts + * configure({ base_url: '', auth, log: (entry) => console.debug(entry.scope, entry.message) }); + * ``` + * + * An entry has no tokens, API keys, cookies, request bodies or input values. + * + * Inside the library, each part logs through a scoped logger, as `std.log.scoped` does in Zig. The + * log function of the application decides where the entries go, as `logFn` does in Zig: + * + * ```ts + * const log = scopedLog('auth', { sink: config.log ?? null }); + * log.info('the authority is loaded', { name }); + * ``` + * + * @module + */ + +/** The part that logs: the REST client, the login, the realtime client or the mock endpoints. */ +export type LogScope = 'http' | 'auth' | 'realtime' | 'mock'; + +/** + * The level of an entry. `print` is a line without a level, as `console.log`. `group` starts a + * group of the entries that follow, and `group_end` ends it. + */ +export type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'print' | 'group' | 'group_end'; + +export interface LogEntry { + readonly scope: LogScope; + readonly level: LogLevel; + /** + * The arguments of the call, as a console method gets them: often a message, then values that + * help to find a problem, such as a status. Never a secret. Empty for `group_end`. + */ + readonly args: readonly unknown[]; +} + +export type LogFunction = (entry: LogEntry) => void; + +/** + * The logger of one scope. The methods have the arguments of the console methods of the same + * name: `log.warn('the socket closed', { attempt })` as `console.warn(...)`. `print` is + * `console.log`. Each call gives one entry to the sink. + */ +export interface ScopedLog { + error(...data: unknown[]): void; + warn(...data: unknown[]): void; + info(...data: unknown[]): void; + debug(...data: unknown[]): void; + print(...data: unknown[]): void; + group(...label: unknown[]): void; + groupEnd(): void; +} + +/** + * A logger for `scope` that gives its entries to `sink`. A `null` sink logs nothing. A sink that + * throws does not change what the caller does, because a log is for debugging only. + */ +export function scopedLog( + scope: LogScope, + options: { readonly sink: LogFunction | null }, +): ScopedLog { + const sink = options.sink; + const write = (level: LogLevel, args: readonly unknown[]) => { + if (sink === null) return; + try { + sink({ scope, level, args }); + } catch { + // The error is in the log function of the application, not in the client. + } + }; + return { + error: (...data) => write('error', data), + warn: (...data) => write('warn', data), + info: (...data) => write('info', data), + debug: (...data) => write('debug', data), + print: (...data) => write('print', data), + group: (...label) => write('group', label), + groupEnd: () => write('group_end', []), + }; +} diff --git a/src/index.ts b/src/index.ts index a635bb7b9..0b9096406 100644 --- a/src/index.ts +++ b/src/index.ts @@ -73,6 +73,7 @@ export { type PageReply, type Reply, } from './core/client.ts'; +export { type LogEntry, type LogFunction, type LogLevel, type LogScope } from './core/log.ts'; export { pageInfo, type PageInfo } from './core/pagination.ts'; export type { Result } from './core/result.ts'; export { diff --git a/src/realtime/realtime.ts b/src/realtime/realtime.ts index 221122129..49e548b14 100644 --- a/src/realtime/realtime.ts +++ b/src/realtime/realtime.ts @@ -18,6 +18,7 @@ */ import { assert, unreachable } from '../core/assert.ts'; import { resolveCredential, type Auth, type Credential } from '../core/client.ts'; +import { scopedLog, type LogFunction } from '../core/log.ts'; import type { Result } from '../core/result.ts'; import { integer, @@ -142,6 +143,8 @@ export interface RealtimeConfig { /** Tells the server that this is a device in a fixed location. */ readonly fixed_device?: boolean; readonly environment?: RealtimeEnvironment; + /** Gets the debug log entries of the socket. See `LogFunction`. */ + readonly log?: LogFunction; } export interface Realtime { @@ -234,6 +237,7 @@ interface Debugger { export function createRealtime(config: RealtimeConfig): Realtime { assert(!config.base_url.endsWith('/'), 'the base_url has no trailing slash'); const environment = config.environment ?? browserRealtimeEnvironment(); + const log = scopedLog('realtime', { sink: config.log ?? null }); let status: RealtimeStatus = { kind: 'idle' }; let socket: RealtimeSocket | null = null; @@ -283,6 +287,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { } function stop(): void { + log.info('stopped'); connect_attempt += 1; setStatus({ kind: 'stopped' }); cancelTimers(); @@ -465,7 +470,9 @@ export function createRealtime(config: RealtimeConfig): Realtime { const this_attempt = connect_attempt; attempt += 1; setStatus({ kind: 'connecting', attempt }); + log.debug('connecting', { attempt }); if (renew_before_connect && config.auth.kind === 'credential' && last_credential !== null) { + log.info('asking the auth for a new credential, after failures to connect'); renew_before_connect = false; await config.auth.rejected(401, last_credential); if (this_attempt !== connect_attempt) return; @@ -475,6 +482,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { if (this_attempt !== connect_attempt) return; if (status.kind !== 'connecting') return; if (credential === null) { + log.warn('no credential to connect with'); scheduleReconnect(); return; } @@ -496,7 +504,9 @@ export function createRealtime(config: RealtimeConfig): Realtime { }); cancelConnectTimer = environment.setTimer(CONNECT_TIMEOUT_MS, () => { cancelConnectTimer = null; - if (current() && status.kind === 'connecting') dropSocket(); + if (!current() || status.kind !== 'connecting') return; + log.warn('the socket did not open in time', { timeout_ms: CONNECT_TIMEOUT_MS }); + dropSocket(); }); } @@ -510,6 +520,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { const opened = socket; assert(opened !== null, 'an open socket exists'); opened.send('ping'); + log.info('connected', { bindings: bindings.size, debuggers: debuggers.size }); // The server forgets the bindings of a closed socket. Bind each one again. for (const binding of bindings.values()) sendBind(binding); for (const entry of debuggers.values()) sendDebug(entry, 'debug'); @@ -526,6 +537,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { last_message_at_ms = environment.now(); if (inbox.length >= INBOX_MAX) { // The listeners are slower than the server. A new socket resyncs each binding. + log.warn('the inbox is full: connecting again', { inbox_max: INBOX_MAX }); dropSocket(); return; } @@ -552,11 +564,22 @@ export function createRealtime(config: RealtimeConfig): Realtime { case 'success': settle(message.id, { ok: true, value: message.value }); break; - case 'error': - settle(message.id, failure(serverError(message))); + case 'error': { + const error = serverError(message); + log.warn('the server refused a request', { id: message.id, error }); + settle(message.id, failure(error)); break; + } case 'notify': if (message.meta !== null) { + const { sys, mod, index, name } = message.meta; + log.debug(`${sys} ${mod}_${index} ${name} changed`, { + sys, + mod, + index, + name, + value: message.value, + }); changed.set(variableKey(message.meta), message.value); } break; @@ -565,6 +588,8 @@ export function createRealtime(config: RealtimeConfig): Realtime { const entry = debuggers.get(debugKey(message.meta.sys, message.meta.mod)); if (entry === undefined) break; const text = message.msg ?? ''; + const { sys, mod } = message.meta; + log.debug(`log of ${mod}`, { sys, mod, level: message.level, message: text }); logs.push([entry, { level: message.level, message: text, received_at_ms }]); break; } @@ -587,6 +612,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { function onDisconnect(): void { // A response can wait in the inbox. Handle it before the requests fail as disconnected. if (inbox.length > 0) drain(); + log.warn('the socket closed', { was_open: status.kind === 'open' }); cancelTimers(); socket = null; if (status.kind !== 'open') failures_before_open += 1; @@ -600,6 +626,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { function scheduleReconnect(): void { if (attempt >= RECONNECT_ATTEMPTS_MAX) { + log.error('stopped after the maximum number of attempts', { attempts: attempt }); setStatus({ kind: 'failed' }); for (const id of [...pending.keys()]) settle(id, failure({ kind: 'unavailable' })); queue.length = 0; @@ -615,6 +642,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { Math.max(1, attempt) * RECONNECT_DELAY_STEP_MS, ); setStatus({ kind: 'waiting', attempt, delay_ms }); + log.info('connecting again after a wait', { attempt, delay_ms }); cancelReconnect = environment.setTimer(delay_ms, () => { cancelReconnect = null; void connect(); @@ -626,6 +654,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { cancelKeepAlive = null; if (status.kind !== 'open' || socket === null) return; if (environment.now() - last_message_at_ms > STALE_MS) { + log.warn('no message from the server: connecting again', { stale_ms: STALE_MS }); dropSocket(); return; } @@ -681,11 +710,13 @@ export function createRealtime(config: RealtimeConfig): Realtime { // in the query. const page_host = new URL(environment.currentUrl()).hostname; if (environment.token_transport === 'query' || url.hostname !== page_host) { + log.debug('the token goes in the query of the socket'); url.searchParams.set(name, token_value); } else { // The server reads the cookie value as it is, so the value must be cookie safe. assert(/^[^;\s]+$/.test(token_value), 'the token has no semicolons or spaces'); const secure_flag = secure ? '; secure' : ''; + log.debug('the token goes in a cookie of the socket path'); environment.setCookie( `${name}=${token_value}; max-age=${COOKIE_MAX_AGE_SECONDS}; ` + `path=${CONTROL_PATH}; samesite=strict${secure_flag}`, diff --git a/test/auth.test.ts b/test/auth.test.ts index bee7790cd..be7c83276 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -3,6 +3,7 @@ * for. Method: run the session against a fake environment and a fake PlaceOS server, then check * the requests, the navigations, the storage and the result. */ +import type { LogEntry } from '../src/core/log.ts'; import { describe, expect, test } from 'bun:test'; import { memoryStore, webStorageStore, type AuthEnvironment } from '../src/auth/environment.ts'; import { @@ -179,6 +180,34 @@ describe('authorization code with PKCE', () => { expect(world.storage.get(`${CLIENT_ID}_access_token`)).toBeNull(); }); + test('logs each step of the login, and no token, code or state', async () => { + const world = fake(); + const state = (await startLogin(world)).get('state') ?? ''; + const verifier = world.session_storage.get(`${CLIENT_ID}_code_verifier`) ?? ''; + world.setUrl(`http://localhost:4200/rooms?code=abc&state=${state}`); + const entries: LogEntry[] = []; + await session(world, { log: (entry) => entries.push(entry) }).start(); + expect(entries.map((entry) => `${entry.level} ${entry.args[0] ?? ''}`)).toEqual([ + 'info start', + 'debug got the login parameters', + 'debug loading the authority', + 'group the authority is loaded', + 'print name: PlaceOS', + 'print version: 2.0.0', + 'print domain: placeos.test', + 'print session: true', + 'print production: false', + 'group_end ', + 'debug exchanging the code of the redirect', + 'info got new tokens', + 'info signed in', + ]); + expect(entries.every((entry) => entry.scope === 'auth')).toBe(true); + const text = JSON.stringify(entries); + for (const secret of ['token-1', 'abc', state, verifier]) + expect(text).not.toContain(secret); + }); + test('refuses a code with a state that this client did not send', async () => { const world = fake(); await startLogin(world); diff --git a/test/client.test.ts b/test/client.test.ts index ae3c05877..a0ff6c44c 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -2,6 +2,7 @@ * Goal: `call` sends what the server expects, and converts each failure to the correct error. * Method: replace `fetch` with a function that records the request and returns a fixed response. */ +import type { LogEntry } from '../src/core/log.ts'; import { describe, expect, test } from 'bun:test'; import { call, @@ -178,6 +179,30 @@ function pageResponse(ids: readonly string[], next: number | null): Response { return response; } +describe('log', () => { + test('gives the name and the status or error of each call, and no token or body', async () => { + const entries: LogEntry[] = []; + const { fetch } = fakeFetch((init) => + init.method === 'PATCH' ? jsonResponse({ id: 'item-1' }) : jsonResponse({}, 404), + ); + const client = clientWith(fetch, { + auth: { kind: 'bearer', token: () => 'secret-token' }, + log: (entry) => entries.push(entry), + }); + await call(UPDATE, { id: 'item-1', body: { name: 'Lobby' } }, { client }); + await call(DOWNLOAD, {}, { client }); + const lines = entries.map((entry) => `${entry.level} ${entry.args[0]}`); + expect(lines.map((line) => line.replace(/\d+ ms/, 'N ms'))).toEqual([ + 'debug items.update: 200 in N ms', + 'warn items.download: http 404 in N ms', + ]); + expect(entries[0]?.args[1]).toMatchObject({ name: 'items.update', method: 'PATCH' }); + const text = JSON.stringify(entries); + expect(text).not.toContain('secret-token'); + expect(text).not.toContain('Lobby'); + }); +}); + describe('pages', () => { test('next() asks for the next offset with the same input and client, to the last page', async () => { const pages = new Map([ diff --git a/test/compat.test.ts b/test/compat.test.ts index 179908541..342ba4bf0 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -3,9 +3,11 @@ * client, so that a mock mode and the tests of an app still work after the migration. * Method: register 6.x style endpoints and systems, and use them through 7.x calls. */ -import { afterEach, expect, test } from 'bun:test'; +import { afterEach, expect, spyOn, test } from 'bun:test'; import { clearMockEndpoints, + consoleLog, + createConsoleLog, deregisterSystem, fromV1Mock, mockFetch, @@ -122,6 +124,38 @@ test('fromV1Mock fits the mockImplementation of an operation, with and without a expect(page.ok && page.value.next()).toBeNull(); }); +test('consoleLog writes the 6.x format with the console method of the level', () => { + const written: string[] = []; + const spies = (['debug', 'warn', 'log', 'group', 'groupEnd'] as const).map((method) => + spyOn(console, method).mockImplementation((...args: unknown[]) => { + written.push(`${method} ${args.map(String).join(' | ')}`); + }), + ); + const plain = createConsoleLog({ colors: false }); + try { + consoleLog({ scope: 'auth', level: 'debug', args: ['off'] }); + Reflect.set(globalThis, 'debug', true); + consoleLog({ scope: 'auth', level: 'debug', args: ['loading 50%', { id: 1 }] }); + plain({ scope: 'realtime', level: 'warn', args: ['the socket closed'] }); + plain({ scope: 'auth', level: 'group', args: ['the authority'] }); + plain({ scope: 'auth', level: 'print', args: ['name:', 'PlaceOS', 2] }); + plain({ scope: 'auth', level: 'group_end', args: [] }); + plain({ scope: 'http', level: 'print', args: [{ id: 2 }] }); + } finally { + Reflect.deleteProperty(globalThis, 'debug'); + for (const spy of spies) spy.mockRestore(); + } + expect(written).toEqual([ + // A `%` in the message goes in with `%s`, so the console does not read it as a format. + 'debug %c[PlaceOS]%c[Auth]%c %s | color: #0288D1 | color: #009688 | color: default | loading 50% | [object Object]', + 'warn [PlaceOS][WS] the socket closed', + 'group [PlaceOS][Auth] the authority', + 'log [PlaceOS][Auth] name: | PlaceOS | 2', + 'groupEnd ', + 'log [PlaceOS][HTTP] | [object Object]', + ]); +}); + test('mockReply and mockPage make the results of test doubles', () => { const zone = { id: 'zone-1' }; expect(orThrow(mockReply(zone))).toBe(zone); diff --git a/test/log.test.ts b/test/log.test.ts new file mode 100644 index 000000000..123e79686 --- /dev/null +++ b/test/log.test.ts @@ -0,0 +1,42 @@ +/** + * Goal: a scoped logger gives one entry with its scope and level to the sink, and a sink that + * throws or is missing does not change the caller. + * Method: log with each method into a sink that records the entries. + */ +import { expect, test } from 'bun:test'; +import { scopedLog, type LogEntry } from '../src/core/log.ts'; + +test('each method gives an entry with the scope and the level', () => { + const entries: LogEntry[] = []; + const log = scopedLog('auth', { sink: (entry) => entries.push(entry) }); + log.error('Error: an error'); + log.warn('Warn: a warning', { status: 401 }, 2); + log.info('Info: a step'); + log.debug('Debug: a detail'); + log.group('A group'); + log.print('Log: a line'); + log.groupEnd(); + expect(entries.map((entry) => [entry.level, entry.args[0]])).toEqual([ + ['error', 'Error: an error'], + ['warn', 'Warn: a warning'], + ['info', 'Info: a step'], + ['debug', 'Debug: a detail'], + ['group', 'A group'], + ['print', 'Log: a line'], + ['group_end', undefined], + ]); + expect(entries.every((entry) => entry.scope === 'auth')).toBe(true); + // The arguments stay as the call gave them, as a console method gets them. + expect(entries[1]?.args).toEqual(['Warn: a warning', { status: 401 }, 2]); + expect(entries[6]?.args).toEqual([]); +}); + +test('a sink that throws or no sink does not change the caller', () => { + const throwing = scopedLog('http', { + sink: () => { + throw new Error('a bug in the log function'); + }, + }); + expect(() => throwing.error('lost')).not.toThrow(); + expect(() => scopedLog('http', { sink: null }).info('nothing')).not.toThrow(); +}); diff --git a/test/realtime.test.ts b/test/realtime.test.ts index 629356178..4d82f3875 100644 --- a/test/realtime.test.ts +++ b/test/realtime.test.ts @@ -3,6 +3,7 @@ * and settles each request. Method: give it fake sockets and a manual clock, play the server's * frames, then check the frames that the client sent and the results. */ +import type { LogEntry } from '../src/core/log.ts'; import { describe, expect, test } from 'bun:test'; import type { Auth } from '../src/core/client.ts'; import type { RealtimeEnvironment, SocketHandlers } from '../src/realtime/environment.ts'; @@ -127,6 +128,33 @@ describe('connection', () => { ); }); + test('logs the connection, a change and a reconnect, and not the token', async () => { + const platform = fakePlatform('cookie'); + const entries: LogEntry[] = []; + const client = realtime(platform, { + base_url: '', + log: (entry) => entries.push(entry), + }); + client.bind(POWER, () => {}); + await platform.open(); + await platform.receive({ id: 0, type: 'notify', value: true, meta: META }); + platform.latest().handlers.close(); + await platform.advance(5_000); + expect(entries.map((entry) => entry.args[0])).toEqual([ + 'connecting', + 'the token goes in a cookie of the socket path', + 'connected', + 'sys-1 Display_1 power changed', + 'the socket closed', + 'connecting again after a wait', + 'connecting', + 'the token goes in a cookie of the socket path', + ]); + expect(entries[3]?.args[1]).toEqual({ ...META, value: true }); + expect(JSON.stringify(entries)).not.toContain('abc'); + client.stop(); + }); + test('puts the token in a cookie on the socket path, not in the URL', async () => { const platform = fakePlatform('cookie'); const auth: Auth = { kind: 'api_key', key: 'key-1' }; From 3a3c8dff87c681a0218f0956360181cd561cd4a1 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Wed, 18 Nov 2026 16:30:47 +1100 Subject: [PATCH 18/29] docs: name the design rules without Zig or TigerStyle The docs compared the logger to Zig and named TigerStyle as the code style. They now describe the logger and the design rules directly. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 +++++++----- src/core/log.ts | 4 ++-- test/style.test.ts | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 197e2aadd..8055e9044 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,7 @@ A typed client for the PlaceOS REST API and the staff API. A script generates the types and the request functions from the OpenAPI documents of [PlaceOS/rest-api](https://github.com/PlaceOS/rest-api/blob/master/OPENAPI_DOC.yml) and -[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api/blob/master/OPENAPI_DOC.yml). The code follows [TigerStyle for JS/TS](https://github.com/tigerbeetle/tigerbeetle/blob/main/docs/TIGER_STYLE.md) -where possible. +[PlaceOS/staff-api](https://github.com/PlaceOS/staff-api/blob/master/OPENAPI_DOC.yml). The library has no runtime dependencies. It runs in browsers, in Node 20.3 and later, and in Bun. @@ -393,11 +392,11 @@ window.debug = true; path only, because the query has the state of the login. - A log function that throws does not change the call, the login or the socket. - The `mock` entries of the 6.x mock endpoints always go to `consoleLog`, as in 6.x. -- In the library, each part logs through a scoped logger, as `std.log.scoped` does in Zig: +- In the library, each part logs through a scoped logger: `const log = scopedLog('auth', { sink: config.log ?? null })`. Its methods have the arguments of the console methods: `log.error(...data)`, `log.warn(...data)`, `log.info(...data)`, `log.debug(...data)`, `log.print(...data)` (`console.log`), `log.group(...label)` and - `log.groupEnd()`. The `log` function of the application is the sink, as `logFn` is in Zig. + `log.groupEnd()`. The `log` function of the application gets the entries. ## Types @@ -597,7 +596,10 @@ arguments, and it finds the 7.x operation with the same method and path. - Classes with methods for each model. 7.x has plain data and functions. -## Where 7.x does not follow TigerStyle +## Exceptions to the design rules + +The library gives errors as values, has no `any` and no unchecked casts, keeps no module state, +keeps its state in plain data, and keeps keyed data in a `Map`. These are the exceptions: - `orThrow` and `orThrowPage` of `@placeos/ts-client/compat` throw. They are for code that moves from 6.x. diff --git a/src/core/log.ts b/src/core/log.ts index 9f453cdbf..012bb189c 100644 --- a/src/core/log.ts +++ b/src/core/log.ts @@ -9,8 +9,8 @@ * * An entry has no tokens, API keys, cookies, request bodies or input values. * - * Inside the library, each part logs through a scoped logger, as `std.log.scoped` does in Zig. The - * log function of the application decides where the entries go, as `logFn` does in Zig: + * Inside the library, each part logs through a scoped logger. The log function of the application + * decides where the entries go: * * ```ts * const log = scopedLog('auth', { sink: config.log ?? null }); diff --git a/test/style.test.ts b/test/style.test.ts index c164d0c0a..35a969c31 100644 --- a/test/style.test.ts +++ b/test/style.test.ts @@ -1,5 +1,5 @@ /** - * Goal: the library does not bypass the type checks (TigerStyle "Boundaries"). + * Goal: the library does not bypass the type checks. * Method: search the source for `any`, `@ts-ignore`, `@ts-expect-error`, non-null assertions and * casts. The casts that the parser needs are listed here, with the reason in the code. */ From 7366c94625472f7f35034ce88c116f2e5fec01bc Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Thu, 19 Nov 2026 01:18:37 +1100 Subject: [PATCH 19/29] fix: read the rest-api time types from the document PlaceOS/rest-api#469 documents the Unix-second timestamps as integers, so the rest-api needs no epoch patch. The staff-api document is not regenerated yet, so it keeps its list. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++-- scripts/generate.ts | 64 +++++++++--------------------- src/generated/schemas.ts | 84 ---------------------------------------- 3 files changed, 24 insertions(+), 133 deletions(-) diff --git a/README.md b/README.md index 8055e9044..acc61c130 100644 --- a/README.md +++ b/README.md @@ -430,10 +430,11 @@ short name too. The short name is the same value and type: The generator changes some parts of the document. Each change has a comment in `scripts/generate.ts`. -- **Time fields.** The document says `date-time` for some fields that the server sends as Unix time - in seconds, for example `created_at` on most models. The generator changes these fields to - integers. The list comes from the source of PlaceOS/models. The generator stops if it finds a - `date-time` field that is not in a list, so each new field gets a decision. +- **Time fields.** The staff-api document says `date-time` for some fields that the server sends + as Unix time in seconds, for example `created_at` on most models. The generator changes these + fields to integers. The list comes from the source of PlaceOS/models. The rest-api document has + the correct types. The generator stops if it finds a `date-time` field that is not in a list, so + each new field gets a decision. - **Enum numbers.** The server sends some enums as numbers, for example `Driver.role` (`99` is `logic`). The document gives their names. The generator changes these fields to the numbers. - **Required fields in a request.** The document marks a field as required when the server always diff --git a/scripts/generate.ts b/scripts/generate.ts index f6b906c6b..4f1736731 100644 --- a/scripts/generate.ts +++ b/scripts/generate.ts @@ -28,70 +28,39 @@ const EMIT_DEPTH_MAX = 32; const LINE_WIDTH_MAX = 100; /** - * The spec generator of the server loses the `type: "integer"` hint of a `Time` field that has an + * The spec generator of the server lost the `type: "integer"` hint of a `Time` field that has an * epoch converter, if the field is a PgORM `attribute` or can be nil. The document then says - * `date-time`, but the server sends and accepts Unix time in seconds. Each entry comes from the - * source of PlaceOS/models and PlaceOS/rest-api. + * `date-time`, but the server sends and accepts Unix time in seconds. PlaceOS/rest-api#469 fixed + * the generator, so the rest-api document is correct. The staff-api document is not regenerated + * yet, and these are its fields. Each entry comes from the source of PlaceOS/models and + * PlaceOS/staff-api. When the document is correct, the patch fails, and the list can go. */ const TIMESTAMPS = ['created_at', 'updated_at']; -const EPOCH_FIELDS: ReadonlyMap = new Map([ - ['PlaceOS.Api.ApiKeys.Response', ['expires_at']], - ['PlaceOS.Model.Alert', TIMESTAMPS], - ['PlaceOS.Model.AlertDashboard', TIMESTAMPS], - ['PlaceOS.Model.ApiKey', [...TIMESTAMPS, 'expires_at']], +const STAFF_EPOCH_FIELDS: ReadonlyMap = new Map([ ['PlaceOS.Model.Asset', TIMESTAMPS], ['PlaceOS.Model.AssetCategory', TIMESTAMPS], ['PlaceOS.Model.AssetPurchaseOrder', TIMESTAMPS], ['PlaceOS.Model.AssetType', TIMESTAMPS], - ['PlaceOS.Model.Authority', TIMESTAMPS], - ['PlaceOS.Model.Broker', TIMESTAMPS], - ['PlaceOS.Model.Chat', TIMESTAMPS], - ['PlaceOS.Model.ControlSystem', [...TIMESTAMPS, 'signage_last_seen']], - ['PlaceOS.Model.DoorkeeperApplication', TIMESTAMPS], - ['PlaceOS.Model.Driver', TIMESTAMPS], - ['PlaceOS.Model.Edge', [...TIMESTAMPS, 'last_seen']], - ['PlaceOS.Model.Edge.KeyResponse', [...TIMESTAMPS, 'last_seen']], - ['PlaceOS.Model.History', ['created_at']], - ['PlaceOS.Model.JsonSchema', TIMESTAMPS], - ['PlaceOS.Model.LdapAuthentication', TIMESTAMPS], - ['PlaceOS.Model.Module', [...TIMESTAMPS, 'error_timestamp']], - ['PlaceOS.Model.OAuthAuthentication', TIMESTAMPS], - ['PlaceOS.Model.Playlist', TIMESTAMPS], - ['PlaceOS.Model.Playlist.Item', TIMESTAMPS], - ['PlaceOS.Model.Playlist.ItemSchedule', TIMESTAMPS], - ['PlaceOS.Model.Playlist.Revision', TIMESTAMPS], - ['PlaceOS.Model.Repository', TIMESTAMPS], - ['PlaceOS.Model.SamlAuthentication', TIMESTAMPS], - ['PlaceOS.Model.Settings', TIMESTAMPS], - ['PlaceOS.Model.Shortener', [...TIMESTAMPS, 'valid_from', 'valid_until']], - ['PlaceOS.Model.SignagePlugin', TIMESTAMPS], - ['PlaceOS.Model.Storage', TIMESTAMPS], - ['PlaceOS.Model.Trigger', TIMESTAMPS], - ['PlaceOS.Model.Trigger.Conditions.TimeDependent', ['time']], - ['PlaceOS.Model.TriggerInstance', TIMESTAMPS], - ['PlaceOS.Model.Upload', TIMESTAMPS], - ['PlaceOS.Model.User.AdminMetadataResponse', ['created_at', 'last_login']], - ['PlaceOS.Model.User.AdminResponse', ['created_at', 'last_login']], - ['PlaceOS.Model.User.PublicMetadataResponse', ['created_at', 'last_login']], - // The staff API. Its models are `ModelWithAutoKey`, which has the epoch `Timestamps`. ['PlaceOS.Model.Attendee', TIMESTAMPS], ['PlaceOS.Model.Booking', TIMESTAMPS], + ['PlaceOS.Model.ControlSystem', [...TIMESTAMPS, 'signage_last_seen']], ['PlaceOS.Model.EventMetadata', TIMESTAMPS], ['PlaceOS.Model.Guest', TIMESTAMPS], + ['PlaceOS.Model.History', ['created_at']], ['PlaceOS.Model.Survey', TIMESTAMPS], ['PlaceOS.Model.Survey.Answer', TIMESTAMPS], ['PlaceOS.Model.Survey.Invitation', TIMESTAMPS], ['PlaceOS.Model.Survey.Question', TIMESTAMPS], + ['PlaceOS.Model.User.AdminResponse', ['created_at', 'last_login']], + ['PlaceOS.Model.Zone', TIMESTAMPS], // PlaceOS/calendar: `Time::EpochConverter` on a `Time?`. ['PlaceCalendar.Event', ['event_end']], - ['PlaceOS.Model.User.PublicResponse', ['created_at', 'last_login']], - ['PlaceOS.Model.Zone', TIMESTAMPS], ]); /** * The `date-time` fields that really are RFC 3339 strings: models with `PgORM::Timestamps`, and - * `Time` fields without a converter. With `EPOCH_FIELDS`, each `date-time` field of a named schema - * must be in one list, so that a new field gets a decision. + * `Time` fields without a converter. Each `date-time` field of a named schema must be in this list + * or in the epoch list of its API, so that a new field gets a decision. */ const STRING_TIME_FIELDS: ReadonlyMap = new Map([ ['PlaceOS.Api.BuildMonitor.TaskStatus', ['timestamp']], @@ -347,6 +316,8 @@ interface ApiSource { /** The path from `dir` to `src/core`. */ readonly core: string; readonly aliases: ReadonlyMap; + /** The `date-time` fields of the document that are Unix time in seconds, by schema. */ + readonly epoch_fields: ReadonlyMap; } const APIS: readonly ApiSource[] = [ @@ -357,6 +328,7 @@ const APIS: readonly ApiSource[] = [ name_prefix: '', core: '../core', aliases: TYPE_ALIASES, + epoch_fields: new Map(), }, { repository: 'PlaceOS/staff-api', @@ -365,6 +337,7 @@ const APIS: readonly ApiSource[] = [ name_prefix: 'staff.', core: '../../core', aliases: new Map(), + epoch_fields: STAFF_EPOCH_FIELDS, }, ]; @@ -443,7 +416,7 @@ async function generate(api: ApiSource, check: boolean): Promise { assert(spec_name !== undefined, `the schema ${name} exists`); const imports: Imports = { combinators: new Set(), schemas: new Set() }; const node = asNode(field(schemas, spec_name), spec_name); - const code = emitNamedSchema(schemas, spec_name, node, imports); + const code = emitNamedSchema(api, schemas, spec_name, node, imports); named.set(name, { code, imports }); pending.push(...imports.schemas); } @@ -699,12 +672,13 @@ function sameSignature(a: OperationPlan, b: OperationPlan): boolean { /** The emit of a named schema. It applies the time field patches to its properties. */ function emitNamedSchema( + api: ApiSource, schemas: SpecNode, spec_name: string, node: SpecNode, imports: Imports, ): string { - const epoch_fields = new Set(EPOCH_FIELDS.get(spec_name) ?? []); + const epoch_fields = new Set(api.epoch_fields.get(spec_name) ?? []); const string_fields = new Set(STRING_TIME_FIELDS.get(spec_name) ?? []); const name = schemaTypeName(spec_name); const description = optionalString(field(node, 'description'), spec_name) ?? ''; diff --git a/src/generated/schemas.ts b/src/generated/schemas.ts index 24209c149..fa9c5b223 100644 --- a/src/generated/schemas.ts +++ b/src/generated/schemas.ts @@ -66,9 +66,7 @@ export type AlertAlertTypeInput = Input; export const AlertAlertType: Schema = AlertAlertTypeSchema; const AlertDashboardSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -172,7 +170,6 @@ export const TriggerConditionsTimeDependentType: Schema< const TriggerConditionsTimeDependentSchema = /* @__PURE__ */ object({ type: /* @__PURE__ */ nullable(TriggerConditionsTimeDependentType), - /** Unix time in seconds. */ time: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), cron: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -200,9 +197,7 @@ export const TriggerConditions: Schema {} export const ApiKey: Schema = ApiKeySchema; const AuthoritySchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -298,7 +288,6 @@ export const UserWorktimePreference: Schema = ApiKeysResponseSchema; const AssetSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), identifier: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), serial_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -410,9 +395,7 @@ export interface AssetInput extends Input {} export const Asset: Schema = AssetSchema; const AssetCategorySchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -426,9 +409,7 @@ export interface AssetCategoryInput extends Input {} export const AssetCategory: Schema = AssetCategorySchema; const AssetPurchaseOrderSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), purchase_order_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), invoice_number: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -446,9 +427,7 @@ export const AssetPurchaseOrder: Schema {} export const AssetType: Schema = AssetTypeSchema; const BrokerSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), /** The number of the enum: 0 certificate, 1 no_auth, 2 user_password. */ auth_type: /* @__PURE__ */ nullable(/* @__PURE__ */ literal([0, 1, 2])), @@ -532,9 +509,7 @@ export const BuildMonitorTaskStatus: Schema = SystemTriggersControlSystemDetailsSchema; const TriggerInstanceSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), enabled: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), triggered: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), @@ -845,9 +818,7 @@ export interface TriggerInstanceInput extends Input = TriggerInstanceSchema; const TriggerSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -868,9 +839,7 @@ export const Trigger: Schema = TriggerSchema; const ZoneSchema = /* @__PURE__ */ object( { - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -933,9 +902,7 @@ export const ModulesDriverDetails: Schema = PlaylistScheduleSchema; const PlaylistSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1041,9 +1005,7 @@ export const PlaylistItemMediaType: Schema = SignagePluginPluginTypeSchema; const SignagePluginSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1135,9 +1095,7 @@ export const SignageTemplateSystemTemplate: Schema< const ControlSystemSchema = /* @__PURE__ */ object( { - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1170,7 +1128,6 @@ const ControlSystemSchema = /* @__PURE__ */ object( sign_width: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), playlists: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), signage: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), - /** Unix time in seconds. */ signage_last_seen: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), playlist_item_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), space_config: /* @__PURE__ */ nullable(/* @__PURE__ */ record(/* @__PURE__ */ json())), @@ -1211,9 +1168,7 @@ const DoorkeeperApplicationSchema = /* @__PURE__ */ object({ subsystems: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), uid: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), }); export interface DoorkeeperApplication extends Output {} @@ -1236,9 +1191,7 @@ export const DriverUpdateInfo: Schema = DriverUpdateInfoSchema; const DriverSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1276,15 +1229,12 @@ export type DriverRoleInput = Input; export const DriverRole: Schema = DriverRoleSchema; const EdgeSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), api_key_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - /** Unix time in seconds. */ last_seen: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), online: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1346,14 +1296,11 @@ export const EdgeHealth: Schema = EdgeHealthSchema; const EdgeKeyResponseSchema = /* @__PURE__ */ object( { - /** Unix time in seconds. */ created_at: /* @__PURE__ */ integer(), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ integer(), name: /* @__PURE__ */ string(), description: /* @__PURE__ */ string(), user_id: /* @__PURE__ */ string(), - /** Unix time in seconds. */ last_seen: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), online: /* @__PURE__ */ boolean(), x_api_key: /* @__PURE__ */ string(), @@ -1460,7 +1407,6 @@ export const GroupInvitation: Schema = Gr const UserPublicResponseSchema = /* @__PURE__ */ object( { - /** Unix time in seconds. */ created_at: /* @__PURE__ */ integer(), name: /* @__PURE__ */ string(), nickname: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1479,7 +1425,6 @@ const UserPublicResponseSchema = /* @__PURE__ */ object( groups: /* @__PURE__ */ array(/* @__PURE__ */ string()), locatable: /* @__PURE__ */ boolean(), login_count: /* @__PURE__ */ integer(), - /** Unix time in seconds. */ last_login: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), work_preferences: /* @__PURE__ */ array(UserWorktimePreference), work_overrides: /* @__PURE__ */ record(UserWorktimePreference), @@ -1642,7 +1587,6 @@ const HistorySchema = /* @__PURE__ */ object({ user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), user_email: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), context: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), }); export interface History extends Output {} @@ -1705,9 +1649,7 @@ export const ImageGenProviderCapabilities: Schema< > = ImageGenProviderCapabilitiesSchema; const JsonSchemaSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -1729,9 +1671,7 @@ export interface KickReasonInput extends Input {} export const KickReason: Schema = KickReasonSchema; const LdapAuthenticationSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), port: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), @@ -2051,9 +1991,7 @@ export type MqttMqttAclInput = Input; export const MqttMqttAcl: Schema = MqttMqttAclSchema; const OauthAuthenticationSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), client_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2151,9 +2089,7 @@ export const PlaylistApprover: Schema = PlaylistApproverSchema; const PlaylistItemScheduleSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), playlist_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), item_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2166,9 +2102,7 @@ export const PlaylistItemSchedule: Schema; export const RepositoryType: Schema = RepositoryTypeSchema; const RepositorySchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2286,9 +2218,7 @@ export const RootSourceResyncStatus: Schema; export const ShortUrlFormat: Schema = ShortUrlFormatSchema; const ShortenerSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), uri: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2381,9 +2307,7 @@ const ShortenerSchema = /* @__PURE__ */ object({ user_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), redirect_count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), enabled: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), - /** Unix time in seconds. */ valid_from: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ valid_until: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2782,9 +2706,7 @@ export type StorageTypeInput = Input; export const StorageType: Schema = StorageTypeSchema; const StorageSchema = /* @__PURE__ */ object({ - /** Unix time in seconds. */ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), - /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), storage_type: /* @__PURE__ */ nullable(StorageType), bucket_name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -2839,9 +2761,7 @@ export const UploadPermissions: Schema = UserJwtSchema; const UserPublicMetadataResponseSchema = /* @__PURE__ */ object( { - /** Unix time in seconds. */ created_at: /* @__PURE__ */ integer(), name: /* @__PURE__ */ string(), nickname: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -3052,7 +2969,6 @@ const UserPublicMetadataResponseSchema = /* @__PURE__ */ object( groups: /* @__PURE__ */ array(/* @__PURE__ */ string()), locatable: /* @__PURE__ */ boolean(), login_count: /* @__PURE__ */ integer(), - /** Unix time in seconds. */ last_login: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), work_preferences: /* @__PURE__ */ array(UserWorktimePreference), work_overrides: /* @__PURE__ */ record(UserWorktimePreference), From 5f7c92e7338e2a7cbbc06c3a95db3520da2db783 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Thu, 19 Nov 2026 10:11:14 +1100 Subject: [PATCH 20/29] fix: patch string fields and missing read-only fields in the documents The API documents type some string fields as object and leave out read-only fields that the server sends. The client dropped those fields. The generator now types the string fields and adds the missing fields. Each patch asserts the document shape, so the generator stops when upstream fixes it (PlaceOS/rest-api#470). Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +++ scripts/generate.ts | 96 ++++++++++++++++++++++++++++++++++ src/generated/schemas.ts | 20 ++++--- src/generated/staff/schemas.ts | 20 ++++++- test/client.test.ts | 16 +++++- 5 files changed, 148 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index acc61c130..f311a80c2 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,13 @@ The generator changes some parts of the document. Each change has a comment in each new field gets a decision. - **Enum numbers.** The server sends some enums as numbers, for example `Driver.role` (`99` is `logic`). The document gives their names. The generator changes these fields to the numbers. +- **String fields.** The document says `object` for some fields that the server sends as strings, + for example `Zone.timezone` (`"Australia/Melbourne"`) and the `scopes` of an API key. The + generator changes these fields to strings. +- **Missing fields.** The document does not have the fields that a request cannot set, for example + `AssetType.asset_count` and `Guest.checked_in`. The generator adds these fields. They are `null` + when the server does not send them. The generator stops when the document gets one of these + fields, so that the patch can go. - **Required fields in a request.** The document marks a field as required when the server always sends it. The server can have a default for the same field in a request. Thus each field of a request body is optional, and the server checks the body. Path and query parameters keep the diff --git a/scripts/generate.ts b/scripts/generate.ts index 4f1736731..74dfa7094 100644 --- a/scripts/generate.ts +++ b/scripts/generate.ts @@ -137,6 +137,70 @@ function valueEnum(spec_name: string, values: Readonly>): return { spec_name, values }; } +/** + * Fields that the document gives as `type: object` without properties, because the spec + * generator of the server does not know their Crystal type. The server sends a string: + * `Time::Location` as its name, `URI` as text, `UserJWT::Scope` as its name, and `JSON::Any` with + * `StringConverter` as JSON text. `string` replaces the object, and `array` replaces the object + * items of an array. Each entry comes from the source of PlaceOS/models and PlaceOS/rest-api. + */ +const STRING_FIELDS: ReadonlyMap>> = new Map([ + ['PlaceOS.Api.ApiKeys.Response', { scopes: 'array' }], + ['PlaceOS.Api.Cluster.NodeStatus', { uri: 'string' }], + ['PlaceOS.Model.ApiKey', { scopes: 'array' }], + ['PlaceOS.Model.ControlSystem', { timezone: 'string' }], + ['PlaceOS.Model.Driver', { json_schema: 'string' }], + ['PlaceOS.Model.UserJWT', { scope: 'array' }], + ['PlaceOS.Model.Zone', { timezone: 'string' }], +]); + +/** + * Fields that the server sends, but the document does not have. The spec generator of the server + * leaves out the fields that a request cannot set: an attribute with `ignore_deserialize`, and a + * getter with a `JSON::Field`. Each field is a schema of the document, from the source of + * PlaceOS/models. It is optional, so it is `null` when the server does not send it. The fields + * that refer to their own schema, such as `Booking.linked_bookings`, are not here, because the + * schemas cannot have a cycle. + */ +const ASSET_COUNT = { + type: 'integer', + format: 'Int64', + description: 'The number of assets of this type.', +}; +const METADATA = { + type: 'object', + additionalProperties: { $ref: '#/components/schemas/PlaceOS.Model.Metadata.Interface' }, + description: 'The metadata of the user, by name.', +}; +const ADDED_FIELDS: ReadonlyMap>> = new Map([ + ['PlaceOS.Model.AssetType', { asset_count: ASSET_COUNT }], + [ + 'PlaceOS.Model.Booking', + { + booked_by_id: { type: 'string' }, + email_digest: { type: 'string', description: 'The digest of `user_email`.' }, + booked_by_email_digest: { + type: 'string', + description: 'The digest of `booked_by_email`.', + }, + created: { type: 'integer', format: 'Int64', description: 'Unix time in seconds.' }, + current_state: { $ref: '#/components/schemas/PlaceOS.Model.Booking.State' }, + }, + ], + [ + 'PlaceOS.Model.Guest', + { + checked_in: { type: 'boolean' }, + visit_expected: { type: 'boolean' }, + booking: { $ref: '#/components/schemas/PlaceOS.Model.Booking' }, + event: { $ref: '#/components/schemas/PlaceCalendar.Event' }, + event_metadata: { description: 'The metadata of the event, as JSON.' }, + }, + ], + ['PlaceOS.Model.User.AdminMetadataResponse', { associated_metadata: METADATA }], + ['PlaceOS.Model.User.PublicMetadataResponse', { associated_metadata: METADATA }], +]); + /** Operations that send JSON, but have no response schema in the document. */ const JSON_RESPONSE_OPERATIONS: ReadonlySet = new Set([ 'PlaceOS::Api::Modules_execute', @@ -872,6 +936,8 @@ function emitObject( const is_time = isDateTime(property); const value_enum_field = time_fields === null ? undefined : VALUE_ENUM_FIELDS.get(time_fields.spec_name)?.[key]; + const string_field = + time_fields === null ? undefined : STRING_FIELDS.get(time_fields.spec_name)?.[key]; if (time_fields === null) { expression = emitSchema(schemas, property, imports, depth + 1); } else if (value_enum_field !== undefined) { @@ -905,6 +971,24 @@ function emitObject( const names = Object.entries(value_enum_field.values).map(([n, v]) => `${v} ${n}`); const separator = description.length > 0 ? '\n\n' : ''; description = `${description}${separator}The number of the enum: ${names.join(', ')}.`; + } else if (string_field !== undefined) { + const subject = `${time_fields.spec_name}.${key}`; + const isBare = (node: SpecNode) => isOnly(node, { type: 'object' }); + const isBareArray = (node: SpecNode) => { + const items = field(node, 'items'); + return isOnly(node, { type: 'array', items }) && isRecord(items) && isBare(items); + }; + assertPatchedShape(property, string_field === 'string' ? isBare : isBareArray, subject); + imports.combinators.add('string'); + expression = 'string()'; + if (string_field === 'array') { + imports.combinators.add('array'); + expression = 'array(string())'; + } + if (isNullable(property)) { + imports.combinators.add('nullable'); + expression = `nullable(${expression})`; + } } else if (time_fields.epoch_fields.has(key)) { const subject = `${time_fields.spec_name}.${key}`; const date_time = { type: 'string', format: 'date-time' }; @@ -927,7 +1011,19 @@ function emitObject( if (time_fields !== null) { const keys = [...time_fields.epoch_fields, ...time_fields.string_fields]; keys.push(...Object.keys(VALUE_ENUM_FIELDS.get(time_fields.spec_name) ?? {})); + keys.push(...Object.keys(STRING_FIELDS.get(time_fields.spec_name) ?? {})); for (const key of keys) assert(Object.hasOwn(properties, key), `${key} is a property`); + const added = Object.entries(ADDED_FIELDS.get(time_fields.spec_name) ?? {}); + for (const [key, property] of added) { + // When the document gets the field, the patch must go. + const subject = `${time_fields.spec_name}.${key}`; + assert(!Object.hasOwn(properties, key), `${subject} is not in the document`); + const description = optionalString(field(property, 'description'), key) ?? ''; + const code = emitSchema(schemas, property, imports, depth + 1); + const expression = code === 'json()' ? code : `nullable(${code})`; + if (code !== 'json()') imports.combinators.add('nullable'); + fields.push(`${docComment(description, 4)}${propertyKey(key)}: ${expression},`); + } } imports.combinators.add('object'); const required_list = required.length > 0 ? `, ${JSON.stringify(required)}` : ''; diff --git a/src/generated/schemas.ts b/src/generated/schemas.ts index fa9c5b223..4dd9c195c 100644 --- a/src/generated/schemas.ts +++ b/src/generated/schemas.ts @@ -231,7 +231,7 @@ const ApiKeySchema = /* @__PURE__ */ object({ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - scopes: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ json())), + scopes: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), permissions: /* @__PURE__ */ nullable(UserJwtPermissions), secret: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), expires_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), @@ -343,7 +343,7 @@ const ApiKeysResponseSchema = /* @__PURE__ */ object( id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), name: /* @__PURE__ */ string(), description: /* @__PURE__ */ string(), - scopes: /* @__PURE__ */ array(/* @__PURE__ */ json()), + scopes: /* @__PURE__ */ array(/* @__PURE__ */ string()), permissions: /* @__PURE__ */ nullable(UserJwtPermissions), user_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), @@ -436,6 +436,8 @@ const AssetTypeSchema = /* @__PURE__ */ object({ images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), category_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** The number of assets of this type. */ + asset_count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), }); export interface AssetType extends Output {} export interface AssetTypeInput extends Input {} @@ -709,7 +711,7 @@ export const Load: Schema = LoadSchema; const ClusterNodeStatusSchema = /* @__PURE__ */ object( { id: /* @__PURE__ */ string(), - uri: /* @__PURE__ */ json(), + uri: /* @__PURE__ */ string(), load: /* @__PURE__ */ nullable(Load), status: /* @__PURE__ */ nullable(CoreStatus), }, @@ -851,7 +853,7 @@ const ZoneSchema = /* @__PURE__ */ object( count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), triggers: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), playlists: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), @@ -1111,7 +1113,7 @@ const ControlSystemSchema = /* @__PURE__ */ object( approval: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), security_groups: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), - timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), support_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), timetable_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), camera_snapshot_urls: /* @__PURE__ */ nullable( @@ -1195,7 +1197,7 @@ const DriverSchema = /* @__PURE__ */ object({ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), name: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), description: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - json_schema: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + json_schema: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), default_uri: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), default_port: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), /** The number of the enum: 0 ssh, 1 device, 2 service, 3 websocket, 99 logic. */ @@ -2883,6 +2885,8 @@ const UserAdminMetadataResponseSchema = /* @__PURE__ */ object( photo_upload_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), subsystem_access: /* @__PURE__ */ array(/* @__PURE__ */ string()), + /** The metadata of the user, by name. */ + associated_metadata: /* @__PURE__ */ nullable(/* @__PURE__ */ record(MetadataInterface)), }, [ 'created_at', @@ -2940,7 +2944,7 @@ const UserJwtSchema = /* @__PURE__ */ object( exp: /* @__PURE__ */ integer(), aud: /* @__PURE__ */ string(), sub: /* @__PURE__ */ string(), - scope: /* @__PURE__ */ array(/* @__PURE__ */ json()), + scope: /* @__PURE__ */ array(/* @__PURE__ */ string()), u: UserJwtMetadata, }, ['iss', 'iat', 'exp', 'aud', 'sub', 'scope', 'u'], @@ -2975,6 +2979,8 @@ const UserPublicMetadataResponseSchema = /* @__PURE__ */ object( authority_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), photo_upload_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** The metadata of the user, by name. */ + associated_metadata: /* @__PURE__ */ nullable(/* @__PURE__ */ record(MetadataInterface)), }, [ 'created_at', diff --git a/src/generated/staff/schemas.ts b/src/generated/staff/schemas.ts index a55271b5d..da53c824e 100644 --- a/src/generated/staff/schemas.ts +++ b/src/generated/staff/schemas.ts @@ -98,6 +98,8 @@ const AssetTypeSchema = /* @__PURE__ */ object({ images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), category_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** The number of assets of this type. */ + asset_count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), }); export interface AssetType extends Output {} export interface AssetTypeInput extends Input {} @@ -134,7 +136,7 @@ const ControlSystemSchema = /* @__PURE__ */ object( approval: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), security_groups: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), - timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), support_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), timetable_url: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), camera_snapshot_urls: /* @__PURE__ */ nullable( @@ -465,6 +467,14 @@ const BookingSchema = /* @__PURE__ */ object({ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + booked_by_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** The digest of `user_email`. */ + email_digest: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** The digest of `booked_by_email`. */ + booked_by_email_digest: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), + /** Unix time in seconds. */ + created: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + current_state: /* @__PURE__ */ nullable(BookingState), }); export interface Booking extends Output {} export interface BookingInput extends Input {} @@ -722,6 +732,12 @@ const GuestSchema = /* @__PURE__ */ object({ created_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), /** Unix time in seconds. */ updated_at: /* @__PURE__ */ nullable(/* @__PURE__ */ integer()), + checked_in: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + visit_expected: /* @__PURE__ */ nullable(/* @__PURE__ */ boolean()), + booking: /* @__PURE__ */ nullable(Booking), + event: /* @__PURE__ */ nullable(PlaceCalendarEvent), + /** The metadata of the event, as JSON. */ + event_metadata: /* @__PURE__ */ json(), }); export interface Guest extends Output {} export interface GuestInput extends Input {} @@ -762,7 +778,7 @@ const ZoneSchema = /* @__PURE__ */ object( count: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), capacity: /* @__PURE__ */ nullable(/* @__PURE__ */ integer('Int32')), map_id: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), - timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ json()), + timezone: /* @__PURE__ */ nullable(/* @__PURE__ */ string()), triggers: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), images: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), playlists: /* @__PURE__ */ nullable(/* @__PURE__ */ array(/* @__PURE__ */ string())), diff --git a/test/client.test.ts b/test/client.test.ts index a0ff6c44c..d447fbcd1 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -22,7 +22,7 @@ import { string, } from '../src/core/schema.ts'; import { join } from 'node:path'; -import { zones } from '../src/index.ts'; +import { asset_types, zones } from '../src/index.ts'; interface Sent { readonly url: string; @@ -381,12 +381,13 @@ describe('call errors', () => { }); describe('generated operations', () => { - test('zones.show reads the epoch timestamps that the server sends', async () => { + test('zones.show reads the epoch timestamps and the timezone that the server sends', async () => { const { fetch, sent } = fakeFetch(() => jsonResponse({ id: 'zone-1', name: 'Level 1', created_at: 1_700_000_000, + timezone: 'Australia/Melbourne', update_systems: false, }), ); @@ -400,6 +401,17 @@ describe('generated operations', () => { expect(result.value.data.created_at).toBe(1_700_000_000); expect(result.value.data.name).toBe('Level 1'); expect(result.value.data.tags).toBeNull(); + // The document says `object`. The patch makes it a string. + const timezone: string | null = result.value.data.timezone; + expect(timezone).toBe('Australia/Melbourne'); + }); + + test('asset_types.show reads asset_count, which the document does not have', async () => { + const { fetch } = fakeFetch(() => + jsonResponse({ id: 'type-1', name: 'Desk', category_id: 'cat-1', asset_count: 3 }), + ); + const result = await asset_types.show({ id: 'type-1' }, { client: clientWith(fetch) }); + expect(result.ok && result.value.data.asset_count).toBe(3); }); }); From 435ecf15cd3387c82914707eda50011779413962 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Thu, 19 Nov 2026 10:28:27 +1100 Subject: [PATCH 21/29] fix: address the review of the 7.x client - With an API key, a call does not follow a redirect, because fetch keeps X-API-Key on a redirect to another origin. short_url.redirect is not generated. - Path parameters cannot be . or .. - mockReply gives next(), so it is a valid double of a paged operation. - The rest-api time fields get the "Unix time in seconds." note again. - plan.path is escaped in the generated code. - The regenerate workflow runs on the branch of the run, with a branch prefix for each base. open_prs skips forks and stops on a full list. - The migration tool gives findings for updateMetadata with a method, unnamed spreads and methods in mock factories, doubles in variables, and unmapped names on a namespace import. The CLI checks the TypeScript version and can use the TypeScript next to the tool. - An aborted call logs at debug. The mock 404 log is in the default not-found handler, as in 6.x. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/regenerate.yml | 5 +- README.md | 26 ++++++-- oauth-resp.html | 2 +- scripts/generate.ts | 92 +++++++++++++++++++++------ scripts/regenerate-pr.sh | 27 ++++++-- scripts/v1-map.ts | 16 ++++- src/compat/http-mock.ts | 8 ++- src/compat/result.ts | 10 ++- src/core/client.ts | 13 +++- src/core/log.ts | 2 +- src/generated/operations/short-url.ts | 27 -------- src/generated/schemas.ts | 84 ++++++++++++++++++++++++ src/migrate/cli.ts | 50 +++++++++++---- src/migrate/migrate.ts | 63 +++++++++++++++++- src/migrate/v1-map.ts | 2 +- test/client.test.ts | 24 +++++++ test/compat.test.ts | 5 +- test/migrate.test.ts | 38 ++++++++++- 18 files changed, 406 insertions(+), 88 deletions(-) diff --git a/.github/workflows/regenerate.yml b/.github/workflows/regenerate.yml index 3bacdb017..9bdd0c5a6 100644 --- a/.github/workflows/regenerate.yml +++ b/.github/workflows/regenerate.yml @@ -1,6 +1,9 @@ # Regenerates the client from the API documents on master each day. A change opens a PR, and the # older regeneration PRs close. See scripts/regenerate-pr.sh. # +# The schedule runs on the default branch. A manual run regenerates the branch that it runs on, such +# as `next`, and opens the PR to that branch. +# # A PR that `GITHUB_TOKEN` opens does not start the CI checks, so the script runs the checks and # puts the results in the PR. Set the secret `REGENERATE_TOKEN` (a token with `contents` and # `pull-requests` write access) to open the PRs as that token, and then the checks start too. @@ -28,7 +31,6 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: master token: ${{ secrets.REGENERATE_TOKEN || github.token }} - uses: oven-sh/setup-bun@v2 @@ -40,3 +42,4 @@ jobs: - run: scripts/regenerate-pr.sh env: GH_TOKEN: ${{ secrets.REGENERATE_TOKEN || github.token }} + BASE: ${{ github.ref_name }} diff --git a/README.md b/README.md index f311a80c2..1ec79591d 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,8 @@ Other parts of the session: - A trusted application with the `implicit` grant uses the code with PKCE. - The frame login checks the `state`. It needs the `oauth-resp.html` of 7.x. - The session removes `x-api-key` from the URL after it reads it. +- With an API key, a call does not follow a redirect. It gets a `network` error. On a redirect to + another origin, `fetch` removes `Authorization`, but it keeps `X-API-Key`. - After a refused refresh token, the login continues immediately. - A refusal on the consent page (`error=access_denied` with the state of this client) stops the login with `authorization_denied`. 6.x sent the user to the authorize page again. @@ -382,7 +384,7 @@ window.debug = true; | `error` | A failure without an answer, such as a timeout. | `console.error` | | `warn` | A refusal or a drop, such as a 404 or a closed socket. | `console.warn` | | `info` | A step, such as a new token or a connected socket. | `console.info` | -| `debug` | A detail, such as each call or each value change. | `console.debug` | +| `debug` | A detail, such as each call or an aborted call. | `console.debug` | | `print` | A line without a level, such as a field of the authority. | `console.log` | | `group` | Starts a group of the entries that follow. | `console.group` | | `group_end` | Ends the group. | `console.groupEnd` | @@ -433,8 +435,9 @@ The generator changes some parts of the document. Each change has a comment in - **Time fields.** The staff-api document says `date-time` for some fields that the server sends as Unix time in seconds, for example `created_at` on most models. The generator changes these fields to integers. The list comes from the source of PlaceOS/models. The rest-api document has - the correct types. The generator stops if it finds a `date-time` field that is not in a list, so - each new field gets a decision. + the correct types. In both clients, the fields of the list have the note "Unix time in seconds.", + because `integer` does not give the unit. The generator stops if it finds a `date-time` field + that is not in a list, so each new field gets a decision. - **Enum numbers.** The server sends some enums as numbers, for example `Driver.role` (`99` is `logic`). The document gives their names. The generator changes these fields to the numbers. - **String fields.** The document says `object` for some fields that the server sends as strings, @@ -462,7 +465,8 @@ The generator changes some parts of the document. Each change has a comment in - **Responses without a schema.** The data is a `Uint8Array` with the raw body. `systems.execute`, `modules.execute` and `modules.stateValue` are exceptions: they return a `JsonValue`. - **WebSocket endpoints** (`systems/control`, `webrtc/signaller` and others) are not in the - client. + client. Also `short_url/{id}/redirect` is not in the client: the useful part of its answer is the + `Location` header, which is for a browser. ## Change the generated code @@ -486,7 +490,8 @@ Each day, the `Regenerate` workflow regenerates the client from the API document of the checks. It also closes the older regeneration PRs, because the new one has their changes. When master matches the documents again, it closes all of them. Each run deletes the regeneration branches that have no open PR, such as the branch of a merged PR. `DRY_RUN=1 -scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. +scripts/regenerate-pr.sh` (from the root of the repository) shows what it would do. A manual run +of the workflow on another branch, such as `next`, regenerates that branch and opens the PR to it. The commit of a regeneration PR is a `fix`, so its merge publishes a patch release. Before the merge, change the commit message to a `feat` for new operations, or add a `BREAKING CHANGE:` footer @@ -529,6 +534,13 @@ npx -p @placeos/ts-client@next placeos-migrate src # Shows the changes npx -p @placeos/ts-client@next placeos-migrate --write src # Writes the changes. ``` +The tool needs TypeScript 4.9 to 6.x, because TypeScript 7 has no JavaScript API. If the project +has TypeScript 7, or no TypeScript, give the tool TypeScript 5: + +```sh +npx -p typescript@5 -p @placeos/ts-client@next placeos-migrate src +``` + The tool makes these changes: - A call of a 6.x REST function becomes the 7.x operation. `.then(orThrow)` gives the data, and an @@ -579,6 +591,10 @@ it keeps its 6.x import, so the compiler also shows it. These uses are: - a `vi.mock` without a factory or `{ spy: true }`: its 7.x functions give `undefined`, and `.then(orThrow)` fails; - a `jest.mock` factory with 6.x functions; +- in a `vi.mock` factory, a 6.x function that is a method, and a spread without a name, such as + `...(await importOriginal())`; +- a test double in a variable, such as `const spy = vi.mocked(showZone)`: the tool changes the + function, but not the calls on `spy`; - an argument that has no place in 7.x, and an argument with side effects that 7.x uses two times. On a copy of backoffice, 329 of the 399 tests pass after the tool. 6.x passes 394. The other tests diff --git a/oauth-resp.html b/oauth-resp.html index 34a891131..814f1331b 100644 --- a/oauth-resp.html +++ b/oauth-resp.html @@ -7,7 +7,7 @@ diff --git a/scripts/regenerate-pr.sh b/scripts/regenerate-pr.sh index 834239bea..2c5bca3e8 100755 --- a/scripts/regenerate-pr.sh +++ b/scripts/regenerate-pr.sh @@ -35,17 +35,22 @@ remote() { # The open regeneration PRs: " " on each line. A PR from a fork is not one, even # when its branch has the prefix. The filter runs after `--limit`, so a full list stops the script: # a regeneration PR can be out of the list. +# +# Bash does not apply `set -e` in a command substitution, such as `prs="$(open_prs)"`. So each step +# returns on a failure. Else a failure of `gh` gives an empty list, and the cleanup deletes the +# branches of open PRs. open_prs() { - local prs + local prs count prs="$(gh pr list --state open --base "$BASE" --limit "$OPEN_PRS_MAX" \ - --json number,headRefName,isCrossRepository)" - if [ "$(jq length <<<"$prs")" -ge "$OPEN_PRS_MAX" ]; then + --json number,headRefName,isCrossRepository)" || return 1 + count="$(jq length <<<"$prs")" || return 1 + if [ "$count" -ge "$OPEN_PRS_MAX" ]; then echo "$OPEN_PRS_MAX or more open PRs to $BASE. Close some, then run again." >&2 exit 1 fi jq -r --arg prefix "$BRANCH_PREFIX" '.[] | select((.isCrossRepository | not) and (.headRefName | startswith($prefix))) - | "\(.number) \(.headRefName)"' <<<"$prs" + | "\(.number) \(.headRefName)"' <<<"$prs" || return 1 } # Closes each open regeneration PR except the one on branch $1, with the comment $2. diff --git a/src/auth/session.ts b/src/auth/session.ts index c6515dd5a..ef18ae3b5 100644 --- a/src/auth/session.ts +++ b/src/auth/session.ts @@ -314,6 +314,11 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { let halted: AuthError | null = null; /** `logout` adds one. A token request from an earlier epoch drops its tokens. */ let epoch = 0; + /** + * The logouts whose request waits. Then `authorize` starts no attempt, because a refresh in the + * new epoch could store tokens after the logout removes them. + */ + let logouts_pending = 0; const listeners = new Set<(status: AuthStatus) => void>(); const session: AuthSession = { @@ -359,18 +364,25 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { } function authorize(): Promise> { - // Check and set in one synchronous step, so that callers share one attempt. + if (logouts_pending > 0) { + return Promise.resolve({ ok: false, error: { kind: 'logged_out' } }); + } + // Check and set in one synchronous step, so that callers share one attempt. The attempt + // starts in a microtask: a listener of a status that it sets can call `authorize` again. if (authorizing !== null) return authorizing; - const attempt = runAuthorize().finally(() => { - authorizing = null; - }); + // A logout during this attempt ends it. Each step checks the epoch after it waits. + const attempt_epoch = epoch; + const attempt = Promise.resolve() + .then(() => runAuthorize(attempt_epoch)) + .finally(() => { + authorizing = null; + }); authorizing = attempt; return attempt; } - async function runAuthorize(): Promise> { - // A logout during this attempt ends it. Each step checks the epoch after it waits. - const attempt_epoch = epoch; + async function runAuthorize(attempt_epoch: number): Promise> { + if (epoch !== attempt_epoch) return failed({ kind: 'logged_out' }); // Read the redirect first, before any wait, so its tokens leave the URL also when the // authority does not load. const redirect_outcome = readRedirectParams(); @@ -486,7 +498,9 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { /** * Tries the credentials that need no action of the user: the current credential, a code from - * a redirect, and the refresh token. Returns `null` if none gives a credential. + * a redirect, and the refresh token. Gives a credential, or a failure that ends the attempt, + * such as a refused code. Gives `null` when none gives a credential, also after a refused + * refresh token. Then the attempt continues with the grant of the configuration. */ async function tokenFromKnownCredentials( attempt_epoch: number, @@ -519,13 +533,26 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { const refresh_token = readTokens().refresh_token; if (refresh_token !== null) { log.debug('refreshing the access token'); - const result = await requestTokens(attempt_epoch, { - grant_type: 'refresh_token', - client_id, - redirect_uri: config.redirect_uri, - refresh_token, - }); + // Trusted tabs share the tokens. Another tab can refresh or log out while this request + // waits. Then the result of this request is old, and the shared tokens are the answer. + const shared = () => readTokens().refresh_token === refresh_token; + const result = await requestTokens( + attempt_epoch, + { + grant_type: 'refresh_token', + client_id, + redirect_uri: config.redirect_uri, + refresh_token, + }, + shared, + ); if (result.ok) return signedIn(result.value); + if (!shared()) { + const current = currentCredential(); + if (current !== null) return signedIn(current); + // A different tab logged out. A grant of this tab must not log the user in again. + return failed({ kind: 'logged_out' }); + } if (!isRefusal(result.error)) return failed(result.error); // Keep a refresh token after a network error, but not after the server refused it. log.warn('the server refused the refresh token'); @@ -534,10 +561,14 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { return null; } - /** Sends a grant to the token endpoint and keeps the tokens of the response. */ + /** + * Sends a grant to the token endpoint and keeps the tokens of the response. If `current` gives + * `false` when the response comes, the tokens are old: it keeps none and gives `logged_out`. + */ async function requestTokens( attempt_epoch: number, params: Readonly>, + current: () => boolean = () => true, ): Promise> { const fetched = await fetchBody( environment.fetch, @@ -550,11 +581,15 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams(params).toString(), + // A 307 or a 308 sends the body again, with the secrets of the grant. The token + // endpoint has no redirect, so a redirect is an error. + redirect: 'error', }, limits, ); // A logout ran while the request waited. Its tokens must not log the user in again. - if (epoch !== attempt_epoch) return { ok: false, error: { kind: 'logged_out' } }; + if (epoch !== attempt_epoch || !current()) + return { ok: false, error: { kind: 'logged_out' } }; const grant = params['grant_type'] ?? ''; if (!fetched.ok) { log.error('the token request failed', { grant, error: fetched.error.kind }); @@ -649,6 +684,7 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { if (status === 511) { // 511: the session on the server ended. The user must log in again. if (handle_login && authority !== null) redirect(loginUrl(authority)); + else failed({ kind: 'login_required' }); return false; } // 401: the session can have changed, so load the authority again before the new attempt. @@ -936,11 +972,20 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { authority === null ? serverUrl(LOGOUT_PATH_DEFAULT) : serverUrl(authority.logout_url); log.info('logging out'); epoch += 1; - const request_headers: Record = { ...headers }; + logouts_pending += 1; + // The logout URL of the authority can be on a different origin. Only the PlaceOS server + // gets the headers of the session and the token. A URL that does not parse gets none. + const page = environment.currentUrl(); + const same_origin = + URL.canParse(url, page) && + new URL(url, page).origin === new URL(serverUrl('/'), page).origin; + const request_headers: Record = same_origin ? { ...headers } : {}; // Send the token also after its local expiry. That has a margin, so the server can still // accept the token, and the logout revokes it. const access_token = readTokens().access_token; - if (access_token !== null) request_headers['Authorization'] = `Bearer ${access_token}`; + if (access_token !== null && same_origin) { + request_headers['Authorization'] = `Bearer ${access_token}`; + } const fetched = await fetchBody( environment.fetch, url, @@ -950,8 +995,11 @@ export function createAuthSession(config: AuthSessionConfig): AuthSession { // Remove the credentials also when the request fails. The navigation ends the session. const location = fetched.ok ? fetched.value.headers.get('location') : null; clearCredentials(); + logouts_pending -= 1; setStatus({ kind: 'signed_out', error: null }); - environment.navigate(location ?? url); + // The browser throws on a URL that does not parse. Then the page stays, signed out. + const target = location ?? url; + if (URL.canParse(target, page)) environment.navigate(target); } /** Removes each stored value of this client: each key that has the client ID, and the link. */ @@ -1098,9 +1146,13 @@ function hasLoginParams(params: ReadonlyMap): boolean { return params.has('error') && params.has('state'); } -/** A 4xx from the token endpoint refuses the grant. Other errors can pass with a new attempt. */ +/** + * A 4xx from the token endpoint refuses the grant, except a 408 (timeout) and a 429 (too many + * requests). A new attempt can pass after these and after other errors. + */ function isRefusal(error: AuthError): boolean { if (error.kind !== 'token_rejected') return false; + if (error.status === 408 || error.status === 429) return false; return error.status >= 400 && error.status < 500; } diff --git a/src/compat/http-mock.ts b/src/compat/http-mock.ts index 358a7db59..2ee862dea 100644 --- a/src/compat/http-mock.ts +++ b/src/compat/http-mock.ts @@ -7,13 +7,14 @@ * id: request.route_params.id, * name: 'Zone', * }) }); - * configure({ base_url: '', auth: { kind: 'none' }, fetch: mockFetch }); + * configure({ base_url: '', auth: { kind: 'none' }, fetch: mockFetch, missing_fields: 'zero' }); * ``` * * The behavior is the same as 6.x: a path segment `:name` is a route parameter, the response comes * after a delay (300 ms by default), and an endpoint that is not registered gives a 404. One * difference: 7.x parses each response with the schema of the operation, so the mock data must - * match the API document. + * match the API document. `missing_fields: 'zero'` fills the fields that the mock data does not + * have, as the 6.x classes did. * * @module */ diff --git a/src/compat/result.ts b/src/compat/result.ts index 2e739fce3..7a150cb4f 100644 --- a/src/compat/result.ts +++ b/src/compat/result.ts @@ -35,23 +35,41 @@ export function orThrow(result: Result, CallError>): T { return result.value.data; } -/** The page of a 6.x query function. 6.x also gave `next`. 7.x gives `next_offset`. */ +/** The page of a 6.x query function. */ export interface Page { readonly data: T; /** The `X-Total-Count` header, or `0` without it, as in 6.x. */ readonly total: number; /** Give it as the `offset` of the next call. `null` on the last page. */ readonly next_offset: number | null; + /** + * Requests the next page, as in 6.x. `null` on the last page. The promise rejects on an error. + * The function gives `null` when the link does not move the offset forward. + */ + readonly next: (() => Promise> | null) | null; +} + +/** A 7.x reply, with `next()` when the operation has pages. */ +interface PagedReply extends Reply { + next?(): Promise, CallError>> | null; } /** The 6.x type of a query function, such as `QueryResponse`. */ export type QueryResponse = Promise>; -/** Gives the data and the totals of a `query` call, or throws `CallFailed`. */ -export function orThrowPage(result: Result, CallError>): Page { +/** + * Gives the data, the totals and `next` of a `query` call, as a 6.x query function did, or throws + * `CallFailed`. + */ +export function orThrowPage(result: Result, CallError>): Page { if (!result.ok) throw new CallFailed(result.error); - const page = pageInfo(result.value.headers); - return { data: result.value.data, total: page.total ?? 0, next_offset: page.next_offset }; + const reply = result.value; + const page = pageInfo(reply.headers); + const next = + reply.next === undefined || page.next_offset === null + ? null + : () => reply.next?.()?.then(orThrowPage) ?? null; + return { data: reply.data, total: page.total ?? 0, next_offset: page.next_offset, next }; } /** diff --git a/src/core/client.ts b/src/core/client.ts index bda953888..9c064b508 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -146,18 +146,18 @@ export type CallError = export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; -/** - * One endpoint of the API, as data. The generated functions call `call` with an operation. - * - * `params` is an object schema with the path parameters and the query parameters. `response` is - * `null` when the API document gives no schema for the body. The data is then the raw bytes. - */ /** * The response of an operation without a response schema. `text` gives the body as a string, and * `bytes` gives it as a `Uint8Array`, for files and images. */ export type RawResponse = 'text' | 'bytes'; +/** + * One endpoint of the API, as data. The generated functions call `call` with an operation. + * + * `params` is an object schema with the path parameters and the query parameters. `response` is + * the schema of the body or, when the API document gives no schema, a `RawResponse`. + */ export interface Operation< P extends AnySchema, B extends AnySchema | null, @@ -230,8 +230,9 @@ export interface Reply { */ export interface PageReply extends Reply { /** - * Requests the next page: the same input with the `offset` of the `Link` header, through the - * same client. `options` replace the options of the first call. `null` on the last page, and + * Requests the next page: the same input with the `offset` of the `Link` header. Each field of + * `options` replaces that field of the request that gave this page, and the other fields stay, + * also `client` and `signal`. `null` on the last page, and * when the offset does not move forward, so that a loop over the pages ends. */ next(options?: CallOptions): Promise> | null; @@ -463,7 +464,8 @@ async function send( setCredentialHeader(headers, credential.value); // On a redirect to another origin, `fetch` removes `Authorization` but keeps `X-API-Key`. // So with an API key, a redirect is a `network` error. The API has no redirect operations. - const redirect: RequestRedirect = credential.value.kind === 'api_key' ? 'error' : 'follow'; + // The key can also come from the `headers` of the client. + const redirect: RequestRedirect = headers.has('X-API-Key') ? 'error' : 'follow'; const init = { method: operation.method, headers, body: body_text, redirect }; const remaining_ms = deadline_ms - Date.now(); if (remaining_ms <= 0) return { ok: false, error: { kind: 'timeout', timeout_ms } }; @@ -480,11 +482,15 @@ async function send( if (client.auth.kind !== 'credential') break; if (status !== 401 && status !== 511) break; if (attempt + 1 >= AUTH_ATTEMPTS_MAX) break; - const rejected = client.auth.rejected; + const credential_auth = client.auth; const used = credential.value; const log = scopedLog('http', { sink: client.log }); log.info(`${operation.name}: ${status}, renewing the credential`); - const renewed = await waitWithin(() => rejected(status, used), deadline_ms, signal); + const renewed = await waitWithin( + () => renewCredential(credential_auth, status, used), + deadline_ms, + signal, + ); if (!renewed.ok) return limitError(renewed.error, timeout_ms); if (!renewed.value) break; } @@ -757,8 +763,37 @@ function isAborted(signal: AbortSignal | undefined): boolean { return signal?.aborted === true; } -/** The credential that `auth` gives now, or `null`. The client and the realtime client use it. */ +/** + * The credential that `auth` gives now, or `null`. The client and the realtime client use it. A + * `token` or `credential` function of the application that throws gives `null`, so the call gives + * `auth_missing` and does not reject. + */ export async function resolveCredential(auth: Auth): Promise { + try { + return await credentialOf(auth); + } catch { + return null; + } +} + +/** + * Calls `rejected` of a `credential` auth, as a method of the auth, so that it can use `this`. A + * callback that throws or rejects gives `false`: no new credential, so the call gives the 401 or + * the 511. + */ +export async function renewCredential( + auth: Extract, + status: 401 | 511, + credential: Credential, +): Promise { + try { + return await auth.rejected(status, credential); + } catch { + return false; + } +} + +async function credentialOf(auth: Auth): Promise { switch (auth.kind) { case 'none': return { kind: 'none' }; diff --git a/src/core/log.ts b/src/core/log.ts index f6caee48c..d13656a1d 100644 --- a/src/core/log.ts +++ b/src/core/log.ts @@ -7,7 +7,9 @@ * configure({ base_url: '', auth, log: (entry) => console.debug(entry.scope, ...entry.args) }); * ``` * - * An entry has no tokens, API keys, cookies, request bodies or input values. + * The library does not put the tokens, API keys, cookies or request bodies that it sends in an + * entry. An entry can have data from the server, such as the body of an HTTP error or the value of + * a realtime binding, and that data can contain secrets. * * Inside the library, each part logs through a scoped logger. The log function of the application * decides where the entries go: diff --git a/src/core/pagination.ts b/src/core/pagination.ts index ec24d21b6..f480e932d 100644 --- a/src/core/pagination.ts +++ b/src/core/pagination.ts @@ -38,9 +38,8 @@ function parseCount(text: string | null): number | null { function parseNextOffset(header: string | null): number | null { if (header === null) return null; if (header.length > LINK_HEADER_LENGTH_MAX) return null; - for (const link of header.split(',')) { - const match = /^\s*<([^>]*)>\s*;\s*rel="?next"?\s*$/.exec(link); - if (match === null) continue; + // A target can have commas, such as `?zone_id=a,b`, so a link ends at a comma after its `>`. + for (const match of header.matchAll(/<([^>]*)>\s*;\s*rel="?next"?\s*(?:,|$)/g)) { const target = match[1] ?? ''; // The target is often a path only. The base makes it a URL that `URL` can parse. if (!URL.canParse(target, 'http://base.invalid')) return null; diff --git a/src/migrate/cli.ts b/src/migrate/cli.ts index 2d6f6afb2..497b9dd08 100644 --- a/src/migrate/cli.ts +++ b/src/migrate/cli.ts @@ -39,8 +39,8 @@ const TS_SUPPORTED = '4.9 to 6.x'; const USAGE = `Usage: placeos-migrate [--write] ... -Rewrites the calls of @placeos/ts-client 6.x to 7.x. Without --write, it shows the changes and -writes no file. Commit your work first, so that you can see and undo the changes.`; +Rewrites the calls of @placeos/ts-client 6.x to 7.x. Without --write, it lists the files that +would change and the uses to change by hand, and writes no file. Commit your work first, so that you can see and undo the changes.`; await main(process.argv.slice(2)); diff --git a/src/migrate/migrate.ts b/src/migrate/migrate.ts index 52f5a8f34..8e3e50db7 100644 --- a/src/migrate/migrate.ts +++ b/src/migrate/migrate.ts @@ -109,20 +109,33 @@ export function migrateSource( const kind = /\.[cm]?tsx$/.test(file_name) ? ts.ScriptKind.TSX : ts.ScriptKind.TS; const source = ts.createSourceFile(file_name, text, ts.ScriptTarget.Latest, true, kind); - const imports = readImports(ts, source); - if (imports.declarations.length === 0) { + const read = readImports(ts, source); + if (read.declarations.length === 0) { return { text, changes: 0, findings: [], migrated: new Set() }; } + // A local declaration with the name of a 6.x import, such as a parameter `showZone`, hides the + // import in its scope. The tool does not read scopes, so it changes no use of that name. + const shadowed = shadowedImports(ts, source, read, tables); + if (shadowed === null) return tooDeep(text); + const imports: V1Imports = { + declarations: read.declarations, + named: new Map([...read.named].filter(([local]) => !shadowed.has(local))), + namespaces: new Set([...read.namespaces].filter((local) => !shadowed.has(local))), + }; // A 6.x class that the file uses only as a type loses its import, so a 7.x type can take its - // name, such as `Survey` for the 6.x `Survey`. + // name, such as `Survey` for the 6.x `Survey`. An import that the file exports stays, so its + // name is not free. + const exported = localExports(ts, source); const typeOnly = (name: string) => { const imported = imports.named.get(name); - return imported !== undefined && imported in tables.types; + return imported !== undefined && imported in tables.types && !exported.has(name); }; const names = declaredNames(ts, source, typeOnly); if (names === null) return tooDeep(text); // A closure does not keep the narrowing of `names`, so this name has the narrow type. const taken: Set = names; + // `export { Zone }` names the import. A new import must not take that name. + for (const name of exported) taken.add(name); const edits: Edit[] = []; const findings: Finding[] = []; const migrated = new Set(); @@ -147,6 +160,15 @@ export function migrateSource( } let changes = 0; let deep = false; + for (const [local, declaration] of shadowed) { + // The import stays, because the tool did not change its uses. + countUse(local, false); + find( + declaration, + local, + `a local declaration hides the 6.x import ${local}: change its uses by hand`, + ); + } // The helpers that a file already imports from the compat module, by name. const compat_imported = new Map(); @@ -648,6 +670,15 @@ export function migrateSource( callee.name.text in tables.calls ) { rewriteCall(node, callee.name.text, callee.expression.text); + } else if ( + ts.isPropertyAccessExpression(callee) && + ts.isIdentifier(callee.expression) && + imports.namespaces.has(callee.expression.text) && + callee.name.text in tables.compat + ) { + // `client.registerSystem(...)` calls the compat function, as a named import does. + replace(callee, compatLocal(callee.name.text)); + changes += 1; } else if ( ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && @@ -691,6 +722,17 @@ export function migrateSource( return; } + // `export { showZone }` gives the 6.x function to other files. The tool cannot change them. + if (ts.isExportSpecifier(node) && node.parent.parent.moduleSpecifier === undefined) { + const local = node.propertyName ?? node.name; + const imported = ts.isIdentifier(local) ? imports.named.get(local.text) : undefined; + if (imported !== undefined && !moved.has(local.text) && isV1Name(tables, imported)) { + countUse(local.text, false); + find(node, imported, 'an export of a 6.x import: change it by hand'); + } + return; + } + if (ts.isIdentifier(node) && isReference(ts, node)) { const imported = imports.named.get(node.text); // A mapped callee or type name is counted at its parent. @@ -872,7 +914,6 @@ function readImports(ts: typeof TS, source: TS.SourceFile): V1Imports { return { declarations, named, namespaces }; } -/** The names that the file declares or uses, so that a new import does not hide one. */ /** The result for a file deeper than `AST_DEPTH_MAX`: no change, and a finding. */ function tooDeep(text: string): MigrateResult { const message = `the file nests deeper than ${AST_DEPTH_MAX} levels: change it by hand`; @@ -926,6 +967,68 @@ function declaredNames( return deep ? null : names; } +/** The local names in `export { name }` statements without a module. */ +function localExports(ts: typeof TS, source: TS.SourceFile): Set { + const names = new Set(); + for (const statement of source.statements) { + if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier !== undefined) continue; + const clause = statement.exportClause; + if (clause === undefined || !ts.isNamedExports(clause)) continue; + for (const element of clause.elements) + names.add((element.propertyName ?? element.name).text); + } + return names; +} + +/** + * The 6.x calls and namespaces whose name a local declaration also has, with the first such + * declaration. `null` for a file deeper than `AST_DEPTH_MAX`. + */ +function shadowedImports( + ts: typeof TS, + source: TS.SourceFile, + imports: V1Imports, + tables: MigrateTables, +): Map | null { + const names = new Set(imports.namespaces); + for (const [local, imported] of imports.named) { + if (imported in tables.calls) names.add(local); + } + const shadowed = new Map(); + let deep = false; + function visit(node: TS.Node, depth: number): void { + if (depth > AST_DEPTH_MAX) { + deep = true; + return; + } + if (ts.isIdentifier(node) && names.has(node.text) && !shadowed.has(node.text)) { + if (isDeclarationName(ts, node)) shadowed.set(node.text, node); + } + ts.forEachChild(node, (child) => visit(child, depth + 1)); + } + if (names.size > 0) visit(source, 0); + return deep ? null : shadowed; +} + +/** + * The name of a variable, a parameter, a function, a class, an enum or a namespace. Not the name of + * an import. + */ +function isDeclarationName(ts: typeof TS, node: TS.Identifier): boolean { + const parent = node.parent; + const declaration = + ts.isVariableDeclaration(parent) || + ts.isParameter(parent) || + ts.isBindingElement(parent) || + ts.isFunctionDeclaration(parent) || + ts.isFunctionExpression(parent) || + ts.isClassDeclaration(parent) || + ts.isClassExpression(parent) || + ts.isEnumDeclaration(parent) || + ts.isModuleDeclaration(parent); + return declaration && parent.name === node; +} + /** `vi.` or `jest.`, or only `.`. */ function isTestCall( ts: typeof TS, @@ -1139,6 +1242,23 @@ function renderCall( return `the 7.x call uses the ${name} argument twice: put it in a variable first`; } } + // The 7.x input can have the arguments in a different order. The order of the keys is the order + // of evaluation. A call or an assignment in one argument can change the value of a name in a + // different argument, so the arguments keep their order when one of them is not simple. Only a + // literal can move. + const order = [...counts.keys()].filter((index) => { + const arg = given[index]; + return ( + arg !== null && arg !== undefined && literalText(ts, { text: '', node: arg }) === null + ); + }); + const has_effects = order.some((index) => { + const arg = given[index]; + return arg !== null && arg !== undefined && !isSimple(ts, arg); + }); + if (has_effects && order.some((index, at) => at > 0 && index < (order[at - 1] ?? -1))) { + return 'the 7.x call evaluates the arguments in a different order: put them in variables first'; + } const value = (index: number): Value | null => { const arg = given[index]; diff --git a/src/realtime/environment.ts b/src/realtime/environment.ts index 03d03ca26..a9e4b1058 100644 --- a/src/realtime/environment.ts +++ b/src/realtime/environment.ts @@ -21,7 +21,10 @@ export interface RealtimeSocket { /** How the socket sends the token. A browser WebSocket cannot set an `Authorization` header. */ export type TokenTransport = - /** A cookie on the path of the socket. The token is not in the URL. */ + /** + * A cookie on the path of the socket, so the token is not in the URL. A cookie reaches only the + * host of the page, so a socket on a different host gets the token in the query. + */ | 'cookie' /** A `bearer_token` or `api-key` query parameter. The server removes these from its logs. */ | 'query'; diff --git a/src/realtime/realtime.ts b/src/realtime/realtime.ts index ff157793c..a35444c3f 100644 --- a/src/realtime/realtime.ts +++ b/src/realtime/realtime.ts @@ -17,7 +17,7 @@ * many notifications for one variable give one call to its listeners, with the last value. */ import { assert, unreachable } from '../core/assert.ts'; -import { resolveCredential, type Auth, type Credential } from '../core/client.ts'; +import { renewCredential, resolveCredential, type Auth, type Credential } from '../core/client.ts'; import { scopedLog, type LogFunction } from '../core/log.ts'; import type { Result } from '../core/result.ts'; import { @@ -99,7 +99,10 @@ export interface DebugTarget { export type RealtimeError = | { readonly kind: 'timeout'; readonly timeout_ms: number } - /** The socket closed after the server got the request. The result is not known. */ + /** + * The client sent the request, and the socket closed before the result came. The client does + * not know if the server got or ran the request. + */ | { readonly kind: 'disconnected' } /** `stop` ran before the response. */ | { readonly kind: 'stopped' } @@ -153,7 +156,10 @@ export interface Realtime { /** Closes the socket. Pending calls give `stopped`. The bindings stay for the next `start`. */ stop(): void; status(): RealtimeStatus; - /** Calls `listener` on each change of the status. Returns the remover. */ + /** + * Calls `listener` after a change of the status, in a later task. When the status changes more + * than one time before that, the listener gets only the last status. Returns the remover. + */ subscribe(listener: (status: RealtimeStatus) => void): () => void; /** Calls a function of a module. The value is the return value of the function. */ exec( @@ -221,7 +227,7 @@ interface Pending { readonly text: string; /** A call of the application, which counts to `PENDING_MAX`. Else a binding command. */ readonly call: boolean; - /** The server got the request. A close then makes its result unknown. */ + /** The client sent the request on the socket. A close then makes its result unknown. */ sent: boolean; readonly resolve: (result: Result) => void; readonly cancelTimer: () => void; @@ -300,6 +306,8 @@ export function createRealtime(config: RealtimeConfig): Realtime { cancelReconnect?.(); cancelReconnect = null; closeSocket(); + // A message of the closed socket can wait for the drain. It must not update a binding now. + inbox.length = 0; for (const id of [...pending.keys()]) settle(id, { ok: false, error: { kind: 'stopped' } }); queue.length = 0; } @@ -345,7 +353,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { if (owner.holders.size > 0) return; bindings.delete(key); // Without a socket, the server has no binding to remove. - if (status.kind === 'open') { + if (isLive()) { void request('unbind', owner.target, null, REQUEST_TIMEOUT_MS); } }; @@ -381,7 +389,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { owner.holders.delete(holder); if (owner.holders.size > 0) return; debuggers.delete(key); - if (status.kind === 'open') sendDebug(owner, 'ignore'); + if (isLive()) sendDebug(owner, 'ignore'); }; } @@ -446,9 +454,18 @@ export function createRealtime(config: RealtimeConfig): Realtime { entry.resolve(result); } + /** + * The socket is open, and not closing. A close sets `socket` to `null` before the last drain, + * so a bind or an unbind of a listener does not wait for the next socket. `onOpen` sends the + * bindings and the debuggers that exist then. + */ + function isLive(): boolean { + return status.kind === 'open' && socket !== null; + } + /** Binds on the server when the socket is open. `onOpen` binds the others. */ function sendBind(binding: Binding): void { - if (status.kind !== 'open') { + if (!isLive()) { if (status.kind === 'idle') start(); return; } @@ -462,7 +479,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { } function sendDebug(entry: Debugger, command: 'debug' | 'ignore'): void { - if (status.kind !== 'open') { + if (!isLive()) { if (status.kind === 'idle') start(); return; } @@ -480,7 +497,7 @@ export function createRealtime(config: RealtimeConfig): Realtime { if (renew_before_connect && config.auth.kind === 'credential' && last_credential !== null) { log.info('asking the auth for a new credential, after failures to connect'); renew_before_connect = false; - await config.auth.rejected(401, last_credential); + await renewCredential(config.auth, 401, last_credential); if (this_attempt !== connect_attempt) return; } const credential = await resolveCredential(config.auth); @@ -616,13 +633,14 @@ export function createRealtime(config: RealtimeConfig): Realtime { } function onDisconnect(): void { + // Without the socket, a request of a listener in the drain waits for the next socket. + socket = null; // A response can wait in the inbox. Handle it before the requests fail as disconnected. if (inbox.length > 0) drain(); log.warn('the socket closed', { was_open: status.kind === 'open' }); cancelTimers(); - socket = null; if (status.kind !== 'open') failures_before_open += 1; - // The result of a request that the server got is not known now. + // The result of a request that the client sent is not known now. for (const [id, entry] of [...pending]) { if (entry.sent) settle(id, failure({ kind: 'disconnected' })); } diff --git a/test/auth.test.ts b/test/auth.test.ts index be7c83276..2bef2a06c 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -26,6 +26,7 @@ interface Sent { readonly method: string; readonly headers: Headers; readonly form: URLSearchParams; + readonly redirect: RequestRedirect | undefined; } interface FakeOptions { @@ -67,6 +68,7 @@ function fake(options: FakeOptions = {}) { method: init.method ?? 'GET', headers: new Headers(init.headers), form, + redirect: init.redirect, }; sent.push(record); const path = new URL(url, 'http://localhost:4200').pathname; @@ -426,6 +428,51 @@ describe('trusted applications and refresh tokens', () => { expect(world.storage.get(`${CLIENT_ID}_refresh_token`)).toBe('old'); expect(world.navigations).toHaveLength(0); }); + + test('a 429 keeps the refresh token, because a later attempt can pass', async () => { + const world = fake({ token: () => new Response('{}', { status: 429 }) }); + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_refresh_token`, 'old'); + await session(world).start(); + expect(world.storage.get(`${CLIENT_ID}_refresh_token`)).toBe('old'); + }); + + test('a refresh that a different tab completes first uses the tokens of that tab', async () => { + let answer: (response: Response) => void = () => {}; + const world = fake({ token: () => new Promise((resolve) => (answer = resolve)) }); + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_refresh_token`, 'refresh-0'); + const pending = session(world).start(); + await Bun.sleep(0); + // The other tab sent the same refresh token, and the server rotated it for that tab. + world.storage.set(`${CLIENT_ID}_access_token`, 'other'); + world.storage.set(`${CLIENT_ID}_refresh_token`, 'refresh-other'); + world.storage.set(`${CLIENT_ID}_expires_at`, String(NOW_MS + 60_000)); + answer(Response.json({ error: 'invalid_grant' }, { status: 400 })); + expect(await pending).toEqual({ ok: true, value: { kind: 'bearer', token: 'other' } }); + expect(world.storage.get(`${CLIENT_ID}_refresh_token`)).toBe('refresh-other'); + }); + + test('a refresh during a logout in a different tab does not log in with a grant', async () => { + let answer: (response: Response) => void = () => {}; + const world = fake({ + token: (form) => + form.get('grant_type') === 'refresh_token' + ? new Promise((resolve) => (answer = resolve)) + : Response.json({ access_token: 'from-password', expires_in: 3600 }), + }); + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_refresh_token`, 'refresh-0'); + const grant = { kind: 'password', username: 'user', password: 'secret' } as const; + const pending = session(world, { grant }).start(); + await Bun.sleep(0); + // The other tab logged out: it removed the shared tokens. + world.storage.remove(`${CLIENT_ID}_refresh_token`); + answer(Response.json({ access_token: 'late', refresh_token: 'late-2', expires_in: 3600 })); + expect(await pending).toEqual({ ok: false, error: { kind: 'logged_out' } }); + expect(world.tokenRequests()).toHaveLength(1); + expect(world.storage.get(`${CLIENT_ID}_access_token`)).toBeNull(); + }); }); describe('other grants', () => { @@ -449,6 +496,8 @@ describe('other grants', () => { await session(world, { grant }).start(); const request = world.tokenRequests()[0]; expect(request?.url).toBe('/auth/oauth/token'); + // A redirect would send the body again, to its target. + expect(request?.redirect).toBe('error'); expect(request?.form.get('grant_type')).toBe('password'); expect(request?.form.get('password')).toBe('secret'); expect(request?.form.get('authority')).toBe('authority-1'); @@ -688,6 +737,80 @@ describe('the session with the client', () => { expect(auth.credential()).toBeNull(); }); + test('a request while logout waits starts no refresh, so it cannot log in again', async () => { + const world = fake(); + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_refresh_token`, 'refresh-0'); + let release: () => void = () => {}; + const held = new Promise((resolve) => (release = resolve)); + let logouts = 0; + const fetch: AuthEnvironment['fetch'] = async (url, init) => { + // Only the first logout request waits. + if (url.endsWith('/logout') && logouts++ === 0) await held; + return world.environment.fetch(url, init); + }; + // A password grant needs no stored token, so only the logout can stop it. + const grant = { kind: 'password', username: 'user', password: 'secret' } as const; + const auth = session(world, { grant, environment: { ...world.environment, fetch } }); + await auth.reloadAuthority(); + const client = createClient({ base_url: '', auth: auth.client_auth, fetch }); + const logout = auth.logout(); + const result = await call(SHOW, { id: 'zone-1' }, { client }); + expect(result).toEqual({ ok: false, error: { kind: 'auth_missing' } }); + // A second logout ends first. The first one still waits, so no attempt starts. + await auth.logout(); + expect(await call(SHOW, { id: 'zone-1' }, { client })).toEqual(result); + release(); + await logout; + expect(world.tokenRequests()).toHaveLength(0); + }); + + test('a 511 with handle_login false signs out, so the application shows its login', async () => { + const world = fake({ api: () => new Response('{}', { status: 511 }) }); + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_access_token`, 'token'); + world.storage.set(`${CLIENT_ID}_expires_at`, String(NOW_MS + 60_000)); + const auth = session(world, { handle_login: false }); + const client = createClient({ + base_url: '', + auth: auth.client_auth, + fetch: world.environment.fetch, + }); + const result = await call(SHOW, { id: 'zone-1' }, { client }); + expect(result.ok === false && result.error.kind === 'http' && result.error.status).toBe( + 511, + ); + expect(auth.status()).toEqual({ kind: 'signed_out', error: { kind: 'login_required' } }); + expect(world.navigations).toHaveLength(0); + }); + + test('logout sends the token and the headers only to the PlaceOS server', async () => { + const world = fake(); + world.authority.logout_url = 'https://idp.test/logout'; + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_access_token`, 'token'); + const auth = session(world, { headers: { 'X-API-Key': 'key-1' } }); + await auth.reloadAuthority(); + await auth.logout(); + expect(world.sent.at(-1)?.url).toBe('https://idp.test/logout'); + expect([...(world.sent.at(-1)?.headers.keys() ?? [])]).toEqual([]); + }); + + test('a logout URL that does not parse still removes the credentials', async () => { + const world = fake(); + world.authority.logout_url = 'https://'; + world.storage.set('trusted', 'true'); + world.storage.set(`${CLIENT_ID}_access_token`, 'token'); + world.storage.set(`${CLIENT_ID}_expires_at`, String(NOW_MS + 60_000)); + const auth = session(world); + await auth.reloadAuthority(); + await auth.logout(); + expect(world.storage.get(`${CLIENT_ID}_access_token`)).toBeNull(); + expect(auth.status().kind).toBe('signed_out'); + // A browser throws on that URL, so the session does not go there. + expect(world.navigations).toEqual([]); + }); + test('logout sends the token also after its local expiry, so the server revokes it', async () => { const world = fake(); world.storage.set('trusted', 'true'); diff --git a/test/client.test.ts b/test/client.test.ts index c769d6587..7f5c43c90 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -9,6 +9,7 @@ import { configure, createClient, operation, + type Auth, type ClientConfig, type FetchFunction, } from '../src/core/client.ts'; @@ -23,6 +24,7 @@ import { } from '../src/core/schema.ts'; import { join } from 'node:path'; import { zones } from '../src/index.ts'; +import { events } from '../src/staff.ts'; interface Sent { readonly url: string; @@ -109,6 +111,16 @@ describe('call', () => { expect(sent[0]?.headers.get('content-type')).toBe('application/json'); }); + test('a query parameter with a wire name goes in the query with that name', async () => { + const { fetch, sent } = fakeFetch(() => new Response('{}', { status: 500 })); + // `staff.events.book` takes the description as `body_text`, because `body` is the body. + const input = { title: 'Standup', event_start: 1, event_end: 2, body_text: 'Notes' }; + await events.book(input, { client: clientWith(fetch) }); + const query = new URL(sent[0]?.url ?? '').searchParams; + expect(query.get('body')).toBe('Notes'); + expect(query.has('body_text')).toBe(false); + }); + test('parses the response with the schema of the operation', async () => { const { fetch } = fakeFetch(() => jsonResponse({ id: 'item-1', extra: 1 })); const result = await call( @@ -149,9 +161,63 @@ describe('call', () => { ok: false, error: { kind: 'auth_missing' }, }); + // A token function that throws gives an error result. The call does not reject. + const failing = clientWith(fetch, { + auth: { + kind: 'bearer', + token: () => { + throw new Error('the token store is closed'); + }, + }, + }); + expect(await call(DOWNLOAD, {}, { client: failing })).toEqual({ + ok: false, + error: { kind: 'auth_missing' }, + }); expect(sent).toHaveLength(2); }); + test('a rejected callback that throws gives the 401 as the result', async () => { + const { fetch } = fakeFetch(() => new Response('{}', { status: 401 })); + const credential = async () => ({ kind: 'bearer', token: 'abc' }) as const; + const failures = [ + () => { + throw new Error('the session is closed'); + }, + () => Promise.reject(new Error('the session is closed')), + ]; + for (const rejected of failures) { + const client = clientWith(fetch, { + auth: { kind: 'credential', credential, rejected }, + }); + const result = await call(DOWNLOAD, {}, { client }); + expect(result.ok === false && result.error.kind === 'http' && result.error.status).toBe( + 401, + ); + } + }); + + test('the client calls rejected as a method of the auth', async () => { + const { fetch } = fakeFetch((init) => + new Headers(init.headers).get('authorization') === 'Bearer new' + ? new Response('') + : new Response('{}', { status: 401 }), + ); + const auth = { + kind: 'credential' as const, + token: 'old', + async credential() { + return { kind: 'bearer', token: this.token } as const; + }, + async rejected() { + this.token = 'new'; + return true; + }, + } satisfies Auth & { token: string }; + const result = await call(DOWNLOAD, {}, { client: clientWith(fetch, { auth }) }); + expect(result.ok).toBe(true); + }); + test('does not send the API key to the target of a redirect', async () => { const target = Bun.serve({ port: 0, @@ -168,6 +234,14 @@ describe('call', () => { }); const result = await call(DOWNLOAD, {}, { client }); expect(result.ok ? 'followed' : result.error.kind).toBe('network'); + // A key in the headers of the client is also an API key. + const in_headers = createClient({ + base_url: `http://localhost:${server.port}`, + auth: { kind: 'none' }, + headers: { 'X-API-Key': 'key-1' }, + }); + const second = await call(DOWNLOAD, {}, { client: in_headers }); + expect(second.ok ? 'followed' : second.error.kind).toBe('network'); } finally { await Promise.all([server.stop(true), target.stop(true)]); } diff --git a/test/compat.test.ts b/test/compat.test.ts index 3e9b46519..9d0f284da 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -24,6 +24,7 @@ import { import { createClient } from '../src/core/client.ts'; import { createRealtime, type BindingState } from '../src/realtime/realtime.ts'; import { settings, zones } from '../src/generated/operations/index.ts'; +import { clearEndpointMocks, endpointMocks, mockEndpoint, respond } from '../src/mock/index.ts'; // An app gives `base_url: ''`. Outside a browser, a URL needs an origin. 6.x mock data often has // only some fields. `missing_fields: 'zero'` fills the others, as the 6.x classes did. @@ -37,6 +38,7 @@ const options = { client }; afterEach(() => { clearMockEndpoints(); + clearEndpointMocks(); deregisterSystem('sys-1'); }); @@ -95,6 +97,9 @@ test('a missing endpoint is a 404, and a thrown status is that status', async () const refused = await zones.destroy({ id: 'zone-1' }, options); expect(missing.ok === false && missing.error.kind === 'http' && missing.error.status).toBe(404); expect(refused.ok === false && refused.error.kind === 'http' && refused.error.status).toBe(403); + // A migrated call rejects, as the 6.x function did. + const rejected = zones.show({ id: 'zone-1' }, options).then(orThrow); + await expect(rejected).rejects.toMatchObject({ name: 'CallFailed', status: 404 }); }); test('without missing_fields: zero, partial mock data is not valid', async () => { @@ -162,11 +167,28 @@ test('mockReply and mockPage make the results of test doubles', () => { // The double of an operation with pages needs `next`. const history: Awaited> = mockReply([]); expect(history.ok && history.value.next()).toBeNull(); - expect(orThrowPage(mockPage({ data: [zone], total: 3 }))).toEqual({ - data: [zone], - total: 3, - next_offset: null, + const page = orThrowPage(mockPage({ data: [zone], total: 3 })); + expect(page).toMatchObject({ data: [zone], total: 3, next_offset: null }); + // On the last page, `next` is `null`, as in 6.x, so `if (page.next)` works. + expect(page.next).toBeNull(); +}); + +test('a page of orThrowPage requests the next page, as in 6.x', async () => { + mockEndpoint('zones.query', (input) => + input.offset === undefined + ? respond([{ id: 'zone-1' }], { next_offset: 1 }) + : respond([{ id: 'zone-2' }]), + ); + const typed = createClient({ + base_url: 'http://mock.invalid', + auth: { kind: 'none' }, + mock: endpointMocks, + missing_fields: 'zero', }); + const first = await zones.query({ limit: 1 }, { client: typed }).then(orThrowPage); + const second = await first.next?.(); + expect(second?.data.map((item) => item.id)).toEqual(['zone-2']); + expect(second?.next).toBeNull(); }); test('a 7.x binding and call use a 6.x mock system', async () => { diff --git a/test/migrate.test.ts b/test/migrate.test.ts index 9dc14d2b8..181ee9450 100644 --- a/test/migrate.test.ts +++ b/test/migrate.test.ts @@ -438,3 +438,79 @@ test('finds the unmapped names on a namespace import', () => { '3 getModule', ]); }); + +test('an exported 6.x type keeps its name, so the 7.x type gets an alias', () => { + const result = migrate( + [ + "import { PlaceZone as Zone } from '@placeos/ts-client';", + 'export { Zone };', + 'let draft: Zone;', + ].join('\n'), + ); + expect(result.text.split('\n')).toEqual([ + "import { PlaceZone as Zone, type Zone as ZoneV7 } from '@placeos/ts-client';", + 'export { Zone };', + 'let draft: ZoneV7;', + ]); + // The exported alias is taken also when the file uses the 6.x name too. + const both = migrate( + [ + "import { PlaceZone, PlaceZone as Zone } from '@placeos/ts-client';", + 'export { Zone };', + 'let draft: PlaceZone;', + ].join('\n'), + ); + expect(both.text).toContain('let draft: ZoneV7;'); +}); + +test('a local name that hides a 6.x import, and an export of one, stay with a finding', () => { + const text = [ + "import { queryZones, showZone } from '@placeos/ts-client';", + 'function load({ queryZones }: { queryZones: () => void }) {', + ' queryZones();', + '}', + 'export { showZone as loadZone };', + ].join('\n'); + const result = migrate(text); + expect(result.text).toBe(text); + expect(result.findings.map(({ line, name }) => ({ line, name }))).toEqual([ + { line: 2, name: 'queryZones' }, + { line: 5, name: 'showZone' }, + ]); + // An enum or a namespace also hides a namespace import. + for (const kind of ['enum', 'namespace']) { + const hidden = [ + "import * as client from '@placeos/ts-client';", + `${kind} client {}`, + "client.showZone('a');", + ].join('\n'); + expect(migrate(hidden).text).toBe(hidden); + } +}); + +test('a call whose 7.x input changes the order of its arguments stays with a finding', () => { + // `getModule()` can change `method`. In 6.x, `method` was read first. + const text = [ + "import { executeOnZone } from '@placeos/ts-client';", + "executeOnZone('zone-1', method, getModule());", + ].join('\n'); + const result = migrate(text); + expect(result.text).toBe(text); + expect(result.findings[0]?.message).toContain('different order'); +}); + +test('a namespace import calls a 6.x mock function from the compat module', () => { + const result = migrate( + [ + "import * as client from '@placeos/ts-client';", + "client.registerSystem('sys-1', {});", + ].join('\n'), + ); + expect(result.text).toBe( + [ + "import * as client from '@placeos/ts-client';", + "import { registerSystem } from '@placeos/ts-client/compat';", + "registerSystem('sys-1', {});", + ].join('\n'), + ); +}); diff --git a/test/pagination.test.ts b/test/pagination.test.ts index a2f8e8cf4..f35300b43 100644 --- a/test/pagination.test.ts +++ b/test/pagination.test.ts @@ -11,6 +11,9 @@ test('reads the total and the offset of the next page', () => { Link: '; rel="next"', }); expect(pageInfo(headers)).toEqual({ total: 250, next_offset: 100 }); + // A query value can have a comma. It does not end the link. + const listed = new Headers({ Link: '; rel="next"' }); + expect(pageInfo(listed).next_offset).toBe(100); }); test('gives null on the last page and for values that are not counts', () => { diff --git a/test/realtime.test.ts b/test/realtime.test.ts index b3a659c8d..1b0869a05 100644 --- a/test/realtime.test.ts +++ b/test/realtime.test.ts @@ -445,6 +445,44 @@ describe('exec', () => { expect(await result).toEqual({ ok: true, value: 1 }); }); + test('a listener in the last batch of a closed socket uses the next socket', async () => { + const platform = fakePlatform(); + const client = realtime(platform); + let release = () => {}; + let result: ReturnType | null = null; + release = client.bind(POWER, (state) => { + if (state.kind !== 'value') return; + release(); + result = client.exec(POWER, [true]); + }); + await platform.open(); + // The notification is in the inbox when the socket closes. + const notify = { id: 0, type: 'notify', value: 1, meta: META }; + platform.latest().handlers.message(JSON.stringify(notify)); + platform.latest().handlers.close(); + client.bind(POWER, () => {}); + await platform.advance(5_000); + await platform.open(); + // No `unbind` after the new `bind`, and the call goes on the new socket. + expect(platform.requests().map((message) => message.cmd)).toEqual(['bind', 'exec']); + expect(result).not.toBeNull(); + }); + + test('stop drops a notification that waits in the inbox', async () => { + const platform = fakePlatform(); + const client = realtime(platform); + const states: BindingState[] = []; + client.bind(POWER, (state) => states.push(state)); + await platform.open(); + platform + .latest() + .handlers.message(JSON.stringify({ id: 0, type: 'notify', value: 1, meta: META })); + client.stop(); + await platform.advance(0); + // `stop` settles the bind request, so the binding gets an error. It gets no value. + expect(states.filter((state) => state.kind === 'value')).toEqual([]); + }); + test('stop settles each pending call and does not reconnect', async () => { const platform = fakePlatform(); const client = realtime(platform); From abe5eb5740ffcf4a919f4fbb13329bf359e13707 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Sun, 22 Nov 2026 11:29:17 +1100 Subject: [PATCH 29/29] fix(compat): keep the next of a 6.x page in mockPage and fromV1Mock The compat page has `next` again, but the 6.x test doubles dropped the `next` of their pages. So `orThrowPage` always gave the last page, and backoffice's "follows pagination" spec failed after the migration. When a 6.x page has a `next` function, the reply's `next()` now calls it and gives the page that it returns, with a `Link` header so that `orThrowPage` follows it. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++++--- src/compat/result.ts | 50 ++++++++++++++++++++++++++++++++++---------- test/compat.test.ts | 19 +++++++++++++++++ test/style.test.ts | 8 ++++++- 4 files changed, 71 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f100b7c1c..7a31699f5 100644 --- a/README.md +++ b/README.md @@ -411,7 +411,9 @@ mockEndpoint('zones.destroy', () => { A 7.x call returns a `Result`, so a test double of a call must also return one. Make it with `mockReply` or `mockPage` from `@placeos/ts-client/compat`. `mockPage` also sets the total of a -page. Both give a reply with `next()`, which returns `null`: +page. `next()` of the reply returns `null`, except when the 6.x page of `mockPage` has a `next` +function. Then `next()` gives the page that the function returns, so the `next` of `orThrowPage` +follows the pages, as in 6.x: ```ts vi.mock('@placeos/ts-client', { spy: true }); @@ -727,8 +729,9 @@ keeps its state in plain data, and keeps keyed data in a `Map`. These are the ex - `missing_fields: 'zero'` accepts data without its required fields. It is for mock data only. - `parseResponse`, `checkRequest` and `call` each have one `as` cast. The compiler cannot prove that the parser output has the type of the schema. The tests check the parser. -- `fromV1Mock` of `@placeos/ts-client/compat` has one `as` cast. A 6.x mock implementation has no - types, so the cast gives its result the type of the test double. +- `fromV1Mock` and `mockPage` of `@placeos/ts-client/compat` each have one `as` cast. A 6.x mock + implementation or 6.x `next` has no types, so the cast gives its result the type of the test + double. - `configure` keeps one client in module state, so a call does not need a client argument. A call before `configure` throws at run time. The compiler cannot find it. - The mocks keep their registries in module state, as 6.x did: the endpoints of diff --git a/src/compat/result.ts b/src/compat/result.ts index 7a150cb4f..8252a7cbb 100644 --- a/src/compat/result.ts +++ b/src/compat/result.ts @@ -89,10 +89,16 @@ export function mockReply( return { ok: true, value: { status, headers: new Headers(), data, next: () => null } }; } +/** The reply of `mockPage`. `next()` gives the next page, or `null` on the last page. */ +export interface MockPage extends Reply { + next(): Promise, CallError>> | null; +} + /** * The 7.x result for a 6.x page, for a test double of a `query` call. `total` goes in the - * `X-Total-Count` header, so `orThrowPage` gives it back. The page is the last one: `next()` gives - * `null`. + * `X-Total-Count` header, so `orThrowPage` gives it back. When the 6.x page has a `next` function, + * `next()` of the reply calls it and gives the page that it returns. Then the `next` of + * `orThrowPage` follows the pages, as in 6.x. Without it, the page is the last one. * * ```ts * vi.mocked(zones.query).mockResolvedValue(mockPage({ data: [zone], total: 1 })); @@ -101,12 +107,38 @@ export function mockReply( export function mockPage(page: { readonly data: T; readonly total?: number; - /** The `next` of a 6.x page. 7.x has no use for it. */ + /** The `next` of a 6.x page: a function that gives the next page, or `null`. */ readonly next?: unknown; -}): Result & { next(): null }, CallError> { +}): Result, CallError> { + const reply = pageReply(page, 0); + // The next pages come from a 6.x double, which has no types. The cast gives their data the + // type of the first page, as `fromV1Mock` does. + return reply as Result, CallError>; +} + +/** + * The 7.x result for a 6.x page `{ data, total, next }`. `read` is the number of items on the pages + * before it, so the `Link` header gives the offset of the next page. + */ +function pageReply(page: unknown, read: number): Result, CallError> { + const value = typeof page === 'object' && page !== null ? page : {}; + const data: unknown = Reflect.get(value, 'data'); + const total: unknown = Reflect.get(value, 'total'); + const more: unknown = Reflect.get(value, 'next'); + const offset = read + (Array.isArray(data) ? data.length : 0); const headers = new Headers(); - if (page.total !== undefined) headers.set('x-total-count', String(page.total)); - return { ok: true, value: { status: 200, headers, data: page.data, next: () => null } }; + if (typeof total === 'number') headers.set('x-total-count', String(total)); + // `orThrowPage` gives a `next` only when the `Link` header has the next offset. + if (typeof more === 'function') headers.set('link', `; rel="next"`); + const next = (): Promise, CallError>> | null => { + if (typeof more !== 'function') return null; + const following: unknown = Reflect.apply(more, value, []); + if (following === null || following === undefined) return null; + return Promise.resolve(following).then((next_page: unknown) => + pageReply(next_page, offset), + ); + }; + return { ok: true, value: { status: 200, headers, data, next } }; } /** In the arguments of `fromV1Mock`, the input values that no other argument has. */ @@ -164,11 +196,7 @@ export function fromV1Mock, CallError>>( : await Reflect.apply(implementation, undefined, values); if (key !== undefined) return mockReply({ [String(input[key])]: value }); if (result === 'data') return mockReply(value); - // A 6.x page is `{ data, total, next }`. - const page = typeof value === 'object' && value !== null ? value : {}; - const total: unknown = Reflect.get(page, 'total'); - const data: unknown = Reflect.get(page, 'data'); - return mockPage(typeof total === 'number' ? { data, total } : { data }); + return pageReply(value, 0); } } diff --git a/test/compat.test.ts b/test/compat.test.ts index 9d0f284da..9c60d1e18 100644 --- a/test/compat.test.ts +++ b/test/compat.test.ts @@ -173,6 +173,25 @@ test('mockReply and mockPage make the results of test doubles', () => { expect(page.next).toBeNull(); }); +test('fromV1Mock and mockPage keep the next of a 6.x page', async () => { + const last = { data: [{ id: 'zone-3' }], total: 3, next: null }; + const second = { data: [{ id: 'zone-2' }], total: 3, next: () => Promise.resolve(last) }; + const query: (...args: Parameters) => ReturnType = + fromV1Mock( + () => Promise.resolve({ data: [{ id: 'zone-1' }], total: 3, next: () => second }), + ['...'], + 'page', + ); + const first = orThrowPage(await query()); + expect(first.next_offset).toBe(1); + const middle = await first.next?.(); + expect(middle).toMatchObject({ data: [{ id: 'zone-2' }], total: 3, next_offset: 2 }); + const end = await middle?.next?.(); + expect(end).toMatchObject({ data: [{ id: 'zone-3' }], next_offset: null, next: null }); + const typed = orThrowPage(mockPage({ data: [{ id: 'zone-1' }], next: () => last })); + expect((await typed.next?.())?.data).toEqual([{ id: 'zone-3' }]); +}); + test('a page of orThrowPage requests the next page, as in 6.x', async () => { mockEndpoint('zones.query', (input) => input.offset === undefined diff --git a/test/style.test.ts b/test/style.test.ts index 35a969c31..be09c25fe 100644 --- a/test/style.test.ts +++ b/test/style.test.ts @@ -8,7 +8,13 @@ import { Glob } from 'bun'; import { join } from 'node:path'; const SOURCE_DIR = join(import.meta.dir, '..', 'src'); -const ALLOWED_CASTS = ['parsed as O', 'checked as I', 'result as CallResult', 'reply as R']; +const ALLOWED_CASTS = [ + 'parsed as O', + 'checked as I', + 'result as CallResult', + 'reply as R', + 'reply as Result', +]; /** The 6.x mock types of the compat module keep `any`, so that the mocks of an app still compile. */ const ALLOWED_ANY = [ 'compat/http-mock.ts: readonly metadata: any;',