@terrascale/sdk 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +177 -67
  3. package/package.json +10 -4
  4. package/sdk-public-v1-route-manifest.json +81 -0
  5. package/sdk-v1-route-manifest.json +896 -15
  6. package/src/http.js +3 -48
  7. package/src/index.js +75 -1
  8. package/src/local/environment.js +0 -1
  9. package/src/ts-auth.js +1 -5
  10. package/src/v1/backups.js +111 -0
  11. package/src/v1/catalog.js +210 -0
  12. package/src/v1/changes.js +225 -0
  13. package/src/v1/database-schema.js +45 -0
  14. package/src/v1/decode.js +5 -5
  15. package/src/v1/errors.js +23 -3
  16. package/src/v1/ids.js +5 -2
  17. package/src/v1/imports.js +72 -0
  18. package/src/v1/indexes.js +76 -0
  19. package/src/v1/json.js +4 -3
  20. package/src/v1/management-decode.js +24 -0
  21. package/src/v1/management-routes.js +67 -0
  22. package/src/v1/management-validation.js +25 -0
  23. package/src/v1/routes.js +32 -7
  24. package/src/v1/saved-queries.js +58 -0
  25. package/src/v1/shape-crypto.js +125 -0
  26. package/src/v1/shape-manifest.js +31 -0
  27. package/src/v1/shape-reader.js +212 -0
  28. package/src/v1/shape-subscription.js +208 -0
  29. package/src/v1/shapes.js +11 -5
  30. package/src/v1/sql.js +98 -0
  31. package/src/v1/system.js +80 -0
  32. package/src/v1/terrabase-v1.js +178 -27
  33. package/src/v1/transport.js +75 -31
  34. package/src/v1/usage.js +101 -0
  35. package/types/http.d.ts +2 -8
  36. package/types/index.d.ts +68 -0
  37. package/types/local/environment.d.ts +1 -1
  38. package/types/ts-auth.d.ts +0 -2
  39. package/types/v1/backups.d.ts +128 -0
  40. package/types/v1/catalog.d.ts +92 -0
  41. package/types/v1/changes.d.ts +53 -0
  42. package/types/v1/database-schema.d.ts +82 -0
  43. package/types/v1/decode.d.ts +15 -4
  44. package/types/v1/errors.d.ts +16 -1
  45. package/types/v1/ids.d.ts +2 -2
  46. package/types/v1/imports.d.ts +132 -0
  47. package/types/v1/indexes.d.ts +75 -0
  48. package/types/v1/management-decode.d.ts +15 -0
  49. package/types/v1/management-routes.d.ts +3 -0
  50. package/types/v1/management-validation.d.ts +8 -0
  51. package/types/v1/routes.d.ts +5 -2
  52. package/types/v1/saved-queries.d.ts +33 -0
  53. package/types/v1/shape-crypto.d.ts +39 -0
  54. package/types/v1/shape-manifest.d.ts +28 -0
  55. package/types/v1/shape-reader.d.ts +45 -0
  56. package/types/v1/shape-subscription.d.ts +35 -0
  57. package/types/v1/shapes.d.ts +16 -2
  58. package/types/v1/sql.d.ts +47 -0
  59. package/types/v1/system.d.ts +85 -0
  60. package/types/v1/terrabase-v1.d.ts +113 -4
  61. package/types/v1/transport.d.ts +25 -8
  62. package/types/v1/usage.d.ts +171 -0
  63. package/src/ts-auth-discovery.js +0 -207
  64. package/types/ts-auth-discovery.d.ts +0 -19
@@ -0,0 +1,67 @@
1
+ /** @typedef {"getShapeManifest" | "healthz" | "readyz" | "backupz" | "replicationHealth" | "listPlatformDatabases" | "listPlatformCollections" | "listPlatformDocuments" | "getPlatformDocument" | "createImport" | "getImport" | "uploadImportSource" | "updateImport" | "startImport" | "cancelImport" | "resumeImport" | "createBackup" | "listBackups" | "restoreBackup" | "getBackupPolicy" | "setBackupPolicy" | "getRestoreWindow" | "planPointInTime" | "restorePointInTime" | "getBackupDestination" | "setBackupDestination" | "deleteBackupDestination" | "getProjectUsage" | "getProjectAnalytics" | "getProjectReplication" | "getDatabaseUsage" | "getDatabaseAnalytics" | "getDatabaseReplication" | "createIndex" | "listIndexes" | "dropIndex" | "getAutoIndexPolicy" | "setAutoIndexPolicy" | "listIndexRecommendations" | "applyIndexRecommendation" | "getDatabaseSchema" | "inferCollectionSchema" | "declareCollectionSchema" | "listQueryShapes" | "createSavedQuery" | "listSavedQueries" | "getSavedQuery" | "updateSavedQuery" | "deleteSavedQuery"} ManagementOperation */
2
+ const saved = "/v1/projects/{project}/saved-queries";
3
+ /** @type {readonly import("./routes.js").V1Route[]} */
4
+ export const managementV1Routes = Object.freeze([
5
+ route("getShapeManifest", "GET", "/v1/projects/{project}/databases/{database}/collections/{collection}/shape/manifest"),
6
+ route("healthz", "GET", "/healthz"),
7
+ route("readyz", "GET", "/readyz"),
8
+ route("backupz", "GET", "/backupz"),
9
+ route("replicationHealth", "GET", "/health/replication"),
10
+ route("listPlatformDatabases", "GET", "/v1/platform/databases"),
11
+ route("listPlatformCollections", "GET", "/v1/platform/databases/{database}/collections"),
12
+ route("listPlatformDocuments", "GET", "/v1/platform/databases/{database}/collections/{collection}/documents"),
13
+ route("getPlatformDocument", "GET", "/v1/platform/databases/{database}/collections/{collection}/documents/by-key"),
14
+ route("createImport", "POST", "/v1/projects/{project}/databases/{database}/import", 201),
15
+ route("getImport", "GET", "/v1/projects/{project}/databases/{database}/import", 200),
16
+ route("uploadImportSource", "PUT", "/v1/projects/{project}/databases/{database}/import/source", 200),
17
+ route("updateImport", "PATCH", "/v1/projects/{project}/databases/{database}/import", 202),
18
+ route("startImport", "POST", "/v1/projects/{project}/databases/{database}/import/start", 202),
19
+ route("cancelImport", "POST", "/v1/projects/{project}/databases/{database}/import/cancel", 202),
20
+ route("resumeImport", "POST", "/v1/projects/{project}/databases/{database}/import/resume", 202),
21
+ route("createBackup", "POST", "/v1/projects/{project}/databases/{database}/backups", 201),
22
+ route("listBackups", "GET", "/v1/projects/{project}/databases/{database}/backups", 200),
23
+ route("restoreBackup", "POST", "/v1/projects/{project}/databases/{database}/backups/{backup}/restore", 201),
24
+ route("getBackupPolicy", "GET", "/v1/projects/{project}/databases/{database}/backup-policy", 200),
25
+ route("setBackupPolicy", "PUT", "/v1/projects/{project}/databases/{database}/backup-policy", 200),
26
+ route("getRestoreWindow", "GET", "/v1/projects/{project}/databases/{database}/point-in-time", 200),
27
+ route("planPointInTime", "POST", "/v1/projects/{project}/databases/{database}/point-in-time/plan", 200),
28
+ route("restorePointInTime", "POST", "/v1/projects/{project}/databases/{database}/point-in-time/restore", 201),
29
+ route("getBackupDestination", "GET", "/v1/projects/{project}/backup-destination", 200),
30
+ route("setBackupDestination", "PUT", "/v1/projects/{project}/backup-destination", 200),
31
+ route("deleteBackupDestination", "DELETE", "/v1/projects/{project}/backup-destination", 204),
32
+ route("getProjectUsage", "GET", "/v1/projects/{project}/usage"),
33
+ route("getProjectAnalytics", "GET", "/v1/projects/{project}/analytics"),
34
+ route("getProjectReplication", "GET", "/v1/projects/{project}/replication"),
35
+ route("getDatabaseUsage", "GET", "/v1/projects/{project}/databases/{database}/usage"),
36
+ route("getDatabaseAnalytics", "GET", "/v1/projects/{project}/databases/{database}/analytics"),
37
+ route("getDatabaseReplication", "GET", "/v1/projects/{project}/databases/{database}/replication"),
38
+ route("createIndex", "POST", "/v1/projects/{project}/databases/{database}/indexes", 201),
39
+ route("listIndexes", "GET", "/v1/projects/{project}/databases/{database}/indexes", 200),
40
+ route("dropIndex", "DELETE", "/v1/projects/{project}/databases/{database}/indexes/{index}", 204),
41
+ route("getAutoIndexPolicy", "GET", "/v1/projects/{project}/databases/{database}/auto-index/{collection}", 200),
42
+ route("setAutoIndexPolicy", "PUT", "/v1/projects/{project}/databases/{database}/auto-index/{collection}", 200),
43
+ route("listIndexRecommendations", "GET", "/v1/projects/{project}/databases/{database}/index-recommendations", 200),
44
+ route("applyIndexRecommendation", "POST", "/v1/projects/{project}/databases/{database}/index-recommendations/{recommendation}/apply", 201),
45
+ route("getDatabaseSchema", "GET", "/v1/projects/{project}/databases/{database}/schema"),
46
+ route("inferCollectionSchema", "GET", "/v1/projects/{project}/databases/{database}/schema/{collection}"),
47
+ route("declareCollectionSchema", "PUT", "/v1/projects/{project}/databases/{database}/schema/{collection}"),
48
+ route("listQueryShapes", "GET", "/v1/projects/{project}/databases/{database}/query-shapes"),
49
+ route("createSavedQuery", "POST", saved, 201),
50
+ route("listSavedQueries", "GET", saved),
51
+ route("getSavedQuery", "GET", `${saved}/{query}`),
52
+ route("updateSavedQuery", "PUT", `${saved}/{query}`),
53
+ route("deleteSavedQuery", "DELETE", `${saved}/{query}`, 204),
54
+ ]);
55
+
56
+ /** @param {ManagementOperation} operation @param {import("./routes.js").V1Route["method"]} method @param {string} pathTemplate @param {number} [status] @returns {import("./routes.js").V1Route} */
57
+ function route(operation, method, pathTemplate, status = 200) {
58
+ const write = method !== "GET" && operation !== "planPointInTime";
59
+ const noBody = ["createBackup", "applyIndexRecommendation", "cancelImport", "resumeImport"].includes(operation);
60
+ return Object.freeze({ operation, method, pathTemplate,
61
+ permission: operation === "getShapeManifest" ? "documents:read" : pathTemplate.startsWith("/v1/platform/") ? "platform-admin" : !pathTemplate.startsWith("/v1/") ? "anonymous" : write ? "databases:write" : "databases:read",
62
+ additionalPermissions: Object.freeze(["createImport", "uploadImportSource", "updateImport", "startImport", "resumeImport"].includes(operation) ? ["documents:write"] : []),
63
+ requestMediaTypes: Object.freeze(noBody ? [] : operation === "uploadImportSource" ? ["application/octet-stream"] : method === "POST" || method === "PUT" || method === "PATCH" ? ["application/json"] : []),
64
+ responseMediaType: status === 204 ? "" : "application/json", successStatuses: Object.freeze(operation === "readyz" || operation === "backupz" ? [200, 503] : operation === "applyIndexRecommendation" || operation === "createImport" ? [200, 201] : [status]),
65
+ idempotencyKey: "none", replaySafe: !write, contract: "docs/terrabase/api.md", contractText: Object.freeze([]),
66
+ });
67
+ }
@@ -0,0 +1,25 @@
1
+ /** @import { V1DatabaseListRequest } from "./catalog.js" */
2
+ /** @param {unknown} request @param {readonly string[]} allowed */
3
+ export function members(request, allowed) {
4
+ if (request === null || typeof request !== "object" || Array.isArray(request) ||
5
+ ![Object.prototype, null].includes(Object.getPrototypeOf(request))) throw new TypeError("Expected a plain request object.");
6
+ for (const key of Object.keys(request)) if (!allowed.includes(key)) throw new TypeError(`Unknown request member ${key}.`);
7
+ }
8
+ /** @param {object} options */
9
+ export function mutationOptions(options) {
10
+ if ("idempotencyKey" in options) throw new TypeError("The producer does not support Idempotency-Key; mutations are never replayed.");
11
+ }
12
+ /** @param {V1DatabaseListRequest} request */
13
+ export function pageQuery(request) {
14
+ members(request, ["after", "limit"]);
15
+ const query = new URLSearchParams();
16
+ if (request.after !== undefined) {
17
+ if (typeof request.after !== "string") throw new TypeError("after must be an opaque string.");
18
+ query.set("after", request.after);
19
+ }
20
+ if (request.limit !== undefined) {
21
+ if (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 100) throw new TypeError("limit must be 1-100.");
22
+ query.set("limit", String(request.limit));
23
+ }
24
+ return query;
25
+ }
package/src/v1/routes.js CHANGED
@@ -1,11 +1,13 @@
1
- // Routes owned by the C# Documents API at 6cb9745 (decision 0004 and shape-reads.md).
2
- /** @typedef {"getDocument" | "putDocument" | "createDocument" | "patchDocument" | "deleteDocument" | "commitTransaction" | "queryDocuments" | "createCollection" | "getCollection" | "listCollections" | "dropCollection" | "readShape"} V1Operation */
1
+ import { managementV1Routes } from "./management-routes.js";
2
+ // Current TerraBase routes at e30ffdc; readShape is retained from release 6cb9745 only.
3
+ /** @typedef {import("./management-routes.js").ManagementOperation | "readFreeShape" | "getShapeKey" | "getDocument" | "putDocument" | "createDocument" | "patchDocument" | "deleteDocument" | "commitTransaction" | "queryDocuments" | "createCollection" | "getCollection" | "listCollections" | "dropCollection" | "readShape" | "runSql" | "checkSql" | "explainSql" | "streamDatabaseChanges" | "listDocuments" | "getCollectionSchema" | "putCollectionSchema" | "deleteCollectionSchema" | "createDatabase" | "listDatabases" | "getDatabase" | "updateDatabase" | "deleteDatabase" | "branchDatabase"} V1Operation */
3
4
  /**
4
5
  * @typedef {object} V1Route
5
6
  * @property {V1Operation} operation
6
7
  * @property {"GET" | "PUT" | "POST" | "PATCH" | "DELETE"} method
7
8
  * @property {string} pathTemplate
8
- * @property {"documents:read" | "documents:write" | "shapes:read"} permission
9
+ * @property {"documents:read" | "documents:write" | "shapes:read" | "databases:read" | "databases:write" | "anonymous" | "platform-admin"} permission
10
+ * @property {readonly string[]} [additionalPermissions]
9
11
  * @property {readonly string[]} requestMediaTypes
10
12
  * @property {string} responseMediaType
11
13
  * @property {readonly number[]} successStatuses
@@ -18,6 +20,7 @@ const database = "/v1/projects/{project}/databases/{database}";
18
20
  const collections = `${database}/collections`;
19
21
  const collection = `${collections}/{collection}`;
20
22
  const documents = `${collection}/documents`;
23
+ const databases = "/v1/projects/{project}/databases";
21
24
  /** @type {readonly V1Route[]} */
22
25
  export const v1Routes = Object.freeze(/** @type {V1Route[]} */ ([
23
26
  { operation: "getDocument", method: "GET", pathTemplate: `${documents}/by-key`, permission: "documents:read", requestMediaTypes: [], successStatuses: [200] },
@@ -32,10 +35,25 @@ export const v1Routes = Object.freeze(/** @type {V1Route[]} */ ([
32
35
  { operation: "listCollections", method: "GET", pathTemplate: collections, permission: "documents:read", requestMediaTypes: [], successStatuses: [200] },
33
36
  { operation: "dropCollection", method: "DELETE", pathTemplate: collection, permission: "documents:write", requestMediaTypes: [], successStatuses: [200] },
34
37
  { operation: "readShape", method: "GET", pathTemplate: `${collection}/shape`, permission: "shapes:read", requestMediaTypes: [], successStatuses: [200, 307] },
38
+ { operation: "runSql", method: "POST", pathTemplate: `${database}/sql`, permission: "databases:read", requestMediaTypes: ["application/json"], successStatuses: [200] },
39
+ { operation: "checkSql", method: "POST", pathTemplate: `${database}/sql/check`, permission: "databases:read", requestMediaTypes: ["application/json"], successStatuses: [200] },
40
+ { operation: "explainSql", method: "POST", pathTemplate: `${database}/sql/explain`, permission: "databases:read", requestMediaTypes: ["application/json"], successStatuses: [200] },
41
+ { operation: "streamDatabaseChanges", method: "GET", pathTemplate: `${database}/changes`, permission: "documents:read", requestMediaTypes: [], successStatuses: [200] },
42
+ { operation: "listDocuments", method: "GET", pathTemplate: documents, permission: "documents:read", requestMediaTypes: [], successStatuses: [200] },
43
+ { operation: "getCollectionSchema", method: "GET", pathTemplate: `${collection}/schema`, permission: "documents:read", requestMediaTypes: [], successStatuses: [200] },
44
+ { operation: "putCollectionSchema", method: "PUT", pathTemplate: `${collection}/schema`, permission: "documents:write", requestMediaTypes: ["application/json"], successStatuses: [200] },
45
+ { operation: "deleteCollectionSchema", method: "DELETE", pathTemplate: `${collection}/schema`, permission: "documents:write", requestMediaTypes: [], successStatuses: [200] },
46
+ { operation: "createDatabase", method: "POST", pathTemplate: databases, permission: "databases:write", requestMediaTypes: ["application/json"], successStatuses: [201] },
47
+ { operation: "listDatabases", method: "GET", pathTemplate: databases, permission: "databases:read", requestMediaTypes: [], successStatuses: [200] },
48
+ { operation: "getDatabase", method: "GET", pathTemplate: database, permission: "databases:read", requestMediaTypes: [], successStatuses: [200] },
49
+ { operation: "updateDatabase", method: "PATCH", pathTemplate: database, permission: "databases:write", requestMediaTypes: ["application/json"], successStatuses: [200] },
50
+ { operation: "deleteDatabase", method: "DELETE", pathTemplate: database, permission: "databases:write", requestMediaTypes: [], successStatuses: [204] },
51
+ { operation: "branchDatabase", method: "POST", pathTemplate: `${database}/branches`, permission: "databases:write", requestMediaTypes: ["application/json"], successStatuses: [201] },
35
52
  ].map(route => ({
36
- ...route, responseMediaType: "application/json", idempotencyKey: "none",
37
- replaySafe: route.permission !== "documents:write",
38
- contract: route.operation === "readShape" ? "docs/shape-reads.md" : "docs/decisions/0004-document-api-v1.md",
53
+ ...route, responseMediaType: route.operation === "deleteDatabase" ? "" : route.operation === "streamDatabaseChanges" ? "text/event-stream" : "application/json", idempotencyKey: "none",
54
+ replaySafe: !route.permission.endsWith(":write"),
55
+ contract: route.operation === "readShape" ? "docs/shape-reads.md" :
56
+ ["runSql", "checkSql", "explainSql", "streamDatabaseChanges"].includes(route.operation) ? "docs/terrabase/api.md" : "docs/decisions/0004-document-api-v1.md",
39
57
  contractText: [],
40
58
  }))).map(route => Object.freeze({
41
59
  ...route, requestMediaTypes: Object.freeze(route.requestMediaTypes),
@@ -43,7 +61,7 @@ export const v1Routes = Object.freeze(/** @type {V1Route[]} */ ([
43
61
  })));
44
62
  /** @param {V1Operation} operation @returns {V1Route} */
45
63
  export function v1Route(operation) {
46
- const route = v1Routes.find(candidate => candidate.operation === operation);
64
+ const route = [...v1Routes, ...shapeV1Routes, ...managementV1Routes].find(candidate => candidate.operation === operation);
47
65
  if (route === undefined) throw new TypeError(`Unknown v1 operation ${operation}.`);
48
66
  return route;
49
67
  }
@@ -55,3 +73,10 @@ export function v1RoutePath(route, params) {
55
73
  return encodeURIComponent(value);
56
74
  });
57
75
  }
76
+
77
+ // Proposed free-read protocol, separately inventoried from historical/runtime route evidence.
78
+ /** @type {readonly V1Route[]} */
79
+ export const shapeV1Routes = Object.freeze([
80
+ Object.freeze({ operation: /** @type {const} */ ("readFreeShape"), method: /** @type {const} */ ("GET"), pathTemplate: `${collection}/shape`, permission: /** @type {const} */ ("documents:read"), requestMediaTypes: Object.freeze([]), responseMediaType: "application/json", successStatuses: Object.freeze([200, 307]), idempotencyKey: /** @type {const} */ ("none"), replaySafe: true, contract: "docs/terrabase/shape-reads.md", contractText: Object.freeze([]) }),
81
+ Object.freeze({ operation: /** @type {const} */ ("getShapeKey"), method: /** @type {const} */ ("GET"), pathTemplate: `${collection}/shape/keys`, permission: /** @type {const} */ ("documents:read"), requestMediaTypes: Object.freeze([]), responseMediaType: "application/json", successStatuses: Object.freeze([200]), idempotencyKey: /** @type {const} */ ("none"), replaySafe: true, contract: "docs/terrabase/shape-reads.md", contractText: Object.freeze([]) }),
82
+ ]);
@@ -0,0 +1,58 @@
1
+ import { requireId } from "../ids.js";
2
+ import { array, malformed, object, string } from "./decode.js";
3
+ import { stringifyExactJson } from "./json.js";
4
+ import { members, mutationOptions, pageQuery } from "./management-validation.js";
5
+ /** @import { V1Transport } from "./transport.js" */
6
+ /** @import { V1RequestOptions } from "./terrabase-v1.js" */
7
+ /** @typedef {{ readonly id: string; readonly name: string; readonly sql: string; readonly createdAt: string; readonly updatedAt: string | null }} V1SavedQuery */
8
+ /** @typedef {{ readonly name: string; readonly sql: string }} V1SavedQueryRequest */
9
+ /** @typedef {{ readonly items: readonly V1SavedQuery[]; readonly next: string | null }} V1SavedQueryPage */
10
+
11
+ /** @param {import("./json.js").JsonValue | undefined} value @returns {V1SavedQuery} */
12
+ function savedQuery(value) {
13
+ const raw = object(value, "saved query");
14
+ return Object.freeze({ id: requireId(raw.id), name: string(raw.name, "saved query name"), sql: string(raw.sql, "saved SQL"),
15
+ createdAt: string(raw.createdAt, "saved query createdAt"), updatedAt: raw.updatedAt === null ? null : string(raw.updatedAt, "saved query updatedAt") });
16
+ }
17
+ /** @param {V1SavedQueryRequest} request */
18
+ function body(request) {
19
+ members(request, ["name", "sql"]);
20
+ if (typeof request.name !== "string" || request.name.trim().length < 1 || request.name.trim().length > 128 ||
21
+ /[\p{Cc}]/u.test(request.name) || !/[\p{L}\p{N}]/u.test(request.name)) throw new TypeError("name must contain a letter or digit and be 1-128 characters without controls.");
22
+ if (typeof request.sql !== "string" || request.sql.trim() === "" || request.sql.length > 16_384)
23
+ throw new TypeError("sql must be a non-empty statement of at most 16384 UTF-16 code units.");
24
+ return stringifyExactJson({ name: request.name, sql: request.sql }, "saved query");
25
+ }
26
+
27
+ /** Saved queries belong to the authorized project, independently of database handles. */
28
+ export class V1SavedQueries {
29
+ /** @type {V1Transport} */
30
+ #transport;
31
+ /** @param {V1Transport} transport */
32
+ constructor(transport) { this.#transport = transport; Object.freeze(this); }
33
+ /** @param {V1SavedQueryRequest} request @param {V1RequestOptions} [options] @returns {Promise<V1SavedQuery>} */
34
+ async create(request, options = {}) {
35
+ mutationOptions(options);
36
+ return savedQuery((await this.#transport.call("createSavedQuery", {}, { body: body(request), signal: options.signal })).value);
37
+ }
38
+ /** @param {import("./catalog.js").V1DatabaseListRequest} [request] @param {V1RequestOptions} [options] @returns {Promise<V1SavedQueryPage>} */
39
+ async list(request = {}, options = {}) {
40
+ const raw = object((await this.#transport.call("listSavedQueries", {}, { query: pageQuery(request), signal: options.signal })).value, "saved query page");
41
+ if (raw.next !== null && (typeof raw.next !== "string" || raw.next === "")) malformed("saved query next");
42
+ return Object.freeze({ items: Object.freeze(array(raw.items, "saved queries").map(savedQuery)), next: raw.next });
43
+ }
44
+ /** @param {string} id @param {V1RequestOptions} [options] @returns {Promise<V1SavedQuery>} */
45
+ async get(id, options = {}) {
46
+ return savedQuery((await this.#transport.call("getSavedQuery", { query: requireId(id) }, { signal: options.signal })).value);
47
+ }
48
+ /** @param {string} id @param {V1SavedQueryRequest} request @param {V1RequestOptions} [options] @returns {Promise<V1SavedQuery>} */
49
+ async update(id, request, options = {}) {
50
+ mutationOptions(options);
51
+ return savedQuery((await this.#transport.call("updateSavedQuery", { query: requireId(id) }, { body: body(request), signal: options.signal })).value);
52
+ }
53
+ /** @param {string} id @param {V1RequestOptions} [options] @returns {Promise<void>} */
54
+ async delete(id, options = {}) {
55
+ mutationOptions(options);
56
+ await this.#transport.call("deleteSavedQuery", { query: requireId(id) }, { signal: options.signal });
57
+ }
58
+ }
@@ -0,0 +1,125 @@
1
+ const MAGIC = "TBS1";
2
+ const HEADER_BYTES = 70;
3
+ const KEY_ID_BYTES = 26;
4
+ const FRAME_BYTES = 1048576;
5
+ const MAX_PLAINTEXT_BYTES = 8388608;
6
+ const TAG_BYTES = 16;
7
+ const LAST_FRAME_FLAG = 0x80000000;
8
+ const LENGTH_MASK = 0x7fffffff;
9
+ const MAX_UINT64 = 2n ** 64n - 1n;
10
+
11
+ /**
12
+ * @typedef {object} ShapeObjectRequest
13
+ * @property {string} handle The shape handle this client requested, e.g. `h1-…`.
14
+ * @property {string} offset Canonical offset of the object's URL, e.g. `2` or `snap.0.0`.
15
+ * @property {string} epoch Decimal epoch the client expects in the header.
16
+ * @property {string} keyId The 26-character project data key id the client expects in the header.
17
+ * @property {Uint8Array} key Raw 32-byte epoch key `K_e`.
18
+ */
19
+
20
+ /**
21
+ * Verifies and decrypts one TBS1 sealed shape object. The plaintext is returned only when the
22
+ * header, every frame tag and the framing rules pass. Any failure throws and yields no bytes.
23
+ *
24
+ * @param {Uint8Array} input Exact TBS1 object bytes.
25
+ * @param {ShapeObjectRequest} request
26
+ * @returns {Promise<Uint8Array>}
27
+ */
28
+ export async function decryptShapeObject(input, { handle, offset, epoch, keyId, key: keyInput }) {
29
+ if (input.byteLength > HEADER_BYTES + 9 * (4 + TAG_BYTES) + MAX_PLAINTEXT_BYTES)
30
+ throw new TypeError("TBS1 object exceeds the maximum sealed size");
31
+ // WebCrypto needs ArrayBuffer-backed views; copying keeps the caller's (possibly shared) buffer out of it.
32
+ const bytes = Uint8Array.from(input);
33
+ const key = Uint8Array.from(keyInput);
34
+ if (key.byteLength !== 32) throw new TypeError("TBS1 epoch key must be 32 bytes");
35
+ if (typeof keyId !== "string" || !/^[\x00-\x7f]{26}$/u.test(keyId))
36
+ throw new TypeError("TBS1 key id must be 26 ASCII characters");
37
+ if (bytes.byteLength < HEADER_BYTES) throw new TypeError("TBS1 header is short");
38
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
39
+ if (new TextDecoder().decode(bytes.subarray(0, 4)) !== MAGIC) throw new TypeError("TBS1 magic mismatch");
40
+ if (view.getBigUint64(4) !== parseEpoch(epoch)) throw new TypeError("TBS1 epoch mismatch");
41
+ if (new TextDecoder().decode(bytes.subarray(12, 12 + KEY_ID_BYTES)) !== keyId) throw new TypeError("TBS1 key id mismatch");
42
+
43
+ const header = bytes.subarray(0, HEADER_BYTES);
44
+ const { subtle } = globalThis.crypto;
45
+ const epochKey = await subtle.importKey("raw", key, "HKDF", false, ["deriveKey"]);
46
+ const objectKey = await subtle.deriveKey(
47
+ {
48
+ name: "HKDF",
49
+ hash: "SHA-256",
50
+ salt: bytes.slice(38, HEADER_BYTES),
51
+ info: new TextEncoder().encode(`TBS1 object\u0000${handle}\u0000${offset}`),
52
+ },
53
+ epochKey,
54
+ { name: "AES-GCM", length: 256 },
55
+ false,
56
+ ["decrypt"],
57
+ );
58
+
59
+ const plaintextParts = [];
60
+ let plaintextTotal = 0;
61
+ let position = HEADER_BYTES;
62
+ for (let index = 0; ; index += 1) {
63
+ if (position + 4 > bytes.byteLength) throw new TypeError("TBS1 object ends before its last frame");
64
+ const lengthWord = view.getUint32(position);
65
+ const last = (lengthWord & LAST_FRAME_FLAG) !== 0;
66
+ const length = lengthWord & LENGTH_MASK;
67
+ if (last ? length >= FRAME_BYTES : length !== FRAME_BYTES) throw new TypeError("TBS1 frame length is invalid");
68
+ plaintextTotal += length;
69
+ if (plaintextTotal > MAX_PLAINTEXT_BYTES) throw new TypeError("TBS1 plaintext exceeds 8 MiB");
70
+ const bodyStart = position + 4;
71
+ const frameEnd = bodyStart + length + TAG_BYTES;
72
+ if (frameEnd > bytes.byteLength) throw new TypeError("TBS1 object is truncated");
73
+ const nonce = concat(new Uint8Array(4), uint64(index));
74
+ const additionalData = concat(header, uint64(index), bytes.subarray(position, bodyStart));
75
+ try {
76
+ const plaintext = await subtle.decrypt(
77
+ { name: "AES-GCM", iv: nonce, additionalData, tagLength: 128 },
78
+ objectKey,
79
+ bytes.subarray(bodyStart, frameEnd),
80
+ );
81
+ plaintextParts.push(new Uint8Array(plaintext));
82
+ } catch {
83
+ throw new TypeError("TBS1 frame failed authentication");
84
+ }
85
+ position = frameEnd;
86
+ if (last) break;
87
+ }
88
+ if (position !== bytes.byteLength) throw new TypeError("TBS1 object has bytes after its last frame");
89
+ return concat(...plaintextParts);
90
+ }
91
+
92
+ /**
93
+ * @param {string} value
94
+ * @returns {bigint}
95
+ */
96
+ function parseEpoch(value) {
97
+ if (!/^(0|[1-9][0-9]*)$/u.test(value)) throw new TypeError("TBS1 epoch must be a canonical decimal");
98
+ const epoch = BigInt(value);
99
+ if (epoch > MAX_UINT64) throw new TypeError("TBS1 epoch exceeds uint64");
100
+ return epoch;
101
+ }
102
+
103
+ /**
104
+ * @param {number} value
105
+ * @returns {Uint8Array}
106
+ */
107
+ function uint64(value) {
108
+ const out = new Uint8Array(8);
109
+ new DataView(out.buffer).setBigUint64(0, BigInt(value));
110
+ return out;
111
+ }
112
+
113
+ /**
114
+ * @param {...Uint8Array} parts
115
+ * @returns {Uint8Array<ArrayBuffer>}
116
+ */
117
+ function concat(...parts) {
118
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
119
+ let at = 0;
120
+ for (const part of parts) {
121
+ out.set(part, at);
122
+ at += part.byteLength;
123
+ }
124
+ return out;
125
+ }
@@ -0,0 +1,31 @@
1
+ import { requireId } from "../ids.js";
2
+ import { malformed } from "./decode.js";
3
+ import { list, numeric, record, text } from "./management-decode.js";
4
+ import { requireFilter } from "./filter.js";
5
+ import { stringifyExactJson } from "./json.js";
6
+ import { requireShapeHandle, requireShapeOffset } from "./shapes.js";
7
+ /** @import { V1Transport } from "./transport.js" */
8
+ const manifest = record({ handle: requireShapeHandle, objects: list(record({ offset: requireShapeOffset, next_offset: requireShapeOffset,
9
+ binding: text, object: text, url: text, expires_at: text, epoch: text, key_id: requireId, sha256: text, size: numeric })) });
10
+ /** @typedef {ReturnType<typeof manifest>} V1ShapeManifest */
11
+ /** @typedef {{readonly handle: string; readonly offset: string; readonly where?: import("./filter.js").V1Filter}} V1ShapeManifestRequest */
12
+ /** @param {V1Transport} transport @param {Readonly<Record<string, string>>} params @param {V1ShapeManifestRequest} request @param {AbortSignal | undefined} signal @returns {Promise<V1ShapeManifest>} */
13
+ export async function readShapeManifest(transport, params, request, signal) {
14
+ const handle = requireShapeHandle(request.handle);
15
+ const offset = requireShapeOffset(request.offset);
16
+ if (offset === "-1") throw new TypeError("A manifest requires a snapshot or log offset.");
17
+ const query = new URLSearchParams({ handle, offset });
18
+ if (request.where !== undefined) query.set("where", stringifyExactJson(requireFilter(request.where), "shape filter"));
19
+ const response = await transport.call("getShapeManifest", params, { query, cache: "no-store", signal });
20
+ const result = manifest(response.value);
21
+ if (result.handle !== handle || result.objects.length > 8) malformed("shape manifest binding");
22
+ let next = offset;
23
+ for (const item of result.objects) {
24
+ if (item.offset !== next || item.next_offset === item.offset || item.offset === "-1" || item.next_offset === "-1" ||
25
+ !/^[a-f0-9]{64}$/u.test(item.sha256) || !/^(?:0|[1-9][0-9]*)$/u.test(item.epoch)) malformed("shape manifest object");
26
+ const url = new URL(item.url);
27
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.hash !== "") malformed("shape object URL");
28
+ next = item.next_offset;
29
+ }
30
+ return result;
31
+ }
@@ -0,0 +1,212 @@
1
+ // The proposed free-read v1 protocol is separate from the historical shape() contract.
2
+ import { requireId } from "../ids.js";
3
+ import { malformed, object, string } from "./decode.js";
4
+ import { decodeShapePage, encodeShapeRequest, requireShapeHandle, requireShapeOffset } from "./shapes.js";
5
+ import { decryptShapeObject } from "./shape-crypto.js";
6
+ import { parseExactJson } from "./json.js";
7
+ import { TerraBaseV1Error } from "./errors.js";
8
+ /** @import { V1Transport } from "./transport.js" */
9
+ /** @import { V1ShapeRequest, V1ShapePage } from "./shapes.js" */
10
+ /** @typedef {{handle: string; offset: string; epoch: string; keyId: string}} V1SealedShapePosition */
11
+ /** @typedef {{ latestEpoch: bigint; keys: Map<string, { epoch: bigint; key: Uint8Array }> }} ShapeKeys */
12
+ /** @type {WeakMap<V1Transport, Map<string, ShapeKeys>>} Keys stay scoped to a credential, database and collection. */
13
+ const shapeKeys = new WeakMap();
14
+ /** @param {Readonly<Record<string, string>>} params */
15
+ const keyScope = params => JSON.stringify([params.database, params.collection]);
16
+ /**
17
+ * A refetch invalidates both the materialized state and any epoch keys for that collection.
18
+ * @param {V1Transport} transport @param {Readonly<Record<string, string>>} params
19
+ * @param {"readFreeShape" | "getShapeKey"} operation @param {import("./transport.js").V1CallOptions} options
20
+ */
21
+ async function shapeCall(transport, params, operation, options) {
22
+ try { return await transport.call(operation, params, options); }
23
+ catch (error) {
24
+ if (error instanceof TerraBaseV1Error && error.status === 409 && error.code === "must_refetch")
25
+ shapeKeys.get(transport)?.delete(keyScope(params));
26
+ throw error;
27
+ }
28
+ }
29
+ /** @param {V1Transport} transport @param {Readonly<Record<string, string>>} params @returns {ShapeKeys} */
30
+ function currentKeys(transport, params) {
31
+ let scopes = shapeKeys.get(transport);
32
+ if (scopes === undefined) { scopes = new Map(); shapeKeys.set(transport, scopes); }
33
+ const scope = keyScope(params);
34
+ let cache = scopes.get(scope);
35
+ if (cache === undefined) { cache = { latestEpoch: 0n, keys: new Map() }; scopes.set(scope, cache); }
36
+ // Expiry is lazy; a higher served epoch also protects against a regressed client clock.
37
+ const epoch = BigInt(Math.floor(Date.now() / 600_000));
38
+ if (epoch > cache.latestEpoch) cache.latestEpoch = epoch;
39
+ for (const [id, entry] of cache.keys) if (entry.epoch < cache.latestEpoch) cache.keys.delete(id);
40
+ return cache;
41
+ }
42
+ /** @param {unknown} value @returns {string} */
43
+ function decimal(value) {
44
+ const text = requireShapeOffset(value);
45
+ if (text === "-1" || text.startsWith("snap.")) malformed("shape decimal");
46
+ return text;
47
+ }
48
+ /** @param {unknown} value @returns {string} */
49
+ function resumeToken(value) {
50
+ // Resume envelopes are opaque: validate header safety, never decode or normalize them.
51
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value)) malformed("shape resume cursor");
52
+ return value;
53
+ }
54
+ /** @param {string} offset @returns {string} */
55
+ function snapshotKey(offset) {
56
+ const encoded = offset.split(".")[2] ?? "";
57
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
58
+ Uint8Array.from(atob(encoded.replace(/-/gu, "+").replace(/_/gu, "/")), c => c.charCodeAt(0)),
59
+ );
60
+ }
61
+ /** @param {import("./json.js").JsonValue | undefined} value @param {Headers} headers @returns {V1ShapePage} */
62
+ export function decodeFreeShapePage(value, headers) {
63
+ const page = decodeShapePage(value, headers);
64
+ const raw = object(value, "free shape page");
65
+ const covered = decimal(raw.covered_offset);
66
+ const values = decimal(raw.values_at);
67
+ resumeToken(raw.cursor_resume);
68
+ if (page.offset === "-1" || page.nextOffset === "-1" || BigInt(values) < BigInt(covered)) malformed("shape coverage");
69
+ if (page.offset.startsWith("snap.")) {
70
+ const head = page.offset.split(".")[1];
71
+ if (covered !== head || values !== head || page.upToDate || page.changes.length !== 1 || page.changes[0]?.offset !== head ||
72
+ page.changes[0]?.ops.some(op => op.op !== "upsert") ||
73
+ (page.nextOffset.startsWith("snap.") ? page.nextOffset.split(".")[1] !== head || page.nextOffset === page.offset : page.nextOffset !== head))
74
+ malformed("shape snapshot coverage");
75
+ if (page.nextOffset.startsWith("snap.") && (page.nextOffset.endsWith(".0") ||
76
+ (!page.offset.endsWith(".0") && snapshotKey(page.nextOffset) <= snapshotKey(page.offset)))) malformed("shape snapshot progression");
77
+ } else {
78
+ if (page.nextOffset.startsWith("snap.") || page.nextOffset !== covered || BigInt(covered) < BigInt(page.offset) ||
79
+ (!page.upToDate && covered === page.offset)) malformed("shape log coverage");
80
+ let previous = BigInt(page.offset);
81
+ for (const change of page.changes) {
82
+ const offset = BigInt(decimal(change.offset));
83
+ if (offset <= previous || offset > BigInt(covered)) malformed("shape commit order");
84
+ previous = offset;
85
+ }
86
+ }
87
+ for (const change of page.changes) {
88
+ let previousId;
89
+ for (const op of change.ops) {
90
+ if (previousId !== undefined && op.id <= previousId) malformed("shape document order");
91
+ previousId = op.id;
92
+ }
93
+ }
94
+ return page;
95
+ }
96
+ /**
97
+ * Follows exactly one authorized same-route 307; credentials never follow an arbitrary Location.
98
+ * @param {V1Transport} transport @param {Readonly<Record<string,string>>} params
99
+ * @param {V1ShapeRequest} request @param {AbortSignal | undefined} signal
100
+ * @param {string | undefined} [ifNoneMatch] A complete entity-tag list or *; 304 throws not_modified with response headers.
101
+ * @returns {Promise<V1ShapePage>}
102
+ */
103
+ export async function readShapePage(transport, params, request, signal, ifNoneMatch) {
104
+ const isResume = (request.offset ?? "-1") === "-1" && request.cursor !== undefined;
105
+ if (isResume && (request.handle !== undefined || request.live !== undefined)) throw new TypeError("Shape resume requires offset=-1 without handle or live.");
106
+ const query = encodeShapeRequest(isResume ? { ...request, cursor: undefined } : request);
107
+ // Canonical filter size is checked by the producer; check our exact wire spelling here.
108
+ if (new TextEncoder().encode(query.get("where") ?? "").byteLength > 8192) throw new TypeError("Shape filters are limited to 8 KiB of UTF-8.");
109
+ if (query.get("offset") === "-1" && query.has("handle")) throw new TypeError("Shape bootstrap must omit handle.");
110
+ /** @type {Record<string,string>} */
111
+ const headers = {};
112
+ if (ifNoneMatch !== undefined) {
113
+ if (typeof ifNoneMatch !== "string" || !/^[ \t]*(?:\*|(?:W\/)?"[\x21\x23-\x7e\x80-\xff]*"(?:[ \t]*,[ \t]*(?:W\/)?"[\x21\x23-\x7e\x80-\xff]*")*)[ \t]*$/u.test(ifNoneMatch))
114
+ throw new TypeError("ifNoneMatch must be * or a list of quoted entity tags.");
115
+ headers["If-None-Match"] = ifNoneMatch;
116
+ }
117
+ const source = new URL(await transport.url("readFreeShape", params, signal));
118
+ if (isResume) {
119
+ query.set("cursor", resumeToken(request.cursor));
120
+ // The producer reserves 64 bytes for request-line framing in its 8 KiB ceiling.
121
+ if (new TextEncoder().encode(`${source.pathname}?${query}`).length > 8192 - 64) {
122
+ headers["TB-Shape-Resume"] = resumeToken(request.cursor);
123
+ query.delete("cursor");
124
+ }
125
+ }
126
+ let response = await shapeCall(transport, params, "readFreeShape", { query, headers, signal });
127
+ if (response.status === 307) {
128
+ if (query.get("offset") !== "-1") malformed("unexpected shape redirect");
129
+ const location = response.headers.get("location");
130
+ if (location === null) malformed("shape redirect Location");
131
+ const target = new URL(location, source);
132
+ if (target.origin !== source.origin || target.pathname !== source.pathname || target.username !== "" || target.password !== "" || target.hash !== "") malformed("shape redirect target");
133
+ for (const key of target.searchParams.keys()) {
134
+ if (!["where", "handle", "offset"].includes(key) || target.searchParams.getAll(key).length !== 1) malformed("shape redirect query");
135
+ }
136
+ const handle = requireShapeHandle(target.searchParams.get("handle"));
137
+ const offset = requireShapeOffset(target.searchParams.get("offset"));
138
+ if (offset === "-1" || (!isResume && !/^snap\.[0-9]+\.0$/u.test(offset)) || (isResume && offset.startsWith("snap."))) malformed("shape redirect offset");
139
+ if (target.searchParams.has("where") !== query.has("where")) malformed("shape redirect filter");
140
+ // Keep the caller's validated filter: the server's canonical spelling must not broaden it.
141
+ query.delete("cursor");
142
+ delete headers["TB-Shape-Resume"];
143
+ query.set("handle", handle);
144
+ query.set("offset", offset);
145
+ response = await shapeCall(transport, params, "readFreeShape", { query, headers, signal });
146
+ if (response.status !== 200) malformed("repeated shape redirect");
147
+ } else if (query.get("offset") === "-1") malformed("shape bootstrap requires redirect");
148
+ const page = decodeFreeShapePage(response.value, response.headers);
149
+ if (page.handle !== query.get("handle") || page.offset !== query.get("offset")) malformed("shape response position");
150
+ const inputCursor = query.get("cursor");
151
+ if (request.live === true && (page.cursor === undefined || (inputCursor !== null && BigInt(page.cursor) <= BigInt(inputCursor)))) malformed("shape live cursor advance");
152
+ return page;
153
+ }
154
+ /**
155
+ * Reuse process-memory keys for this handle/epoch/KID; fetch misses without HTTP cache reuse.
156
+ * @param {V1Transport} transport @param {Readonly<Record<string,string>>} params
157
+ * @param {Uint8Array} bytes @param {V1SealedShapePosition} position @param {AbortSignal | undefined} signal
158
+ * @returns {Promise<V1ShapePage>}
159
+ */
160
+ export async function decryptSealedShapePage(transport, params, bytes, position, signal) {
161
+ const handle = requireShapeHandle(position.handle);
162
+ const offset = requireShapeOffset(position.offset);
163
+ if (offset === "-1") throw new TypeError("Sealed shapes require a snapshot or log offset.");
164
+ if (typeof position.epoch !== "string" || !/^(?:0|[1-9][0-9]*)$/u.test(position.epoch) || BigInt(position.epoch) > (1n << 64n) - 1n) throw new TypeError("Shape epoch must be a canonical uint64.");
165
+ const epoch = position.epoch;
166
+ const keyId = requireId(position.keyId, "Shape key ID");
167
+ signal?.throwIfAborted();
168
+ const cache = currentKeys(transport, params);
169
+ const cacheId = JSON.stringify([handle, epoch, keyId]);
170
+ let raw = cache.keys.get(cacheId)?.key;
171
+ if (raw === undefined) {
172
+ const query = new URLSearchParams({ handle, epoch, key_id: keyId });
173
+ const response = await shapeCall(transport, params, "getShapeKey", { query, cache: "no-store", signal });
174
+ const key = object(response.value, "shape epoch key");
175
+ if (key.handle !== handle || key.epoch !== epoch || key.key_id !== keyId) malformed("shape epoch key binding");
176
+ const encoded = string(key.key, "shape epoch key");
177
+ if (!/^[A-Za-z0-9_-]{43}$/u.test(encoded)) malformed("shape epoch key encoding");
178
+ raw = Uint8Array.from(atob(encoded.replace(/-/gu, "+").replace(/_/gu, "/")), c => c.charCodeAt(0));
179
+ if (btoa(String.fromCharCode(...raw)).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "") !== encoded) malformed("shape epoch key encoding");
180
+ const servedEpoch = BigInt(epoch);
181
+ const active = currentKeys(transport, params);
182
+ if (active === cache && servedEpoch >= cache.latestEpoch) {
183
+ cache.latestEpoch = servedEpoch;
184
+ for (const [id, entry] of cache.keys) if (entry.epoch < servedEpoch) cache.keys.delete(id);
185
+ cache.keys.set(cacheId, { epoch: servedEpoch, key: raw });
186
+ }
187
+ }
188
+ const plaintext = await decryptShapeObject(bytes, { handle, offset, epoch, keyId, key: raw });
189
+ signal?.throwIfAborted();
190
+ const page = decodeFreeShapePage(parseExactJson(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(plaintext)), new Headers());
191
+ if (page.handle !== handle || page.offset !== offset || page.upToDate) malformed("sealed shape position");
192
+ return page;
193
+ }
194
+
195
+ /** @typedef {{readonly handle: string; readonly epoch: string; readonly keyId: string}} V1ShapeKeyRequest */
196
+ /** @typedef {V1ShapeKeyRequest & {readonly key: Uint8Array}} V1ShapeKey */
197
+ /** @param {V1Transport} transport @param {Readonly<Record<string, string>>} params @param {V1ShapeKeyRequest} request @param {AbortSignal | undefined} signal @returns {Promise<V1ShapeKey>} */
198
+ export async function readShapeKey(transport, params, request, signal) {
199
+ const handle = requireShapeHandle(request.handle);
200
+ const epoch = decimal(request.epoch);
201
+ const keyId = requireId(request.keyId);
202
+ const response = await shapeCall(transport, params, "getShapeKey", {
203
+ query: new URLSearchParams({ handle, epoch, key_id: keyId }), cache: "no-store", signal,
204
+ });
205
+ const key = object(response.value, "shape epoch key");
206
+ if (key.handle !== handle || key.epoch !== epoch || key.key_id !== keyId) malformed("shape epoch key binding");
207
+ const encoded = string(key.key, "shape key");
208
+ if (!/^[A-Za-z0-9_-]{43}$/u.test(encoded)) malformed("shape key encoding");
209
+ const bytes = Uint8Array.from(atob(encoded.replace(/-/gu, "+").replace(/_/gu, "/")), c => c.charCodeAt(0));
210
+ if (btoa(String.fromCharCode(...bytes)).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "") !== encoded) malformed("shape key encoding");
211
+ return Object.freeze({ handle, epoch, keyId, key: bytes });
212
+ }