@tapedb/tapedb 0.0.0-stage → 0.1.0
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.
- package/API.md +301 -0
- package/LICENSE +21 -0
- package/LIMITATIONS.md +34 -0
- package/PRIVACY.md +119 -0
- package/README.md +720 -2
- package/RELEASING.md +117 -0
- package/SECURITY.md +121 -0
- package/dist/chunk-3AL32Q4K.js +241 -0
- package/dist/chunk-3AL32Q4K.js.map +1 -0
- package/dist/chunk-CYDXFAEB.js +33 -0
- package/dist/chunk-CYDXFAEB.js.map +1 -0
- package/dist/chunk-UYZJAMBR.js +27 -0
- package/dist/chunk-UYZJAMBR.js.map +1 -0
- package/dist/chunk-VWW5OS5B.js +841 -0
- package/dist/chunk-VWW5OS5B.js.map +1 -0
- package/dist/cli.d.ts +44 -0
- package/dist/cli.js +1501 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-DgSnn9BE.d.ts +646 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +3007 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +41 -0
- package/dist/react.js +59 -0
- package/dist/react.js.map +1 -0
- package/dist/schema-CVcGZJfR.d.ts +691 -0
- package/dist/schema-entry-CpO_IGFv.d.ts +522 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +22 -0
- package/dist/schema.js.map +1 -0
- package/dist/worker.d.ts +437 -0
- package/dist/worker.js +9270 -0
- package/dist/worker.js.map +1 -0
- package/package.json +93 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engine/value-to-api.ts","../src/engine/tx-types.ts","../src/engine/tx-validate.ts","../src/engine/tx-permissions.ts","../src/engine/topics.ts","../src/engine/audit.ts","../src/engine/schema-evolution.ts","../src/engine/personal.ts","../src/engine/query-stages.ts","../src/engine/query-types.ts","../src/engine/sql-binding.ts","../src/engine/tx-apply.ts","../src/engine/query-aggregate.ts","../src/engine/query-compile.ts","../src/engine/query-execute.ts","../src/engine/file-access.ts","../src/engine/durability/retention.ts","../src/engine/r2-keys.ts","../src/engine/workspace-room.ts","../src/engine/tx-hash.ts","../src/http.ts","../src/engine/durability/log-segment.ts","../src/engine/durability/types.ts","../src/engine/durability/manifest.ts","../src/engine/durability/flusher.ts","../src/engine/r2-list.ts","../src/engine/durability/snapshot.ts","../src/engine/durability/durability.ts","../src/engine/tx-log.ts","../src/engine/tx-bulk.ts","../src/engine/tx-pipeline.ts","../src/engine/file-index.ts","../src/engine/durability/recovery.ts","../src/engine/durability/recovery-support.ts","../src/engine/migrations.ts","../src/engine/subscriptions.ts","../src/engine/storage-routes.ts","../src/engine/export.ts","../src/engine/import-workspace.ts","../src/engine/workspace-move.ts","../src/engine/claim-limits.ts","../src/engine/socket-state.ts","../src/verify.ts","../src/engine/trusted-claim.ts","../src/engine/personal-migrate.ts","../src/engine/personal-write.ts","../src/engine/tx-sql.ts","../src/engine/ws-handshake.ts","../src/engine/ws-types.ts","../src/mint.ts","../src/claim-route.ts","../src/worker/index.ts"],"sourcesContent":["import type { AttributeType } from \"./registry\";\nimport type { SqlValue } from \"./tx-sql\";\n\n/** Converts a stored value to the API shape for its registry type. */\nexport function fromStoredValue(\n type: AttributeType,\n value: SqlValue | undefined\n): unknown {\n if (value === null || value === undefined) return null;\n\n switch (type) {\n case \"string\":\n return typeof value === \"string\" ? value : String(value);\n case \"number\":\n return typeof value === \"number\" ? value : Number(value);\n case \"boolean\":\n return value !== 0;\n case \"date\":\n return toEpochMilliseconds(value);\n case \"json\":\n case \"any\":\n return typeof value === \"string\" ? parseJson(value) : value;\n }\n}\n\nfunction toEpochMilliseconds(value: SqlValue): number | null {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : null;\n }\n if (typeof value === \"string\") {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction parseJson(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n // Stored JSON should be valid; keep the request alive if it is not.\n return value;\n }\n}\n\n","/**\n * Transaction contract shared by the client and the workspace engine.\n *\n * This module is intentionally dependency-free: it describes the wire shape\n * only. Validation, permission checks, SQL compilation and execution live in\n * the engine's transaction pipeline.\n *\n * Op names match the familiar `transact(tx.ns[id].update/merge/link/...)` API.\n * `namespace` and `link` are registry API names (camelCase), never SQL table\n * names. All ids are client-generated strings (UUIDv7).\n */\n\nexport type TxOpKind =\n | \"insert\"\n | \"patch\"\n | \"upsert\"\n | \"patchMany\"\n | \"deleteMany\"\n | \"update\"\n | \"merge\"\n | \"link\"\n | \"unlink\"\n | \"delete\";\n\nexport interface TxOpBase {\n op: TxOpKind;\n /** Namespace API name, e.g. \"documents\" or \"boards\". */\n namespace: string;\n /** Entity id (UUID string). */\n id: string;\n}\n\n/** Creates the row. Fails with `unique_violation` when the id already exists. */\nexport interface TxInsertOp extends TxOpBase {\n op: \"insert\";\n values: Record<string, unknown>;\n}\n\n/** Writes the supplied attributes. Fails with `not_found` when the row is missing. */\nexport interface TxPatchOp extends TxOpBase {\n op: \"patch\";\n values: Record<string, unknown>;\n}\n\n/** Upsert: creates the row if missing, otherwise writes the supplied attributes. */\nexport interface TxUpdateOp extends TxOpBase {\n op: \"update\";\n values: Record<string, unknown>;\n}\n\n/** Same as `update`: an upsert of the supplied attributes. Kept for old clients. */\n/**\n * Creates the row from `create` when it is missing, otherwise writes `values`.\n * The engine decides inside the transaction, so the choice cannot race.\n */\nexport interface TxUpsertOp extends TxOpBase {\n op: \"upsert\";\n values: Record<string, unknown>;\n create: Record<string, unknown>;\n}\n\nexport interface TxMergeOp extends TxOpBase {\n op: \"merge\";\n values: Record<string, unknown>;\n}\n\n/** Links the source entity to a target through a registered link. */\nexport interface TxLinkOp extends TxOpBase {\n op: \"link\";\n /** Link API name, e.g. \"folderDocuments\". */\n link: string;\n targetId: string;\n}\n\n/** Removes a link created by `link`. */\nexport interface TxUnlinkOp extends TxOpBase {\n op: \"unlink\";\n link: string;\n targetId: string;\n}\n\n/** Deletes the row; FK rules decide whether dependent rows cascade or null. */\nexport interface TxDeleteOp extends TxOpBase {\n op: \"delete\";\n}\n\n/**\n * Writes every row matching `where`. The engine resolves the rows inside the\n * transaction and logs what it resolved, so a replay changes the same rows as\n * the original — re-running the filter later could not promise that.\n */\nexport interface TxPatchManyOp {\n op: \"patchMany\";\n namespace: string;\n where: Record<string, unknown>;\n values: Record<string, unknown>;\n /** Resume after this id: the `more` cursor of the previous batch. */\n after?: string;\n}\n\n/** Deletes every row matching `where`. Resolved and logged like `patchMany`. */\nexport interface TxDeleteManyOp {\n op: \"deleteMany\";\n namespace: string;\n where: Record<string, unknown>;\n after?: string;\n}\n\nexport type TxOp =\n | TxPatchManyOp\n | TxDeleteManyOp\n | TxInsertOp\n | TxPatchOp\n | TxUpsertOp\n | TxUpdateOp\n | TxMergeOp\n | TxLinkOp\n | TxUnlinkOp\n | TxDeleteOp;\n\nexport interface TxEnvelope {\n /** Server-visible transaction id. */\n txId: string;\n /** Client id used to dedupe retries of the same optimistic write. */\n clientTxId?: string;\n /**\n * When the client first issued the transaction (ms), resent unchanged on\n * every retry. Unknown writes older than a legacy receipt boundary are\n * refused with `retry_expired`; retained receipts have no age limit.\n */\n issuedAt?: number;\n ops: TxOp[];\n}\n\nexport interface TxResult {\n txId: string;\n /** Rows a bulk op matched, keyed by its index in the envelope. */\n matched?: Record<number, number>;\n /**\n * For a bulk op that matched more rows than one batch holds: the cursor to\n * send back as its `after`, keyed by its index in the envelope.\n */\n more?: Record<number, string>;\n /** `_tx_log.seq` assigned to this transaction. */\n seq: number;\n /** Number of ops that changed a row. */\n applied: number;\n}\n\nexport type TxErrorCode =\n | \"invalid_envelope\"\n | \"invalid_op\"\n | \"unknown_namespace\"\n | \"unknown_attribute\"\n | \"unknown_link\"\n | \"invalid_value\"\n | \"not_found\"\n | \"conflict\"\n | \"unique_violation\"\n | \"foreign_key_violation\"\n | \"permission_denied\"\n | \"retry_expired\"\n | \"storage_error\";\n\n/** Plain-object form of a transaction error, suitable for JSON responses. */\nexport interface TxErrorShape {\n code: TxErrorCode;\n message: string;\n txId?: string;\n opIndex?: number;\n}\n\nexport interface TxErrorOptions {\n txId?: string;\n opIndex?: number;\n}\n\nexport class TxError extends Error {\n readonly code: TxErrorCode;\n readonly txId?: string;\n readonly opIndex?: number;\n\n constructor(\n code: TxErrorCode,\n message: string,\n options: TxErrorOptions = {}\n ) {\n super(message);\n this.name = \"TxError\";\n this.code = code;\n this.txId = options.txId;\n this.opIndex = options.opIndex;\n }\n\n toJSON(): TxErrorShape {\n return {\n code: this.code,\n message: this.message,\n ...(this.txId === undefined ? {} : { txId: this.txId }),\n ...(this.opIndex === undefined ? {} : { opIndex: this.opIndex }),\n };\n }\n}\n","/**\n * Transaction validation.\n *\n * Validation happens before any mutation so a bad op cannot leave a partial\n * row behind. It normalises wire values into SQLite bindings:\n *\n * - `date` (epoch ms number or ISO-8601 string) -> epoch ms number\n * - `boolean` -> 1/0\n * - `json` / `any` -> JSON text\n * - `createdAt` / `updatedAt` are accepted but ignored; the engine owns them\n * - `id` and `updatedSeq` / `updated_seq` are reserved and rejected\n */\n\nimport {\n findNamespace,\n LINKS,\n toSnakeCase,\n type AttributeDefinition,\n type LinkDefinition,\n type NamespaceDefinition,\n} from \"./registry\";\nimport type { SqlValue } from \"./tx-sql\";\nimport { TxError, type TxOpKind } from \"./tx-types\";\n\nconst ID_PATTERN = /^[A-Za-z0-9_:|.-]{1,128}$/;\nconst ISO_DATE_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\nconst RESERVED_ATTRIBUTES = new Set([\"id\", \"updatedSeq\", \"updated_seq\"]);\nconst ENGINE_MANAGED_ATTRIBUTES = new Set([\"createdAt\", \"updatedAt\"]);\nconst OP_KINDS = new Set<TxOpKind>([\n \"insert\",\n \"patch\",\n \"upsert\",\n \"patchMany\",\n \"deleteMany\",\n \"update\",\n \"merge\",\n \"link\",\n \"unlink\",\n \"delete\",\n]);\n\nexport interface ValidatedValuesOp {\n kind: \"insert\" | \"patch\" | \"upsert\" | \"update\" | \"merge\";\n namespace: string;\n id: string;\n /** Values keyed by SQLite column name. */\n values: Record<string, SqlValue>;\n /** `upsert` only: the values for the row when it does not exist yet. */\n createValues?: Record<string, SqlValue>;\n}\n\n/** A bulk write, before the engine resolves which rows it touches. */\nexport interface ValidatedBulkOp {\n kind: \"patchMany\" | \"deleteMany\";\n namespace: string;\n /** Client-shaped query filter; compiled when the rows are resolved. */\n where: Record<string, unknown>;\n /** `patchMany` only: values keyed by SQLite column name. */\n values?: Record<string, SqlValue>;\n /** Resume after this id. */\n after?: string;\n}\n\nexport interface ValidatedDeleteOp {\n kind: \"delete\";\n namespace: string;\n id: string;\n}\n\nexport interface ValidatedLinkOp {\n kind: \"link\" | \"unlink\";\n namespace: string;\n id: string;\n link: string;\n targetId: string;\n /** Namespace that owns the foreign key. */\n childNamespace: string;\n /** Row whose foreign key is written. */\n childId: string;\n /** Row the foreign key points at. */\n parentId: string;\n foreignKeyAttribute: string;\n foreignKeyColumn: string;\n}\n\nexport type ValidatedOp =\n | ValidatedBulkOp\n | ValidatedValuesOp\n | ValidatedDeleteOp\n | ValidatedLinkOp;\n\nexport interface ValidatedTx {\n txId: string;\n clientTxId?: string;\n /** When the client first issued this transaction (ms). Retries carry the original time. */\n issuedAt?: number;\n ops: ValidatedOp[];\n /** Original ops array, used for the stable log hash. */\n rawOps: unknown[];\n}\n\ninterface ValidationContext {\n txId: string;\n opIndex: number;\n}\n\nexport function validateEnvelope(value: unknown): ValidatedTx {\n if (!isPlainObject(value)) {\n throw new TxError(\"invalid_envelope\", \"Transaction must be an object.\");\n }\n\n const txId = value.txId;\n if (typeof txId !== \"string\" || txId.trim().length === 0) {\n throw new TxError(\n \"invalid_envelope\",\n \"Transaction id must be a non-empty string.\"\n );\n }\n\n const clientTxId = value.clientTxId;\n if (\n clientTxId !== undefined &&\n (typeof clientTxId !== \"string\" || clientTxId.trim().length === 0)\n ) {\n throw new TxError(\n \"invalid_envelope\",\n \"clientTxId must be a non-empty string when present.\",\n { txId }\n );\n }\n\n const issuedAt = value.issuedAt;\n if (issuedAt !== undefined && (typeof issuedAt !== \"number\" || !Number.isFinite(issuedAt))) {\n throw new TxError(\"invalid_envelope\", \"issuedAt must be a timestamp in milliseconds when present.\", { txId });\n }\n\n const rawOps = value.ops;\n if (!Array.isArray(rawOps) || rawOps.length < 1) {\n throw new TxError(\n \"invalid_envelope\",\n \"Transaction must contain at least one op.\",\n { txId }\n );\n }\n\n const ops = rawOps.map((op, opIndex) => validateOp(op, { txId, opIndex }));\n\n return {\n txId,\n ...(clientTxId === undefined ? {} : { clientTxId }),\n ...(issuedAt === undefined ? {} : { issuedAt }),\n ops,\n rawOps,\n };\n}\n\nfunction validateOp(value: unknown, context: ValidationContext): ValidatedOp {\n if (!isPlainObject(value)) {\n throw invalidOp(\"Op must be an object.\", context);\n }\n\n const kind = value.op;\n if (typeof kind !== \"string\" || !OP_KINDS.has(kind as TxOpKind)) {\n throw invalidOp(\"Op kind is not recognised.\", context);\n }\n const opKind = kind as TxOpKind;\n\n const namespaceName = value.namespace;\n if (typeof namespaceName !== \"string\" || namespaceName.length === 0) {\n throw invalidOp(\"Op namespace is required.\", context);\n }\n\n if (opKind === \"patchMany\" || opKind === \"deleteMany\") {\n const namespace = findNamespace(namespaceName);\n if (!namespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${namespaceName}\".`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n if (!isPlainObject(value.where)) {\n throw invalidOp(`\"${opKind}\" needs a \"where\" object.`, context);\n }\n if (value.after !== undefined && (typeof value.after !== \"string\" || !ID_PATTERN.test(value.after))) {\n throw invalidOp(`\"${opKind}\" \"after\" must be a row id.`, context);\n }\n return {\n kind: opKind,\n namespace: namespaceName,\n where: value.where,\n ...(value.after !== undefined ? { after: value.after } : {}),\n ...(opKind === \"patchMany\"\n ? { values: validateValues(namespace, value.values, context) }\n : {}),\n } as ValidatedOp;\n }\n\n const namespace = findNamespace(namespaceName);\n if (!namespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${namespaceName}\".`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n\n const id = value.id;\n if (typeof id !== \"string\" || !ID_PATTERN.test(id)) {\n throw invalidOp(\"Op id must match [A-Za-z0-9_:|.-]{1,128}.\", context);\n }\n\n switch (opKind) {\n case \"insert\":\n case \"patch\":\n case \"update\":\n case \"merge\":\n return {\n kind: opKind,\n namespace: namespaceName,\n id,\n values: validateValues(namespace, value.values, context),\n };\n case \"upsert\":\n return {\n kind: \"upsert\",\n namespace: namespaceName,\n id,\n values: validateValues(namespace, value.values, context),\n createValues: validateValues(namespace, value.create, context),\n };\n case \"delete\":\n return { kind: \"delete\", namespace: namespaceName, id };\n case \"link\":\n case \"unlink\":\n return validateLinkOp(opKind, value, namespaceName, id, context);\n }\n}\n\nfunction validateValues(\n namespace: NamespaceDefinition,\n value: unknown,\n context: ValidationContext\n): Record<string, SqlValue> {\n if (!isPlainObject(value)) {\n throw invalidOp(\"update/merge values must be a plain object.\", context);\n }\n\n const normalised: Record<string, SqlValue> = {};\n\n for (const [attribute, attributeValue] of Object.entries(value)) {\n if (RESERVED_ATTRIBUTES.has(attribute)) {\n throw new TxError(\n \"unknown_attribute\",\n `Attribute \"${attribute}\" is reserved.`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n\n const definition = namespace.attributes[attribute];\n if (!definition) {\n throw new TxError(\n \"unknown_attribute\",\n `Unknown attribute \"${attribute}\" on namespace \"${namespace.apiName}\".`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n\n const normalisedValue = normaliseValue(\n attribute,\n definition,\n attributeValue,\n context\n );\n\n // The engine sets these columns itself; accept them on the wire but do not\n // let a client claim them.\n if (ENGINE_MANAGED_ATTRIBUTES.has(attribute)) continue;\n\n normalised[toSnakeCase(attribute)] = normalisedValue;\n }\n\n return normalised;\n}\n\nfunction validateLinkOp(\n kind: \"link\" | \"unlink\",\n value: Record<string, unknown>,\n namespaceName: string,\n id: string,\n context: ValidationContext\n): ValidatedLinkOp {\n const linkName = value.link;\n if (typeof linkName !== \"string\" || linkName.length === 0) {\n throw invalidOp(\"link/unlink requires a link api name.\", context);\n }\n\n const link = (LINKS as Record<string, LinkDefinition>)[linkName];\n if (!link) {\n throw new TxError(\"unknown_link\", `Unknown link \"${linkName}\".`, {\n txId: context.txId,\n opIndex: context.opIndex,\n });\n }\n\n const targetId = value.targetId;\n if (typeof targetId !== \"string\" || !ID_PATTERN.test(targetId)) {\n throw invalidOp(\n \"link/unlink target id must match [A-Za-z0-9_:|.-]{1,128}.\",\n context\n );\n }\n\n const forwardMatch = namespaceName === link.forward.namespace;\n const reverseMatch = namespaceName === link.reverse.namespace;\n if (!forwardMatch && !reverseMatch) {\n throw invalidOp(\n `Link \"${linkName}\" does not connect namespace \"${namespaceName}\".`,\n context\n );\n }\n\n const childNamespace = findNamespace(link.foreignKey.namespace);\n if (!childNamespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown link child namespace \"${link.foreignKey.namespace}\".`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n\n const foreignKeyAttribute = link.foreignKey.attribute;\n if (!childNamespace.attributes[foreignKeyAttribute]) {\n throw new TxError(\n \"unknown_link\",\n `Link \"${linkName}\" has an unregistered foreign key.`,\n { txId: context.txId, opIndex: context.opIndex }\n );\n }\n\n // For a self-referential link (folderChildren, blockChildren) both labels\n // share one namespace, so the api name is interpreted in its forward\n // direction: source is the parent, target is the child.\n const useForward = forwardMatch;\n const childId = useForward ? targetId : id;\n const parentId = useForward ? id : targetId;\n\n return {\n kind,\n namespace: namespaceName,\n id,\n link: linkName,\n targetId,\n childNamespace: childNamespace.apiName,\n childId,\n parentId,\n foreignKeyAttribute,\n foreignKeyColumn: toSnakeCase(foreignKeyAttribute),\n };\n}\n\n/**\n * True when `value` is acceptable for the attribute under today's registry.\n * Recovery uses it to drop an old value a later type change no longer fits.\n */\nexport function acceptsValue(namespaceName: string, attribute: string, value: unknown): boolean {\n const definition = findNamespace(namespaceName)?.attributes[attribute];\n if (!definition) return false;\n try {\n normaliseValue(attribute, definition, value, { txId: \"recovery\", opIndex: 0 });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normaliseValue(\n attribute: string,\n definition: AttributeDefinition,\n value: unknown,\n context: ValidationContext\n): SqlValue {\n if (value === null) {\n if (!definition.optional) {\n throw invalidValue(\n `Attribute \"${attribute}\" is required and cannot be null.`,\n context\n );\n }\n return null;\n }\n\n switch (definition.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n throw invalidValue(\n `Attribute \"${attribute}\" must be a string.`,\n context\n );\n }\n return value;\n case \"number\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw invalidValue(\n `Attribute \"${attribute}\" must be a finite number.`,\n context\n );\n }\n return value;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw invalidValue(\n `Attribute \"${attribute}\" must be a boolean.`,\n context\n );\n }\n return value ? 1 : 0;\n case \"date\":\n return normaliseDate(attribute, value, context);\n case \"json\":\n case \"any\":\n assertJsonSerialisable(attribute, value, context, new Set<object>());\n return JSON.stringify(value);\n }\n}\n\nfunction normaliseDate(\n attribute: string,\n value: unknown,\n context: ValidationContext\n): number {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\" && ISO_DATE_PATTERN.test(value)) {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n\n throw invalidValue(\n `Attribute \"${attribute}\" must be epoch milliseconds or an ISO-8601 date.`,\n context\n );\n}\n\nfunction assertJsonSerialisable(\n attribute: string,\n value: unknown,\n context: ValidationContext,\n seen: Set<object>\n): void {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidValue(\n `Attribute \"${attribute}\" contains a non-finite number.`,\n context\n );\n }\n return;\n }\n\n if (Array.isArray(value)) {\n enterObject(value, attribute, context, seen);\n for (const item of value) {\n assertJsonSerialisable(attribute, item, context, seen);\n }\n seen.delete(value);\n return;\n }\n\n if (isPlainObject(value)) {\n enterObject(value, attribute, context, seen);\n for (const item of Object.values(value)) {\n assertJsonSerialisable(attribute, item, context, seen);\n }\n seen.delete(value);\n return;\n }\n\n throw invalidValue(\n `Attribute \"${attribute}\" must be JSON-serialisable.`,\n context\n );\n}\n\nfunction enterObject(\n value: object,\n attribute: string,\n context: ValidationContext,\n seen: Set<object>\n): void {\n if (seen.has(value)) {\n throw invalidValue(\n `Attribute \"${attribute}\" contains a circular value.`,\n context\n );\n }\n seen.add(value);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function isEngineManagedAttribute(attribute: string): boolean {\n return ENGINE_MANAGED_ATTRIBUTES.has(attribute);\n}\n\n/**\n * Columns that must be supplied when a row is inserted. Engine-managed\n * timestamps are excluded because `tx-apply` always writes them.\n */\nexport function requiredColumns(namespace: NamespaceDefinition): string[] {\n return Object.entries(namespace.attributes)\n .filter(\n ([attribute, definition]) =>\n !definition.optional && !ENGINE_MANAGED_ATTRIBUTES.has(attribute)\n )\n .map(([attribute]) => toSnakeCase(attribute));\n}\n\n/** True for an unresolved bulk write. `expandBulkOps` replaces these. */\nexport function isBulkOp(op: ValidatedOp): op is ValidatedBulkOp {\n return op.kind === \"patchMany\" || op.kind === \"deleteMany\";\n}\n\nexport function isLinkOp(op: ValidatedOp): op is ValidatedLinkOp {\n return op.kind === \"link\" || op.kind === \"unlink\";\n}\n\nfunction invalidOp(message: string, context: ValidationContext): TxError {\n return new TxError(\"invalid_op\", message, {\n txId: context.txId,\n opIndex: context.opIndex,\n });\n}\n\nfunction invalidValue(message: string, context: ValidationContext): TxError {\n return new TxError(\"invalid_value\", message, {\n txId: context.txId,\n opIndex: context.opIndex,\n });\n}\n","/**\n * Permissions.\n *\n * Two kinds of decision, one place:\n *\n * - a **role level** (the default: view=MEMBER, write=EDITOR, delete=MODERATOR)\n * - a **row rule**: a predicate that sees the caller and the row\n *\n * Row rules exist because role levels cannot express \"only the author may edit\n * this\". They run inside the transaction, next to the write they gate, so the\n * row they judge is the row being changed.\n *\n * `view` accepts two rule forms. A function rule is evaluated per fetched row,\n * so it can express anything but cannot use an index: the executor scans to\n * fill a page, bounded by a cap. A `where` rule returns a query filter for the\n * caller, which is compiled into the SQL of every level that reads the\n * namespace, so it uses indexes and never short-fills a page.\n */\n\nimport { hasRole, WORKSPACE_ROLE_LEVELS, type RoleClaim, type WorkspaceRole } from \"../claims\";\nimport { assertDecisionShape, isViewWhereRule } from \"./permission-shape\";\nimport type { QueryWhere } from \"./query-types\";\nimport { findNamespace, toSnakeCase } from \"./registry\";\nimport type { SqlExecutor, SqlRow } from \"./tx-sql\";\nimport { fromStoredValue } from \"./value-to-api\";\nimport { TxError } from \"./tx-types\";\nimport { isBulkOp, isLinkOp, type ValidatedOp } from \"./tx-validate\";\n\nexport type PermissionAction = \"view\" | \"create\" | \"update\" | \"delete\";\n\n/** The caller, as far as a rule is concerned. */\nexport interface PermissionAuth {\n sub: string;\n role: WorkspaceRole;\n workspaceId: string;\n}\n\n/**\n * What a rule receives.\n *\n * `data` is the stored row for update, delete and link operations, with API\n * attribute names. `next` is the incoming values for create and update.\n */\nexport interface PermissionContext {\n auth: PermissionAuth;\n data?: Record<string, unknown>;\n next?: Record<string, unknown>;\n /**\n * API attribute names this op writes. Lets a rule gate one field: \"only the\n * owner may change `price`\" is\n * `changed.includes(\"price\") ? data.ownerId === auth.sub : true`.\n */\n changed?: string[];\n}\n\n/** A rule returns true to allow. Throw or return false to deny. */\nexport type PermissionRule = (context: PermissionContext) => boolean;\n\n/**\n * A `view` rule SQL can evaluate: the rows the caller may see, as a `where`\n * filter. An array is OR of its branches, so \"mine or public\" is\n * `[{ ownerId: auth.sub }, { isPublic: true }]`. An empty array hides\n * everything. Only valid for `view`.\n */\nexport interface ViewWhereRule {\n where: (auth: PermissionAuth) => QueryWhere | readonly QueryWhere[];\n}\n\nexport type PermissionDecision = WorkspaceRole | PermissionRule | ViewWhereRule;\n\nexport type PermissionOverrides = Record<\n string,\n Partial<Record<PermissionAction, PermissionDecision>>\n>;\n\nexport interface PermissionConfig {\n overrides?: PermissionOverrides;\n}\n\nexport { assertDecisionShape, isViewWhereRule };\n\nfunction isRule(decision: PermissionDecision): boolean {\n return typeof decision === \"function\" || isViewWhereRule(decision);\n}\n\nconst DEFAULT_PERMISSIONS: Record<PermissionAction, WorkspaceRole> = {\n view: WORKSPACE_ROLE_LEVELS.MEMBER,\n create: WORKSPACE_ROLE_LEVELS.EDITOR,\n update: WORKSPACE_ROLE_LEVELS.EDITOR,\n delete: WORKSPACE_ROLE_LEVELS.MODERATOR,\n};\n\n/** Explicit per-namespace overrides supplied by the deployment's schema. */\nconst NAMESPACE_OVERRIDES: PermissionOverrides = {};\n\n/** Installs the deployment's permission overrides. Called once per instance. */\nexport function configurePermissions(config: PermissionConfig = {}): void {\n for (const key of Object.keys(NAMESPACE_OVERRIDES)) {\n delete NAMESPACE_OVERRIDES[key];\n }\n for (const [namespace, actions] of Object.entries(config.overrides ?? {})) {\n for (const [action, decision] of Object.entries(actions ?? {})) {\n assertDecisionShape(namespace, action, decision);\n }\n NAMESPACE_OVERRIDES[namespace] = actions;\n }\n}\n\nfunction authOf(claim: RoleClaim): PermissionAuth {\n return { sub: claim.sub, role: claim.role, workspaceId: claim.workspaceId };\n}\n\n/**\n * The caller's `where` view filter for a namespace, as OR branches.\n *\n * `null` means the namespace has no where rule. A rule that throws returns no\n * branches, which hides every row: a broken rule must never widen access. The\n * shape is validated by the compiler, so a malformed filter is an error, not a\n * silent pass.\n */\nexport function viewWhereBranches(\n claim: RoleClaim,\n namespace: string\n): readonly QueryWhere[] | null {\n const decision = decisionFor(namespace, \"view\");\n if (!isViewWhereRule(decision)) return null;\n\n let result: QueryWhere | readonly QueryWhere[];\n try {\n result = decision.where(authOf(claim));\n } catch {\n return [];\n }\n return Array.isArray(result) ? result : [result as QueryWhere];\n}\n\nfunction decisionFor(\n namespace: string,\n action: PermissionAction\n): PermissionDecision {\n return NAMESPACE_OVERRIDES[namespace]?.[action] ?? DEFAULT_PERMISSIONS[action];\n}\n\n/**\n * True when what a caller may read of the namespace depends on who they are,\n * not only on their role: a function rule or a `where` rule, both of which\n * see the caller's subject. Role levels and the defaults depend on the role\n * alone, so two callers with the same role read the same rows.\n */\nexport function viewDependsOnSubject(namespace: string): boolean {\n const decision = decisionFor(namespace, \"view\");\n return typeof decision === \"function\" || isViewWhereRule(decision);\n}\n\n/**\n * True when the namespace's `view` decision is a function rule, which runs\n * after fetch. A count over such a namespace would include rows the rule\n * hides, so the executor refuses one.\n */\nexport function hasFunctionViewRule(namespace: string): boolean {\n return typeof decisionFor(namespace, \"view\") === \"function\";\n}\n\n/**\n * Evaluates a `view` rule against one row.\n *\n * Read rules cannot be pushed into SQL: they are arbitrary predicates. The\n * query executor calls this per fetched row, so a page can come back smaller\n * than the limit.\n */\nexport function allowRowView(\n claim: RoleClaim,\n namespace: string,\n data: Record<string, unknown>\n): boolean {\n const decision = decisionFor(namespace, \"view\");\n // Level decisions were checked up front; where rules already ran in SQL.\n if (typeof decision !== \"function\") return true;\n\n try {\n return (\n decision({\n auth: {\n sub: claim.sub,\n role: claim.role,\n workspaceId: claim.workspaceId,\n },\n data,\n }) === true\n );\n } catch {\n // Fail closed: a broken read rule hides the row rather than exposing it.\n return false;\n }\n}\n\n/** Minimum role for a level decision. Throws when the namespace uses a rule. */\nexport function minimumRole(\n namespace: string,\n action: PermissionAction\n): WorkspaceRole {\n if (!findNamespace(namespace)) {\n throw new TxError(\"permission_denied\", `Unknown namespace \"${namespace}\".`);\n }\n\n const decision = decisionFor(namespace, action);\n if (isRule(decision)) {\n throw new TxError(\n \"permission_denied\",\n `\"${namespace}.${action}\" is a row rule, not a role level.`\n );\n }\n return decision as WorkspaceRole;\n}\n\n/**\n * Level check. A namespace whose action is a row rule is skipped here: the\n * rule is evaluated against the row inside the transaction instead.\n */\nexport function assertPermission(\n claim: RoleClaim,\n namespace: string,\n action: PermissionAction\n): void {\n if (!findNamespace(namespace)) {\n throw new TxError(\"permission_denied\", `Unknown namespace \"${namespace}\".`);\n }\n\n const decision = decisionFor(namespace, action);\n if (isRule(decision)) return;\n\n if (!hasRole(claim, decision as WorkspaceRole)) {\n throw new TxError(\n \"permission_denied\",\n `Role ${claim.role} is not allowed to ${action} \"${namespace}\".`\n );\n }\n}\n\nexport function assertOpPermission(claim: RoleClaim, op: ValidatedOp): void {\n if (isLinkOp(op)) {\n assertPermission(claim, op.childNamespace, \"update\");\n return;\n }\n\n switch (op.kind) {\n case \"patchMany\":\n assertPermission(claim, op.namespace, \"update\");\n return;\n case \"deleteMany\":\n assertPermission(claim, op.namespace, \"delete\");\n return;\n case \"insert\":\n assertPermission(claim, op.namespace, \"create\");\n return;\n case \"patch\":\n assertPermission(claim, op.namespace, \"update\");\n return;\n case \"upsert\":\n case \"update\":\n case \"merge\": {\n // Existence decides the action inside the transaction. At this point\n // reject only if neither branch can possibly be allowed.\n const create = decisionFor(op.namespace, \"create\");\n const update = decisionFor(op.namespace, \"update\");\n if (!isRule(create) && !hasRole(claim, create as WorkspaceRole) &&\n !isRule(update) && !hasRole(claim, update as WorkspaceRole)) {\n assertPermission(claim, op.namespace, \"update\");\n }\n return;\n }\n case \"delete\":\n assertPermission(claim, op.namespace, \"delete\");\n return;\n }\n}\n\nexport function authorizeOps(claim: RoleClaim, ops: ValidatedOp[]): void {\n for (const op of ops) assertOpPermission(claim, op);\n}\n\ninterface RowTarget {\n namespace: string;\n action: PermissionAction;\n id: string;\n values?: Record<string, unknown>;\n}\n\n/**\n * Which action an op represents.\n *\n * `update` is an upsert in this engine, so the action depends on whether the\n * row exists: an insert is a `create` and must satisfy the create rule, not\n * the update rule. Deciding from the op kind alone would let a create skip the\n * create rule entirely.\n */\nfunction targetOf(op: ValidatedOp, rowExists: boolean): RowTarget {\n if (isBulkOp(op)) {\n // expandBulkOps resolves these to per-row ops before rules are evaluated.\n throw new TxError(\n \"invalid_op\",\n `\"${op.kind}\" reached the row rules; it should have been resolved to rows first.`\n );\n }\n if (isLinkOp(op)) {\n // A link writes the child's foreign key, so the child's update rule decides.\n return { namespace: op.childNamespace, action: \"update\", id: op.childId,\n values: { [op.foreignKeyColumn]: op.kind === \"link\" ? op.parentId : null } };\n }\n if (op.kind === \"delete\") {\n return { namespace: op.namespace, action: \"delete\", id: op.id };\n }\n // insert and patch name their action outright; the apply step refuses an\n // insert over an existing row and a patch of a missing one.\n const action =\n op.kind === \"insert\"\n ? \"create\"\n : op.kind === \"patch\"\n ? \"update\"\n : rowExists\n ? \"update\"\n : \"create\";\n return {\n namespace: op.namespace,\n action,\n id: op.id,\n // An upsert that creates is judged on what it will create.\n values:\n op.kind === \"upsert\" && !rowExists && op.createValues !== undefined\n ? op.createValues\n : op.values,\n };\n}\n\n/**\n * Whether the caller may update or delete the stored row `id`: the\n * namespace's role level, or its row rule against the row as stored. A row\n * that does not exist, or a rule that throws, denies.\n */\nexport function allowStoredRow(\n sql: SqlExecutor,\n claim: RoleClaim,\n namespace: string,\n id: string,\n action: \"update\" | \"delete\"\n): boolean {\n if (!findNamespace(namespace)) return false;\n const data = readRow(sql, namespace, id);\n if (data === undefined) return false;\n const decision = decisionFor(namespace, action);\n if (typeof decision !== \"function\") return hasRole(claim, decision as WorkspaceRole);\n try {\n return decision({ auth: authOf(claim), data }) === true;\n } catch {\n return false;\n }\n}\n\n/** Stored row with API attribute names, or undefined when it does not exist. */\nfunction readRow(\n sql: SqlExecutor,\n namespace: string,\n id: string\n): Record<string, unknown> | undefined {\n const definition = findNamespace(namespace);\n if (!definition) return undefined;\n\n let row = sql.one<SqlRow>(\n `SELECT * FROM \"${definition.table}\" WHERE \"id\" = ?`,\n id\n );\n if (row === undefined) return undefined;\n row = sql.decodeRows?.(namespace, [row])[0] ?? row;\n\n const output: Record<string, unknown> = { id };\n for (const attribute of Object.keys(definition.attributes)) {\n const column = toSnakeCase(attribute);\n if (column in row) output[attribute] = fromStoredValue(definition.attributes[attribute].type, row[column]);\n }\n return output;\n}\n\n/** Incoming values arrive keyed by column; rules see API attribute names. */\nfunction valuesToApi(\n namespace: string,\n values: Record<string, unknown>\n): Record<string, unknown> {\n const definition = findNamespace(namespace);\n if (!definition) return values;\n\n const byColumn = new Map<string, string>();\n for (const attribute of Object.keys(definition.attributes)) {\n byColumn.set(toSnakeCase(attribute), attribute);\n }\n\n const output: Record<string, unknown> = {};\n for (const [column, value] of Object.entries(values)) {\n const attribute = byColumn.get(column) ?? column;\n output[attribute] = definition.attributes[attribute]\n ? fromStoredValue(definition.attributes[attribute].type, value as never)\n : value;\n }\n return output;\n}\n\n/**\n * Evaluates row rules for every op. Must run inside the transaction so the row\n * a rule reads is the row the write will change.\n *\n * A rule that throws denies: a broken rule must never widen access.\n */\nexport function assertRowPermissions(\n sql: SqlExecutor,\n claim: RoleClaim,\n ops: ValidatedOp[]\n): void {\n for (const op of ops) {\n if (isBulkOp(op)) {\n throw new TxError(\n \"invalid_op\",\n `\"${op.kind}\" reached the row rules; it should have been resolved to rows first.`\n );\n }\n const id = isLinkOp(op) ? op.childId : op.id;\n const namespace = isLinkOp(op) ? op.childNamespace : op.namespace;\n const data = readRow(sql, namespace, id);\n const target = targetOf(op, data !== undefined);\n\n assertPermission(claim, target.namespace, target.action);\n const decision = decisionFor(target.namespace, target.action);\n if (typeof decision !== \"function\") continue;\n\n const context: PermissionContext = {\n auth: {\n sub: claim.sub,\n role: claim.role,\n workspaceId: claim.workspaceId,\n },\n data,\n next:\n target.values === undefined\n ? undefined\n : valuesToApi(target.namespace, target.values),\n changed:\n target.values === undefined\n ? undefined\n : Object.keys(valuesToApi(target.namespace, target.values)),\n };\n\n let allowed = false;\n try {\n allowed = decision(context) === true;\n } catch {\n allowed = false;\n }\n\n if (!allowed) {\n throw new TxError(\n \"permission_denied\",\n `Row rule denied ${target.action} on \"${target.namespace}\".`\n );\n }\n }\n}\n\n/** Exposed for tests and for future query-side authorization. */\nexport const PERMISSION_MATRIX = {\n defaults: DEFAULT_PERMISSIONS,\n overrides: NAMESPACE_OVERRIDES,\n} as const;\n","/**\n * Broadcast topics: fire-and-forget messages between the sockets of one\n * workspace, on the socket they already hold.\n *\n * A socket joins topics; a message sent to a topic reaches every other socket\n * joined to it, with the sender's client id and subject, and a per-topic\n * sequence number. The room keeps the last `replaySeconds` of each topic\n * (default 60, at most `REPLAY_MESSAGES`): a client that rejoins after a\n * reconnect passes the last sequence it saw and gets what it missed first.\n * Joined topics live in the socket attachment, so they survive hibernation,\n * and the client rejoins them after a reconnect.\n *\n * Who may join or send is the deployment's call (`defineTapeDB({ topics })`);\n * by default anyone with a claim for the workspace may, guests included, as\n * with presence.\n */\n\nimport type { RoleClaim } from \"../claims\";\n\n/** Topic names: the same alphabet and length as presence targets. */\nexport const TOPIC_PATTERN = /^[A-Za-z0-9:_.-]{1,128}$/;\n\nexport function isTopic(value: unknown): value is string {\n return typeof value === \"string\" && TOPIC_PATTERN.test(value);\n}\n\n/** @experimental May change in a minor release. */\nexport type TopicAction = \"join\" | \"send\";\n\n/**\n * Decides whether a caller may join a topic or send to it. Return false (or\n * throw) to refuse; the socket gets a `topic:error` and nothing else happens.\n *\n * @experimental May change in a minor release.\n */\nexport type TopicAuthorizer = (context: {\n auth: { sub: string; role: number; workspaceId: string };\n topic: string;\n action: TopicAction;\n}) => boolean;\n\nlet authorizer: TopicAuthorizer | null = null;\nlet replayMs = 60_000;\n\n/** Messages kept per topic for replay, however short their age. */\nexport const REPLAY_MESSAGES = 1000;\n\n/**\n * Topic options for `defineTapeDB({ topics })`.\n *\n * @experimental May change in a minor release.\n */\nexport interface TopicOptions {\n authorize?: TopicAuthorizer;\n /** Seconds of each topic kept for clients that reconnect; 0 keeps none. Default 60. */\n replaySeconds?: number;\n}\n\n/** Installed by `defineTapeDB({ topics })`. */\nexport function configureTopics(options: TopicOptions | undefined): void {\n authorizer = options?.authorize ?? null;\n const seconds = options?.replaySeconds ?? 60;\n if (!(typeof seconds === \"number\" && seconds >= 0 && Number.isFinite(seconds))) {\n throw new Error(\"topics.replaySeconds must be a number of seconds, 0 or more.\");\n }\n replayMs = seconds * 1000;\n}\n\nexport function topicReplayMs(): number {\n return replayMs;\n}\n\nexport function topicAllowed(claim: RoleClaim, topic: string, action: TopicAction): boolean {\n if (authorizer === null) return true;\n try {\n return (\n authorizer({\n auth: { sub: claim.sub, role: claim.role, workspaceId: claim.workspaceId },\n topic,\n action,\n }) === true\n );\n } catch {\n return false;\n }\n}\n","/**\n * Opt-in write audit: who changed each row, and when.\n *\n * Off by default, because the writer's identity is personal data nothing in\n * the engine needs. With `defineTapeDB({ audit: true })`:\n *\n * - every transaction's log row carries the claim's subject and role, in the\n * local log and in the log lines shipped to R2, and recovery restores them;\n * - a trigger on each model table records (table, row, seq, time, subject,\n * role) in `_tx_audit` for every row a transaction changes, cascades\n * included. It reads the writer from the transaction's own log row, which\n * every write path appends before it touches data.\n *\n * `_tx_audit` is snapshotted and restored with the workspace, and pruned by\n * age with the rest of the history (`retention.days`), so the writer's\n * identity leaves every copy within the retention.\n */\n\nimport { namespaceTables } from \"./registry\";\nimport type { SqlExecutor } from \"./tx-sql\";\n\nexport const AUDIT_TABLE = \"_tx_audit\";\n\nlet enabled = false;\n\n/** Installed by `defineTapeDB({ audit })`. */\nexport function configureAudit(on: boolean | undefined): void {\n enabled = on === true;\n}\n\nexport function auditEnabled(): boolean {\n return enabled;\n}\n\nconst triggerName = (table: string, action: string) => `_tapedb_audit_${table}_${action}`;\n\n/**\n * Removes the capture triggers. Runs before schema migrations, so a\n * migration's own writes (a backfill, a table rebuild) are not attributed to\n * the last transaction's writer.\n */\nexport function dropAuditCapture(sql: SqlExecutor): void {\n for (const row of sql.all<{ name: string }>(\n `SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE '\\_tapedb\\_audit\\_%' ESCAPE '\\\\'`\n )) {\n sql.exec(`DROP TRIGGER IF EXISTS \"${row.name}\"`);\n }\n}\n\n/**\n * Creates the capture triggers when audit is on and drops them when it is\n * off, so turning audit off stops recording at the next boot.\n */\nexport function syncAuditCapture(sql: SqlExecutor): void {\n for (const table of namespaceTables()) {\n for (const action of [\"INSERT\", \"UPDATE\", \"DELETE\"] as const) {\n const name = triggerName(table, action);\n if (!enabled) {\n sql.exec(`DROP TRIGGER IF EXISTS \"${name}\"`);\n continue;\n }\n const row = action === \"DELETE\" ? \"OLD\" : \"NEW\";\n // Writes outside a logged transaction (a restore from a snapshot) find\n // no log row and record nothing.\n sql.exec(\n `CREATE TRIGGER IF NOT EXISTS \"${name}\" AFTER ${action} ON \"${table}\"\n WHEN EXISTS (SELECT 1 FROM \"_tx_log\")\n BEGIN\n INSERT OR REPLACE INTO \"${AUDIT_TABLE}\" (id, table_name, row_id, seq, at, user_id, role, action)\n SELECT '${table}' || char(31) || ${row}.id || char(31) || seq,\n '${table}', ${row}.id, seq, at, user_id, role, '${action.toLowerCase()}'\n FROM \"_tx_log\" ORDER BY seq DESC LIMIT 1;\n END`\n );\n }\n }\n}\n\nexport interface AuditEntry {\n seq: number;\n at: number;\n /** The writer's claim subject. */\n sub: string | null;\n role: number | null;\n action: \"insert\" | \"update\" | \"delete\";\n}\n\n/** Every recorded change to one row, oldest first. */\nexport function rowHistory(sql: SqlExecutor, table: string, id: string): AuditEntry[] {\n return sql\n .all<{ seq: number; at: number; user_id: string | null; role: number | null; action: string }>(\n `SELECT seq, at, user_id, role, action FROM \"${AUDIT_TABLE}\" WHERE table_name = ? AND row_id = ? ORDER BY seq`,\n table,\n id\n )\n .map((row) => ({\n seq: Number(row.seq),\n at: Number(row.at),\n sub: row.user_id,\n role: row.role === null ? null : Number(row.role),\n action: row.action as AuditEntry[\"action\"],\n }));\n}\n","/**\n * Reading old data through later schema changes.\n *\n * Recovery restores a snapshot and replays log lines that were written under\n * whatever schema was current at the time. If a migration since then dropped\n * or renamed a field, an old line still names it, and replaying it against\n * today's registry would fail and leave the workspace unable to boot.\n *\n * Migrations therefore declare what they changed, and recovery projects old\n * rows and ops through every change made after they were written. Only\n * declared changes are tolerated: an attribute or column that no migration\n * accounts for is still an error, so corrupted or foreign data fails closed.\n */\n\nimport {\n BASELINE_MIGRATION_ID,\n isEngineMigration,\n WORKSPACE_MIGRATIONS,\n} from \"./migrations-bundle\";\n\nexport type SchemaChange =\n | { kind: \"dropModel\"; model: string; table: string }\n | { kind: \"renameModel\"; from: string; to: string; fromTable: string; toTable: string }\n /** `table` is the model's table as of this migration. */\n | { kind: \"dropField\"; model: string; table: string; field: string; column: string }\n | {\n kind: \"renameField\";\n model: string;\n table: string;\n from: string;\n to: string;\n fromColumn: string;\n toColumn: string;\n }\n /** The field's type changed; an old value that no longer fits is dropped. */\n | { kind: \"retypeField\"; model: string; field: string };\n\n/** App-track changes made after `version`, oldest first. */\nexport function changesAfter(version: string | null | undefined): SchemaChange[] {\n const after =\n version === undefined || version === null || version === \"unknown\" || isEngineMigration(version)\n ? BASELINE_MIGRATION_ID\n : version;\n return WORKSPACE_MIGRATIONS.filter(\n (migration) => !isEngineMigration(migration.id) && migration.id > after\n ).flatMap((migration) => migration.changes ?? []);\n}\n\n/** Where an old model name lives now, or null when it was dropped. */\nexport function evolveModel(model: string, changes: readonly SchemaChange[]): string | null {\n let current = model;\n for (const change of changes) {\n if (change.kind === \"renameModel\" && change.from === current) current = change.to;\n else if (change.kind === \"dropModel\" && change.model === current) return null;\n }\n return current;\n}\n\nexport interface EvolvedField {\n field: string;\n /** True when a later migration changed its type. */\n retyped: boolean;\n}\n\n/** Where an old field lives now, or null when it was dropped. */\nexport function evolveField(\n model: string,\n field: string,\n changes: readonly SchemaChange[]\n): EvolvedField | null {\n let currentModel = model;\n let current = field;\n let retyped = false;\n for (const change of changes) {\n switch (change.kind) {\n case \"renameModel\":\n if (change.from === currentModel) currentModel = change.to;\n break;\n case \"dropModel\":\n if (change.model === currentModel) return null;\n break;\n case \"renameField\":\n if (change.model === currentModel && change.from === current) current = change.to;\n break;\n case \"dropField\":\n if (change.model === currentModel && change.field === current) return null;\n break;\n case \"retypeField\":\n if (change.model === currentModel && change.field === current) retyped = true;\n break;\n }\n }\n return { field: current, retyped };\n}\n\n/** Where an old table lives now, or null when it was dropped. */\nexport function evolveTable(table: string, changes: readonly SchemaChange[]): string | null {\n let current = table;\n for (const change of changes) {\n if (change.kind === \"renameModel\" && change.fromTable === current) current = change.toTable;\n else if (change.kind === \"dropModel\" && change.table === current) return null;\n }\n return current;\n}\n\n/** Where an old column lives now, or null when it was dropped. */\nexport function evolveColumn(\n table: string,\n column: string,\n changes: readonly SchemaChange[]\n): string | null {\n let currentTable = table;\n let current = column;\n for (const change of changes) {\n switch (change.kind) {\n case \"renameModel\":\n if (change.fromTable === currentTable) currentTable = change.toTable;\n break;\n case \"dropModel\":\n if (change.table === currentTable) return null;\n break;\n case \"renameField\":\n if (change.table === currentTable && change.fromColumn === current) current = change.toColumn;\n break;\n case \"dropField\":\n if (change.table === currentTable && change.column === current) return null;\n break;\n }\n }\n return current;\n}\n\n","import { changesAfter, evolveTable, evolveColumn } from \"./schema-evolution\";\nimport type { Env } from \"../types\";\nimport { NAMESPACES, toSnakeCase, type NamespaceDefinition } from \"./registry\";\nimport type { SqlExecutor, SqlRow, SqlValue } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\n\nconst PREFIX = \"tapedb:personal:v1:\";\nconst encoder = new TextEncoder(), decoder = new TextDecoder();\nconst bytes = (value: Uint8Array): ArrayBuffer => value.slice().buffer as ArrayBuffer;\nfunction b64(value: ArrayBuffer | Uint8Array): string {\n const data = new Uint8Array(value instanceof Uint8Array ? value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) : value);\n let text = \"\"; for (let at = 0; at < data.length; at += 32768) text += String.fromCharCode(...data.subarray(at, at + 32768));\n return btoa(text);\n}\nfunction unb64(value: string): Uint8Array { return Uint8Array.from(atob(value), c => c.charCodeAt(0)); }\ninterface Envelope { s: string; k: string; n: string; c: string; erased?: boolean; t: string; f: string; v: string | null }\ninterface WrappedKey { id: string; n: string; c: string }\ninterface Key { id: string; key: CryptoKey }\nexport function hasPersonalFields(): boolean { return Object.values(NAMESPACES).some(model => Object.values(model.attributes).some(field => field.personal)); }\nexport const personalKeyPrefix = (workspace: string) => `keys/${workspace}/`;\nexport class PersonalPending extends Error {\n constructor(readonly tasks: Array<() => Promise<void>>) { super(\"Personal values need cryptographic preparation.\"); }\n}\nfunction envelope(value: SqlValue): { token: string; value: Envelope } | null {\n if (typeof value !== \"string\") return null;\n let text = value;\n if (text.startsWith('\"')) { try { text = JSON.parse(text); } catch { return null; } }\n if (typeof text !== \"string\" || !text.startsWith(PREFIX)) return null;\n const parsed = JSON.parse(text.slice(PREFIX.length)) as Envelope;\n if (typeof parsed.s !== \"string\" || typeof parsed.k !== \"string\" || typeof parsed.n !== \"string\" || typeof parsed.c !== \"string\") throw new Error(\"Invalid personal ciphertext.\");\n return { token: text, value: parsed };\n}\n\nexport function isPersonalCiphertext(value: SqlValue): boolean { return envelope(value) !== null; }\n\n/** Plaintext kept across reads, in UTF-16 units; the oldest goes first. */\nexport const PLAINTEXT_CACHE_UNITS = 8 * 1024 * 1024;\n\nfunction units(key: string, value: SqlValue): number {\n return key.length + (typeof value === \"string\" ? value.length : JSON.stringify(value ?? null).length);\n}\n\n/** Per-room keys and plaintext live only in memory. R2 stores wrapped keys. */\nexport class PersonalRuntime {\n private readonly keys = new Map<string, Key | null>();\n /** Bounded, least recently used first; a Durable Object has 128 MB. */\n private readonly clear = new Map<string, SqlValue>();\n private clearUnits = 0;\n /** What each read in progress has decrypted, kept until it finishes. */\n private readonly reading = new Set<Map<string, SqlValue>>();\n private readonly erasing = new Set<string>();\n private readonly pending = new Map<string, Set<Promise<unknown>>>();\n private epoch = 0;\n private readonly kek: Promise<CryptoKey>;\n private readonly naming: Promise<CryptoKey>;\n constructor(private readonly env: Env, readonly workspace: string) {\n if (!env.TAPEDB_KEY_SECRET || env.TAPEDB_KEY_SECRET.length < 32) throw new Error(\"Personal fields require TAPEDB_KEY_SECRET with at least 32 characters.\");\n this.kek = crypto.subtle.digest(\"SHA-256\", encoder.encode(`tapedb-wrap:${env.TAPEDB_KEY_SECRET}`)).then(raw => crypto.subtle.importKey(\"raw\", raw, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]));\n this.naming = crypto.subtle.importKey(\"raw\", encoder.encode(env.TAPEDB_KEY_SECRET), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n }\n async subjectHash(subject: string): Promise<string> {\n return Array.from(new Uint8Array(await crypto.subtle.sign(\"HMAC\", await this.naming, encoder.encode(`${this.workspace}:${subject}`))), byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n private aad(hash: string, keyId: string, model: string, id: string, field: string): Uint8Array {\n return encoder.encode(JSON.stringify([this.workspace, hash, keyId, model, id, field]));\n }\n private async load(hash: string, create: boolean): Promise<Key | null> {\n if (this.erasing.has(hash)) throw new TxError(\"storage_error\", \"This subject is being erased; retry shortly.\");\n const known = this.keys.get(hash);\n if (known || known === null && !create) return known;\n const path = personalKeyPrefix(this.workspace) + hash;\n let object = await this.env.DATA.get(path);\n if (!object && create) {\n const raw = crypto.getRandomValues(new Uint8Array(32)), id = crypto.randomUUID(), iv = crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: bytes(iv), additionalData: bytes(this.aad(hash, id, \"key\", \"\", \"\")) }, await this.kek, bytes(raw));\n await this.env.DATA.put(path, JSON.stringify({ id, n: b64(iv), c: b64(ciphertext) } satisfies WrappedKey), { onlyIf: { etagDoesNotMatch: \"*\" } });\n object = await this.env.DATA.get(path);\n }\n if (!object) { this.keys.set(hash, null); return null; }\n const wrapped = await object.json<WrappedKey>();\n const raw = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: bytes(unb64(wrapped.n)), additionalData: bytes(this.aad(hash, wrapped.id, \"key\", \"\", \"\")) }, await this.kek, bytes(unb64(wrapped.c)));\n const key = { id: wrapped.id, key: await crypto.subtle.importKey(\"raw\", raw, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]) };\n this.keys.set(hash, key); return key;\n }\n private async track<T>(hash: string, operation: () => Promise<T>): Promise<T> {\n if (this.erasing.has(hash)) throw new TxError(\"storage_error\", \"This subject is being erased; retry shortly.\");\n const tasks = this.pending.get(hash) ?? new Set<Promise<unknown>>(); this.pending.set(hash, tasks);\n const task = operation(); tasks.add(task);\n try { return await task; } finally { tasks.delete(task); if (!tasks.size) this.pending.delete(hash); }\n }\n async seal(model: NamespaceDefinition, id: string, field: string, value: SqlValue, subject: string, version: string | null = null): Promise<SqlValue> {\n if (value === null) return null;\n const hash = await this.subjectHash(subject);\n return this.track(hash, async () => {\n const key = (await this.load(hash, true))!;\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const cipher = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: bytes(iv), additionalData: bytes(this.aad(hash, key.id, model.table, id, field)) }, key.key, encoder.encode(JSON.stringify(value)));\n const token = PREFIX + JSON.stringify({ s: hash, k: key.id, n: b64(iv), c: b64(cipher), t: model.table, f: field, v: version } satisfies Envelope);\n // Cache the stored form, not an API projection.\n this.remember(`${model.table}:${id}:${field}:${token}`, value);\n return model.attributes[field].type === \"json\" ? JSON.stringify(token) : token;\n });\n }\n private remember(cache: string, value: SqlValue): void {\n for (const pinned of this.reading) pinned.set(cache, value);\n const prior = this.clear.get(cache);\n if (this.clear.has(cache)) {\n this.clearUnits -= units(cache, prior!);\n this.clear.delete(cache);\n }\n this.clear.set(cache, value);\n this.clearUnits += units(cache, value);\n for (const [key, old] of this.clear) {\n if (this.clearUnits <= PLAINTEXT_CACHE_UNITS) break;\n this.clear.delete(key);\n this.clearUnits -= units(key, old);\n }\n }\n private recall(cache: string): { value: SqlValue } | undefined {\n for (const pinned of this.reading) if (pinned.has(cache)) return { value: pinned.get(cache)! };\n if (!this.clear.has(cache)) return undefined;\n const value = this.clear.get(cache)!;\n this.clear.delete(cache);\n this.clear.set(cache, value);\n return { value };\n }\n /** Entries and size of the plaintext cache, for tests. */\n cacheSize(): { entries: number; units: number } {\n return { entries: this.clear.size, units: this.clearUnits };\n }\n private async open(model: NamespaceDefinition, id: string, field: string, item: { token: string; value: Envelope }): Promise<void> {\n const { value, token } = item;\n const version = this.epoch;\n const changes = changesAfter(value.v);\n if (evolveTable(value.t, changes) !== model.table || evolveColumn(value.t, toSnakeCase(value.f), changes) !== toSnakeCase(field))\n throw new Error(\"Personal ciphertext belongs to a different field.\");\n await this.track(value.s, async () => {\n const key = value.erased ? null : await this.load(value.s, false);\n let plain: SqlValue = null;\n if (key?.id === value.k) {\n const raw = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: bytes(unb64(value.n)), additionalData: bytes(this.aad(value.s, key.id, value.t, id, value.f)) }, key.key, bytes(unb64(value.c)));\n plain = JSON.parse(decoder.decode(raw)) as SqlValue;\n }\n if (version === this.epoch) this.remember(`${model.table}:${id}:${field}:${token}`, plain);\n });\n }\n decodeRows(namespace: string, rows: SqlRow[]): SqlRow[] {\n const model = NAMESPACES[namespace]; if (!model) return rows;\n const pending: Array<() => Promise<void>> = [];\n const output = rows.map(row => {\n const copy = { ...row }; const erased: string[] = [];\n for (const [field, definition] of Object.entries(model.attributes)) {\n const column = toSnakeCase(field); if (!definition.personal || !(column in copy)) continue;\n const item = envelope(copy[column]); if (!item) continue;\n const cache = `${model.table}:${String(row.id)}:${field}:${item.token}`;\n const known = this.recall(cache);\n if (!known) { pending.push(() => this.open(model, String(row.id), field, item)); continue; }\n copy[column] = known.value;\n if (copy[column] === null) erased.push(field);\n }\n if (erased.length) copy.__tapedb_erased = JSON.stringify(erased);\n return copy;\n });\n if (pending.length) throw new PersonalPending(pending);\n return output;\n }\n async read<T>(fn: () => T): Promise<T> {\n // Values this read decrypts stay available to it however small the\n // shared cache is, so a read larger than the cache still finishes.\n const pinned = new Map<string, SqlValue>();\n this.reading.add(pinned);\n try {\n for (;;) {\n try { return fn(); }\n catch (error) {\n if (!(error instanceof PersonalPending)) throw error;\n // Bounded concurrent key reads and Web Crypto work.\n let next = 0;\n await Promise.all(Array.from({ length: Math.min(8, error.tasks.length) }, async () => { while (next < error.tasks.length) await error.tasks[next++](); }));\n }\n }\n } finally {\n this.reading.delete(pinned);\n }\n }\n sql(base: SqlExecutor): SqlExecutor { return { ...base, decodeRows: (namespace, rows) => this.decodeRows(namespace, rows) }; }\n async prepare(sql: SqlExecutor, model: NamespaceDefinition, id: string, values: Record<string, SqlValue>, inserting: boolean, erased: readonly string[] = []): Promise<Record<string, SqlValue>> {\n if (!Object.values(model.attributes).some(field => field.personal)) return values;\n const stored = sql.one<SqlRow>(`SELECT * FROM \"${model.table}\" WHERE id = ?`, id);\n const old = stored ? await this.read(() => this.decodeRows(model.apiName, [stored])[0]) : undefined;\n const result = { ...values };\n for (const [field, definition] of Object.entries(model.attributes)) {\n const personal = definition.personal; if (!personal) continue;\n const column = toSnakeCase(field);\n if (erased.includes(field)) {\n if (values[column] !== null) throw new TxError(\"invalid_op\", \"An erased field must be null.\");\n const subject = personal.subject === \"self\" ? id : values[toSnakeCase(personal.subject)];\n const token = PREFIX + JSON.stringify({ s: await this.subjectHash(String(subject)), k: crypto.randomUUID(), n: \"\", c: \"\", erased: true, t: model.table, f: field, v: null } satisfies Envelope);\n result[column] = definition.type === \"json\" ? JSON.stringify(token) : token;\n continue;\n }\n if (personal.required && column in values && values[column] === null) throw new TxError(\"invalid_op\", `Personal field ${field} is required.`);\n if (inserting && !(column in result)) {\n if (personal.defaultValue !== undefined) result[column] = personal.defaultValue;\n else if (personal.required) throw new TxError(\"invalid_op\", `Personal field ${field} is required.`);\n }\n const subjectColumn = personal.subject === \"self\" ? \"id\" : toSnakeCase(personal.subject);\n const subject = personal.subject === \"self\" ? id : (subjectColumn in values ? values[subjectColumn] : stored?.[subjectColumn]);\n const subjectChanged = stored && subjectColumn in values && values[subjectColumn] !== stored[subjectColumn];\n if (!(column in result) && subjectChanged) {\n if (old?.[column] === null && stored && envelope(stored[column])) {\n result[column] = stored[column];\n continue; // Preserve the erased marker; no key can recover this value.\n }\n result[column] = old?.[column] ?? null;\n }\n if (!(column in result)) continue;\n if (result[column] !== null && typeof subject !== \"string\") throw new TxError(\"invalid_op\", `Personal field ${field} needs a string subject.`);\n result[column] = await this.seal(model, id, field, result[column], String(subject), sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'schema_version'`)?.value ?? null);\n }\n return result;\n }\n async erase(subject: string): Promise<void> {\n const hash = await this.subjectHash(subject);\n this.erasing.add(hash); this.epoch++;\n try {\n await Promise.allSettled([...(this.pending.get(hash) ?? [])]);\n await this.env.DATA.delete(personalKeyPrefix(this.workspace) + hash);\n this.keys.delete(hash); this.clearPlaintext(); this.epoch++;\n } finally { this.erasing.delete(hash); }\n }\n clearPlaintext(): void {\n this.clear.clear();\n this.clearUnits = 0;\n for (const pinned of this.reading) pinned.clear();\n }\n /**\n * The receipt hash of a transaction that may carry personal values: an\n * HMAC under the key secret, so the hash kept in receipts and log lines\n * cannot be brute-forced back to a short value (a phone number, a date).\n */\n async receiptHash(rawOps: unknown): Promise<string> {\n const signature = await crypto.subtle.sign(\"HMAC\", await this.naming, encoder.encode(`receipt:${JSON.stringify(rawOps)}`));\n return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n}\n","/**\n * Staged evaluation: running part of a filter first, into a scratch table, so\n * the statement that uses it stays within SQLite's limits.\n *\n * A Durable Object's SQLite refuses expressions deeper than 100 and very long\n * statements. A relation filter compiles to a correlated subquery, and SQLite\n * counts the enclosing expression again for every subquery nested inside\n * another, so one statement holds only a few hops. A filter with thousands of\n * branches makes a statement too long. Neither is a property of the query\n * being unreasonable, so neither is refused: the compiler cuts the filter into\n * stages. Each stage is a shallow `INSERT ... SELECT` of matching ids into\n * `_tapedb_scratch`, run in dependency order, and the statement that needed it\n * tests membership with a one-level subquery.\n *\n * Temporary tables are not authorised in a Durable Object (`SQLITE_AUTH`), so\n * the scratch table is an ordinary one. Its rows live only for one statement:\n * stages, statement and cleanup run synchronously in one turn of the object,\n * so nothing else can observe them, and a transaction that rolls back takes\n * them with it. Recovery, snapshots and export only touch the tables on their\n * allow-lists, so the scratch table never reaches a copy of the workspace.\n */\n\nimport type { SqlExecutor, SqlRow, SqlValue } from \"./tx-sql\";\n\nexport const SCRATCH_TABLE = \"_tapedb_scratch\";\n\n/** Relation filters nested this many hops inside a statement start a new stage. */\nexport const STAGE_DEPTH = 3;\n\n/** Conditions longer than this many characters are split into stages. */\nexport const MAX_CONDITION_SQL = 30_000;\n\nexport interface Stage {\n /** Placeholder for this stage's scratch key; replaced with a fresh key per run. */\n key: string;\n /** `INSERT OR IGNORE INTO _tapedb_scratch (k, id) SELECT ?, ...`; the first parameter is `key`. */\n sql: string;\n params: SqlValue[];\n /**\n * A stage a SQL predicate cannot express: `sql` selects candidate rows\n * (`alias.*` plus the staged value as `\"__tapedb_staged\"`), they are read in\n * id order a chunk at a time, and only those `keep` accepts are staged.\n * Used for a read rule that is a function, which runs on fetched rows.\n */\n scan?: { alias: string; keep: (row: SqlRow) => boolean };\n}\n\n/** Rows a scan stage reads per statement, and ids it stages per insert. */\nconst SCAN_CHUNK = 1000;\n\n// Placeholders carry a random per-isolate prefix: a filter value a client\n// sends can equal one only by guessing it. Made on first use, because a\n// Worker may not generate random values at module load.\nlet keyPrefix: string | null = null;\nlet nextKey = 0;\n\n/** A fresh stage placeholder. */\nexport function stageKey(): string {\n keyPrefix ??= `\\u0000tapedb-stage:${globalThis.crypto.randomUUID()}:`;\n nextKey += 1;\n return `${keyPrefix}${nextKey}`;\n}\n\n/** `column IN (ids staged under key)`, or `NOT IN`. */\nexport function membership(column: string, key: string, negate = false): { sql: string; params: SqlValue[] } {\n return {\n sql: `${column} ${negate ? \"NOT IN\" : \"IN\"} (SELECT \"id\" FROM \"${SCRATCH_TABLE}\" WHERE \"k\" = ?)`,\n params: [key],\n };\n}\n\n/** The `INSERT ... SELECT` that stages `select` (an id-valued expression) from `from` where `where` holds. */\nexport function stageInsert(key: string, select: string, from: string, where: string, params: SqlValue[]): Stage {\n return {\n key,\n sql: `INSERT OR IGNORE INTO \"${SCRATCH_TABLE}\" (\"k\", \"id\") SELECT ?, ${select} FROM ${from} WHERE ${where}`,\n params: [key, ...params],\n };\n}\n\n/**\n * Creates the scratch table if it is missing. Not remembered per executor:\n * erasing a workspace (`deleteAll`) or resetting it for recovery drops every\n * table while the room keeps the same executor.\n */\nexport function ensureScratch(sql: SqlExecutor): void {\n sql.exec(\n `CREATE TABLE IF NOT EXISTS \"${SCRATCH_TABLE}\" (\"k\" TEXT NOT NULL, \"id\" TEXT NOT NULL, PRIMARY KEY (\"k\", \"id\")) WITHOUT ROWID`\n );\n}\n\nfunction freshKey(): string {\n return globalThis.crypto.randomUUID();\n}\n\n/**\n * Runs `stages` in order, then `run` with `params`, then removes the staged\n * rows. Every stage placeholder in the stages' and the statement's parameters\n * is replaced with a key unique to this run, so a compiled query can be run\n * again, or by another subscriber, without its stages colliding.\n */\nexport function runStaged<T>(\n sql: SqlExecutor,\n stages: readonly Stage[] | undefined,\n params: readonly SqlValue[],\n run: (params: SqlValue[]) => T\n): T {\n if (stages === undefined || stages.length === 0) return run([...params]);\n\n const keys = new Map<string, string>();\n for (const stage of stages) {\n if (!keys.has(stage.key)) keys.set(stage.key, freshKey());\n }\n const bind = (values: readonly SqlValue[]): SqlValue[] =>\n values.map((value) => (typeof value === \"string\" && keys.has(value) ? keys.get(value)! : value));\n\n ensureScratch(sql);\n const used = [...keys.values()];\n try {\n for (const stage of stages) {\n if (stage.scan === undefined) sql.exec(stage.sql, ...bind(stage.params));\n else runScan(sql, stage, bind(stage.params));\n }\n return run(bind(params));\n } finally {\n sql.exec(`DELETE FROM \"${SCRATCH_TABLE}\" WHERE \"k\" IN (SELECT value FROM json_each(?))`, JSON.stringify(used));\n }\n}\n\n/** The `SELECT` a scan stage reads candidates with; the first parameter is the key. */\nexport function stageScan(\n key: string,\n alias: string,\n select: string,\n from: string,\n where: string,\n params: SqlValue[],\n keep: (row: SqlRow) => boolean\n): Stage {\n return {\n key,\n sql: `SELECT ${alias}.*, ${select} AS \"__tapedb_staged\" FROM ${from} WHERE ${where}`,\n params: [key, ...params],\n scan: { alias, keep },\n };\n}\n\nfunction runScan(sql: SqlExecutor, stage: Stage, params: SqlValue[]): void {\n const [key, ...where] = params;\n const { alias, keep } = stage.scan!;\n let after: SqlValue | null = null;\n for (;;) {\n const rows: SqlRow[] =\n after === null\n ? sql.all(`${stage.sql} ORDER BY ${alias}.\"id\" LIMIT ${SCAN_CHUNK}`, ...where)\n : sql.all(`${stage.sql} AND ${alias}.\"id\" > ? ORDER BY ${alias}.\"id\" LIMIT ${SCAN_CHUNK}`, ...where, after);\n const kept = rows\n .filter((row) => row.__tapedb_staged !== null && keep(row))\n .map((row) => row.__tapedb_staged);\n if (kept.length > 0) {\n sql.exec(\n `INSERT OR IGNORE INTO \"${SCRATCH_TABLE}\" (\"k\", \"id\") SELECT ?, value FROM json_each(?)`,\n key,\n JSON.stringify(kept)\n );\n }\n if (rows.length < SCAN_CHUNK) return;\n after = rows[rows.length - 1].id;\n }\n}\n\n/** Every stage a set of conditions depends on, in order, once each. */\nexport function stagesOf(conditions: readonly { stages?: readonly Stage[] }[]): Stage[] | undefined {\n // Deduplicated by identity, not key: an OR stages each of its chunks under\n // one key, and every one of them has to run.\n const out: Stage[] = [];\n const seen = new Set<Stage>();\n for (const condition of conditions) {\n for (const stage of condition.stages ?? []) {\n if (seen.has(stage)) continue;\n seen.add(stage);\n out.push(stage);\n }\n }\n return out.length === 0 ? undefined : out;\n}\n","/**\n * Query document wire contract for the workspace engine.\n *\n * `where`, `order`, `limit`, `after`, `count`, `select`, `aggregate` and\n * nested link traversal at any depth. This module owns the typed\n * shapes and the registry-independent validation. Registry-specific checks\n * (namespace, attribute and link existence) live in `query-compile.ts`.\n *\n * Values describe the API shape: attribute names are camelCase registry names,\n * booleans are real booleans, dates are epoch milliseconds and `json`/`any`\n * attributes are JSON values. Storage conversion happens in `query-execute.ts`.\n */\n\nimport { parseAggregate, type AggregateGroup, type QueryAggregate } from \"./query-aggregate\";\nimport { TxError } from \"./tx-types\";\n\n/**\n * Rows one statement reads. A read with a larger `limit`, or none, is served\n * in keyset chunks of this size, and includes hydrate this many parents per\n * statement, so no single statement grows with the result.\n */\nexport const QUERY_CHUNK_ROWS = 1000;\n\nexport type SortDirection = \"asc\" | \"desc\";\n\n/** Scalars accepted by `where` and by comparison operators. */\nexport type QueryScalar = string | number | boolean | null;\n\n/** Supported comparison operators. Anything else is rejected. */\nexport interface QueryComparison {\n $ne?: QueryScalar;\n $in?: QueryScalar[];\n /** Not in the list. Like `$ne`, also matches rows where the value is null. */\n $nin?: QueryScalar[];\n $gt?: QueryScalar;\n $gte?: QueryScalar;\n $lt?: QueryScalar;\n $lte?: QueryScalar;\n}\n\nexport type QueryWhereValue = QueryScalar | QueryComparison;\n\n/**\n * Attribute conditions, ANDed. Three reserved keys combine whole filters:\n * `$or` and `$and` take non-empty arrays of filters, `$not` takes one.\n */\n/** How a relation filter matches: the parent row, or some/every/no children. */\nexport type RelationMode = \"parent\" | \"some\" | \"every\" | \"none\";\n\n/**\n * A filter on a linked namespace, by the same label `include` uses. Compiled\n * into a correlated subquery, so the rows are never fetched.\n */\nexport interface QueryRelationFilter {\n label: string;\n mode: RelationMode;\n where: QueryWhere;\n}\n\nexport interface QueryWhere {\n [attribute: string]:\n | QueryWhereValue\n | QueryWhere\n | QueryWhere[]\n | QueryRelationFilter[]\n | undefined;\n $or?: QueryWhere[];\n $and?: QueryWhere[];\n $not?: QueryWhere;\n $link?: QueryRelationFilter[];\n}\n\n\nexport interface QueryOptions {\n where?: QueryWhere;\n order?: Record<string, SortDirection>;\n limit?: number;\n /**\n * Opaque cursor from a previous page's `pageInfo.nextCursor`. Requires an\n * explicit `order`, because a cursor is only meaningful against a total\n * order.\n */\n after?: string;\n /**\n * Top level only: also report how many rows match, ignoring `after` and\n * `limit`, as `pageInfo[namespace].count`. With `limit: 0` no rows are read.\n */\n count?: boolean;\n /**\n * Attributes to return, by API name. Omitted means every attribute. `id`\n * is always returned: live diffs key rows by it.\n */\n select?: string[];\n /**\n * Top level only: count, sum, avg, min and max over the matching rows,\n * optionally grouped. Reads no rows; the result is\n * `pageInfo[namespace].aggregate`.\n */\n aggregate?: QueryAggregate;\n}\n\n/**\n * One namespace/link level.\n *\n * `$` carries options; every other key is a registered link label for the\n * namespace at this level.\n */\nexport interface QueryNodeInput {\n $?: QueryOptions;\n [link: string]: QueryOptions | QueryNodeInput | undefined;\n}\n\n/** A query document keyed by top-level namespace API name. */\nexport interface QueryDocument {\n [namespace: string]: QueryNodeInput;\n}\n\n/** Result payload keyed by the requested top-level namespace names. */\nexport interface QueryResult {\n [namespace: string]: unknown[];\n}\n\n/**\n * Truncation metadata for one namespace. The default result cap is silent, so\n * a caller cannot otherwise tell 100 rows from the first 100 of 500.\n */\nexport interface PageInfo {\n /** The effective limit, or null when the namespace is uncapped. */\n limit: number | null;\n /** Rows actually returned for this namespace. */\n returned: number;\n /** True when more rows matched than were returned. */\n hasMore: boolean;\n /**\n * Opaque cursor for the next page, present only when `hasMore` is true and\n * the query has an explicit `order`. Pass it back as `$: { after }`.\n */\n nextCursor?: string;\n /** Total matching rows, when the query asked for `count`. */\n count?: number;\n /** The groups, when the query asked for `aggregate`. */\n aggregate?: AggregateGroup[];\n}\n\nexport type QueryPageInfo = Record<string, PageInfo>;\n\nexport interface QueryResponse {\n ok: true;\n data: QueryResult;\n}\n\nexport interface QueryErrorResponse {\n ok: false;\n error: {\n code: string;\n message: string;\n };\n}\n\nconst OPTION_KEYS = new Set([\"where\", \"order\", \"limit\", \"after\", \"count\", \"select\", \"aggregate\"]);\nconst LOGICAL_KEYS = new Set([\"$or\", \"$and\", \"$not\", \"$link\"]);\nconst RELATION_MODES = new Set([\"parent\", \"some\", \"every\", \"none\"]);\nconst COMPARISON_OPERATORS = new Set([\n \"$ne\",\n \"$in\",\n \"$nin\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n]);\n\nconst ISO_DATE_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Validates the request envelope `{ query: {...} }` and returns the query\n * document. Unknown envelope keys are rejected rather than ignored.\n */\nexport function parseQueryEnvelope(value: unknown): QueryDocument {\n if (!isPlainObject(value)) {\n throw invalidOp(\"Query request body must be a JSON object.\");\n }\n\n for (const key of Object.keys(value)) {\n if (key !== \"query\") {\n throw invalidOp(`Unknown query envelope key \"${key}\".`);\n }\n }\n\n if (!(\"query\" in value)) {\n throw invalidOp('Query request body requires a \"query\" object.');\n }\n\n const query = value.query;\n if (!isPlainObject(query)) {\n throw invalidOp('\"query\" must be a plain object.');\n }\n\n return query as QueryDocument;\n}\n\n/**\n * Validates an options object (`$`). Attribute and link names are checked\n * later, against the registry.\n */\nexport function parseQueryOptions(value: unknown): QueryOptions {\n if (!isPlainObject(value)) {\n throw invalidOp('\"$\" must be an object.');\n }\n\n for (const key of Object.keys(value)) {\n if (!OPTION_KEYS.has(key)) {\n throw invalidOp(`Unknown query option \"$${key}\".`);\n }\n }\n\n const options: QueryOptions = {};\n\n if (\"where\" in value) {\n options.where = parseWhere(value.where);\n }\n if (\"order\" in value) {\n options.order = parseOrder(value.order);\n }\n if (\"count\" in value) {\n if (typeof value.count !== \"boolean\") {\n throw invalidValue('\"count\" must be true or false.');\n }\n options.count = value.count;\n }\n if (\"aggregate\" in value) {\n options.aggregate = parseAggregate(value.aggregate);\n }\n if (\"limit\" in value) {\n // limit 0 only makes sense as \"count or aggregate, read no rows\".\n options.limit =\n value.limit === 0 && (options.count === true || options.aggregate !== undefined)\n ? 0\n : parseLimit(value.limit);\n }\n if (\"after\" in value) {\n options.after = parseCursor(value.after);\n }\n if (\"select\" in value) {\n options.select = parseSelect(value.select);\n }\n\n return options;\n}\n\n/**\n * Pagination cursor: the ordered column values of the last row on the page.\n *\n * Keyset, not offset: an offset cursor silently skips or repeats rows when\n * something is inserted above the window, which is the normal case for a live\n * database.\n */\nexport interface QueryCursor {\n v: 1;\n /** Physical columns the cursor is ordered by. */\n cols: string[];\n /** Values of those columns on the last returned row. */\n vals: (string | number | null)[];\n}\n\nfunction base64UrlEncode(text: string): string {\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction base64UrlDecode(value: string): string {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n}\n\nexport function encodeQueryCursor(cursor: QueryCursor): string {\n return base64UrlEncode(JSON.stringify(cursor));\n}\n\n/** Decodes and validates a cursor. A malformed cursor is a client error. */\nexport function decodeQueryCursor(value: string): QueryCursor {\n let parsed: unknown;\n try {\n parsed = JSON.parse(base64UrlDecode(value));\n } catch {\n throw invalidOp('\"after\" is not a valid cursor.');\n }\n\n if (!isPlainObject(parsed) || parsed.v !== 1) {\n throw invalidOp('\"after\" is not a valid cursor.');\n }\n\n const cols = parsed.cols;\n const vals = parsed.vals;\n if (!Array.isArray(cols) || cols.length === 0 || !cols.every((c) => typeof c === \"string\")) {\n throw invalidOp('\"after\" cursor has no columns.');\n }\n if (!Array.isArray(vals) || vals.length !== cols.length) {\n throw invalidOp('\"after\" cursor does not match its columns.');\n }\n for (const val of vals) {\n if (val !== null && typeof val !== \"string\" && typeof val !== \"number\") {\n throw invalidOp('\"after\" cursor contains an unsupported value.');\n }\n }\n\n return { v: 1, cols: cols as string[], vals: vals as (string | number | null)[] };\n}\n\nfunction parseSelect(value: unknown): string[] {\n if (!Array.isArray(value) || value.length === 0) {\n throw invalidOp('\"select\" must be a non-empty array of attribute names.');\n }\n const names = new Set<string>();\n for (const name of value) {\n if (typeof name !== \"string\" || name.length === 0) {\n throw invalidOp('\"select\" must be a non-empty array of attribute names.');\n }\n names.add(name);\n }\n return [...names];\n}\n\nfunction parseCursor(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw invalidOp('\"after\" must be a non-empty cursor string.');\n }\n return value;\n}\n\n/** Validates a `where` object. Exported for view rules, which share the shape. */\nexport function parseWhere(value: unknown): QueryWhere {\n if (!isPlainObject(value)) {\n throw invalidOp('\"where\" must be an object.');\n }\n\n const where: QueryWhere = {};\n for (const [attribute, raw] of Object.entries(value)) {\n if (attribute.startsWith(\"$\")) {\n if (!LOGICAL_KEYS.has(attribute)) {\n throw invalidOp(`Unknown where key \"${attribute}\".`);\n }\n if (attribute === \"$not\") {\n where.$not = parseWhere(raw);\n continue;\n }\n if (attribute === \"$link\") {\n if (!Array.isArray(raw) || raw.length === 0) {\n throw invalidOp('\"$link\" needs a non-empty array of relation filters.');\n }\n where.$link = raw.map((entry) => parseRelationFilter(entry));\n continue;\n }\n if (!Array.isArray(raw) || raw.length === 0) {\n // An empty $or would match nothing and an empty $and everything; both\n // are more likely a bug in the caller than a request.\n throw invalidOp(`\"${attribute}\" needs a non-empty array of filters.`);\n }\n where[attribute as \"$or\" | \"$and\"] = raw.map((branch) =>\n parseWhere(branch)\n );\n continue;\n }\n if (isPlainObject(raw)) {\n where[attribute] = parseComparison(attribute, raw);\n } else {\n where[attribute] = parseScalar(attribute, raw);\n }\n }\n return where;\n}\n\nfunction parseRelationFilter(value: unknown): QueryRelationFilter {\n if (!isPlainObject(value)) {\n throw invalidOp('Each \"$link\" entry must be an object.');\n }\n const { label, mode, where } = value;\n if (typeof label !== \"string\" || label.length === 0) {\n throw invalidOp('A \"$link\" entry needs a link label.');\n }\n if (typeof mode !== \"string\" || !RELATION_MODES.has(mode)) {\n throw invalidOp(\n `\"$link\" mode for \"${label}\" must be one of parent, some, every, none.`\n );\n }\n return { label, mode: mode as RelationMode, where: parseWhere(where) };\n}\n\nfunction parseComparison(\n attribute: string,\n value: Record<string, unknown>\n): QueryComparison {\n const keys = Object.keys(value);\n if (keys.length === 0) {\n throw invalidValue(`Comparison for \"${attribute}\" has no operators.`);\n }\n\n const comparison: QueryComparison = {};\n for (const operator of keys) {\n if (!COMPARISON_OPERATORS.has(operator)) {\n throw invalidValue(\n `Unsupported where operator \"${operator}\" on \"${attribute}\".`\n );\n }\n\n const operand = value[operator];\n switch (operator) {\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw invalidValue(`\"$in\" on \"${attribute}\" requires an array.`);\n }\n comparison.$in = operand.map((item, index) =>\n parseScalar(`${attribute}.$in[${index}]`, item)\n );\n break;\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw invalidValue(`\"$nin\" on \"${attribute}\" requires an array.`);\n }\n comparison.$nin = operand.map((item, index) =>\n parseScalar(`${attribute}.$nin[${index}]`, item)\n );\n break;\n case \"$ne\":\n comparison.$ne = parseScalar(attribute, operand);\n break;\n case \"$gt\":\n comparison.$gt = parseScalar(attribute, operand);\n break;\n case \"$gte\":\n comparison.$gte = parseScalar(attribute, operand);\n break;\n case \"$lt\":\n comparison.$lt = parseScalar(attribute, operand);\n break;\n case \"$lte\":\n comparison.$lte = parseScalar(attribute, operand);\n break;\n }\n }\n\n return comparison;\n}\n\nfunction parseOrder(value: unknown): Record<string, SortDirection> {\n if (!isPlainObject(value)) {\n throw invalidOp('\"order\" must be an object.');\n }\n\n const order: Record<string, SortDirection> = {};\n for (const [attribute, direction] of Object.entries(value)) {\n if (direction !== \"asc\" && direction !== \"desc\") {\n throw invalidValue(`Order for \"${attribute}\" must be \"asc\" or \"desc\".`);\n }\n order[attribute] = direction;\n }\n return order;\n}\n\nfunction parseLimit(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n throw invalidValue(\"Limit must be a positive integer.\");\n }\n return value;\n}\n\nfunction parseScalar(attribute: string, value: unknown): QueryScalar {\n if (value === null) return null;\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw invalidValue(\n `Value for \"${attribute}\" must be a scalar (string, number, boolean or null).`\n );\n}\n\nexport function isPlainObject(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function isIsoDate(value: string): boolean {\n return ISO_DATE_PATTERN.test(value);\n}\n\nexport function invalidOp(message: string): TxError {\n return new TxError(\"invalid_op\", message);\n}\n\nexport function invalidValue(message: string): TxError {\n return new TxError(\"invalid_value\", message);\n}\n","/**\n * Fitting statements into a Durable Object's SQLite limits: 100 bound\n * parameters and an expression depth of 100.\n *\n * SQLite in a Durable Object binds at most 100 parameters per statement\n * (Cloudflare's documented limit; plain SQLite allows 32,766, which is why\n * tests on `bun:sqlite` never hit it). The compiler already keeps lists in\n * one parameter (`IN (SELECT value FROM json_each(?))`), so ordinary queries\n * stay far below it. A statement that still goes over — a filter with a\n * hundred `OR` branches, an insert into a model with a hundred fields — is\n * rewritten here instead of failing: every value travels in one JSON array,\n * bound once, and each placeholder reads its element back with\n * `json_extract`. Blobs cannot travel in JSON, so they keep their own\n * numbered parameters.\n */\n\nimport type { SqlValue } from \"./tx-sql\";\n\n/**\n * Joins conditions as a balanced tree: `((a OR b) OR (c OR d))`, not\n * `a OR b OR c OR d`. SQLite parses a chain into a tree as deep as the chain\n * is long, and a Durable Object's SQLite refuses expressions deeper than 100\n * (measured in workerd; plain SQLite allows 1000), so a filter with a hundred\n * branches would fail as a chain. Balanced, the depth grows with log2 of the\n * branch count. The order of the parts, and so of their parameters, is\n * unchanged.\n */\nexport function balancedJoin(parts: readonly string[], joiner: \" AND \" | \" OR \"): string {\n if (parts.length === 0) return joiner === \" AND \" ? \"1 = 1\" : \"0 = 1\";\n if (parts.length === 1) return `(${parts[0]})`;\n const middle = Math.ceil(parts.length / 2);\n return `(${balancedJoin(parts.slice(0, middle), joiner)}${joiner}${balancedJoin(parts.slice(middle), joiner)})`;\n}\n\n/** Cloudflare's per-statement bound-parameter limit for SQLite-backed Durable Objects. */\nexport const DO_MAX_BOUND_PARAMETERS = 100;\n\n/**\n * Offsets of the anonymous `?` placeholders in `sql`, skipping string\n * literals, quoted identifiers and comments.\n */\nfunction placeholderOffsets(sql: string): number[] {\n const offsets: number[] = [];\n let index = 0;\n while (index < sql.length) {\n const char = sql[index];\n if (char === \"'\" || char === '\"' || char === \"`\") {\n // Quoted: runs to the matching quote; a doubled quote is an escape.\n index += 1;\n while (index < sql.length) {\n if (sql[index] === char) {\n if (sql[index + 1] === char) {\n index += 2;\n continue;\n }\n break;\n }\n index += 1;\n }\n index += 1;\n continue;\n }\n if (char === \"[\") {\n const end = sql.indexOf(\"]\", index + 1);\n index = end === -1 ? sql.length : end + 1;\n continue;\n }\n if (char === \"-\" && sql[index + 1] === \"-\") {\n const end = sql.indexOf(\"\\n\", index + 2);\n index = end === -1 ? sql.length : end + 1;\n continue;\n }\n if (char === \"/\" && sql[index + 1] === \"*\") {\n const end = sql.indexOf(\"*/\", index + 2);\n index = end === -1 ? sql.length : end + 2;\n continue;\n }\n if (char === \"?\") {\n // A numbered parameter (?1) is not ours to renumber.\n if (/[0-9]/.test(sql[index + 1] ?? \"\")) return [];\n offsets.push(index);\n }\n index += 1;\n }\n return offsets;\n}\n\n/**\n * Returns the statement unchanged when it fits, or rewritten to bind its\n * values through one JSON parameter when it does not. A statement whose\n * placeholders cannot be matched to its values is returned unchanged, so\n * SQLite reports the problem as it would have.\n */\nexport function fitBindings(\n sql: string,\n params: readonly SqlValue[],\n limit = DO_MAX_BOUND_PARAMETERS\n): { sql: string; params: SqlValue[] } {\n if (params.length <= limit) return { sql, params: [...params] };\n\n const offsets = placeholderOffsets(sql);\n if (offsets.length !== params.length) return { sql, params: [...params] };\n\n const values: Array<string | number | null> = [];\n const blobs: ArrayBuffer[] = [];\n const replacements = params.map((value) => {\n if (value instanceof ArrayBuffer) {\n blobs.push(value);\n return `?${blobs.length + 1}`;\n }\n values.push(value);\n return `json_extract(?1, '$[${values.length - 1}]')`;\n });\n if (blobs.length + 1 > limit) return { sql, params: [...params] };\n\n let rewritten = \"\";\n let previous = 0;\n offsets.forEach((offset, index) => {\n rewritten += sql.slice(previous, offset) + replacements[index];\n previous = offset + 1;\n });\n rewritten += sql.slice(previous);\n\n return { sql: rewritten, params: [JSON.stringify(values), ...blobs] };\n}\n","/**\n * Applies validated ops to workspace SQLite.\n *\n * Table and column names come only from the registry and are quoted. Every\n * value is parameterised. Each mutation advances `updated_seq` to the current\n * transaction sequence and refreshes `updated_at`; inserts also set\n * `created_at`.\n */\n\nimport {\n findNamespace,\n toSnakeCase,\n type NamespaceDefinition,\n} from \"./registry\";\nimport type { SqlExecutor, SqlValue } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\nimport {\n isLinkOp,\n requiredColumns,\n type ValidatedLinkOp,\n type ValidatedOp,\n type ValidatedValuesOp,\n} from \"./tx-validate\";\n\nexport interface ApplyContext {\n sql: SqlExecutor;\n seq: number;\n now: number;\n txId?: string;\n /**\n * Recovery replay. An op that succeeded once is re-applied against a\n * database that may already hold its effect, so insert behaves as an upsert\n * and a patch of a missing row is a no-op instead of an error.\n */\n replay?: boolean;\n /** Authorize against the row immediately before each mutation. */\n beforeOp?: (op: ValidatedOp) => void;\n}\n\ninterface ErrorContext {\n txId?: string;\n opIndex?: number;\n}\n\nexport function applyOps(context: ApplyContext, ops: ValidatedOp[]): number {\n let applied = 0;\n\n for (const [opIndex, op] of ops.entries()) {\n try {\n context.beforeOp?.(op);\n applied += applyOp(context, op);\n } catch (error) {\n throw toTxError(error, { txId: context.txId, opIndex });\n }\n }\n\n return applied;\n}\n\nfunction applyOp(context: ApplyContext, op: ValidatedOp): number {\n if (isLinkOp(op)) {\n return applyLink(context, op);\n }\n\n const namespace = findNamespace(op.namespace);\n if (!namespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${op.namespace}\".`\n );\n }\n\n switch (op.kind) {\n case \"insert\":\n case \"patch\":\n case \"upsert\":\n case \"update\":\n case \"merge\":\n return applyValues(context, op, namespace);\n case \"patchMany\":\n case \"deleteMany\":\n // expandBulkOps replaces these before anything is applied.\n throw new TxError(\n \"invalid_op\",\n `\"${op.kind}\" reached the apply step; it should have been resolved to rows first.`\n );\n case \"delete\": {\n const table = quoteIdentifier(namespace.table);\n const changes = context.sql.exec(\n `DELETE FROM ${table} WHERE \"id\" = ?`,\n op.id\n );\n return changes > 0 ? 1 : 0;\n }\n }\n}\n\nfunction applyValues(\n context: ApplyContext,\n op: ValidatedValuesOp,\n namespace: NamespaceDefinition\n): number {\n const table = quoteIdentifier(namespace.table);\n const existing = context.sql.one(\n `SELECT 1 AS \"present\" FROM ${table} WHERE \"id\" = ? LIMIT 1`,\n op.id\n );\n\n if (existing === undefined) {\n if (op.kind === \"patch\") {\n if (context.replay) return 0;\n throw new TxError(\n \"not_found\",\n `No \"${namespace.apiName}\" row with id \"${op.id}\" to update.`\n );\n }\n return insertRow(\n context,\n op.kind === \"upsert\" && op.createValues !== undefined\n ? { ...op, values: op.createValues }\n : op,\n namespace,\n table\n );\n }\n\n if (op.kind === \"insert\" && !context.replay) {\n throw new TxError(\n \"unique_violation\",\n `A \"${namespace.apiName}\" row with id \"${op.id}\" already exists.`\n );\n }\n\n const columns = Object.keys(op.values);\n const assignments = columns.map((column) => `${quoteIdentifier(column)} = ?`);\n assignments.push(`\"updated_at\" = ?`, `\"updated_seq\" = ?`);\n\n const params: SqlValue[] = columns.map((column) => op.values[column]);\n params.push(context.now, context.seq, op.id);\n\n const changes = context.sql.exec(\n `UPDATE ${table} SET ${assignments.join(\", \")} WHERE \"id\" = ?`,\n ...params\n );\n\n return changes > 0 ? 1 : 0;\n}\n\nfunction insertRow(\n context: ApplyContext,\n op: ValidatedValuesOp,\n namespace: NamespaceDefinition,\n table: string\n): number {\n // A replayed insert was valid when it was written; a field made required\n // since then is filled by its column default instead.\n for (const column of context.replay ? [] : requiredColumns(namespace)) {\n if (!(column in op.values)) {\n throw new TxError(\n \"invalid_op\",\n `Insert into \"${namespace.apiName}\" requires attribute \"${column}\".`\n );\n }\n }\n\n const valueColumns = Object.keys(op.values);\n const columns = [\n \"id\",\n ...valueColumns,\n \"created_at\",\n \"updated_at\",\n \"updated_seq\",\n ];\n const placeholders = columns.map(() => \"?\").join(\", \");\n const params: SqlValue[] = [\n op.id,\n ...valueColumns.map((column) => op.values[column]),\n context.now,\n context.now,\n context.seq,\n ];\n\n context.sql.exec(\n `INSERT INTO ${table} (${columns\n .map(quoteIdentifier)\n .join(\", \")}) VALUES (${placeholders})`,\n ...params\n );\n\n return 1;\n}\n\nfunction applyLink(context: ApplyContext, op: ValidatedLinkOp): number {\n const childNamespace = findNamespace(op.childNamespace);\n if (!childNamespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${op.childNamespace}\".`\n );\n }\n\n const foreignKey = childNamespace.attributes[op.foreignKeyAttribute];\n if (!foreignKey) {\n throw new TxError(\n \"unknown_link\",\n `Link \"${op.link}\" has no foreign key attribute on \"${op.childNamespace}\".`\n );\n }\n\n if (op.kind === \"unlink\" && !foreignKey.optional) {\n throw new TxError(\n \"foreign_key_violation\",\n `Cannot unlink \"${op.link}\": \"${op.childNamespace}.${op.foreignKeyAttribute}\" is NOT NULL.`\n );\n }\n\n const table = quoteIdentifier(childNamespace.table);\n const child = context.sql.one(\n `SELECT 1 AS \"present\" FROM ${table} WHERE \"id\" = ? LIMIT 1`,\n op.childId\n );\n if (child === undefined) {\n throw new TxError(\n \"not_found\",\n `Cannot ${op.kind} \"${op.link}\": child row \"${op.childId}\" does not exist.`\n );\n }\n\n const foreignKeyColumn = quoteIdentifier(\n op.foreignKeyColumn || toSnakeCase(op.foreignKeyAttribute)\n );\n\n if (op.kind === \"unlink\") {\n // An unlink is a no-op unless the child currently points at this parent.\n // Nulling unconditionally would detach a child another client has already\n // moved to a different parent.\n const current = context.sql.one(\n `SELECT ${foreignKeyColumn} AS \"fk\" FROM ${table} WHERE \"id\" = ?`,\n op.childId\n );\n if (current === undefined) {\n throw new TxError(\n \"not_found\",\n `Cannot unlink \"${op.link}\": child row \"${op.childId}\" does not exist.`\n );\n }\n if (current.fk !== op.parentId) return 0;\n }\n\n const value: SqlValue = op.kind === \"link\" ? op.parentId : null;\n const changes = context.sql.exec(\n `UPDATE ${table} SET ${foreignKeyColumn} = ?, \"updated_at\" = ?, \"updated_seq\" = ? WHERE \"id\" = ?`,\n value,\n context.now,\n context.seq,\n op.childId\n );\n\n if (changes === 0) {\n throw new TxError(\n \"not_found\",\n `Cannot ${op.kind} \"${op.link}\": child row \"${op.childId}\" does not exist.`\n );\n }\n\n return 1;\n}\n\n/** Maps SQLite constraint failures onto the transaction error vocabulary. */\nexport function toTxError(error: unknown, context: ErrorContext = {}): TxError {\n if (error instanceof TxError) {\n const txId = error.txId ?? context.txId;\n const opIndex = error.opIndex ?? context.opIndex;\n return new TxError(error.code, error.message, {\n ...(txId === undefined ? {} : { txId }),\n ...(opIndex === undefined ? {} : { opIndex }),\n });\n }\n\n const message = error instanceof Error ? error.message : String(error);\n\n if (/UNIQUE constraint failed/i.test(message)) {\n return new TxError(\"unique_violation\", message, context);\n }\n if (/FOREIGN KEY constraint failed/i.test(message)) {\n return new TxError(\"foreign_key_violation\", message, context);\n }\n if (/NOT NULL constraint failed|CHECK constraint failed/i.test(message)) {\n return new TxError(\"invalid_value\", message, context);\n }\n\n return new TxError(\"storage_error\", message, context);\n}\n\n/**\n * Registry identifiers are trusted, but quoting still validates the shape so a\n * future registry mistake cannot inject SQL.\n */\nexport function quoteIdentifier(identifier: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {\n throw new TxError(\n \"storage_error\",\n `Invalid SQL identifier \"${identifier}\".`\n );\n }\n return `\"${identifier}\"`;\n}\n","/**\n * Aggregates over one namespace: count, sum, avg, min and max, optionally\n * grouped.\n *\n * An aggregate is a top-level `$.aggregate` option. It reads no rows: the\n * result rides `pageInfo[namespace].aggregate`, which live subscriptions\n * already push when it changes, and which optimistic writes never touch.\n *\n * It runs over exactly the conditions a read of the same `where` uses, `where`\n * read rules included, so an aggregate never counts a row the caller could not\n * read. A namespace whose read rule is a function cannot be aggregated in SQL;\n * the executor then walks the matching rows in bounded chunks, applies the rule\n * to each, and folds the visible ones here, in the same shape.\n */\n\nimport { invalidOp, invalidValue, isPlainObject } from \"./query-types\";\nimport { toSnakeCase, type AttributeType, type NamespaceDefinition } from \"./registry\";\nimport { stagesOf, type Stage } from \"./query-stages\";\nimport { balancedJoin } from \"./sql-binding\";\nimport { quoteIdentifier } from \"./tx-apply\";\nimport type { SqlValue } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\n\n/** The wire shape of `$.aggregate`. Attribute names are API names. */\nexport interface QueryAggregate {\n /** Group by these attributes. Omitted: one group over every matching row. */\n groupBy?: string[];\n /** Count matching rows. */\n count?: boolean;\n /** Count rows where each attribute is not null. */\n countOf?: string[];\n sum?: string[];\n avg?: string[];\n min?: string[];\n max?: string[];\n /** Order groups by their keys. Default: every key ascending. */\n order?: Record<string, \"asc\" | \"desc\">;\n /** At most this many groups. */\n limit?: number;\n}\n\n/** One group of an aggregate result. */\nexport interface AggregateGroup {\n /** The group's key values; empty without `groupBy`. */\n key: Record<string, unknown>;\n count?: number;\n countOf?: Record<string, number>;\n sum?: Record<string, number | null>;\n avg?: Record<string, number | null>;\n min?: Record<string, unknown>;\n max?: Record<string, unknown>;\n}\n\ninterface AggregateField {\n name: string;\n column: string;\n type: AttributeType;\n}\n\nexport interface CompiledAggregate {\n groupBy: AggregateField[];\n count: boolean;\n countOf: AggregateField[];\n sum: AggregateField[];\n avg: AggregateField[];\n min: AggregateField[];\n max: AggregateField[];\n order: Array<{ field: AggregateField; direction: \"asc\" | \"desc\" }>;\n limit: number | null;\n}\n\nconst AGGREGATE_KEYS = new Set([\n \"groupBy\",\n \"count\",\n \"countOf\",\n \"sum\",\n \"avg\",\n \"min\",\n \"max\",\n \"order\",\n \"limit\",\n]);\n\nconst FIELD_LISTS = [\"groupBy\", \"countOf\", \"sum\", \"avg\", \"min\", \"max\"] as const;\n\n/** Validates `$.aggregate` without the registry. */\nexport function parseAggregate(value: unknown): QueryAggregate {\n if (!isPlainObject(value)) {\n throw invalidOp('\"aggregate\" must be an object.');\n }\n for (const key of Object.keys(value)) {\n if (!AGGREGATE_KEYS.has(key)) {\n throw invalidOp(`Unknown aggregate option \"${key}\".`);\n }\n }\n\n const aggregate: QueryAggregate = {};\n for (const key of FIELD_LISTS) {\n if (!(key in value)) continue;\n const list = value[key];\n if (\n !Array.isArray(list) ||\n list.length === 0 ||\n !list.every((name) => typeof name === \"string\" && name.length > 0)\n ) {\n throw invalidOp(`\"aggregate.${key}\" must be a non-empty array of attribute names.`);\n }\n aggregate[key] = [...new Set(list as string[])];\n }\n if (\"count\" in value) {\n if (typeof value.count !== \"boolean\") {\n throw invalidValue('\"aggregate.count\" must be true or false.');\n }\n aggregate.count = value.count;\n }\n if (\"order\" in value) {\n if (!isPlainObject(value.order)) {\n throw invalidOp('\"aggregate.order\" must be an object.');\n }\n const order: Record<string, \"asc\" | \"desc\"> = {};\n for (const [name, direction] of Object.entries(value.order)) {\n if (direction !== \"asc\" && direction !== \"desc\") {\n throw invalidValue(`Order for \"${name}\" must be \"asc\" or \"desc\".`);\n }\n order[name] = direction;\n }\n aggregate.order = order;\n }\n if (\"limit\" in value) {\n const limit = value.limit;\n if (typeof limit !== \"number\" || !Number.isSafeInteger(limit) || limit < 1) {\n throw invalidValue('\"aggregate.limit\" must be a positive integer.');\n }\n aggregate.limit = limit;\n }\n\n const measures =\n aggregate.count === true ||\n aggregate.countOf !== undefined ||\n aggregate.sum !== undefined ||\n aggregate.avg !== undefined ||\n aggregate.min !== undefined ||\n aggregate.max !== undefined;\n if (!measures && aggregate.groupBy === undefined) {\n throw invalidOp('\"aggregate\" needs count, countOf, sum, avg, min, max or groupBy.');\n }\n return aggregate;\n}\n\nfunction resolve(namespace: NamespaceDefinition, name: string): AggregateField {\n if (name === \"id\") return { name, column: \"id\", type: \"string\" };\n if (name === \"createdAt\" && !(\"createdAt\" in namespace.attributes)) {\n return { name, column: \"created_at\", type: \"date\" };\n }\n if (name === \"updatedAt\" && !(\"updatedAt\" in namespace.attributes)) {\n return { name, column: \"updated_at\", type: \"date\" };\n }\n const definition = namespace.attributes[name];\n if (definition === undefined) {\n throw new TxError(\n \"unknown_attribute\",\n `Unknown attribute \"${name}\" on namespace \"${namespace.apiName}\".`\n );\n }\n if (definition.personal) {\n throw new TxError(\"invalid_value\", `Personal field \"${name}\" cannot be filtered, ordered or aggregated.`);\n }\n return { name, column: toSnakeCase(name), type: definition.type };\n}\n\nfunction fields(\n namespace: NamespaceDefinition,\n names: string[] | undefined,\n measure: string,\n allowed: ReadonlySet<AttributeType>\n): AggregateField[] {\n return (names ?? []).map((name) => {\n const field = resolve(namespace, name);\n if (!allowed.has(field.type)) {\n throw invalidValue(`Cannot ${measure} \"${name}\": it is a ${field.type} attribute.`);\n }\n return field;\n });\n}\n\nconst NUMERIC = new Set<AttributeType>([\"number\"]);\nconst ORDERED = new Set<AttributeType>([\"number\", \"date\", \"string\"]);\nconst SCALAR = new Set<AttributeType>([\"number\", \"date\", \"string\", \"boolean\"]);\nconst ANY = new Set<AttributeType>([\"number\", \"date\", \"string\", \"boolean\", \"json\", \"any\"]);\n\n/** Resolves every attribute against the registry. */\nexport function compileAggregate(\n namespace: NamespaceDefinition,\n aggregate: QueryAggregate\n): CompiledAggregate {\n const groupBy = fields(namespace, aggregate.groupBy, \"group by\", SCALAR);\n const order = Object.entries(aggregate.order ?? {}).map(([name, direction]) => {\n const field = groupBy.find((candidate) => candidate.name === name);\n if (field === undefined) {\n throw invalidOp(`\"aggregate.order\" can only name a groupBy attribute; \"${name}\" is not one.`);\n }\n return { field, direction };\n });\n for (const field of groupBy) {\n if (!order.some((entry) => entry.field === field)) order.push({ field, direction: \"asc\" });\n }\n if (aggregate.limit !== undefined && groupBy.length === 0) {\n throw invalidOp('\"aggregate.limit\" needs a groupBy: without one there is a single group.');\n }\n\n return {\n groupBy,\n count: aggregate.count === true,\n countOf: fields(namespace, aggregate.countOf, \"count\", ANY),\n sum: fields(namespace, aggregate.sum, \"sum\", NUMERIC),\n avg: fields(namespace, aggregate.avg, \"average\", NUMERIC),\n min: fields(namespace, aggregate.min, \"take the minimum of\", ORDERED),\n max: fields(namespace, aggregate.max, \"take the maximum of\", ORDERED),\n order,\n limit: aggregate.limit ?? null,\n };\n}\n\n/** The physical columns the in-memory fold reads. */\nexport function aggregateColumns(aggregate: CompiledAggregate): string[] {\n return [\n ...aggregate.groupBy,\n ...aggregate.countOf,\n ...aggregate.sum,\n ...aggregate.avg,\n ...aggregate.min,\n ...aggregate.max,\n ].map((field) => field.column);\n}\n\n/** One `SELECT ... GROUP BY` over the read's conditions (joined like `buildSelectSql`). */\nexport function buildAggregateSql(\n table: string,\n aggregate: CompiledAggregate,\n conditions: ReadonlyArray<{ sql: string; params: SqlValue[]; stages?: Stage[] }>\n): { sql: string; params: SqlValue[]; stages?: Stage[] } {\n const columns: string[] = [];\n aggregate.groupBy.forEach((field, index) =>\n columns.push(`${quoteIdentifier(field.column)} AS \"g${index}\"`)\n );\n if (aggregate.count) columns.push(`COUNT(*) AS \"count\"`);\n const measure = (fn: string, list: AggregateField[], prefix: string) =>\n list.forEach((field, index) =>\n columns.push(`${fn}(${quoteIdentifier(field.column)}) AS \"${prefix}${index}\"`)\n );\n measure(\"COUNT\", aggregate.countOf, \"c\");\n measure(\"SUM\", aggregate.sum, \"s\");\n measure(\"AVG\", aggregate.avg, \"a\");\n measure(\"MIN\", aggregate.min, \"lo\");\n measure(\"MAX\", aggregate.max, \"hi\");\n // A select list needs one column even when only groups are asked for.\n if (columns.length === 0) columns.push(`COUNT(*) AS \"count\"`);\n\n const params = conditions.flatMap((condition) => condition.params);\n const whereSql =\n conditions.length > 0\n ? ` WHERE ${balancedJoin(conditions.map((condition) => condition.sql), \" AND \")}`\n : \"\";\n const groupSql =\n aggregate.groupBy.length > 0\n ? ` GROUP BY ${aggregate.groupBy.map((field) => quoteIdentifier(field.column)).join(\", \")}`\n : \"\";\n const orderSql =\n aggregate.order.length > 0\n ? ` ORDER BY ${aggregate.order\n .map((entry) => `${quoteIdentifier(entry.field.column)} ${entry.direction.toUpperCase()}`)\n .join(\", \")}`\n : \"\";\n let limitSql = \"\";\n if (aggregate.limit !== null) {\n limitSql = \" LIMIT ?\";\n params.push(aggregate.limit);\n }\n\n return {\n sql: `SELECT ${columns.join(\", \")} FROM ${quoteIdentifier(table)}${whereSql}${groupSql}${orderSql}${limitSql}`,\n params,\n stages: stagesOf(conditions),\n };\n}\n\ntype Convert = (type: AttributeType, value: SqlValue | undefined) => unknown;\n\n/** Turns the statement's rows into groups with API-shaped values. */\nexport function groupsFromSql(\n aggregate: CompiledAggregate,\n rows: Array<Record<string, SqlValue>>,\n convert: Convert\n): AggregateGroup[] {\n return rows.map((row) => {\n const group: AggregateGroup = { key: {} };\n aggregate.groupBy.forEach((field, index) => {\n group.key[field.name] = convert(field.type, row[`g${index}`]);\n });\n if (aggregate.count) group.count = Number(row.count ?? 0);\n const fill = (\n list: AggregateField[],\n prefix: string,\n read: (field: AggregateField, value: SqlValue | undefined) => unknown\n ): Record<string, never> | undefined => {\n if (list.length === 0) return undefined;\n const out: Record<string, unknown> = {};\n list.forEach((field, index) => {\n out[field.name] = read(field, row[`${prefix}${index}`]);\n });\n return out as Record<string, never>;\n };\n const number = (_field: AggregateField, value: SqlValue | undefined) =>\n value === null || value === undefined ? null : Number(value);\n const same = (field: AggregateField, value: SqlValue | undefined) => convert(field.type, value);\n const countOf = fill(aggregate.countOf, \"c\", (_field, value) => Number(value ?? 0));\n const sum = fill(aggregate.sum, \"s\", number);\n const avg = fill(aggregate.avg, \"a\", number);\n const min = fill(aggregate.min, \"lo\", same);\n const max = fill(aggregate.max, \"hi\", same);\n if (countOf) group.countOf = countOf;\n if (sum) group.sum = sum;\n if (avg) group.avg = avg;\n if (min) group.min = min;\n if (max) group.max = max;\n return group;\n });\n}\n\n/**\n * SQLite's ordering for one value: NULL, then numbers, then text. The fold\n * sorts and compares with it so its groups come out in the order, and with\n * the extremes, the SQL path would give.\n */\nfunction compareStored(a: SqlValue, b: SqlValue): number {\n const rank = (value: SqlValue) =>\n value === null ? 0 : typeof value === \"number\" ? 1 : typeof value === \"string\" ? 2 : 3;\n const difference = rank(a) - rank(b);\n if (difference !== 0) return difference;\n if (a === null || b === null) return 0;\n if (typeof a === \"string\" && typeof b === \"string\") return a < b ? -1 : a > b ? 1 : 0;\n return Number(a) - Number(b);\n}\n\ninterface Accumulator {\n keyValues: SqlValue[];\n count: number;\n countOf: number[];\n sum: Array<number | null>;\n avgSum: number[];\n avgCount: number[];\n min: SqlValue[];\n max: SqlValue[];\n}\n\n/**\n * The same aggregate folded in memory, for rows a function read rule has\n * already filtered. Feed it chunks with `add`, then read `groups()`.\n */\nexport class AggregateFold {\n private readonly accumulators = new Map<string, Accumulator>();\n\n constructor(private readonly aggregate: CompiledAggregate) {\n if (aggregate.groupBy.length === 0) this.accumulator([]);\n }\n\n private accumulator(keyValues: SqlValue[]): Accumulator {\n const key = JSON.stringify(keyValues);\n let accumulator = this.accumulators.get(key);\n if (accumulator === undefined) {\n const { countOf, sum, avg, min, max } = this.aggregate;\n accumulator = {\n keyValues,\n count: 0,\n countOf: countOf.map(() => 0),\n sum: sum.map(() => null),\n avgSum: avg.map(() => 0),\n avgCount: avg.map(() => 0),\n min: min.map(() => null),\n max: max.map(() => null),\n };\n this.accumulators.set(key, accumulator);\n }\n return accumulator;\n }\n\n add(row: Record<string, SqlValue>): void {\n const { groupBy, countOf, sum, avg, min, max } = this.aggregate;\n const accumulator = this.accumulator(groupBy.map((field) => row[field.column] ?? null));\n accumulator.count += 1;\n countOf.forEach((field, index) => {\n if (row[field.column] !== null && row[field.column] !== undefined) accumulator.countOf[index] += 1;\n });\n sum.forEach((field, index) => {\n const value = row[field.column];\n if (value === null || value === undefined) return;\n accumulator.sum[index] = (accumulator.sum[index] ?? 0) + Number(value);\n });\n avg.forEach((field, index) => {\n const value = row[field.column];\n if (value === null || value === undefined) return;\n accumulator.avgSum[index] += Number(value);\n accumulator.avgCount[index] += 1;\n });\n min.forEach((field, index) => {\n const value = row[field.column] ?? null;\n // MIN and MAX ignore nulls, as SQL's do.\n if (value === null) return;\n const current = accumulator.min[index];\n if (current === null || compareStored(value, current) < 0) accumulator.min[index] = value;\n });\n max.forEach((field, index) => {\n const value = row[field.column] ?? null;\n if (value === null) return;\n const current = accumulator.max[index];\n if (current === null || compareStored(value, current) > 0) accumulator.max[index] = value;\n });\n }\n\n groups(convert: Convert): AggregateGroup[] {\n const { order, limit } = this.aggregate;\n const list = [...this.accumulators.values()];\n list.sort((a, b) => {\n for (const entry of order) {\n const index = this.aggregate.groupBy.indexOf(entry.field);\n const difference = compareStored(a.keyValues[index], b.keyValues[index]);\n if (difference !== 0) return entry.direction === \"asc\" ? difference : -difference;\n }\n return 0;\n });\n const kept = limit === null ? list : list.slice(0, limit);\n\n // Shaped as the statement's rows, so one conversion serves both paths.\n const rows = kept.map((accumulator) => {\n const row: Record<string, SqlValue> = {};\n accumulator.keyValues.forEach((value, index) => (row[`g${index}`] = value));\n row.count = accumulator.count;\n accumulator.countOf.forEach((value, index) => (row[`c${index}`] = value));\n accumulator.sum.forEach((value, index) => (row[`s${index}`] = value));\n accumulator.avgCount.forEach((count, index) => {\n row[`a${index}`] = count === 0 ? null : accumulator.avgSum[index] / count;\n });\n accumulator.min.forEach((value, index) => (row[`lo${index}`] = value));\n accumulator.max.forEach((value, index) => (row[`hi${index}`] = value));\n return row;\n });\n return groupsFromSql(this.aggregate, rows, convert);\n }\n}\n","/**\n * Query-document-to-SQLite compiler for the workspace engine.\n *\n * The compiler resolves every namespace, table, column and link from the\n * registry; client input never names a SQL identifier. Each requested level\n * becomes its own parameterised `SELECT` and the executor hydrates one link\n * level at a time. That keeps link direction handling simple: forward links\n * filter the child table by its foreign key, reverse links look the parent up\n * by id.\n *\n * Supported subset: equality and `$ne`/`$in`/`$gt`/`$gte`/`$lt`/`$lte` on\n * scalar attributes, `order` and `limit` (1..1000). JSON/`any` attributes are\n * returned but cannot be filtered or ordered on. Links nest as deep as the\n * document asks (one statement per level). Relation filters nest as deep as\n * the document asks too: past a few hops, and past a statement length SQLite\n * accepts, the filter is cut into stages that run first (`query-stages.ts`).\n */\n\nimport { compileAggregate, type CompiledAggregate } from \"./query-aggregate\";\nimport { balancedJoin } from \"./sql-binding\";\nimport {\n MAX_CONDITION_SQL,\n membership,\n STAGE_DEPTH,\n stageInsert,\n stageKey,\n stageScan,\n stagesOf,\n type Stage,\n} from \"./query-stages\";\nimport {\n invalidOp,\n invalidValue,\n isIsoDate,\n isPlainObject,\n parseQueryOptions,\n parseWhere,\n decodeQueryCursor,\n type QueryComparison,\n type QueryOptions,\n type QueryScalar,\n type QueryRelationFilter,\n type QueryWhere,\n type SortDirection,\n} from \"./query-types\";\nimport {\n findNamespace,\n LINKS,\n registryGeneration,\n toSnakeCase,\n type AttributeDefinition,\n type AttributeType,\n type LinkDefinition,\n type NamespaceDefinition,\n} from \"./registry\";\nimport { quoteIdentifier } from \"./tx-apply\";\nimport type { SqlRow, SqlValue } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\n\nexport type LinkDirection = \"forward\" | \"reverse\";\nexport type LinkMultiplicity = \"one\" | \"many\";\n\nexport interface CompiledCondition {\n sql: string;\n params: SqlValue[];\n /** Statements that must run first, in order (see `query-stages.ts`). */\n stages?: Stage[];\n /** The `after` keyset predicate: a count ignores it. */\n cursor?: true;\n}\n\nexport interface CompiledOrder {\n column: string;\n direction: SortDirection;\n}\n\nexport interface CompiledNode {\n /** Namespace API name, e.g. \"boards\". */\n namespace: string;\n /** Registered SQLite table. */\n table: string;\n /** 0 for a top-level namespace, 1 or 2 for link levels. */\n depth: number;\n /**\n * Physical columns to read. With a `select` this is the selected columns\n * plus what the engine itself needs: id, ordering keys and the foreign keys\n * that join link levels.\n */\n columns: string[];\n /** API attribute names to return, or null for every attribute. */\n select: string[] | null;\n conditions: CompiledCondition[];\n order: CompiledOrder[];\n /** `null` means \"no SQL LIMIT\" (nested levels are unbounded by default). */\n limit: number | null;\n /** True when the caller asked for `limit`; false for the implicit default. */\n explicitLimit: boolean;\n /** Top level only: also count every matching row. */\n count: boolean;\n /**\n * Namespaces this level's filters read through relation subqueries, and\n * through the read rules compiled into them. A write to one changes which\n * rows match, so live subscriptions re-run on it.\n */\n references: string[];\n /** Top level only: aggregate the matching rows instead of reading them. */\n aggregate: CompiledAggregate | null;\n children: CompiledChild[];\n}\n\nexport interface CompiledChild {\n /** Link label as it appeared in the query. */\n label: string;\n /** Target namespace of the traversal. */\n target: string;\n direction: LinkDirection;\n multiplicity: LinkMultiplicity;\n /** Physical FK column used to join this level to its target. */\n foreignKeyColumn: string;\n node: CompiledNode;\n}\n\nexport interface CompiledQuery {\n nodes: CompiledNode[];\n}\n\n/** Extra predicate applied by the executor during link hydration. */\nexport interface ForeignKeyFilter {\n column: string;\n ids: string[];\n}\n\ninterface LinkLabelInfo {\n link: LinkDefinition;\n direction: LinkDirection;\n}\n\ninterface ResolvedAttribute {\n column: string;\n type: AttributeType;\n}\n\n/** namespace -> link label -> direction. Built once from the registry. */\n/**\n * Link labels are indexed lazily: the deployment schema is installed by\n * `configureRegistry()` after this module loads, so a module-level snapshot\n * would be empty forever.\n */\nlet linkLabelCache: {\n generation: number;\n index: Map<string, Map<string, LinkLabelInfo>>;\n} | null = null;\n\nfunction linkLabels(): Map<string, Map<string, LinkLabelInfo>> {\n const generation = registryGeneration();\n if (linkLabelCache === null || linkLabelCache.generation !== generation) {\n linkLabelCache = { generation, index: buildLinkLabels() };\n }\n return linkLabelCache.index;\n}\n\n/**\n * Compiles a query document.\n *\n * `view` is how relation filters learn what the caller may read: their\n * subqueries run over rows that are never returned, so without it a filter on\n * a linked namespace could reveal rows a read rule hides. Omitting it compiles\n * without read rules, which matches executing without a claim.\n */\nexport function compileQuery(value: unknown, view?: ViewAccess): CompiledQuery {\n if (!isPlainObject(value)) {\n throw invalidOp(\"Query must be a plain object keyed by namespace.\");\n }\n\n try {\n const nodes = Object.entries(value).map(([namespace, node]) =>\n compileNode(namespace, node, 0, view)\n );\n return { nodes };\n } catch (error) {\n // Links, relation filters and logical filters nest as deep as the\n // document does. A document deep enough to exhaust the stack is a bad\n // request, not a server fault.\n if (error instanceof RangeError) {\n throw invalidOp(\"The query nests too deeply to compile.\");\n }\n throw error;\n }\n}\n\n/**\n * SQLite's own bounds on one statement, reported as a bad request naming\n * the bound. Queries should not reach them: deep relation filters and long\n * filters are staged (`query-stages.ts`), `balancedJoin` keeps AND/OR chains\n * logarithmic, and lists travel as one JSON parameter. This stays as a guard,\n * so a bound no stage covers is a 400 that names it, not a 500.\n */\nexport function sqliteLimitError(error: unknown): TxError | null {\n const message = error instanceof Error ? error.message : String(error);\n if (/expression tree is too large|recursion limit|too many terms|parser stack overflow|too many SQL variables|string or blob too big|statement too long/i.test(message)) {\n return invalidOp(`The query is larger than SQLite can run as one statement (${message}). Split the filter.`);\n }\n return null;\n}\n\n/**\n * Builds the parameterised `SELECT` for one level. `extra` adds the link\n * predicate (`foreign_key IN (...)` or `id IN (...)`) without rebuilding the\n * level's own options.\n */\nexport function buildSelectSql(\n node: CompiledNode,\n extra?: ForeignKeyFilter\n): { sql: string; params: SqlValue[]; stages?: Stage[] } {\n const conditions = [...node.conditions];\n\n if (extra !== undefined) {\n if (extra.ids.length === 0) {\n conditions.push({ sql: \"0 = 1\", params: [] });\n } else {\n // One parameter for the whole list: a page of parents can hold a\n // thousand ids, and a Durable Object binds at most 100 parameters.\n conditions.push({\n sql: `${quoteIdentifier(extra.column)} IN ${valueList()}`,\n params: [JSON.stringify(extra.ids)],\n });\n }\n }\n\n const params = conditions.flatMap((condition) => condition.params);\n const whereSql =\n conditions.length > 0\n ? ` WHERE ${balancedJoin(conditions.map((condition) => condition.sql), \" AND \")}`\n : \"\";\n const orderSql =\n node.order.length > 0\n ? ` ORDER BY ${node.order\n .map(\n (entry) =>\n `${quoteIdentifier(entry.column)} ${entry.direction.toUpperCase()}`\n )\n .join(\", \")}`\n : \"\";\n\n const limitSql = node.limit === null ? \"\" : \" LIMIT ?\";\n if (node.limit !== null) params.push(node.limit);\n\n return {\n sql: `SELECT ${node.columns\n .map(quoteIdentifier)\n .join(\", \")} FROM ${quoteIdentifier(\n node.table\n )}${whereSql}${orderSql}${limitSql}`,\n params,\n stages: stagesOf(conditions),\n };\n}\n\nfunction compileNode(\n namespaceName: string,\n value: unknown,\n depth: number,\n view?: ViewAccess\n): CompiledNode {\n const namespace = findNamespace(namespaceName);\n if (!namespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${namespaceName}\".`\n );\n }\n\n if (!isPlainObject(value)) {\n throw invalidOp(`Query for \"${namespaceName}\" must be an object.`);\n }\n\n const options: QueryOptions = \"$\" in value ? parseQueryOptions(value.$) : {};\n\n const children: CompiledChild[] = [];\n /** Columns this level must read for its links, whatever it selects. */\n const linkColumns: string[] = [];\n for (const [label, raw] of Object.entries(value)) {\n if (label === \"$\") continue;\n\n const info = findLinkLabel(namespaceName, label);\n if (!info) {\n throw new TxError(\n \"unknown_link\",\n `Unknown link \"${label}\" on namespace \"${namespaceName}\".`\n );\n }\n\n if (!isPlainObject(raw)) {\n throw invalidOp(`Link \"${label}\" must be an object.`);\n }\n\n const target = linkTarget(info);\n const foreignKeyColumn = toSnakeCase(info.link.foreignKey.attribute);\n const node = compileNode(target.namespace, raw, depth + 1, view);\n // Forward links group the child rows by their key; reverse links look\n // the target up by this row's key. Either way the key is read.\n if (info.direction === \"forward\") {\n if (!node.columns.includes(foreignKeyColumn)) node.columns.push(foreignKeyColumn);\n } else {\n linkColumns.push(foreignKeyColumn);\n }\n children.push({\n label,\n target: target.namespace,\n direction: info.direction,\n multiplicity: linkMultiplicity(info),\n foreignKeyColumn,\n node,\n });\n }\n\n if (options.count === true && depth > 0) {\n throw invalidOp('\"count\" is only available on a top-level namespace.');\n }\n if (options.limit === 0 && children.length > 0) {\n throw invalidOp('\"limit: 0\" reads no rows, so it cannot traverse links.');\n }\n if (options.aggregate !== undefined) {\n if (depth > 0) {\n throw invalidOp('\"aggregate\" is only available on a top-level namespace.');\n }\n if (options.limit !== undefined && options.limit !== 0) {\n throw invalidOp('\"aggregate\" reads no rows: leave \"limit\" out or set it to 0.');\n }\n for (const key of [\"after\", \"order\", \"select\"] as const) {\n if (options[key] !== undefined) {\n throw invalidOp(`\"aggregate\" cannot be combined with \"${key}\"; order groups with \"aggregate.order\".`);\n }\n }\n if (children.length > 0) {\n throw invalidOp('\"aggregate\" reads no rows, so it cannot traverse links.');\n }\n }\n\n const order = compileOrder(namespace, options.order);\n const references = new Set<string>();\n const conditions = compileWhere(namespace, options.where, { view, references });\n // The caller's own `where` read rule is ANDed in at execution; a relation\n // filter inside it reads other namespaces just the same.\n const ownRule = view?.branches(namespaceName);\n if (ownRule !== undefined && ownRule !== null) {\n try {\n compileViewCondition(namespaceName, ownRule, undefined, references);\n } catch {\n // An invalid rule is refused when the query executes.\n }\n }\n if (options.after !== undefined) {\n conditions.push({ ...cursorCondition(options.after, order), cursor: true });\n }\n\n const select =\n options.select === undefined ? null : compileSelect(namespace, options.select);\n const columns =\n select === null\n ? selectColumns(namespace)\n : unique([\n \"id\",\n ...select.map((name) => selectableColumn(namespace, name)!),\n ...order.map((entry) => entry.column),\n ...linkColumns,\n ]);\n\n return {\n namespace: namespaceName,\n table: namespace.table,\n depth,\n columns,\n select,\n conditions,\n references: [...references],\n order,\n // No limit reads every matching row. A nested level's limit is applied\n // per parent (see `hydrateChild`), never as one shared LIMIT.\n limit: options.aggregate !== undefined ? 0 : (options.limit ?? null),\n explicitLimit: options.limit !== undefined,\n count: options.count === true,\n aggregate:\n options.aggregate === undefined ? null : compileAggregate(namespace, options.aggregate),\n children,\n };\n}\n\n/**\n * Lexicographic \"after the cursor row\" predicate.\n *\n * For order (a ASC, b DESC) the next page starts at\n * `a > va OR (a = va AND b < vb)`. The cursor becomes an ordinary WHERE\n * clause, so the executor needs no pagination awareness.\n */\nfunction cursorCondition(\n after: string,\n order: CompiledOrder[]\n): CompiledCondition {\n if (order.length === 0) {\n throw invalidOp('\"after\" requires an explicit \"$.order\".');\n }\n\n const cursor = decodeQueryCursor(after);\n const columns = order.map((entry) => entry.column);\n\n if (\n cursor.cols.length !== columns.length ||\n cursor.cols.some((column, index) => column !== columns[index])\n ) {\n throw invalidOp('\"after\" cursor does not match this query\\'s \"$.order\".');\n }\n\n return conditionAfterValues(order, cursor.vals);\n}\n\n/** SQLite puts NULL first in ascending order and last in descending order. */\nexport function conditionAfterValues(\n order: CompiledOrder[],\n values: readonly (string | number | null)[]\n): CompiledCondition {\n const clauses: string[] = [];\n const params: SqlValue[] = [];\n for (let index = 0; index < order.length; index += 1) {\n const entry = order[index];\n const value = values[index];\n if (value === null && entry.direction === \"desc\") continue;\n const parts: string[] = [];\n for (let prior = 0; prior < index; prior += 1) {\n parts.push(`${quoteIdentifier(order[prior].column)} IS ?`);\n params.push(values[prior]);\n }\n const column = quoteIdentifier(entry.column);\n if (value === null) {\n parts.push(`${column} IS NOT NULL`);\n } else {\n parts.push(entry.direction === \"desc\" ? `(${column} < ? OR ${column} IS NULL)` : `${column} > ?`);\n params.push(value);\n }\n clauses.push(balancedJoin(parts, \" AND \"));\n }\n return { sql: clauses.length ? balancedJoin(clauses, \" OR \") : \"0 = 1\", params };\n}\n\n/**\n * Compiles a `where` view rule's branches into one condition: AND inside a\n * branch, OR across branches. No branches compiles to \"no rows\".\n *\n * Branches are validated with the same parser as client filters, so an\n * unsupported operator is refused instead of being ignored. Ignoring one would\n * compile to `1 = 1` and widen access.\n */\nexport function compileViewCondition(\n namespaceName: string,\n branches: readonly unknown[],\n alias?: string,\n references?: Set<string>,\n depth = 0\n): CompiledCondition {\n const namespace = findNamespace(namespaceName);\n if (!namespace) {\n throw new TxError(\n \"unknown_namespace\",\n `Unknown namespace \"${namespaceName}\".`\n );\n }\n if (branches.length === 0) return { sql: \"0 = 1\", params: [] };\n\n const parts: string[] = [];\n const params: SqlValue[] = [];\n const all: CompiledCondition[] = [];\n for (const branch of branches) {\n let conditions: CompiledCondition[];\n try {\n conditions = compileWhere(namespace, parseWhere(branch), { alias, references, depth });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new TxError(\n \"permission_denied\",\n `View rule for \"${namespaceName}\" returned an invalid filter: ${reason}`\n );\n }\n if (conditions.length === 0) {\n parts.push(\"1 = 1\");\n continue;\n }\n parts.push(balancedJoin(conditions.map((condition) => condition.sql), \" AND \"));\n for (const condition of conditions) params.push(...condition.params);\n all.push(...conditions);\n }\n\n return { sql: balancedJoin(parts, \" OR \"), params, stages: stagesOf(all) };\n}\n\n/** The physical column behind a selectable API name, or undefined. */\nfunction selectableColumn(\n namespace: NamespaceDefinition,\n name: string\n): string | undefined {\n switch (name) {\n case \"id\":\n return \"id\";\n case \"createdAt\":\n return \"created_at\";\n case \"updatedAt\":\n return \"updated_at\";\n case \"updatedSeq\":\n return \"updated_seq\";\n }\n return name in namespace.attributes ? toSnakeCase(name) : undefined;\n}\n\nfunction compileSelect(namespace: NamespaceDefinition, names: string[]): string[] {\n for (const name of names) {\n if (selectableColumn(namespace, name) === undefined) {\n throw new TxError(\n \"unknown_attribute\",\n `Unknown attribute \"${name}\" on namespace \"${namespace.apiName}\".`\n );\n }\n }\n return names;\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)];\n}\n\n/** Every column of a namespace: what a read without `select` returns. */\nexport function selectColumns(namespace: NamespaceDefinition): string[] {\n const columns = new Set<string>([\"id\"]);\n for (const attribute of Object.keys(namespace.attributes)) {\n columns.add(toSnakeCase(attribute));\n }\n columns.add(\"created_at\");\n columns.add(\"updated_at\");\n columns.add(\"updated_seq\");\n return [...columns];\n}\n\n/**\n * How a subquery sees the caller's access to a namespace. Supplied by the\n * executor, which holds the claim; the compiler only places what it returns.\n */\nexport interface ViewAccess {\n /** `where` view-rule branches to AND into a read, or null when there is none. */\n branches(namespace: string): readonly QueryWhere[] | null;\n /** A reason the namespace cannot be filtered on in SQL, or null. */\n refusal(namespace: string): string | null;\n /**\n * The namespace's read rule as a predicate on a stored row, when it is a\n * function and so cannot run in SQL; null otherwise.\n */\n rowRule?(namespace: string): ((row: SqlRow) => boolean) | null;\n}\n\ninterface WhereContext {\n /** Table alias to qualify columns with, for correlated subqueries. */\n alias?: string;\n view?: ViewAccess;\n /** Relation nesting so far. */\n depth?: number;\n /** Shared counter, so every subquery in one statement gets its own alias. */\n aliases?: { next: number };\n /** Collects every namespace a relation subquery reads. */\n references?: Set<string>;\n}\n\nfunction compileWhere(\n namespace: NamespaceDefinition,\n where: QueryWhere | undefined,\n context: WhereContext = {}\n): CompiledCondition[] {\n if (where === undefined) return [];\n\n const conditions: CompiledCondition[] = [];\n for (const [attribute, value] of Object.entries(where)) {\n if (attribute === \"$link\") {\n for (const relation of value as QueryRelationFilter[]) {\n conditions.push(compileRelationFilter(namespace, relation, context));\n }\n continue;\n }\n if (attribute === \"$or\" || attribute === \"$and\") {\n const branches = (value as QueryWhere[]).map((branch) =>\n conjunction(compileWhere(namespace, branch, context))\n );\n conditions.push(\n fitJoin(branches, attribute === \"$or\" ? \" OR \" : \" AND \", namespace, context)\n );\n continue;\n }\n if (attribute === \"$not\") {\n const inner = conjunction(compileWhere(namespace, value as QueryWhere, context));\n // SQL's NOT of an unknown is unknown, which drops the row. A row whose\n // field is null does not match `{ status: \"done\" }`, so it should match\n // its negation: COALESCE treats unknown as false before negating.\n conditions.push({\n sql: `NOT COALESCE((${inner.sql}), 0)`,\n params: inner.params,\n stages: inner.stages,\n });\n continue;\n }\n\n const resolved = resolveAttribute(namespace, attribute);\n if (!resolved) {\n throw new TxError(\n \"unknown_attribute\",\n `Unknown attribute \"${attribute}\" on namespace \"${namespace.apiName}\".`\n );\n }\n\n if (resolved.type === \"json\" || resolved.type === \"any\") {\n throw invalidValue(\n `Cannot filter on non-scalar attribute \"${attribute}\".`\n );\n }\n\n conditions.push(\n isPlainObject(value)\n ? compileComparison(\n resolved.column,\n resolved.type,\n attribute,\n value as QueryComparison,\n context.alias\n )\n : compileEquality(resolved, attribute, value as QueryScalar, context.alias)\n );\n }\n const length = conditions.reduce((total, condition) => total + condition.sql.length + 9, 0);\n return length > MAX_CONDITION_SQL ? [fitJoin(conditions, \" AND \", namespace, context)] : conditions;\n}\n\n/**\n * Joins conditions, staging them when the joined text would be longer than\n * SQLite takes in one statement. An OR stages every chunk under one key (the\n * union); an AND stages each chunk under its own key and requires membership\n * in all of them. Each chunk selects this level's ids from this level's table\n * under the same alias, so correlated subqueries inside it still resolve.\n */\nfunction fitJoin(\n conditions: CompiledCondition[],\n joiner: \" AND \" | \" OR \",\n namespace: NamespaceDefinition,\n context: WhereContext\n): CompiledCondition {\n const joined = joinConditions(conditions, joiner);\n if (joined.sql.length <= MAX_CONDITION_SQL) return joined;\n\n const chunks: CompiledCondition[][] = [];\n let chunk: CompiledCondition[] = [];\n let size = 0;\n for (const condition of conditions) {\n // The balanced join wraps each part in parentheses and adds the joiner.\n const cost = condition.sql.length + joiner.length + 4;\n if (chunk.length > 0 && size + cost > MAX_CONDITION_SQL) {\n chunks.push(chunk);\n chunk = [];\n size = 0;\n }\n chunk.push(condition);\n size += cost;\n }\n if (chunk.length > 0) chunks.push(chunk);\n\n const alias = context.alias ?? namespace.table;\n const from =\n context.alias === undefined\n ? quoteIdentifier(namespace.table)\n : `${quoteIdentifier(namespace.table)} AS ${quoteIdentifier(context.alias)}`;\n const idColumn = qualify(\"id\", alias);\n const stages: Stage[] = [];\n const memberships: CompiledCondition[] = [];\n const unionKey = joiner === \" OR \" ? stageKey() : null;\n for (const part of chunks) {\n const key = unionKey ?? stageKey();\n const inner = joinConditions(part, joiner);\n stages.push(...(inner.stages ?? []), stageInsert(key, idColumn, from, inner.sql, inner.params));\n if (unionKey === null || memberships.length === 0) memberships.push(membership(idColumn, key));\n }\n const result = joinConditions(memberships, \" AND \");\n return { ...result, stages: [...stages, ...(result.stages ?? [])] };\n}\n\n/**\n * One relation filter, as a correlated subquery over the linked table.\n *\n * parent the row this one points at matches fk IN (SELECT id ...)\n * some at least one child matches EXISTS (...)\n * none no child matches NOT EXISTS (...)\n * every no child fails NOT EXISTS (... AND NOT inner)\n *\n * The linked rows are never returned, so the caller could otherwise learn\n * about rows a read rule hides. The target's `where` view rule is therefore\n * compiled into the subquery, and a target whose rule is a function — which\n * only runs after fetch — is refused rather than filtered without it.\n */\nfunction compileRelationFilter(\n namespace: NamespaceDefinition,\n relation: QueryRelationFilter,\n context: WhereContext\n): CompiledCondition {\n const depth = context.depth ?? 0;\n\n const info = findLinkLabel(namespace.apiName, relation.label);\n if (!info) {\n throw new TxError(\n \"unknown_link\",\n `Unknown link \"${relation.label}\" on namespace \"${namespace.apiName}\".`\n );\n }\n\n const target = findNamespace(linkTarget(info).namespace);\n if (!target) {\n throw new TxError(\n \"unknown_namespace\",\n `Link \"${relation.label}\" points at an unregistered namespace.`\n );\n }\n\n context.references?.add(target.apiName);\n const refusal = context.view?.refusal(target.apiName);\n if (refusal !== undefined && refusal !== null) {\n throw new TxError(\"invalid_op\", refusal);\n }\n\n const multiplicity = linkMultiplicity(info);\n if (relation.mode === \"parent\" && multiplicity !== \"one\") {\n throw invalidOp(\n `\"${relation.label}\" is a to-many link: filter it with some, every or none.`\n );\n }\n if (relation.mode !== \"parent\" && multiplicity === \"one\") {\n throw invalidOp(\n `\"${relation.label}\" is a to-one link: filter it directly, not with ${relation.mode}.`\n );\n }\n\n const aliases = context.aliases ?? { next: 0 };\n const alias = `__r${aliases.next++}`;\n const foreignKey = toSnakeCase(info.link.foreignKey.attribute);\n const inner = compileWhere(target, relation.where, {\n alias,\n view: context.view,\n depth: depth + 1,\n aliases,\n references: context.references,\n });\n\n const viewBranches = context.view?.branches(target.apiName);\n if (viewBranches !== undefined && viewBranches !== null) {\n inner.push(compileViewCondition(target.apiName, viewBranches, alias, context.references, depth + 1));\n }\n\n const params: SqlValue[] = inner.flatMap((condition) => condition.params);\n const innerStages = stagesOf(inner) ?? [];\n const innerSql =\n inner.length === 0 ? \"1 = 1\" : balancedJoin(inner.map((condition) => condition.sql), \" AND \");\n const from = `${quoteIdentifier(target.table)} AS ${quoteIdentifier(alias)}`;\n const outer = context.alias ?? namespace.table;\n\n const rowRule = context.view?.rowRule?.(target.apiName) ?? null;\n if (rowRule !== null) {\n // The target's read rule is a function: it runs on fetched rows, so SQL\n // cannot apply it inside a subquery. Read the candidates, keep the rows\n // the rule shows the caller, and test membership in those.\n const key = stageKey();\n const fk = qualify(foreignKey, alias);\n const quoted = quoteIdentifier(alias);\n const staged =\n relation.mode === \"parent\"\n ? stageScan(key, quoted, qualify(\"id\", alias), from, `(${innerSql})`, params, rowRule)\n : stageScan(\n key,\n quoted,\n fk,\n from,\n `(${fk} IS NOT NULL AND ${relation.mode === \"every\" ? `NOT COALESCE((${innerSql}), 0)` : `(${innerSql})`})`,\n params,\n rowRule\n );\n const test =\n relation.mode === \"parent\"\n ? membership(qualify(foreignKey, outer), key)\n : membership(qualify(\"id\", outer), key, relation.mode !== \"some\");\n return { ...test, stages: [...innerStages, staged] };\n }\n\n if (depth > 0 && depth % STAGE_DEPTH === 0) {\n // Deep enough that nesting further would exhaust SQLite's expression\n // depth: run this hop first, into the scratch table, and test membership.\n const key = stageKey();\n const fk = qualify(foreignKey, alias);\n const staged =\n relation.mode === \"parent\"\n ? stageInsert(key, qualify(\"id\", alias), from, `(${innerSql})`, params)\n : stageInsert(\n key,\n fk,\n from,\n `${fk} IS NOT NULL AND ${relation.mode === \"every\" ? `NOT COALESCE((${innerSql}), 0)` : `(${innerSql})`}`,\n params\n );\n const test =\n relation.mode === \"parent\"\n ? membership(qualify(foreignKey, outer), key)\n : membership(qualify(\"id\", outer), key, relation.mode !== \"some\");\n return { ...test, stages: [...innerStages, staged] };\n }\n\n if (relation.mode === \"parent\") {\n // The outer row holds the key. A null key matches nothing, which is what\n // \"its parent matches\" means for a row that has no parent.\n return {\n sql: `${qualify(foreignKey, context.alias ?? namespace.table)} IN (SELECT ${quoteIdentifier(alias)}.\"id\" FROM ${from} WHERE ${innerSql})`,\n params,\n stages: stagesOf(inner),\n };\n }\n\n const correlation = `${qualify(foreignKey, alias)} = ${qualify(\"id\", context.alias ?? namespace.table)}`;\n if (relation.mode === \"every\") {\n // \"every child matches\" is \"no child fails\", which is also true when there\n // are no children — the same reading SQL's universal quantifier has.\n return {\n sql: `NOT EXISTS (SELECT 1 FROM ${from} WHERE ${correlation} AND NOT COALESCE((${innerSql}), 0))`,\n params,\n stages: stagesOf(inner),\n };\n }\n const exists = `EXISTS (SELECT 1 FROM ${from} WHERE ${correlation} AND (${innerSql}))`;\n return { sql: relation.mode === \"none\" ? `NOT ${exists}` : exists, params, stages: stagesOf(inner) };\n}\n\n/** AND of a branch's conditions; an empty branch matches everything. */\nfunction conjunction(conditions: CompiledCondition[]): CompiledCondition {\n if (conditions.length === 0) return { sql: \"1 = 1\", params: [] };\n return joinConditions(conditions, \" AND \");\n}\n\nfunction joinConditions(\n conditions: CompiledCondition[],\n joiner: \" AND \" | \" OR \"\n): CompiledCondition {\n return {\n sql: balancedJoin(conditions.map((condition) => condition.sql), joiner),\n params: conditions.flatMap((condition) => condition.params),\n stages: stagesOf(conditions),\n };\n}\n\n\nfunction compileOrder(\n namespace: NamespaceDefinition,\n order: Record<string, SortDirection> | undefined\n): CompiledOrder[] {\n if (order === undefined) return [];\n\n const compiled: CompiledOrder[] = [];\n for (const [attribute, direction] of Object.entries(order)) {\n const resolved = resolveAttribute(namespace, attribute);\n if (!resolved) {\n throw new TxError(\n \"unknown_attribute\",\n `Unknown attribute \"${attribute}\" on namespace \"${namespace.apiName}\".`\n );\n }\n if (resolved.type === \"json\" || resolved.type === \"any\") {\n throw invalidValue(\n `Cannot order by non-scalar attribute \"${attribute}\".`\n );\n }\n compiled.push({ column: resolved.column, direction });\n }\n return compiled;\n}\n\nfunction resolveAttribute(\n namespace: NamespaceDefinition,\n attribute: string\n): ResolvedAttribute | undefined {\n if (attribute === \"id\") {\n return { column: \"id\", type: \"string\" };\n }\n\n const definition: AttributeDefinition | undefined =\n namespace.attributes[attribute];\n if (!definition) return undefined;\n if (definition.personal) throw invalidValue(`Personal field \"${attribute}\" cannot be filtered, ordered or aggregated.`);\n return { column: toSnakeCase(attribute), type: definition.type };\n}\n\n/**\n * A list bound as one JSON array parameter. Values compare exactly as bound\n * ones would: the column's affinity applies to the right-hand side either\n * way.\n */\nfunction valueList(): string {\n return \"(SELECT value FROM json_each(?))\";\n}\n\n/** `\"column\"` or `\"alias\".\"column\"`: unqualified names bind to the nearest FROM. */\nfunction qualify(column: string, alias?: string): string {\n return alias === undefined\n ? quoteIdentifier(column)\n : `${quoteIdentifier(alias)}.${quoteIdentifier(column)}`;\n}\n\nfunction compileEquality(\n attribute: ResolvedAttribute,\n name: string,\n value: QueryScalar,\n alias?: string\n): CompiledCondition {\n const normalised = normaliseFilterValue(attribute.type, value, name);\n const column = qualify(attribute.column, alias);\n\n if (normalised === null) {\n return { sql: `${column} IS NULL`, params: [] };\n }\n return { sql: `${column} = ?`, params: [normalised] };\n}\n\nfunction compileComparison(\n columnName: string,\n type: AttributeType,\n name: string,\n comparison: QueryComparison,\n alias?: string\n): CompiledCondition {\n const column = qualify(columnName, alias);\n const clauses: string[] = [];\n const params: SqlValue[] = [];\n\n for (const [operator, operand] of Object.entries(comparison)) {\n if (operand === undefined) continue;\n\n switch (operator) {\n case \"$ne\": {\n const value = normaliseOperand(type, operand, name);\n if (value === null) {\n clauses.push(`${column} IS NOT NULL`);\n } else {\n // `$ne` also matches entities where the attribute is\n // null or missing. Bare `<>` drops those rows through SQL's\n // three-valued logic, which silently hides every entity that never\n // set the field.\n clauses.push(`(${column} IS NULL OR ${column} <> ?)`);\n params.push(value);\n }\n break;\n }\n case \"$in\": {\n if (!Array.isArray(operand)) {\n throw invalidValue(`\"$in\" on \"${name}\" requires an array.`);\n }\n const values = operand.map((item, index) =>\n normaliseFilterValue(type, item, `${name}.$in[${index}]`)\n );\n const nonNull = values.filter(\n (item): item is Exclude<SqlValue, null> => item !== null\n );\n const hasNull = values.length !== nonNull.length;\n\n if (nonNull.length === 0 && !hasNull) {\n clauses.push(\"0 = 1\");\n } else {\n const parts: string[] = [];\n if (nonNull.length > 0) {\n parts.push(`${column} IN ${valueList()}`);\n params.push(JSON.stringify(nonNull));\n }\n if (hasNull) parts.push(`${column} IS NULL`);\n clauses.push(parts.join(\" OR \"));\n }\n break;\n }\n case \"$nin\": {\n if (!Array.isArray(operand)) {\n throw invalidValue(`\"$nin\" on \"${name}\" requires an array.`);\n }\n const values = operand.map((item, index) =>\n normaliseFilterValue(type, item, `${name}.$nin[${index}]`)\n );\n const nonNull = values.filter(\n (item): item is Exclude<SqlValue, null> => item !== null\n );\n const excludesNull = values.length !== nonNull.length;\n const parts: string[] = [];\n if (nonNull.length > 0) {\n parts.push(`${column} NOT IN ${valueList()}`);\n params.push(JSON.stringify(nonNull));\n }\n if (excludesNull) {\n parts.unshift(`${column} IS NOT NULL`);\n clauses.push(parts.join(\" AND \"));\n } else if (parts.length > 0) {\n // As with $ne, a row whose field is null is not in the list.\n clauses.push(`${column} IS NULL OR ${parts[0]}`);\n } else {\n clauses.push(\"1 = 1\");\n }\n break;\n }\n case \"$gt\":\n case \"$gte\":\n case \"$lt\":\n case \"$lte\": {\n const value = normaliseOperand(type, operand, name);\n if (value === null) {\n throw invalidValue(\n `Comparison \"${operator}\" on \"${name}\" cannot use null.`\n );\n }\n const sqlOperator =\n operator === \"$gt\"\n ? \">\"\n : operator === \"$gte\"\n ? \">=\"\n : operator === \"$lt\"\n ? \"<\"\n : \"<=\";\n clauses.push(`${column} ${sqlOperator} ?`);\n params.push(value);\n break;\n }\n }\n }\n\n return {\n sql:\n clauses.length > 0\n ? balancedJoin(clauses, \" AND \")\n : \"1 = 1\",\n params,\n };\n}\n\nfunction normaliseOperand(\n type: AttributeType,\n value: unknown,\n name: string\n): SqlValue {\n if (typeof value === \"object\" && value !== null) {\n throw invalidValue(`Comparison value for \"${name}\" must be a scalar.`);\n }\n return normaliseFilterValue(type, value, name);\n}\n\nfunction normaliseFilterValue(\n type: AttributeType,\n value: unknown,\n name: string\n): SqlValue {\n if (value === null) return null;\n\n switch (type) {\n case \"string\":\n if (typeof value !== \"string\") {\n throw invalidValue(`\"${name}\" must be a string.`);\n }\n return value;\n case \"number\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw invalidValue(`\"${name}\" must be a finite number.`);\n }\n return value;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw invalidValue(`\"${name}\" must be a boolean.`);\n }\n return value ? 1 : 0;\n case \"date\": {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === \"string\" && isIsoDate(value)) {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n throw invalidValue(\n `\"${name}\" must be epoch milliseconds or an ISO-8601 date.`\n );\n }\n case \"json\":\n case \"any\":\n throw invalidValue(`Cannot filter on non-scalar attribute \"${name}\".`);\n }\n}\n\nfunction buildLinkLabels(): Map<string, Map<string, LinkLabelInfo>> {\n const byNamespace = new Map<string, Map<string, LinkLabelInfo>>();\n\n for (const link of Object.values(LINKS)) {\n addLinkLabel(byNamespace, link.forward.namespace, link.forward.label, {\n link,\n direction: \"forward\",\n });\n addLinkLabel(byNamespace, link.reverse.namespace, link.reverse.label, {\n link,\n direction: \"reverse\",\n });\n }\n\n return byNamespace;\n}\n\nfunction addLinkLabel(\n byNamespace: Map<string, Map<string, LinkLabelInfo>>,\n namespace: string,\n label: string,\n info: LinkLabelInfo\n): void {\n let labels = byNamespace.get(namespace);\n if (!labels) {\n labels = new Map<string, LinkLabelInfo>();\n byNamespace.set(namespace, labels);\n }\n labels.set(label, info);\n}\n\nfunction findLinkLabel(\n namespace: string,\n label: string\n): LinkLabelInfo | undefined {\n return linkLabels().get(namespace)?.get(label);\n}\n\nfunction linkTarget(info: LinkLabelInfo): { namespace: string } {\n return info.direction === \"forward\"\n ? { namespace: info.link.foreignKey.namespace }\n : { namespace: info.link.forward.namespace };\n}\n\nfunction linkMultiplicity(info: LinkLabelInfo): LinkMultiplicity {\n return info.direction === \"forward\"\n ? info.link.forward.has\n : info.link.reverse.has;\n}\n","/**\n * Executes compiled query documents against workspace SQLite.\n *\n * Entity rows are read as physical columns, hydrated one link level at a time,\n * then folded back into the API shape: camelCase registry attributes, real\n * booleans, epoch-millisecond dates and parsed JSON. Permission checks run on\n * every requested and traversed namespace before any SQL executes.\n */\n\nimport { fromStoredValue } from \"./value-to-api\";\nimport { runStaged, stagesOf } from \"./query-stages\";\nimport type { RoleClaim } from \"../claims\";\nimport {\n buildSelectSql,\n compileQuery,\n sqliteLimitError,\n selectColumns,\n conditionAfterValues,\n compileViewCondition,\n type ViewAccess,\n type CompiledChild,\n type CompiledCondition,\n type CompiledNode,\n type CompiledOrder,\n type CompiledQuery,\n} from \"./query-compile\";\nimport {\n AggregateFold,\n aggregateColumns,\n buildAggregateSql,\n groupsFromSql,\n} from \"./query-aggregate\";\nimport type { AggregateGroup } from \"./query-aggregate\";\nimport { balancedJoin } from \"./sql-binding\";\nimport {\n encodeQueryCursor,\n parseQueryEnvelope,\n QUERY_CHUNK_ROWS,\n type QueryPageInfo,\n type QueryResult,\n} from \"./query-types\";\nimport { findNamespace, toSnakeCase, type AttributeType } from \"./registry\";\nimport {\n allowRowView,\n assertPermission,\n hasFunctionViewRule,\n viewWhereBranches,\n} from \"./tx-permissions\";\nimport { TxError as PermissionError } from \"./tx-types\";\nimport { quoteIdentifier } from \"./tx-apply\";\nimport type { SqlExecutor, SqlValue } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\nimport { PersonalPending } from \"./personal\";\n\ntype PhysicalRow = Record<string, SqlValue>;\n\ninterface HydratedEntity {\n namespace: string;\n row: PhysicalRow;\n /** API attributes the query selected, or null for all of them. */\n select: string[] | null;\n links: Record<string, HydratedEntity | HydratedEntity[] | null>;\n}\n\n/**\n * Parses the envelope, compiles the query, authorizes every namespace and\n * executes it. Invalid queries and permission failures surface as `TxError`;\n * driver failures become `storage_error` so the route maps them to 500.\n */\n/**\n * What a relation filter's subquery may see, for this caller. A namespace the\n * caller cannot read at all, or whose read rule is a function that only runs\n * after fetch, cannot be filtered on in SQL without leaking the rows it hides.\n */\nexport function viewAccess(claim: RoleClaim): ViewAccess {\n return {\n branches: (namespace) => viewWhereBranches(claim, namespace),\n refusal: (namespace) => {\n try {\n assertPermission(claim, namespace, \"view\");\n } catch (error) {\n return error instanceof PermissionError\n ? error.message\n : `Cannot filter on \"${namespace}\".`;\n }\n return null;\n },\n rowRule: (namespace) =>\n hasFunctionViewRule(namespace)\n ? (row) => allowRowView(claim, namespace, rowToApi({ namespace, row } as HydratedEntity))\n : null,\n };\n}\n\nexport function executeQuery(\n sql: SqlExecutor,\n claim: RoleClaim,\n envelope: unknown\n): QueryResult {\n const document = parseQueryEnvelope(envelope);\n const compiled = compileQuery(document, viewAccess(claim));\n\n authorizeQuery(claim, compiled);\n\n try {\n // The claim applies its read rules; without it every matching row comes back.\n return executeCompiledQuery(sql, compiled, claim);\n } catch (error) {\n if (error instanceof TxError || error instanceof PersonalPending) throw error;\n throw new TxError(\"storage_error\", errorMessage(error));\n }\n}\n\n/** `executeQuery` plus per-namespace truncation metadata. */\nexport function executeQueryWithPageInfo(\n sql: SqlExecutor,\n claim: RoleClaim,\n envelope: unknown\n): { data: QueryResult; pageInfo: QueryPageInfo } {\n const document = parseQueryEnvelope(envelope);\n const compiled = compileQuery(document, viewAccess(claim));\n\n authorizeQuery(claim, compiled);\n\n try {\n return executeCompiledQueryWithPageInfo(sql, compiled, claim);\n } catch (error) {\n if (error instanceof TxError || error instanceof PersonalPending) throw error;\n throw new TxError(\"storage_error\", errorMessage(error));\n }\n}\n\n/**\n * Requires `view` on the top-level namespace and every traversed namespace.\n */\nexport function authorizeQuery(\n claim: RoleClaim,\n compiled: CompiledQuery\n): void {\n const checked = new Set<string>();\n\n const visit = (node: CompiledNode): void => {\n if (!checked.has(node.namespace)) {\n assertPermission(claim, node.namespace, \"view\");\n checked.add(node.namespace);\n }\n for (const child of node.children) visit(child.node);\n };\n\n for (const node of compiled.nodes) visit(node);\n}\n\n/** Executes an already compiled and authorized query. */\nexport function executeCompiledQuery(\n sql: SqlExecutor,\n compiled: CompiledQuery,\n claim?: RoleClaim\n): QueryResult {\n return executeCompiledQueryWithPageInfo(sql, compiled, claim).data;\n}\n\n/**\n * Executes a compiled query and reports truncation per namespace.\n *\n * Each chunk asks for one row beyond the limit so `hasMore` is exact instead of\n * a guess, and the extra row is discarded before hydration.\n *\n * Row-level `view` rules run in TypeScript, so they cannot be pushed into SQL:\n * they see API-shaped values and may be arbitrary predicates. A page is\n * therefore filled by scanning further until it has enough visible rows or\n * exhausts the matching rows. `hasMore` and `nextCursor` stay honest: `returned`\n * counts visible rows only, `hasMore` means matching rows remain outside this\n * page, and `nextCursor` resumes after the last VISIBLE row.\n */\nexport function executeCompiledQueryWithPageInfo(\n sql: SqlExecutor,\n compiled: CompiledQuery,\n claim?: RoleClaim\n): { data: QueryResult; pageInfo: QueryPageInfo } {\n try {\n return executePages(sql, compiled, claim);\n } catch (error) {\n throw sqliteLimitError(error) ?? error;\n }\n}\n\nfunction executePages(\n sql: SqlExecutor,\n compiled: CompiledQuery,\n claim?: RoleClaim\n): { data: QueryResult; pageInfo: QueryPageInfo } {\n const data: QueryResult = {};\n const pageInfo: QueryPageInfo = {};\n const nodes =\n claim === undefined\n ? compiled.nodes\n : compiled.nodes.map((node) => withViewConditions(node, claim));\n\n for (const node of nodes) {\n const limit = node.limit;\n\n if (limit === null) {\n // No limit: every matching row, so there is no page to fill and no\n // cursor to resume from.\n const entities = hydrateNode(sql, node);\n const visible =\n claim === undefined ? entities : visibleOnly(entities, claim);\n const count = node.count ? countRows(sql, node, claim) : undefined;\n\n data[node.namespace] = visible.map(toApiEntity);\n pageInfo[node.namespace] = {\n limit,\n returned: visible.length,\n hasMore: false,\n ...(count === undefined ? {} : { count }),\n };\n continue;\n }\n\n const count = node.count ? countRows(sql, node, claim) : undefined;\n const aggregate =\n node.aggregate === null ? undefined : aggregateRows(sql, node, claim);\n\n // limit 0 is a count or aggregate with no rows: nothing to fill, nothing\n // to resume.\n const { page, hasMore } =\n limit === 0\n ? { page: [] as HydratedEntity[], hasMore: (count ?? 0) > 0 }\n : fillPage(sql, node, claim, limit);\n\n data[node.namespace] = page.map(toApiEntity);\n\n const nextCursor = cursorFor(node, page, hasMore);\n pageInfo[node.namespace] = {\n limit,\n returned: page.length,\n hasMore,\n ...(nextCursor === undefined ? {} : { nextCursor }),\n ...(count === undefined ? {} : { count }),\n ...(aggregate === undefined ? {} : { aggregate }),\n };\n }\n\n return { data, pageInfo };\n}\n\n/**\n * Aggregates the rows matching the node's conditions, `where` read rules\n * included. A function read rule cannot run in SQL, so for one the matching\n * rows are walked in bounded chunks in id order, the rule applied to each,\n * and the visible ones folded; no limit on how far the walk goes.\n */\nfunction aggregateRows(\n sql: SqlExecutor,\n node: CompiledNode,\n claim: RoleClaim | undefined\n): AggregateGroup[] {\n const aggregate = node.aggregate!;\n const conditions = node.conditions.filter((condition) => !condition.cursor);\n\n if (claim === undefined || !hasFunctionViewRule(node.namespace)) {\n const statement = buildAggregateSql(node.table, aggregate, conditions);\n const rows = runStaged(sql, statement.stages, statement.params, (params) =>\n sql.all<PhysicalRow>(statement.sql, ...params)\n );\n return groupsFromSql(aggregate, rows, fromStoredValue);\n }\n\n const namespace = findNamespace(node.namespace);\n const fold = new AggregateFold(aggregate);\n const chunk = 200;\n const base: CompiledNode = {\n ...node,\n columns: [\n ...new Set([\n ...(namespace === undefined ? node.columns : selectColumns(namespace)),\n ...aggregateColumns(aggregate),\n ]),\n ],\n conditions,\n order: [{ column: \"id\", direction: \"asc\" }],\n children: [],\n limit: chunk,\n };\n let cursor: CompiledCondition | null = null;\n for (;;) {\n const rows = hydrateNode(sql, cursor === null ? base : { ...base, conditions: [...conditions, cursor] });\n for (const entity of rows) {\n if (allowRowView(claim, entity.namespace, rowToApi(entity))) fold.add(entity.row);\n }\n if (rows.length < chunk) return fold.groups(fromStoredValue);\n cursor = conditionAfter(base.order, rows[rows.length - 1].row)!;\n }\n}\n\n/**\n * Pushes `where` view rules into the SQL of every level that reads a\n * namespace with one. Those rows never reach the post-fetch filter, so a page\n * fills directly from its SQL index.\n */\nfunction withViewConditions(node: CompiledNode, claim: RoleClaim): CompiledNode {\n const branches = viewWhereBranches(claim, node.namespace);\n const children = node.children.map((child) => ({\n ...child,\n node: withViewConditions(child.node, claim),\n }));\n // A function read rule sees the whole row, so a projected read still\n // fetches every column; only the response is narrowed.\n const namespace = findNamespace(node.namespace);\n const columns =\n node.select !== null && namespace !== undefined && hasFunctionViewRule(node.namespace)\n ? [...new Set([...node.columns, ...selectColumns(namespace)])]\n : node.columns;\n if (branches === null) return { ...node, columns, children };\n\n return {\n ...node,\n columns,\n conditions: [\n ...node.conditions,\n compileViewCondition(node.namespace, branches),\n ],\n children,\n };\n}\n\n/**\n * Rows matching the node's filters, ignoring `after` and `limit`. Uses the\n * same conditions the page used, `where` view rules included, so the count\n * never sees a row the caller could not read.\n */\nfunction countRows(\n sql: SqlExecutor,\n node: CompiledNode,\n claim: RoleClaim | undefined\n): number {\n if (claim !== undefined && hasFunctionViewRule(node.namespace)) {\n // Arbitrary predicates cannot be compiled to SQL. Walk bounded chunks in\n // primary-key order, applying the same rule as reads, without limiting how\n // far through the matching set the count may look.\n const base: CompiledNode = {\n ...node,\n conditions: node.conditions.filter((condition) => !condition.cursor),\n order: [{ column: \"id\", direction: \"asc\" }],\n children: [],\n limit: 200,\n };\n let cursor: CompiledCondition | null = null;\n let total = 0;\n for (;;) {\n const rows = hydrateNode(sql, cursor === null ? base : {\n ...base, conditions: [...base.conditions, cursor],\n });\n total += visibleOnly(rows, claim).length;\n if (rows.length < 200) return total;\n cursor = conditionAfter(base.order, rows[rows.length - 1].row)!;\n }\n }\n\n const conditions = node.conditions.filter((condition) => !condition.cursor);\n const whereSql =\n conditions.length > 0\n ? ` WHERE ${balancedJoin(conditions.map((condition) => condition.sql), \" AND \")}`\n : \"\";\n const row = runStaged(sql, stagesOf(conditions), conditions.flatMap((condition) => condition.params), (params) =>\n sql.one<{ total: number }>(`SELECT COUNT(*) AS \"total\" FROM ${quoteIdentifier(node.table)}${whereSql}`, ...params)\n );\n return Number(row?.total ?? 0);\n}\n\n/** Rows the namespace's `view` rule hides are dropped at every link depth. */\nfunction visibleOnly(\n entities: HydratedEntity[],\n claim: RoleClaim\n): HydratedEntity[] {\n return entities\n .map((entity) => filterVisible(entity, claim))\n .filter((entity): entity is HydratedEntity => entity !== null);\n}\n\n/**\n * Fills one page by scanning forward while `view` rules hide rows.\n *\n * Stops on the first of a full page with another visible row, or exhaustion.\n * `hasMore` requires another visible row; hidden rows cannot truncate a\n * page or create an empty follow-up page.\n */\nfunction fillPage(\n sql: SqlExecutor,\n node: CompiledNode,\n claim: RoleClaim | undefined,\n limit: number\n): { page: HydratedEntity[]; hasMore: boolean } {\n const page: HydratedEntity[] = [];\n\n const more =\n node.order.length === 0\n ? fillUnordered(sql, node, claim, limit, page)\n : fillOrdered(sql, node, claim, limit, page);\n\n return { page, hasMore: more && page.length > 0 };\n}\n\n/**\n * Ordered scan: keyset, one chunk at a time, appending visible rows.\n *\n * The page's own limit plus one probe row is the chunk size. Once the page is\n * full the scan keeps looking for one more VISIBLE row, so `hasMore` is never\n * set on the strength of a hidden row: a client is not sent on an extra round\n * trip to fetch an empty page. Each chunk resumes after the last row actually\n * read, which is what keeps the scan linear in rows read.\n *\n * Returns whether a visible row remains outside the page.\n */\nfunction fillOrdered(\n sql: SqlExecutor,\n node: CompiledNode,\n claim: RoleClaim | undefined,\n limit: number,\n page: HydratedEntity[]\n): boolean {\n let cursor: CompiledCondition | null = null;\n\n for (;;) {\n // A wide page is read in bounded chunks, each resuming after the last.\n const chunkLimit = Math.min(limit, QUERY_CHUNK_ROWS) + 1;\n const chunkNode: CompiledNode =\n cursor === null\n ? { ...node, limit: chunkLimit }\n : { ...node, limit: chunkLimit, conditions: [...node.conditions, cursor] };\n\n const chunk = hydrateNode(sql, chunkNode);\n if (chunk.length === 0) return false;\n\n for (const entity of chunk) {\n const visible = claim === undefined ? entity : filterVisible(entity, claim);\n if (visible === null) continue;\n if (page.length < limit) {\n page.push(visible);\n continue;\n }\n return true; // a visible row sits outside the page\n }\n\n // A short chunk is the end of the match set, so nothing is left to return.\n if (chunk.length < chunkLimit) return false;\n\n const next = conditionAfter(node.order, chunk[chunk.length - 1].row);\n if (next === null) throw new TxError(\"storage_error\", \"Cannot read an ordering column from the stored row.\");\n cursor = next;\n }\n}\n\n/**\n * Unordered scan: no total order exists, so there is no keyset to advance.\n * Re-read one widening window from the start instead of inventing offsets.\n * The window doubles until enough visible rows or the end of the result set\n * is reached.\n */\nfunction fillUnordered(\n sql: SqlExecutor,\n node: CompiledNode,\n claim: RoleClaim | undefined,\n limit: number,\n page: HydratedEntity[]\n): boolean {\n let window = limit + 1;\n\n for (;;) {\n const rows = hydrateNode(sql, { ...node, limit: window });\n const visible = claim === undefined ? rows : visibleOnly(rows, claim);\n\n page.length = 0;\n page.push(...visible.slice(0, limit));\n\n if (rows.length < window) return false; // exhausted\n if (visible.length > limit) return true; // window held more than a page\n\n window *= 2;\n }\n}\n\n/**\n * Keyset predicate for \"strictly after `row`\" in the node's order.\n *\n * Mirrors the compiler's private `cursorCondition`: for `(a ASC, b DESC)` it\n * builds `a > ? OR (a = ? AND b < ?)`. The executor needs it mid-scan, from a\n * row it just read rather than an opaque client cursor. Both paths share the\n * same null-aware tuple comparison. Missing or invalid ordering columns fail closed.\n */\nfunction conditionAfter(\n order: CompiledOrder[],\n row: PhysicalRow\n): CompiledCondition | null {\n const values = order.map(entry => row[entry.column]);\n if (values.some(value => value !== null && typeof value !== \"string\" && typeof value !== \"number\")) return null;\n return conditionAfterValues(order, values as (string | number | null)[]);\n}\n\n/** Drops rows the namespace's `view` rule hides, at every link depth. */\nfunction filterVisible(\n entity: HydratedEntity,\n claim: RoleClaim\n): HydratedEntity | null {\n if (!allowRowView(claim, entity.namespace, rowToApi(entity))) return null;\n\n const links: HydratedEntity[\"links\"] = {};\n for (const [label, value] of Object.entries(entity.links)) {\n if (Array.isArray(value)) {\n links[label] = value\n .map((child) => filterVisible(child, claim))\n .filter((child): child is HydratedEntity => child !== null);\n } else if (value === null) {\n links[label] = null;\n } else {\n links[label] = filterVisible(value, claim);\n }\n }\n\n return { ...entity, links };\n}\n\n/** Stored row with API attribute names, for rule evaluation. */\nfunction rowToApi(entity: HydratedEntity): Record<string, unknown> {\n const namespace = findNamespace(entity.namespace);\n if (!namespace) return { id: entity.row.id };\n\n const output: Record<string, unknown> = { id: entity.row.id };\n if (typeof entity.row.__tapedb_erased === \"string\") output.$erased = JSON.parse(entity.row.__tapedb_erased);\n for (const [attribute, definition] of Object.entries(namespace.attributes)) {\n // Rules see the same values a client would: booleans as booleans, JSON\n // parsed, dates as epoch millis. Handing them raw SQLite integers would\n // make `data.isPublic === true` fail for every row.\n output[attribute] = fromStoredValue(\n definition.type,\n entity.row[toSnakeCase(attribute)]\n );\n }\n return output;\n}\n\n/**\n * Cursor for the next page, or undefined when there is nothing to resume from.\n *\n * Requires an explicit order: without one there is no total order for a keyset\n * cursor to sit in. Null ordering values use SQLite's null-aware ordering.\n */\nfunction cursorFor(\n node: CompiledNode,\n page: HydratedEntity[],\n hasMore: boolean\n): string | undefined {\n if (!hasMore || node.order.length === 0 || page.length === 0) return undefined;\n\n const last = page[page.length - 1];\n const values: (string | number | null)[] = [];\n\n for (const entry of node.order) {\n const value = last.row[entry.column];\n if (value !== null && typeof value !== \"string\" && typeof value !== \"number\") return undefined;\n values.push(value);\n }\n\n return encodeQueryCursor({\n v: 1,\n cols: node.order.map((entry) => entry.column),\n vals: values,\n });\n}\n\nfunction hydrateNode(\n sql: SqlExecutor,\n node: CompiledNode,\n extra?: { column: string; ids: string[] }\n): HydratedEntity[] {\n const { sql: statement, params, stages } = buildSelectSql(node, extra);\n const stored = runStaged(sql, stages, params, (bound) => sql.all<PhysicalRow>(statement, ...bound));\n const rows = sql.decodeRows?.(node.namespace, stored) ?? stored;\n const entities: HydratedEntity[] = rows.map((row) => ({\n namespace: node.namespace,\n row,\n select: node.select,\n links: {},\n }));\n\n for (const child of node.children) {\n hydrateChild(sql, entities, child);\n }\n\n return entities;\n}\n\n/**\n * Hydrates one link level for every parent, a chunk of parents at a time: the\n * parents' keys travel as one JSON list per statement, and a list of every\n * key on an unbounded page would outgrow what one bound value may hold.\n * Each parent's children come from the one statement that holds its key, so\n * per-parent order and limits are unchanged.\n */\nfunction hydrateChild(\n sql: SqlExecutor,\n entities: HydratedEntity[],\n child: CompiledChild\n): void {\n for (let start = 0; start < entities.length; start += QUERY_CHUNK_ROWS) {\n hydrateChildChunk(sql, entities.slice(start, start + QUERY_CHUNK_ROWS), child);\n }\n}\n\nfunction hydrateChildChunk(\n sql: SqlExecutor,\n entities: HydratedEntity[],\n child: CompiledChild\n): void {\n if (entities.length === 0) return;\n\n const foreignKey = child.foreignKeyColumn;\n\n if (child.direction === \"forward\") {\n // Forward links store the FK on the child: fetch children whose FK is one\n // of the current parent ids, then group by that FK.\n const parentIds = uniqueIds(entities.map((entity) => entity.row.id));\n\n // One SQL LIMIT over `fk IN (...)` is shared by every parent, so the last\n // parents silently get nothing. Apply an explicit limit per parent instead:\n // fetch unbounded when several parents are in play, then trim each group.\n const perParentLimit =\n child.node.explicitLimit && parentIds.length > 1\n ? child.node.limit\n : null;\n const children =\n parentIds.length > 0\n ? hydrateNode(\n sql,\n perParentLimit === null\n ? child.node\n : { ...child.node, limit: null },\n {\n column: foreignKey,\n ids: parentIds,\n }\n )\n : [];\n\n if (child.multiplicity === \"many\") {\n const groups = new Map<string, HydratedEntity[]>();\n for (const entry of children) {\n const key = stringValue(entry.row[foreignKey]);\n if (key === null) continue;\n const group = groups.get(key);\n if (group) {\n if (perParentLimit !== null && group.length >= perParentLimit) {\n continue;\n }\n group.push(entry);\n } else {\n groups.set(key, [entry]);\n }\n }\n for (const entity of entities) {\n const key = stringValue(entity.row.id);\n entity.links[child.label] = key === null ? [] : (groups.get(key) ?? []);\n }\n return;\n }\n\n const firstByKey = new Map<string, HydratedEntity>();\n for (const entry of children) {\n const key = stringValue(entry.row[foreignKey]);\n if (key !== null && !firstByKey.has(key)) {\n firstByKey.set(key, entry);\n }\n }\n for (const entity of entities) {\n const key = stringValue(entity.row.id);\n entity.links[child.label] =\n key === null ? null : (firstByKey.get(key) ?? null);\n }\n return;\n }\n\n // Reverse traversal: the current rows own the foreign key, so look the\n // target rows up by id.\n const keys = uniqueIds(entities.map((entity) => entity.row[foreignKey]));\n const targets =\n keys.length > 0\n ? hydrateNode(sql, child.node, { column: \"id\", ids: keys })\n : [];\n const byId = new Map<string, HydratedEntity>();\n for (const target of targets) {\n const id = stringValue(target.row.id);\n if (id !== null) byId.set(id, target);\n }\n\n if (child.multiplicity === \"many\") {\n for (const entity of entities) {\n const id = stringValue(entity.row[foreignKey]);\n const target = id === null ? undefined : byId.get(id);\n entity.links[child.label] = target ? [target] : [];\n }\n return;\n }\n\n for (const entity of entities) {\n const id = stringValue(entity.row[foreignKey]);\n entity.links[child.label] = id === null ? null : (byId.get(id) ?? null);\n }\n}\n\nfunction toApiEntity(entity: HydratedEntity): Record<string, unknown> {\n const namespace = findNamespace(entity.namespace);\n if (!namespace) {\n throw new TxError(\n \"storage_error\",\n `Namespace \"${entity.namespace}\" is not registered.`\n );\n }\n\n const output: Record<string, unknown> = { id: entity.row.id };\n if (typeof entity.row.__tapedb_erased === \"string\") output.$erased = JSON.parse(entity.row.__tapedb_erased);\n if (entity.select !== null) {\n for (const name of entity.select) {\n if (name === \"id\") continue;\n const definition = namespace.attributes[name];\n if (definition !== undefined) {\n output[name] = fromStoredValue(definition.type, entity.row[toSnakeCase(name)]);\n } else if (name === \"createdAt\") {\n output.createdAt = fromStoredValue(\"date\", entity.row.created_at);\n } else if (name === \"updatedAt\") {\n output.updatedAt = fromStoredValue(\"date\", entity.row.updated_at);\n } else if (name === \"updatedSeq\") {\n output.updatedSeq = fromStoredValue(\"number\", entity.row.updated_seq) ?? 0;\n }\n }\n appendLinks(output, entity);\n return output;\n }\n const attributes = new Set<string>([\"id\"]);\n\n for (const [attribute, definition] of Object.entries(namespace.attributes)) {\n output[attribute] = fromStoredValue(\n definition.type,\n entity.row[toSnakeCase(attribute)]\n );\n attributes.add(attribute);\n }\n\n // Engine columns are part of every row even when the namespace does not\n // declare them as attributes. Expose them consistently under API names.\n if (!attributes.has(\"createdAt\")) {\n output.createdAt = fromStoredValue(\"date\", entity.row.created_at);\n }\n if (!attributes.has(\"updatedAt\")) {\n output.updatedAt = fromStoredValue(\"date\", entity.row.updated_at);\n }\n output.updatedSeq = fromStoredValue(\"number\", entity.row.updated_seq) ?? 0;\n appendLinks(output, entity);\n return output;\n}\n\nfunction appendLinks(output: Record<string, unknown>, entity: HydratedEntity): void {\n for (const [label, value] of Object.entries(entity.links)) {\n output[label] = Array.isArray(value)\n ? value.map(toApiEntity)\n : value === null\n ? null\n : toApiEntity(value);\n }\n}\n\nexport { fromStoredValue } from \"./value-to-api\";\n\nfunction uniqueIds(values: SqlValue[]): string[] {\n const ids = new Set<string>();\n for (const value of values) {\n const id = stringValue(value);\n if (id !== null) ids.add(id);\n }\n return [...ids];\n}\n\nfunction stringValue(value: SqlValue | undefined): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { PersonalPending } from \"./personal\";\n/**\n * Per-file access rules: who may read, write and delete each file.\n *\n * Installed from the schema's `files` rules by `defineTapeDB`, in the Worker\n * and in every Durable Object. Without rules the defaults are role levels\n * (read: member, write and delete: editor), checked by the Worker alone, as\n * before. With any rule the workspace's Durable Object decides every byte\n * route and filters the file list, because only it holds the index (who\n * uploaded what) and the rows a file can be attached to.\n *\n * A rule is one of:\n * - a role level;\n * - a check over the caller and the file (and, for a write, the file it\n * replaces);\n * - attachment to a row: the file follows the row's own rules. Reading it\n * needs the row to be readable by the caller, writing or deleting it needs\n * the caller to be allowed to update the row. A path that names no row, or\n * a row that does not exist, denies.\n *\n * Every rule fails closed: one that throws denies.\n */\n\nimport { hasRole, WORKSPACE_ROLE_LEVELS, type RoleClaim } from \"../claims\";\nimport { executeQuery } from \"./query-execute\";\nimport { findNamespace } from \"./registry\";\nimport { allowStoredRow } from \"./tx-permissions\";\nimport type { SqlExecutor } from \"./tx-sql\";\n\nexport type FileAction = \"read\" | \"write\" | \"delete\";\n\n/** A file as rules see it. */\nexport interface FileInfo {\n path: string;\n /** Bytes; null for a write whose size is not known yet. */\n size: number | null;\n contentType: string | null;\n /** The uploader's claim subject. */\n uploadedBy: string;\n}\n\nexport interface FileCheckContext {\n auth: { sub: string; role: number; workspaceId: string };\n /** For read and delete, the stored file; for write, the incoming one. */\n file: FileInfo;\n /** For write, the stored file it would replace, if any. */\n existing?: FileInfo;\n}\n\nexport type FileRule =\n | { readonly decision: \"role\"; readonly level: number }\n | { readonly decision: \"check\"; readonly test: (context: FileCheckContext) => boolean }\n | {\n readonly decision: \"attachedTo\";\n readonly model: string;\n readonly locate: (path: string) => string | null | undefined;\n };\n\nexport interface FileRules {\n read?: FileRule;\n write?: FileRule;\n delete?: FileRule;\n}\n\nconst DEFAULTS: Record<FileAction, FileRule> = {\n read: { decision: \"role\", level: WORKSPACE_ROLE_LEVELS.MEMBER },\n write: { decision: \"role\", level: WORKSPACE_ROLE_LEVELS.EDITOR },\n delete: { decision: \"role\", level: WORKSPACE_ROLE_LEVELS.EDITOR },\n};\n\nlet rules: FileRules = {};\n\nexport function configureFileAccess(next: FileRules | undefined): void {\n for (const [action, rule] of Object.entries(next ?? {})) {\n if (![\"read\", \"write\", \"delete\"].includes(action)) {\n throw new Error(`files.${action} is not a file action; use read, write or delete.`);\n }\n if (rule === undefined) continue;\n if (rule.decision === \"role\") {\n if (!Number.isInteger(rule.level)) throw new Error(`files.${action}: role() needs a role level.`);\n } else if (rule.decision === \"check\") {\n if (typeof rule.test !== \"function\") throw new Error(`files.${action}: fileCheck() needs a function.`);\n } else if (rule.decision === \"attachedTo\") {\n if (typeof rule.locate !== \"function\") throw new Error(`files.${action}: attachedTo() needs a function from path to row id.`);\n } else {\n throw new Error(`files.${action}: use role(), fileCheck() or attachedTo().`);\n }\n }\n rules = { ...(next ?? {}) };\n}\n\n/** True when the schema sets any file rule; the defaults need no Durable Object. */\nexport function fileRulesConfigured(): boolean {\n return Object.values(rules).some((rule) => rule !== undefined);\n}\n\nfunction ruleFor(action: FileAction): FileRule {\n return rules[action] ?? DEFAULTS[action];\n}\n\n/** The role a role-only rule needs, or null when the rule looks at the file. */\nexport function fileRoleFloor(action: FileAction): number | null {\n const rule = ruleFor(action);\n return rule.decision === \"role\" ? rule.level : null;\n}\n\nfunction authOf(claim: RoleClaim) {\n return { sub: claim.sub, role: claim.role, workspaceId: claim.workspaceId };\n}\n\nfunction locate(rule: Extract<FileRule, { decision: \"attachedTo\" }>, path: string): string | null {\n try {\n const id = rule.locate(path);\n return typeof id === \"string\" && id.length > 0 ? id : null;\n } catch {\n return null;\n }\n}\n\n/** Ids among `ids` the caller can read in `model`, under its read rules. */\nfunction readableRows(sql: SqlExecutor, claim: RoleClaim, model: string, ids: string[]): Set<string> {\n const visible = new Set<string>();\n if (!findNamespace(model)) return visible;\n for (let start = 0; start < ids.length; start += 1000) {\n const chunk = ids.slice(start, start + 1000);\n try {\n const result = executeQuery(sql, claim, { query: { [model]: { $: { where: { id: { $in: chunk } } } } } });\n for (const row of result[model] ?? []) {\n const id = (row as { id?: unknown }).id;\n if (typeof id === \"string\") visible.add(id);\n }\n } catch (error) {\n if (error instanceof PersonalPending) throw error;\n // A read the caller may not make at all shows nothing.\n }\n }\n return visible;\n}\n\n/**\n * Whether the caller may take `action` on `file`. For a write, `file` is the\n * incoming file and `existing` the stored one it would replace.\n */\nexport function authorizeFile(\n sql: SqlExecutor,\n claim: RoleClaim,\n action: FileAction,\n file: FileInfo,\n existing?: FileInfo\n): boolean {\n const rule = ruleFor(action);\n switch (rule.decision) {\n case \"role\":\n return hasRole(claim, rule.level as never);\n case \"check\":\n try {\n return rule.test({ auth: authOf(claim), file, ...(existing ? { existing } : {}) }) === true;\n } catch {\n return false;\n }\n case \"attachedTo\": {\n const id = locate(rule, file.path);\n if (id === null) return false;\n return action === \"read\"\n ? readableRows(sql, claim, rule.model, [id]).has(id)\n : allowStoredRow(sql, claim, rule.model, id, \"update\");\n }\n }\n}\n\n/** The files the caller may read, in order. Attached rows are read in chunks. */\nexport function readableFiles<T extends FileInfo>(sql: SqlExecutor, claim: RoleClaim, files: T[]): T[] {\n const rule = ruleFor(\"read\");\n if (rule.decision !== \"attachedTo\") {\n return files.filter((file) => authorizeFile(sql, claim, \"read\", file));\n }\n const ids = files.map((file) => locate(rule, file.path));\n const visible = readableRows(\n sql,\n claim,\n rule.model,\n [...new Set(ids.filter((id): id is string => id !== null))]\n );\n return files.filter((_, index) => ids[index] !== null && visible.has(ids[index]!));\n}\n","/**\n * How long a workspace keeps history: old values in R2 log segments, older\n * snapshots and the local replay log. Storage limitation: a value deleted or\n * overwritten at time T is gone from every copy by T + retention.\n *\n * The bound holds because, with R the retention:\n * - a workspace with changes since its newest snapshot takes a new one once\n * that snapshot is R/2 old, so a pre-T snapshot is superseded by T + R/2;\n * - a superseded snapshot, a log segment it covers and a covered local log row\n * are deleted once older than R/2, with a superseded snapshot kept at least\n * SUPERSEDED_GRACE_MS as a fallback should the new one prove unreadable.\n * R/2 + grace <= R because the minimum retention is twice the grace.\n */\n\nexport const DAY_MS = 24 * 60 * 60 * 1000;\nexport const DEFAULT_HISTORY_RETENTION_MS = 30 * DAY_MS;\nexport const SUPERSEDED_GRACE_MS = DAY_MS;\nexport const MIN_HISTORY_RETENTION_MS = 2 * SUPERSEDED_GRACE_MS;\n\nlet configured = DEFAULT_HISTORY_RETENTION_MS;\n\nexport interface RetentionOptions {\n /** Days a deleted or overwritten value may remain in history. Defaults to 30; at least 2. */\n days?: number;\n}\n\n/** Installed by defineTapeDB; the room reads it on every durability pass. */\nexport function configureRetention(options: RetentionOptions | undefined): void {\n const days = options?.days ?? DEFAULT_HISTORY_RETENTION_MS / DAY_MS;\n if (typeof days !== \"number\" || !Number.isFinite(days) || days * DAY_MS < MIN_HISTORY_RETENTION_MS) {\n throw new Error(`retention.days must be a number of at least ${MIN_HISTORY_RETENTION_MS / DAY_MS}.`);\n }\n configured = days * DAY_MS;\n}\n\nexport function historyRetentionMs(): number {\n return configured;\n}\n\n/** History older than this (relative to now) is due for deletion. */\nexport function historyAgeLimit(retentionMs: number): number {\n return retentionMs / 2;\n}\n","/**\n * Single source of truth for the `tapedb-data` key layout.\n *\n * Layout:\n * ws/{workspaceId}/manifest.json\n * ws/{workspaceId}/log/{fromSeq}-{toSeq}.ndjson\n * ws/{workspaceId}/snapshots/{seq}.sqlite.gz\n * ws/{workspaceId}/docs/{docId}/{version}.yjs\n * ws/{workspaceId}/$files/{path}\n * ws/{workspaceId}/exports/{exportId}.zip\n * users/{userId}/avatar/{fileId}.{ext}\n */\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;\nconst EXTENSION_PATTERN = /^[A-Za-z0-9]{1,10}$/;\n\nexport const MANIFEST_VERSION = 2 as const;\n\nexport interface ManifestChunk {\n /** R2 key relative to the workspace prefix (e.g. `log/1-42.ndjson`). */\n key: string;\n rows: number;\n bytes: number;\n sha256: string;\n}\n\nexport interface ManifestTable {\n name: string;\n chunks: ManifestChunk[];\n}\n\nexport interface WorkspaceManifest {\n version: typeof MANIFEST_VERSION;\n workspaceId: string;\n /** Sequence the snapshot/base state covers. */\n baseSeq: number;\n /** Highest sequence included in the manifest. */\n logSeq: number;\n /** ISO 8601 timestamp for when the manifest was written. */\n createdAt: string;\n engineVersion: string;\n /** The app schema the snapshot was taken under; absent before it was recorded. */\n schemaVersion?: string;\n /** Receipts are complete after this epoch time; zero means complete for all time. */\n receiptFloor?: number;\n tables: ManifestTable[];\n totalRows: number;\n totalBytes: number;\n}\n\nexport function isWorkspaceId(value: string): boolean {\n return UUID_PATTERN.test(value);\n}\n\nexport function assertWorkspaceId(value: string): string {\n if (!isWorkspaceId(value)) {\n throw new Error(\"Workspace id must be a UUID.\");\n }\n return value;\n}\n\nfunction assertSafeSegment(value: string, label: string): string {\n if (!SAFE_SEGMENT_PATTERN.test(value)) {\n throw new Error(`${label} must match [A-Za-z0-9][A-Za-z0-9._~-]{0,127}.`);\n }\n return value;\n}\n\nfunction assertNonNegativeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative integer.`);\n }\n return value;\n}\n\nfunction assertPositiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${label} must be a positive integer.`);\n }\n return value;\n}\n\n/** Where a workspace's uploaded files live, in the FILES bucket. */\nexport function filesPrefix(workspaceId: string): string {\n return `workspaces/${workspaceId}/files/`;\n}\n\nexport function workspacePrefix(workspaceId: string): string {\n return `ws/${assertWorkspaceId(workspaceId)}`;\n}\n\nexport function manifestKey(workspaceId: string): string {\n return `${workspacePrefix(workspaceId)}/manifest.json`;\n}\n\n/**\n * The ops of one log entry too large for a segment line: one JSON array per\n * line, in part order. Sorts before the segments in `log/`, which a segment\n * name (digits-digits.ndjson) never matches.\n */\nexport function logOpsKey(workspaceId: string, seq: number): string {\n if (!Number.isSafeInteger(seq) || seq < 1) throw new Error(\"seq must be a positive integer.\");\n return `${workspacePrefix(workspaceId)}/log/ops/${String(seq).padStart(20, \"0\")}.ndjson`;\n}\n\nexport function logSegmentKey(\n workspaceId: string,\n fromSeq: number,\n toSeq: number\n): string {\n assertNonNegativeInteger(fromSeq, \"fromSeq\");\n assertNonNegativeInteger(toSeq, \"toSeq\");\n if (toSeq < fromSeq) {\n throw new Error(\"toSeq must be greater than or equal to fromSeq.\");\n }\n return `${workspacePrefix(workspaceId)}/log/${fromSeq}-${toSeq}.ndjson`;\n}\n\nexport function snapshotKey(workspaceId: string, seq: number): string {\n assertNonNegativeInteger(seq, \"seq\");\n return `${workspacePrefix(workspaceId)}/snapshots/${seq}.sqlite.gz`;\n}\n\nexport function yjsSnapshotKey(\n workspaceId: string,\n documentId: string,\n version: number\n): string {\n const doc = assertSafeSegment(documentId, \"documentId\");\n assertPositiveInteger(version, \"version\");\n return `${workspacePrefix(workspaceId)}/docs/${doc}/${version}.yjs`;\n}\n\n/** Encodes each path segment so `$files/{path}` stays a single R2 key. */\nexport function encodeFilePath(path: string): string {\n if (path.startsWith(\"/\") || path.includes(\"\\\\\")) {\n throw new Error(\"File path must be relative and use forward slashes.\");\n }\n\n const segments = path.split(\"/\");\n if (segments.length === 0) {\n throw new Error(\"File path is empty.\");\n }\n\n return segments\n .map((segment) => {\n if (segment === \"\" || segment === \".\" || segment === \"..\") {\n throw new Error(\"File path contains an unsafe segment.\");\n }\n return encodeURIComponent(segment);\n })\n .join(\"/\");\n}\n\nexport function workspaceFileKey(workspaceId: string, path: string): string {\n return `${workspacePrefix(workspaceId)}/$files/${encodeFilePath(path)}`;\n}\n\nexport function exportKey(workspaceId: string, exportId: string): string {\n return `${workspacePrefix(workspaceId)}/exports/${assertSafeSegment(\n exportId,\n \"exportId\"\n )}.zip`;\n}\n\nexport function avatarKey(\n userId: string,\n fileId: string,\n extension: string\n): string {\n const user = assertSafeSegment(userId, \"userId\");\n const file = assertSafeSegment(fileId, \"fileId\");\n if (!EXTENSION_PATTERN.test(extension)) {\n throw new Error(\"extension must be 1-10 alphanumeric characters.\");\n }\n return `users/${user}/avatar/${file}.${extension}`;\n}\n\nconst SHA256_PATTERN = /^[0-9a-f]{64}$/i;\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isManifestChunk(value: unknown): value is ManifestChunk {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Record<string, unknown>;\n return (\n isNonEmptyString(candidate.key) &&\n isNonNegativeInteger(candidate.rows) &&\n isNonNegativeInteger(candidate.bytes) &&\n typeof candidate.sha256 === \"string\" &&\n SHA256_PATTERN.test(candidate.sha256)\n );\n}\n\nfunction isManifestTable(value: unknown): value is ManifestTable {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Record<string, unknown>;\n return (\n isNonEmptyString(candidate.name) &&\n Array.isArray(candidate.chunks) &&\n candidate.chunks.every(isManifestChunk)\n );\n}\n\nexport function isWorkspaceManifest(\n value: unknown\n): value is WorkspaceManifest {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Record<string, unknown>;\n if (\n candidate.version !== MANIFEST_VERSION ||\n !isNonEmptyString(candidate.workspaceId) ||\n !isWorkspaceId(candidate.workspaceId) ||\n !isNonNegativeInteger(candidate.baseSeq) ||\n !isNonNegativeInteger(candidate.logSeq) ||\n candidate.baseSeq > candidate.logSeq ||\n !isNonEmptyString(candidate.createdAt) ||\n !isNonEmptyString(candidate.engineVersion) ||\n !Array.isArray(candidate.tables) ||\n !candidate.tables.every(isManifestTable) ||\n !isNonNegativeInteger(candidate.totalRows) ||\n !isNonNegativeInteger(candidate.totalBytes) ||\n (candidate.receiptFloor !== undefined && !isNonNegativeInteger(candidate.receiptFloor))\n ) {\n return false;\n }\n\n const tableNames = candidate.tables.map((table) => table.name);\n return new Set(tableNames).size === tableNames.length;\n}\n\n/**\n * Writes the manifest with a conditional PUT.\n *\n * - With an ETag, the write only succeeds if the stored object still matches.\n * - Without one, the write only succeeds if the object does not exist yet.\n *\n * Returns null when the precondition failed, so the caller can re-read and\n * retry instead of overwriting another writer.\n */\nexport async function putManifest(\n bucket: R2Bucket,\n workspaceId: string,\n manifest: WorkspaceManifest,\n etag?: string\n): Promise<R2Object | null> {\n const body = `${JSON.stringify(manifest, null, 2)}\\n`;\n return bucket.put(manifestKey(workspaceId), body, {\n onlyIf: etag ? { etagMatches: etag } : { etagDoesNotMatch: \"*\" },\n httpMetadata: { contentType: \"application/json; charset=utf-8\" },\n });\n}\n\nexport async function readManifest(\n bucket: R2Bucket,\n workspaceId: string\n): Promise<{ manifest: WorkspaceManifest; etag: string } | null> {\n const object = await bucket.get(manifestKey(workspaceId));\n if (!object) return null;\n\n const parsed: unknown = await object.json();\n if (!isWorkspaceManifest(parsed)) {\n throw new Error(\"Stored manifest has an invalid shape.\");\n }\n return { manifest: parsed, etag: object.etag };\n}\n","import { DurableObject } from \"cloudflare:workers\";\n\nimport { stableStringify } from \"./tx-hash\";\nimport type { RoleClaim } from \"../claims\";\nimport { apiError, discardBody, json } from \"../http\";\nimport type { Env } from \"../types\";\nimport {\n durabilityTick,\n durableObjectRecoverySqlExecutor,\n readFlushState,\n readSnapshotState,\n recoverWorkspace,\n historyPruneAt,\n snapshotDueAt,\n} from \"./durability\";\nimport {\n isEngineMigration,\n WORKSPACE_MIGRATIONS,\n type BundledWorkspaceMigration,\n} from \"./migrations-bundle\";\nimport {\n assertMigrationOrder,\n migrationChecksum,\n applyMigrationWithoutCascades,\n MIGRATIONS_TABLE_SQL,\n} from \"./migrations\";\nimport { forgetFileEntry, recordFileEntry } from \"./file-index\";\nimport { compileQuery, type CompiledQuery } from \"./query-compile\";\nimport {\n authorizeQuery,\n executeCompiledQuery,\n executeCompiledQueryWithPageInfo,\n executeQueryWithPageInfo,\n viewAccess,\n} from \"./query-execute\";\nimport {\n isPlainObject,\n type QueryDocument,\n type QueryPageInfo,\n type QueryResult,\n} from \"./query-types\";\nimport { filesPrefix, isWorkspaceId, manifestKey, workspacePrefix } from \"./r2-keys\";\nimport { deleteR2Keys, listAllR2 } from \"./r2-list\";\nimport { WORKSPACE_ROLE_LEVELS } from \"../claims\";\nimport { ENGINE_TABLES, LINKS, NAMESPACES } from \"./registry\";\nimport {\n DEFAULT_INVALIDATION_DEBOUNCE_MS,\n diffQueryResults,\n queryMatchesTouched,\n touchedNamespacesFromEnvelope,\n} from \"./subscriptions\";\nimport { storageHandler } from \"./storage-routes\";\nimport { exportStream } from \"./export\";\nimport { importWorkspace, assertEmpty } from \"./import-workspace\";\nimport { readMove, readMoveWithRetries, writeMove, sourceEnvironment, jurisdiction, copyWorkspace, type MoveState } from \"./workspace-move\";\nimport { flushPending, snapshotWorkspace } from \"./durability\";\nimport { viewDependsOnSubject } from \"./tx-permissions\";\nimport { isTopic, REPLAY_MESSAGES, topicAllowed, topicReplayMs } from \"./topics\";\nimport { auditEnabled, dropAuditCapture, rowHistory, syncAuditCapture } from \"./audit\";\nimport { findNamespace } from \"./registry\";\nimport { handleLimitRequest, isLimiterName } from \"./claim-limits\";\nimport { MAX_SOCKET_MESSAGE_BYTES } from \"../socket-protocol\";\nimport { SocketLimitError, acceptPart, forgetOtherSockets, forgetSocket, isSpilled, loadAttachment, storeAttachment } from \"./socket-state\";\nimport { authorizeFile, fileRulesConfigured, readableFiles, type FileInfo } from \"./file-access\";\nimport { readTrustedRoleClaim } from \"./trusted-claim\";\nimport { migratePersonal } from \"./personal-migrate\";\nimport { PersonalRuntime, hasPersonalFields, personalKeyPrefix } from \"./personal\";\nimport { installPersonalCapture, runPersonalTransaction } from \"./personal-write\";\nimport { runTransaction } from \"./tx-pipeline\";\nimport { durableObjectSqlExecutor, type SqlValue, type SqlExecutor } from \"./tx-sql\";\nimport { TxError, type TxErrorCode } from \"./tx-types\";\nimport { acceptVerifiedSocket } from \"./ws-handshake\";\nimport { offeredProtocols, SOCKET_PROTOCOL } from \"../socket-protocol\";\nimport {\n claimFromAttachment,\n isPresenceTarget,\n parseSocketAttachment,\n type PresencePeer,\n type QueryDiffMessage,\n type SocketAttachment,\n type StoredSubscription,\n} from \"./ws-types\";\n\ntype AppliedRow = Record<string, SqlStorageValue> & {\n id: string;\n checksum: string;\n};\n\ntype IdRow = Record<string, SqlStorageValue> & { id: string };\ntype NameRow = Record<string, SqlStorageValue> & { name: string };\ntype CountRow = Record<string, SqlStorageValue> & { total: number };\n\n/** Delay between a write and the first durability pass. */\nconst DURABILITY_ALARM_DELAY_MS = 30_000;\n/** How long a recovery waits after R2 failed to answer. */\nconst RECOVERY_R2_RETRY_MS = 5_000;\n\n/** Recovery work a boot may do; Cloudflare resets a boot past 30 s. */\nlet RECOVERY_BOOT_BUDGET_MS = 15_000;\n/** Recovery work per alarm while a large restore continues. */\nlet RECOVERY_STEP_BUDGET_MS = 10_000;\n\n/** A restore was started and has not finished or failed. */\nfunction recoveryInProgress(sql: SqlStorage): boolean {\n try {\n return (\n sql.exec<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'recovery_status'`).toArray()[0]?.value ===\n \"running\"\n );\n } catch {\n return false;\n }\n}\n\n/** Test hook: recovery budgets (0 = one chunk or segment per step). */\nexport function setRecoveryBudgetsForTests(boot: number, step: number): void {\n RECOVERY_BOOT_BUDGET_MS = boot;\n RECOVERY_STEP_BUDGET_MS = step;\n}\n\n/**\n * One workspace engine, addressed by `idFromName(workspaceId)`.\n *\n * Owns its SQLite schema, applies bundled Atlas migrations on boot, commits\n * transactions, and flushes/snapshots to R2 on a 30-second alarm.\n */\n/** Left in an erased workspace's otherwise empty SQLite: when it was erased, nothing else. */\nconst ERASED_TABLE = \"_tapedb_erased\";\nconst ERASING_TABLE = \"_tapedb_erasing\";\n\nexport class WorkspaceRoom extends DurableObject<Env> {\n /**\n * Last emitted result per socket client id and subscription id. This is a\n * cache, not a source of truth: hibernation clears it and the next pass\n * falls back to a full `query:data` payload.\n */\n private readonly subscriptionResults = new Map<\n string,\n Map<string, CachedResult>\n >();\n\n /** Namespaces touched since the current debounce window opened. */\n private pendingInvalidationNamespaces = new Set<string>();\n\n private personal?: PersonalRuntime;\n private erased = false;\n private erasurePending = false;\n private erasureRun: Promise<{ historyObjects: number; files: number }> | null = null;\n private readonly activeWork = new Set<Promise<unknown>>();\n private fileWork: Promise<void> = Promise.resolve();\n\n private serializeFileWork<T>(operation: () => Promise<T>): Promise<T> {\n const next = this.fileWork.then(operation, operation);\n this.fileWork = next.then(() => undefined, () => undefined);\n return next;\n }\n\n private async trackWork<T>(operation: () => Promise<T>): Promise<T> {\n const work = Promise.resolve().then(operation);\n this.activeWork.add(work);\n try { return await work; }\n finally { this.activeWork.delete(work); }\n }\n private importing = false;\n private moving = false;\n private moveState: MoveState | null = null;\n /** Boot stopped on a storage read that failed; the next request boots again. */\n private bootDeferred = false;\n private readonly roomEnv: Env;\n /** Restoring from R2 in budgeted steps; requests wait (503). */\n private recovering = false;\n private limiter = false;\n private misplaced: string | null = null;\n private invalidationTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n this.roomEnv = env.TAPEDB_MOVE_FROM !== undefined &&\n (ctx.id.jurisdiction ?? undefined) === jurisdiction(env.TAPEDB_MOVE_FROM) &&\n jurisdiction(env.TAPEDB_MOVE_FROM) !== jurisdiction(env.TAPEDB_JURISDICTION)\n ? sourceEnvironment(env) : env;\n void ctx.blockConcurrencyWhile(() => this.boot());\n }\n\n /** Readiness, migrations and recovery before the first request. */\n private async boot(): Promise<void> {\n const ctx = this.ctx;\n const env = this.roomEnv;\n // A room reached outside the configured jurisdiction stores nothing.\n const expected = env.TAPEDB_JURISDICTION;\n if (expected && ctx.id.jurisdiction !== expected) {\n this.misplaced = `This workspace's Durable Object is in jurisdiction ${JSON.stringify(ctx.id.jurisdiction ?? null)}, not ${JSON.stringify(expected)}; it serves nothing.`;\n return;\n }\n\n // A claim-limiter object (see claim-limits.ts) holds buckets only.\n if (isLimiterName(ctx.id.name)) {\n this.limiter = true;\n return;\n }\n\n // An interrupted erase is never reopened as an ordinary workspace.\n if (ctx.storage.sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${ERASING_TABLE}'`).toArray().length > 0) {\n this.erased = true;\n this.erasurePending = true;\n await ctx.storage.setAlarm(Date.now());\n return;\n }\n\n // An erased workspace stays erased: no migrations, no recovery, no alarm.\n if (ctx.storage.sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '${ERASED_TABLE}'`).toArray().length > 0) {\n this.erased = true;\n return;\n }\n\n if (isWorkspaceId(ctx.id.name ?? \"\")) {\n try {\n this.moveState = await readMoveWithRetries(env.DATA, ctx.id.name!);\n } catch (error) {\n // Whether the workspace moved is unknown, so nothing is served:\n // requests answer 503 and the next one boots again.\n console.error(\"workspace_boot_deferred\", { workspaceId: this.workspaceId, error: String(error) });\n this.bootDeferred = true;\n return;\n }\n if (this.moveState?.state === \"moved\") return;\n }\n\n // Foreign-key enforcement is per connection and off by default in\n // SQLite. Set it before migrations so every request sees it.\n ctx.storage.sql.exec(\"PRAGMA foreign_keys = ON\");\n dropAuditCapture(durableObjectSqlExecutor(ctx.storage));\n await this.applyMigrations();\n syncAuditCapture(durableObjectSqlExecutor(ctx.storage));\n if (hasPersonalFields()) {\n this.personal = new PersonalRuntime(env, this.workspaceId);\n installPersonalCapture(durableObjectSqlExecutor(ctx.storage));\n }\n\n // A wiped DO rebuilds from the R2 manifest before serving traffic. A\n // populated DO returns immediately without touching R2.\n // Recovery gets a budget well inside the 30 s Cloudflare allows a\n // boot; a larger restore continues from alarms (see recoverStep).\n try {\n if (recoveryInProgress(ctx.storage.sql)) {\n // A restore an earlier boot or alarm started continues on alarms,\n // outside the boot's 30 s, so a slow unit cannot reset the object\n // at every boot.\n this.recovering = true;\n await ctx.storage.setAlarm(Date.now());\n } else {\n await this.recoverStep(RECOVERY_BOOT_BUDGET_MS);\n }\n } catch (error) {\n // A failed boot would reset the object and fail every request with\n // an exception. The workspace answers 503 instead, and alarms retry.\n console.error(\"workspace_recovery_failed\", { workspaceId: this.workspaceId, error: String(error) });\n this.recovering = true;\n await ctx.storage.setAlarm(Date.now() + DURABILITY_ALARM_DELAY_MS);\n }\n\n // Sockets that closed while the object was evicted left their stored\n // state behind; hibernated sockets still open keep theirs.\n const live = (ctx.getWebSockets?.() ?? [])\n .map((socket) => (socket.deserializeAttachment() as { clientId?: unknown } | null)?.clientId)\n .filter((clientId): clientId is string => typeof clientId === \"string\");\n forgetOtherSockets(durableObjectSqlExecutor(ctx.storage), live);\n if (!this.recovering) await this.scheduleNextDurabilityAlarm(Date.now());\n }\n\n /** Boots again after a deferred boot; false while it still cannot. */\n private async bootAgain(): Promise<boolean> {\n if (!this.bootDeferred) return true;\n await this.ctx.blockConcurrencyWhile(async () => {\n if (!this.bootDeferred) return;\n this.bootDeferred = false;\n await this.boot();\n });\n return !this.bootDeferred;\n }\n\n /**\n * One budgeted step of a restore from R2. Progress is committed as it\n * goes; a step that runs out of budget leaves the workspace recovering,\n * answering 503, and continues on an alarm right away.\n */\n private async recoverStep(budgetMs: number): Promise<void> {\n const started = Date.now();\n let last = started;\n let slowest = 0;\n let unit = \"start\";\n let slowestUnit = unit;\n const recovery = await recoverWorkspace(\n this.roomEnv.DATA,\n durableObjectRecoverySqlExecutor(this.ctx.storage),\n this.workspaceId,\n {\n // Called between chunks, segments and the parts of a large log\n // entry. A unit as slow as the slowest so far must still fit: a step\n // that runs past Cloudflare's 30 s of CPU resets the object.\n shouldPause: () => Date.now() + slowest >= started + budgetMs,\n onUnit: (next) => {\n const now = Date.now();\n if (now - last > slowest) {\n slowest = now - last;\n slowestUnit = unit;\n }\n unit = next;\n last = now;\n },\n }\n );\n if (Date.now() - last > slowest) {\n slowest = Date.now() - last;\n slowestUnit = unit;\n }\n // Recovery may toggle foreign keys while restoring; make sure the\n // connection is back in enforcing mode before serving writes.\n this.ctx.storage.sql.exec(\"PRAGMA foreign_keys = ON\");\n if (!recovery.recovered && recovery.reason === \"unavailable\") {\n // R2 did not answer. The progress is kept; try again shortly.\n console.error(\"workspace_recovery_r2_unavailable\", { workspaceId: this.workspaceId, error: recovery.error });\n this.recovering = true;\n await this.ctx.storage.setAlarm(Date.now() + RECOVERY_R2_RETRY_MS);\n return;\n }\n if (!recovery.recovered && recovery.reason === \"paused\") {\n console.log(\"workspace_recovering\", { workspaceId: this.workspaceId, stepMs: Date.now() - started, slowestMs: slowest, slowestUnit });\n this.recovering = true;\n await this.ctx.storage.setAlarm(Date.now());\n return;\n }\n const wasRecovering = this.recovering;\n this.recovering = false;\n if (this.personal && !await migratePersonal(durableObjectSqlExecutor(this.ctx.storage), this.personal, fn => this.ctx.storage.transaction(fn), Date.now() + Math.min(budgetMs, 4000))) {\n this.recovering = true;\n await this.ctx.storage.setAlarm(Date.now());\n return;\n }\n if (recovery.recovered) {\n console.log(\"workspace_recovered\", {\n workspaceId: this.workspaceId,\n baseSeq: recovery.baseSeq,\n logSeq: recovery.logSeq,\n rows: recovery.rows,\n replayed: recovery.replayed,\n stepMs: Date.now() - started,\n slowestMs: slowest,\n slowestUnit,\n });\n }\n if (wasRecovering) await this.scheduleNextDurabilityAlarm(Date.now());\n }\n\n private get workspaceId(): string {\n const name = this.ctx.id.name;\n if (!name || !isWorkspaceId(name)) {\n throw new Error(\"Workspace DO must be addressed by a UUID name.\");\n }\n return name;\n }\n\n /**\n * Applies pending migrations before the object serves any request. Each\n * migration and its `_migrations` row commit in the same transaction, so a\n * failed boot cannot leave a half-migrated schema, and each runs with\n * foreign keys off and checked before commit (see\n * `applyMigrationWithoutCascades`).\n */\n private async applyMigrations(): Promise<void> {\n assertMigrationOrder();\n\n const sql = this.ctx.storage.sql;\n sql.exec(MIGRATIONS_TABLE_SQL);\n\n const applied = new Map<string, string>(\n sql\n .exec<AppliedRow>(`SELECT id, checksum FROM \"_migrations\"`)\n .toArray()\n .map((row) => [row.id, row.checksum])\n );\n\n for (const migration of WORKSPACE_MIGRATIONS) {\n const checksum = await migrationChecksum(migration.sql);\n const existing = applied.get(migration.id);\n\n if (existing !== undefined) {\n if (existing !== checksum) {\n throw new Error(\n `Workspace migration ${migration.id} checksum mismatch; refusing to boot on a divergent schema.`\n );\n }\n continue;\n }\n\n await this.applyMigration(migration, checksum);\n }\n }\n\n private async applyMigration(\n migration: BundledWorkspaceMigration,\n checksum: string\n ): Promise<void> {\n const storage = this.ctx.storage;\n const sql = storage.sql;\n await applyMigrationWithoutCascades(\n {\n run: (statements) => void sql.exec(statements),\n all: (query) => sql.exec<Record<string, SqlValue>>(query).toArray(),\n transaction: (fn) => storage.transactionSync(fn),\n settle: async () => {\n // Writes made so far in this event sit in an implicit transaction;\n // syncing them closes it, so the pragma that follows takes effect.\n if (typeof storage.sync === \"function\") await storage.sync();\n else await new Promise((resolve) => setTimeout(resolve, 0));\n },\n },\n migration,\n () => {\n sql.exec(\n `INSERT INTO \"_migrations\" (id, checksum, applied_at) VALUES (?, ?, ?)`,\n migration.id,\n checksum,\n Date.now()\n );\n // Log lines record the app schema they were written under, so recovery\n // knows which later changes to read them through.\n if (!isEngineMigration(migration.id)) {\n sql.exec(\n `INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES ('schema_version', ?)`,\n migration.id\n );\n }\n }\n );\n }\n\n async fetch(request: Request): Promise<Response> {\n if (!(await this.bootAgain())) {\n await discardBody(request);\n const response = apiError(503, \"workspace_recovering\", \"The workspace could not read its state from storage. Retry shortly.\");\n response.headers.set(\"retry-after\", \"1\");\n return response;\n }\n if (this.misplaced !== null) {\n await discardBody(request);\n return apiError(500, \"jurisdiction_mismatch\", this.misplaced);\n }\n if (this.moveState?.state === \"moved\" && !new URL(request.url).pathname.startsWith(\"/move/\")) {\n await discardBody(request);\n return apiError(308, \"workspace_moved\", `This workspace moved to ${this.moveState.to}.`);\n }\n if (this.erased) {\n if (this.erasurePending && request.method === \"DELETE\" && new URL(request.url).pathname === \"/\") return this.erase(request);\n await discardBody(request);\n return apiError(410, \"workspace_erased\", \"This workspace was erased.\");\n }\n if (this.limiter) return handleLimitRequest(request, durableObjectSqlExecutor(this.ctx.storage));\n if (this.recovering) {\n // Serving a partly restored workspace would show data as missing that\n // is only not restored yet.\n await discardBody(request);\n const response = apiError(503, \"workspace_recovering\", \"The workspace is being restored from storage. Retry shortly.\");\n response.headers.set(\"retry-after\", \"2\");\n return response;\n }\n try {\n const erase = request.method === \"DELETE\" && new URL(request.url).pathname === \"/\";\n return await (erase ? this.route(request) : this.trackWork(() => this.route(request)));\n }\n finally {\n this.personal?.clearPlaintext();\n await discardBody(request);\n }\n }\n\n private async route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (url.pathname.startsWith(\"/move/\")) return this.moveControl(request, url.pathname);\n if (this.importing) return apiError(409, \"workspace_importing\", \"The import is still being checked.\");\n if (url.pathname === \"/import\") {\n const claim = readTrustedRoleClaim(request, this.workspaceId);\n if (claim.role < WORKSPACE_ROLE_LEVELS.OWNER) return apiError(403, \"insufficient_role\", \"Only an owner can import a workspace.\");\n if (request.method !== \"POST\") return apiError(405, \"method_not_allowed\", \"Import uses POST.\");\n this.importing = true;\n try {\n const rows = await importWorkspace(durableObjectSqlExecutor(this.ctx.storage), request, claim, this.workspaceId, this.personal);\n await this.scheduleNextDurabilityAlarm(Date.now());\n return json({ ok: true, imported: { rows } });\n } catch (error) { return apiError(error instanceof TxError && error.code === \"conflict\" ? 409 : 400, \"import_failed\", errorMessage(error)); }\n finally { this.importing = false; }\n }\n\n if (this.moveState?.state === \"frozen\" &&\n !(request.method === \"GET\" || url.pathname === \"/query\" || url.pathname === \"/files/authorize\")) {\n return apiError(409, \"workspace_moving\", \"Writes resume after this workspace finishes moving.\");\n }\n\n if (url.pathname.startsWith(\"/storage/\")) {\n const claim = readTrustedRoleClaim(request, this.workspaceId);\n const handle = storageHandler(async (_env, _workspace, path, init, trustedClaim) => {\n const headers = new Headers(init.headers);\n headers.set(\"x-tapedb-claims\", trustedClaim);\n return this.route(new Request(new URL(path, \"https://room.internal\"), { ...init, headers }));\n });\n return this.serializeFileWork(() => {\n if (this.moveState?.state === \"frozen\" || this.moveState?.state === \"moved\") return Promise.resolve(apiError(409, \"workspace_moving\", \"File operations resume after the move.\"));\n return handle(request, this.roomEnv, this.workspaceId, url.pathname.slice(\"/storage/\".length), claim.role, request.headers.get(\"x-tapedb-claims\")!);\n });\n }\n\n if (url.pathname === \"/websocket\") {\n if (request.method !== \"GET\") {\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n return this.handleWebSocket(request);\n }\n\n // DELETE /engine/workspaces/:id: erase everything the workspace holds.\n if (url.pathname === \"/\" && request.method === \"DELETE\") {\n return this.erase(request);\n }\n\n if (url.pathname === \"/status\" || url.pathname === \"/health\") {\n if (request.method !== \"GET\") {\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n try {\n readTrustedRoleClaim(request, this.workspaceId);\n } catch (error) {\n if (error instanceof TxError) return apiError(403, error.code, error.message);\n throw error;\n }\n return this.status();\n }\n\n if (url.pathname.startsWith(\"/subjects/\")) {\n if (request.method !== \"DELETE\") return apiError(405, \"method_not_allowed\", \"Erase a subject with DELETE.\");\n const claim = readTrustedRoleClaim(request, this.workspaceId);\n if (claim.role < WORKSPACE_ROLE_LEVELS.OWNER) return apiError(403, \"insufficient_role\", \"Only an owner can erase personal data.\");\n if (!this.personal) return apiError(400, \"invalid_op\", \"This schema has no personal fields.\");\n let subject: string;\n try { subject = decodeURIComponent(url.pathname.slice(\"/subjects/\".length)); }\n catch { return apiError(400, \"invalid_subject\", \"The subject must be URL encoded.\"); }\n if (!subject) return apiError(400, \"invalid_subject\", \"A subject is required.\");\n await this.ctx.storage.transaction(() => this.personal!.erase(subject));\n this.subscriptionResults.clear();\n this.scheduleInvalidation(Object.keys(NAMESPACES));\n return json({ ok: true });\n }\n\n if (url.pathname === \"/transact\") {\n if (request.method !== \"POST\") {\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n return this.transact(request);\n }\n\n // Introspection for tooling (the studio, your own scripts). Costs one\n // registry read and needs the same claim as any other engine route.\n if (url.pathname === \"/schema\") {\n if (request.method !== \"GET\") {\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n return this.schemaDocument();\n }\n\n if (url.pathname === \"/query\") {\n if (request.method !== \"POST\") {\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n return this.query(request);\n }\n\n // Who changed one row, and when (audit.ts). Admins and owners only: it\n // names other users.\n if (url.pathname === \"/history\") {\n if (request.method !== \"GET\") {\n return apiError(405, \"method_not_allowed\", `${request.method} is not supported for ${url.pathname}.`);\n }\n let claim: RoleClaim;\n try {\n claim = readTrustedRoleClaim(request, this.workspaceId);\n } catch (error) {\n if (error instanceof TxError) return apiError(statusForQueryError(error.code), error.code, error.message);\n throw error;\n }\n if (claim.role < WORKSPACE_ROLE_LEVELS.ADMIN) {\n return apiError(403, \"insufficient_role\", \"Reading the history needs an admin or owner.\");\n }\n if (!auditEnabled()) {\n return apiError(409, \"audit_disabled\", \"This deployment does not record an audit; set defineTapeDB({ audit: true }).\");\n }\n const model = findNamespace(url.searchParams.get(\"model\") ?? \"\");\n const id = url.searchParams.get(\"id\");\n if (!model || !id) return apiError(400, \"invalid_history\", \"History needs ?model=<model>&id=<row id>.\");\n return json({ ok: true, data: rowHistory(durableObjectSqlExecutor(this.ctx.storage), model.table, id) });\n }\n\n // Every row the caller may read, as NDJSON, streamed a chunk at a time.\n if (url.pathname === \"/export\") {\n if (request.method !== \"GET\") {\n return apiError(405, \"method_not_allowed\", `${request.method} is not supported for ${url.pathname}.`);\n }\n let claim: RoleClaim;\n try {\n claim = readTrustedRoleClaim(request, this.workspaceId);\n } catch (error) {\n if (error instanceof TxError) {\n return apiError(statusForQueryError(error.code), error.code, error.message);\n }\n throw error;\n }\n return new Response(\n exportStream(durableObjectSqlExecutor(this.ctx.storage), claim, this.workspaceId, this.personal),\n { headers: { \"content-type\": \"application/x-ndjson; charset=utf-8\", \"cache-control\": \"no-store\" } }\n );\n }\n\n // File metadata. Bytes live in R2 and are handled by the Worker; this is\n // the queryable index so a workspace can be asked what it contains.\n if (url.pathname === \"/files\" || url.pathname === \"/files/authorize\" || url.pathname === \"/files/locate\") {\n // Without file rules, the same roles as the byte routes the Worker\n // serves: reading files needs a member, changing them an editor. With\n // rules, the Worker asks /files/authorize before touching bytes, and\n // the list shows only the files the caller may read.\n let claim: RoleClaim;\n try {\n claim = readTrustedRoleClaim(request, this.workspaceId);\n } catch (error) {\n if (error instanceof TxError) return apiError(403, error.code, error.message);\n throw error;\n }\n if (url.pathname === \"/files/locate\") {\n const body = await request.json() as { path?: string; action?: string };\n const action = body.action === \"delete\" ? \"delete\" : \"read\";\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const stored = typeof body.path === \"string\" ? this.storedFile(sql, body.path) : undefined;\n const allowed = stored && (fileRulesConfigured() ? await this.readPersonal(view => authorizeFile(view, claim, action, stored)) : claim.role >= (action === \"read\" ? WORKSPACE_ROLE_LEVELS.MEMBER : WORKSPACE_ROLE_LEVELS.EDITOR));\n if (!allowed) return apiError(404, \"not_found\", \"No such file.\");\n return json(sql.one<{ key: string }>(`SELECT r2_key AS key FROM \"_files\" WHERE path = ?`, body.path!) ?? {});\n }\n if (url.pathname === \"/files/authorize\") {\n return request.method === \"POST\"\n ? this.authorizeFileRequest(request, claim)\n : apiError(405, \"method_not_allowed\", `${request.method} is not supported for ${url.pathname}.`);\n }\n if (!fileRulesConfigured()) {\n const needed = request.method === \"GET\" ? WORKSPACE_ROLE_LEVELS.MEMBER : WORKSPACE_ROLE_LEVELS.EDITOR;\n if (claim.role < needed) return apiError(403, \"insufficient_role\", \"Insufficient role for this file operation.\");\n }\n if (request.method === \"GET\") return this.listFiles(claim);\n if (request.method === \"POST\") return this.recordFile(request, claim);\n if (request.method === \"DELETE\") return this.forgetFile(request);\n return apiError(\n 405,\n \"method_not_allowed\",\n `${request.method} is not supported for ${url.pathname}.`\n );\n }\n\n return apiError(\n 404,\n \"not_found\",\n `No engine route for ${request.method} ${url.pathname}`\n );\n }\n\n private async moveControl(request: Request, path: string): Promise<Response> {\n const claim = readTrustedRoleClaim(request, this.workspaceId);\n if (claim.role < WORKSPACE_ROLE_LEVELS.OWNER) return apiError(403, \"insufficient_role\", \"Only an owner can move a workspace.\");\n if (request.method !== \"POST\") return apiError(405, \"method_not_allowed\", \"Move controls require POST.\");\n if (this.importing) return apiError(409, \"workspace_importing\", \"Wait for the import to finish.\");\n if (path === \"/move/run\") {\n if (this.moving) return apiError(409, \"workspace_moving\", \"Another request is already moving this workspace.\");\n this.moving = true;\n try {\n const env = this.roomEnv;\n const source = sourceEnvironment(env);\n const to = jurisdiction(env.TAPEDB_JURISDICTION) ?? \"none\";\n const body = await request.json() as { to?: string };\n if (body.to !== to || (jurisdiction(source.TAPEDB_JURISDICTION) === jurisdiction(env.TAPEDB_JURISDICTION) && !env.WORKSPACE_FROM))\n return apiError(400, \"invalid_move\", \"The destination must match a different configured jurisdiction.\");\n const sourceControl = async (action: string) => {\n let ns = source.WORKSPACE;\n if (source.TAPEDB_JURISDICTION) ns = ns.jurisdiction(source.TAPEDB_JURISDICTION as DurableObjectJurisdiction);\n return ns.get(ns.idFromName(this.workspaceId)).fetch(new Request(`https://room.internal/move/${action}`, {\n method: \"POST\", headers: request.headers, body: JSON.stringify({ to }),\n }));\n };\n let state = await readMove(env.DATA, this.workspaceId);\n if (state && state.to !== to) return apiError(409, \"move_conflict\", \"Another move is in progress.\");\n if (!state) assertEmpty(durableObjectSqlExecutor(this.ctx.storage));\n if (state?.state !== \"ready\") {\n const frozen = await sourceControl(\"freeze\"); if (!frozen.ok) return frozen;\n if (state?.state !== \"copied\") {\n await writeMove(env.DATA, this.workspaceId, { state: \"copying\", to });\n const files = await sourceControl(\"files\");\n if (!files.ok || !files.body) return files;\n await copyWorkspace(source, env, this.workspaceId, files.body);\n await writeMove(env.DATA, this.workspaceId, { state: \"copied\", to });\n }\n await this.recoverStep(RECOVERY_BOOT_BUDGET_MS);\n if (this.recovering) return apiError(503, \"workspace_recovering\", \"Retry to finish the move.\");\n await writeMove(env.DATA, this.workspaceId, { state: \"ready\", to });\n }\n const finished = await sourceControl(\"finish\"); if (!finished.ok) return finished;\n return json({ ok: true, moved: { workspaceId: this.workspaceId, to } });\n } catch (error) { return apiError(error instanceof TxError ? 409 : 503, \"move_incomplete\", errorMessage(error)); }\n finally { this.moving = false; }\n }\n\n if (path === \"/move/files\") {\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const keys = (function* () {\n let after = \"\";\n for (;;) {\n const rows = sql.all<{ path: string; key: string }>(`SELECT path, r2_key AS key FROM \"_files\" WHERE path > ? ORDER BY path LIMIT 100`, after);\n if (!rows.length) break;\n for (const row of rows) { yield JSON.stringify(row.key) + \"\\n\"; after = row.path; }\n }\n })();\n const encoder = new TextEncoder();\n return new Response(new ReadableStream({ pull(controller) { const next = keys.next(); if (next.done) controller.close(); else controller.enqueue(encoder.encode(next.value)); } }));\n }\n if (path === \"/move/prepare\") {\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n try { assertEmpty(sql); return json({ ok: true }); }\n catch { return apiError(409, \"workspace_not_empty\", \"The destination must be empty.\"); }\n }\n if (path === \"/move/restore\") {\n await this.recoverStep(RECOVERY_BOOT_BUDGET_MS);\n return this.recovering ? apiError(503, \"workspace_recovering\", \"Retry to continue the restore.\") : json({ ok: true });\n }\n if (path === \"/move/freeze\") {\n const body = await request.json() as { to?: string };\n const to = body.to;\n if (!to || ![\"none\", \"eu\", \"fedramp\"].includes(to)) return apiError(400, \"invalid_move\", \"Choose none, eu or fedramp.\");\n if (this.moveState && this.moveState.to !== to) return apiError(409, \"move_conflict\", \"This workspace is moving to another destination.\");\n if (this.moveState?.state === \"moved\") return json({ ok: true, moved: true });\n this.moveState = { state: \"frozen\", to };\n await writeMove(this.roomEnv.DATA, this.workspaceId, this.moveState);\n for (const socket of this.ctx.getWebSockets()) this.closeSocket(socket, 1012, \"workspace moving\");\n const sql = durableObjectRecoverySqlExecutor(this.ctx.storage);\n for (;;) {\n const result = await flushPending(this.roomEnv.DATA, sql, this.workspaceId, Date.now());\n if (result.error) return apiError(503, \"move_flush_failed\", result.error);\n if (!result.flushed) break;\n }\n const snapshot = await snapshotWorkspace(this.roomEnv.DATA, sql, this.workspaceId, Date.now());\n return snapshot.snapshotted ? json({ ok: true }) : apiError(503, \"move_snapshot_failed\", snapshot.error ?? \"Snapshot failed.\");\n }\n if (path === \"/move/finish\") {\n const state = this.moveState;\n if (!state) return apiError(409, \"move_not_started\", \"Freeze the source first.\");\n this.moveState = { ...state, state: \"moved\" };\n await writeMove(this.roomEnv.DATA, this.workspaceId, this.moveState);\n const history = await listAllR2(this.roomEnv.DATA, `${workspacePrefix(this.workspaceId)}/`);\n await deleteR2Keys(this.roomEnv.DATA, history.map(object => object.key));\n await deleteR2Keys(this.roomEnv.DATA, (await listAllR2(this.roomEnv.DATA, personalKeyPrefix(this.workspaceId))).map(object => object.key));\n if (this.roomEnv.FILES) await deleteR2Keys(this.roomEnv.FILES, (await listAllR2(this.roomEnv.FILES, filesPrefix(this.workspaceId))).map(object => object.key));\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n return json({ ok: true });\n }\n return apiError(404, \"not_found\", \"Unknown move operation.\");\n }\n\n private readPersonal<T>(fn: (sql: ReturnType<typeof durableObjectSqlExecutor>) => T): Promise<T> {\n const raw = durableObjectSqlExecutor(this.ctx.storage);\n const run = () => fn(this.personal?.sql(raw) ?? raw);\n return this.personal ? this.personal.read(run) : Promise.resolve(run());\n }\n\n private async transact(request: Request): Promise<Response> {\n let envelope: unknown;\n try {\n envelope = await request.json();\n } catch {\n return json(\n {\n ok: false,\n error: {\n code: \"invalid_envelope\",\n message: \"Request body must be valid JSON.\",\n },\n },\n 400\n );\n }\n\n try {\n const workspaceId = this.workspaceId;\n const claim = readTrustedRoleClaim(request, workspaceId);\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const result = this.personal\n ? await this.ctx.storage.transaction(() => runPersonalTransaction(sql, this.personal!, workspaceId, claim, envelope))\n : runTransaction(sql, workspaceId, claim, envelope);\n try {\n await this.scheduleNextDurabilityAlarm(Date.now());\n } catch (error) {\n // The transaction is already durable; do not turn a scheduling failure\n // into a failed acknowledgement. The next write or boot retries it.\n console.error(\"workspace_durability_schedule_failed\", {\n workspaceId,\n error: String(error),\n });\n }\n\n // Replays and no-op deletes changed no rows; do not re-run queries.\n const touched = touchedNamespacesFromEnvelope(envelope);\n if (result.applied > 0 && touched.size > 0) {\n this.scheduleInvalidation(touched);\n }\n\n return json({ ok: true, result });\n } catch (error) {\n if (error instanceof TxError) {\n return json(\n { ok: false, error: error.toJSON() },\n statusForTxError(error.code)\n );\n }\n throw error;\n }\n }\n\n /**\n * Runs a query document against this workspace. The claim is read from the\n * Worker-forwarded header; `executeQuery` requires `view` on every requested\n * and traversed namespace before touching SQL.\n */\n private async query(request: Request): Promise<Response> {\n let envelope: unknown;\n try {\n envelope = await request.json();\n } catch {\n return json(\n {\n ok: false,\n error: {\n code: \"invalid_envelope\",\n message: \"Request body must be valid JSON.\",\n },\n },\n 400\n );\n }\n\n try {\n const workspaceId = this.workspaceId;\n const claim = readTrustedRoleClaim(request, workspaceId);\n const raw = durableObjectSqlExecutor(this.ctx.storage);\n const run = () => executeQueryWithPageInfo(this.personal?.sql(raw) ?? raw, claim, envelope);\n const { data, pageInfo } = this.personal ? await this.personal.read(run) : run();\n return json({ ok: true, data, pageInfo });\n } catch (error) {\n if (error instanceof TxError) {\n return json(\n { ok: false, error: error.toJSON() },\n statusForQueryError(error.code)\n );\n }\n throw error;\n }\n }\n\n // ---- WebSocket live queries ---------------------------------------------\n\n private handleWebSocket(request: Request): Response {\n const accepted = acceptVerifiedSocket<SocketAttachment>({\n ctx: this.ctx,\n request,\n workspaceId: this.workspaceId,\n buildAttachment: (claim, clientId) => ({\n clientId,\n sub: claim.sub,\n role: claim.role,\n exp: claim.exp,\n subscriptions: [],\n }),\n });\n if (!accepted.accepted) return accepted.response;\n\n const connections = Math.max(1, this.ctx.getWebSockets().length);\n this.send(accepted.server, {\n type: \"session:ready\",\n workspaceId: this.workspaceId,\n connections,\n });\n\n // A client that offered subprotocols fails the handshake unless one is selected.\n const offered = offeredProtocols(request.headers.get(\"sec-websocket-protocol\"));\n return new Response(null, {\n status: 101,\n webSocket: accepted.client,\n ...(offered.includes(SOCKET_PROTOCOL) ? { headers: { \"sec-websocket-protocol\": SOCKET_PROTOCOL } } : {}),\n });\n }\n\n async webSocketMessage(\n ws: WebSocket,\n message: string | ArrayBuffer\n ): Promise<void> {\n if (!(await this.bootAgain()) || this.recovering || this.misplaced !== null) { this.closeSocket(ws, 1012, \"workspace unavailable\"); return; }\n if (this.erased) { this.closeSocket(ws, 4410, \"workspace erased\"); return; }\n try { return await this.trackWork(() => this.handleSocketMessage(ws, message)); }\n catch (error) {\n if (!(error instanceof SocketLimitError)) throw error;\n this.send(ws, { type: \"error\", code: \"message_limit_exceeded\", message: error.message });\n this.closeSocket(ws, 1009, \"socket memory budget exceeded\");\n }\n }\n\n private async handleSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n if (this.moveState?.state === \"frozen\" || this.moveState?.state === \"moved\") {\n this.closeSocket(ws, 1012, \"workspace moving\"); return;\n }\n const attachment = this.readSocket(ws);\n if (attachment === null) {\n this.send(ws, {\n type: \"session:error\",\n code: \"unauthenticated\",\n message: \"This socket has no verified role claim.\",\n });\n this.closeSocket(ws, 1008, \"unauthenticated\");\n return;\n }\n\n if (attachment.exp <= Math.floor(Date.now() / 1000)) {\n this.send(ws, {\n type: \"session:error\",\n code: \"claim_expired\",\n message: \"The role claim for this socket has expired.\",\n });\n this.closeSocket(ws, 1008, \"claim expired\");\n return;\n }\n\n const text =\n typeof message === \"string\" ? message : new TextDecoder().decode(message);\n await this.handleText(ws, attachment, text, false);\n }\n\n /**\n * One whole message. A frame is at most Cloudflare's 32 MiB; a larger\n * message comes as `part` frames, stored until the last (see\n * socket-state.ts), and then runs here like any other.\n */\n private async handleText(ws: WebSocket, attachment: SocketAttachment, text: string, reassembled: boolean): Promise<void> {\n if (text.length > MAX_SOCKET_MESSAGE_BYTES || new TextEncoder().encode(text).byteLength > MAX_SOCKET_MESSAGE_BYTES) throw new SocketLimitError(\"A complete WebSocket message is at most 4 MiB.\");\n let payload: Record<string, unknown>;\n try {\n const parsed: unknown = JSON.parse(text);\n if (!isPlainObject(parsed)) {\n this.send(ws, {\n type: \"error\",\n code: \"invalid_message\",\n message: \"Message must be a JSON object.\",\n });\n return;\n }\n payload = parsed;\n } catch {\n this.send(ws, {\n type: \"error\",\n code: \"invalid_json\",\n message: \"Message is not valid JSON.\",\n });\n return;\n }\n\n switch (payload.type) {\n case \"part\": {\n const { id, index, last, data } = payload;\n if (\n reassembled ||\n typeof id !== \"string\" || id.length === 0 || id.length > 128 ||\n !Number.isInteger(index) || (index as number) < 0 ||\n typeof last !== \"boolean\" || typeof data !== \"string\"\n ) {\n this.send(ws, { type: \"error\", code: \"invalid_part\", message: \"A part is { id, index, last, data }.\" });\n return;\n }\n const outcome = acceptPart(durableObjectSqlExecutor(this.ctx.storage), attachment.clientId, { id: `message:${id}`, index: index as number, last, data });\n if (\"error\" in outcome) {\n this.send(ws, { type: \"error\", code: outcome.error, message: `Message ${id} was dropped: ${outcome.error}.` });\n } else if (\"text\" in outcome) {\n await this.handleText(ws, attachment, outcome.text, true);\n }\n return;\n }\n case \"ping\":\n this.handlePing(ws, payload);\n return;\n case \"query:subscribe\":\n await this.handleSubscribe(ws, attachment, payload);\n return;\n case \"query:unsubscribe\":\n this.handleUnsubscribe(ws, attachment, payload);\n return;\n case \"presence:set\":\n this.handlePresenceSet(ws, attachment, payload);\n return;\n case \"presence:clear\":\n this.handlePresenceClear(ws, attachment, payload);\n return;\n case \"cursor:set\":\n this.handleCursorSet(ws, attachment, payload);\n return;\n case \"drag:set\":\n this.handleDragSet(ws, attachment, payload);\n return;\n case \"drag:clear\":\n this.handleDragClear(ws, attachment, payload);\n return;\n case \"topic:join\":\n this.handleTopicJoin(ws, attachment, payload);\n return;\n case \"topic:leave\":\n this.handleTopicLeave(ws, attachment, payload);\n return;\n case \"topic:send\":\n this.handleTopicSend(ws, attachment, payload);\n return;\n default:\n this.send(ws, { type: \"error\", code: \"unsupported_message_type\" });\n }\n }\n\n webSocketClose(ws: WebSocket, code: number, reason: string): void {\n if (this.erased) { this.closeSocket(ws, 4410, \"workspace erased\"); return; }\n this.dropSubscriptionResults(ws);\n this.removePresence(ws);\n this.forgetSocketState(ws);\n // Completes the closing handshake. A client that closes without a status\n // arrives as 1005 (an abnormal drop as 1006); those codes may not be sent,\n // and echoing them threw, so the client never got its close frame and\n // waited out its timeout. Reply 1000 instead.\n this.closeSocket(ws, sendableCloseCode(code), reason);\n }\n\n webSocketError(ws: WebSocket): void {\n if (this.erased) { this.closeSocket(ws, 4410, \"workspace erased\"); return; }\n this.dropSubscriptionResults(ws);\n this.removePresence(ws);\n this.forgetSocketState(ws);\n this.closeSocket(ws, 1011, \"websocket error\");\n }\n\n /** A socket's attachment, with any state stored past its 16 KiB. */\n private readSocket(ws: WebSocket): SocketAttachment | null {\n const raw = ws.deserializeAttachment();\n if (!isSpilled(raw)) return parseSocketAttachment(raw);\n try {\n return parseSocketAttachment(loadAttachment(durableObjectSqlExecutor(this.ctx.storage), raw));\n } catch {\n return null;\n }\n }\n\n private writeSocket(ws: WebSocket, attachment: SocketAttachment): void {\n const spilled = isSpilled(ws.deserializeAttachment());\n ws.serializeAttachment(storeAttachment(durableObjectSqlExecutor(this.ctx.storage), attachment, spilled));\n }\n\n private forgetSocketState(ws: WebSocket): void {\n const raw = ws.deserializeAttachment() as { clientId?: unknown } | null;\n if (typeof raw?.clientId !== \"string\") return;\n try {\n forgetSocket(durableObjectSqlExecutor(this.ctx.storage), raw.clientId);\n } catch {\n // Best effort; the next boot clears state of sockets that are gone.\n }\n }\n\n private handlePing(ws: WebSocket, payload: Record<string, unknown>): void {\n const pong: { type: \"pong\"; at?: unknown; now: number } = {\n type: \"pong\",\n now: Date.now(),\n };\n if (\"at\" in payload) pong.at = payload.at;\n this.send(ws, pong);\n }\n\n // ---- Broadcast topics ------------------------------------------------------\n\n private topicError(ws: WebSocket, topic: unknown, code: string, message: string): void {\n this.send(ws, { type: \"topic:error\", topic: isTopic(topic) ? topic : null, code, message });\n }\n\n private handleTopicJoin(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const topic = payload.topic;\n if (!isTopic(topic)) {\n this.topicError(ws, topic, \"invalid_topic\", \"A topic is 1 to 128 of A-Z a-z 0-9 : _ . -\");\n return;\n }\n if (!topicAllowed(claimFromAttachment(attachment, this.workspaceId), topic, \"join\")) {\n this.topicError(ws, topic, \"permission_denied\", `Not allowed to join topic \"${topic}\".`);\n return;\n }\n const topics = attachment.topics ?? [];\n if (!topics.includes(topic)) {\n attachment.topics = [...topics, topic];\n this.writeSocket(ws, attachment);\n }\n // What the socket missed while it was away, then where the topic is now.\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const since = payload.since;\n if (Number.isInteger(since) && (since as number) >= 0 && topicReplayMs() > 0) {\n const frames = sql.all<{ frame: string }>(\n `SELECT frame FROM \"_topic_buffer\" WHERE topic = ? AND seq > ? AND at >= ? ORDER BY seq`,\n topic,\n since as number,\n Date.now() - topicReplayMs()\n );\n for (const { frame } of frames) {\n try {\n ws.send(frame);\n } catch {\n return;\n }\n }\n }\n const seq = Number(sql.one<{ seq: number }>(`SELECT seq FROM \"_topic_seq\" WHERE topic = ?`, topic)?.seq ?? 0);\n this.send(ws, { type: \"topic:joined\", topic, seq });\n }\n\n /**\n * The next sequence number of a topic, and the frame kept for replay.\n * Old frames go as new ones arrive, by age and by count.\n */\n private sequenceTopicFrame(topic: string, frame: (seq: number) => string): string {\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const now = Date.now();\n let text = \"\";\n sql.transactionSync(() => {\n const seq = Number(sql.one<{ seq: number }>(`SELECT seq FROM \"_topic_seq\" WHERE topic = ?`, topic)?.seq ?? 0) + 1;\n sql.exec(`INSERT INTO \"_topic_seq\" (topic, seq) VALUES (?, ?) ON CONFLICT(topic) DO UPDATE SET seq = excluded.seq`, topic, seq);\n text = frame(seq);\n if (topicReplayMs() > 0) {\n sql.exec(`INSERT INTO \"_topic_buffer\" (topic, seq, at, frame) VALUES (?, ?, ?, ?)`, topic, seq, now, text);\n sql.exec(\n `DELETE FROM \"_topic_buffer\" WHERE topic = ? AND (seq <= ? OR at < ?)`,\n topic,\n seq - REPLAY_MESSAGES,\n now - topicReplayMs()\n );\n // Count alone is insufficient when frames are large. Keep replay\n // globally bounded so a reconnect cannot buffer an unbounded result.\n sql.exec(`DELETE FROM \"_topic_buffer\" WHERE (topic, seq) IN (\n SELECT topic, seq FROM (\n SELECT topic, seq, SUM(length(CAST(frame AS BLOB))) OVER (ORDER BY at DESC, topic, seq DESC) AS bytes\n FROM \"_topic_buffer\"\n ) WHERE bytes > ?\n )`, 8 * 1024 * 1024);\n }\n });\n return text;\n }\n\n private handleTopicLeave(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const topic = payload.topic;\n if (!isTopic(topic)) {\n this.topicError(ws, topic, \"invalid_topic\", \"A topic is 1 to 128 of A-Z a-z 0-9 : _ . -\");\n return;\n }\n const topics = attachment.topics ?? [];\n if (topics.includes(topic)) {\n attachment.topics = topics.filter((joined) => joined !== topic);\n this.writeSocket(ws, attachment);\n }\n }\n\n /**\n * Delivers to every other socket joined to the topic. The sender need not\n * be joined; it never receives its own message.\n *\n * A message too large for one frame comes as parts\n * (`{ topic, part: { id, index, last }, data }`, `data` a slice of the\n * message's JSON). Each part is checked and relayed as it arrives, and the\n * receivers join them: the room never holds a whole message, so a\n * broadcast has no size bound here.\n */\n private handleTopicSend(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const topic = payload.topic;\n const part = payload.part as { id?: unknown; index?: unknown; last?: unknown } | undefined;\n const isPart =\n part !== undefined &&\n typeof part === \"object\" &&\n part !== null &&\n typeof part.id === \"string\" && part.id.length > 0 && part.id.length <= 128 &&\n Number.isInteger(part.index) && (part.index as number) >= 0 &&\n typeof part.last === \"boolean\" &&\n typeof payload.data === \"string\";\n if (!isTopic(topic) || (part === undefined ? !(\"message\" in payload) : !isPart)) {\n this.topicError(ws, topic, \"invalid_topic_message\", \"topic:send needs a topic and a message (or a part and its data).\");\n return;\n }\n if (!topicAllowed(claimFromAttachment(attachment, this.workspaceId), topic, \"send\")) {\n this.topicError(ws, topic, \"permission_denied\", `Not allowed to send to topic \"${topic}\".`);\n return;\n }\n if (isPart) {\n const outcome = acceptPart(durableObjectSqlExecutor(this.ctx.storage), attachment.clientId,\n { id: `topic:${topic}:${part!.id}`, index: part!.index as number, last: part!.last as boolean, data: payload.data as string }, false);\n if (\"error\" in outcome) {\n this.topicError(ws, topic, outcome.error, \"The multipart broadcast exceeded a quota or arrived out of order.\");\n return;\n }\n }\n const from = { clientId: attachment.clientId, sub: attachment.sub };\n // A client instance's stable id, so it can skip its own messages when they\n // are replayed to it on a later connection.\n const origin = typeof payload.origin === \"string\" && payload.origin.length <= 128 ? payload.origin : undefined;\n const delivery = this.sequenceTopicFrame(topic, (seq) =>\n JSON.stringify(\n isPart\n ? { type: \"topic:message\", topic, seq, part: { id: part!.id, index: part!.index, last: part!.last }, data: payload.data, from, ...(origin ? { origin } : {}) }\n : { type: \"topic:message\", topic, seq, message: payload.message, from, ...(origin ? { origin } : {}) }\n )\n );\n const now = Math.floor(Date.now() / 1000);\n for (const other of this.ctx.getWebSockets?.() ?? []) {\n if (other === ws) continue;\n const peer = this.readSocket(other);\n // A socket whose claim has run out hears nothing more.\n if (!peer?.topics?.includes(topic) || peer.exp <= now) continue;\n try {\n other.send(delivery);\n } catch {\n // A closing socket is cleaned up by its close handler.\n }\n }\n }\n\n private handlePresenceSet(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const target = payload.target;\n if (!isPresenceTarget(target)) {\n this.send(ws, { type: \"error\", code: \"invalid_target\" });\n return;\n }\n if (!(\"presence\" in payload)) {\n this.send(ws, { type: \"error\", code: \"invalid_presence\" });\n return;\n }\n\n const previous = attachment.presence;\n if (previous && previous.target !== target) {\n this.broadcastPresence(previous.target, attachment.clientId);\n }\n attachment.presence =\n previous && previous.target === target\n ? { ...previous, presence: payload.presence }\n : { target, presence: payload.presence };\n this.writeSocket(ws, attachment);\n this.broadcastPresence(target);\n }\n\n private handlePresenceClear(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const target = payload.target;\n if (!isPresenceTarget(target)) {\n this.send(ws, { type: \"error\", code: \"invalid_target\" });\n return;\n }\n const current = attachment.presence;\n if (!current || current.target !== target) return;\n attachment.presence = undefined;\n this.writeSocket(ws, attachment);\n this.broadcastPresence(target, attachment.clientId);\n }\n\n private handleCursorSet(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const target = payload.target;\n if (!isPresenceTarget(target) || !(\"cursor\" in payload)) {\n this.send(ws, { type: \"error\", code: \"invalid_cursor\" });\n return;\n }\n const current = attachment.presence;\n if (!current || current.target !== target) {\n this.send(ws, { type: \"error\", code: \"not_in_target\" });\n return;\n }\n current.cursor = payload.cursor;\n this.writeSocket(ws, attachment);\n this.broadcastToTarget(\n target,\n {\n type: \"cursor:update\",\n target,\n clientId: attachment.clientId,\n cursor: payload.cursor,\n },\n attachment.clientId\n );\n }\n\n private handleDragSet(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const target = payload.target;\n if (!isPresenceTarget(target) || !(\"drag\" in payload)) {\n this.send(ws, { type: \"error\", code: \"invalid_drag\" });\n return;\n }\n const current = attachment.presence;\n if (!current || current.target !== target) {\n this.send(ws, { type: \"error\", code: \"not_in_target\" });\n return;\n }\n current.drag = payload.drag;\n this.writeSocket(ws, attachment);\n this.broadcastToTarget(\n target,\n {\n type: \"drag:update\",\n target,\n clientId: attachment.clientId,\n drag: payload.drag,\n },\n attachment.clientId\n );\n }\n\n private handleDragClear(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const target = payload.target;\n if (!isPresenceTarget(target)) {\n this.send(ws, { type: \"error\", code: \"invalid_target\" });\n return;\n }\n const current = attachment.presence;\n if (!current || current.target !== target) return;\n delete current.drag;\n this.writeSocket(ws, attachment);\n this.broadcastToTarget(\n target,\n {\n type: \"drag:update\",\n target,\n clientId: attachment.clientId,\n drag: null,\n },\n attachment.clientId\n );\n }\n\n private broadcastPresence(target: string, excludeClientId?: string): void {\n const peers = this.presencePeers(target, excludeClientId);\n for (const { ws, attachment } of this.socketsForTarget(target)) {\n if (excludeClientId && attachment.clientId === excludeClientId) continue;\n this.send(ws, { type: \"presence:update\", target, peers });\n }\n }\n\n private broadcastToTarget(\n target: string,\n message: unknown,\n excludeClientId?: string\n ): void {\n for (const { ws, attachment } of this.socketsForTarget(target)) {\n if (excludeClientId && attachment.clientId === excludeClientId) continue;\n this.send(ws, message);\n }\n }\n\n private presencePeers(\n target: string,\n excludeClientId?: string\n ): PresencePeer[] {\n const peers: PresencePeer[] = [];\n for (const { attachment } of this.socketsForTarget(target)) {\n if (excludeClientId && attachment.clientId === excludeClientId) continue;\n const presence = attachment.presence;\n if (!presence) continue;\n const peer: PresencePeer = {\n clientId: attachment.clientId,\n presence: presence.presence ?? null,\n };\n if (presence.cursor !== undefined) peer.cursor = presence.cursor;\n if (presence.drag !== undefined) peer.drag = presence.drag;\n peers.push(peer);\n }\n return peers.sort((left, right) =>\n left.clientId.localeCompare(right.clientId)\n );\n }\n\n private socketsForTarget(\n target: string\n ): Array<{ ws: WebSocket; attachment: SocketAttachment }> {\n const sockets: Array<{ ws: WebSocket; attachment: SocketAttachment }> = [];\n for (const ws of this.ctx.getWebSockets?.() ?? []) {\n const attachment = this.readSocket(ws);\n if (attachment?.presence?.target === target) {\n sockets.push({ ws, attachment });\n }\n }\n return sockets;\n }\n\n private removePresence(ws: WebSocket): void {\n const attachment = this.readSocket(ws);\n if (!attachment?.presence) return;\n this.broadcastPresence(attachment.presence.target, attachment.clientId);\n }\n\n private async handleSubscribe(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): Promise<void> {\n const id = payload.id;\n if (typeof id !== \"string\" || id.length === 0 || id.length > 128) {\n this.send(ws, {\n type: \"query:error\",\n id: typeof id === \"string\" ? id : null,\n code: \"invalid_subscription_id\",\n message:\n \"Subscription id must be a non-empty string up to 128 characters.\",\n });\n return;\n }\n\n const query = payload.query;\n if (!isPlainObject(query)) {\n this.send(ws, {\n type: \"query:error\",\n id,\n code: \"invalid_query\",\n message: \"query must be a plain object keyed by namespace.\",\n });\n return;\n }\n\n let data: QueryResult;\n let pageInfo: QueryPageInfo;\n try {\n const socketClaim = claimFromAttachment(attachment, this.workspaceId);\n const compiled = compileQuery(query, viewAccess(socketClaim));\n authorizeQuery(socketClaim, compiled);\n const raw = durableObjectSqlExecutor(this.ctx.storage);\n const run = () => executeCompiledQueryWithPageInfo(this.personal?.sql(raw) ?? raw, compiled, socketClaim);\n ({ data, pageInfo } = this.personal ? await this.personal.read(run) : run());\n } catch (error) {\n const txError = error instanceof TxError ? error : null;\n this.send(ws, {\n type: \"query:error\",\n id,\n code: txError?.code ?? \"internal_error\",\n message: txError?.message ?? errorMessage(error),\n });\n return;\n }\n\n const subscription = upsertSubscription(\n attachment,\n id,\n query as QueryDocument\n );\n this.writeSocket(ws, attachment);\n this.resultsFor(attachment.clientId).set(id, { data, pageInfo });\n this.send(ws, {\n type: \"query:data\",\n id,\n seq: subscription.seq,\n data,\n pageInfo,\n });\n }\n\n private handleUnsubscribe(\n ws: WebSocket,\n attachment: SocketAttachment,\n payload: Record<string, unknown>\n ): void {\n const id = payload.id;\n if (typeof id !== \"string\" || id.length === 0) {\n this.send(ws, {\n type: \"query:error\",\n id: typeof id === \"string\" ? id : null,\n code: \"invalid_subscription_id\",\n message: \"Subscription id must be a non-empty string.\",\n });\n return;\n }\n\n const remaining = attachment.subscriptions.filter(\n (subscription) => subscription.id !== id\n );\n if (remaining.length !== attachment.subscriptions.length) {\n attachment.subscriptions = remaining;\n this.writeSocket(ws, attachment);\n }\n this.resultsFor(attachment.clientId).delete(id);\n this.send(ws, { type: \"query:unsubscribed\", id });\n }\n\n /**\n * Erases the workspace: its R2 history (manifest first, so nothing can\n * recover from what is left), its uploaded files, then its Durable Object\n * storage and alarm. Owners only. Each step is idempotent, so a failed\n * erase is retried by calling it again. A tombstone stays behind so the\n * workspace answers 410 from then on: a reconnecting client's outbox cannot\n * quietly recreate it under the same id.\n */\n private async erase(request: Request): Promise<Response> {\n let claim: RoleClaim;\n try {\n claim = readTrustedRoleClaim(request, this.workspaceId);\n } catch (error) {\n if (error instanceof TxError) return apiError(403, error.code, error.message);\n throw error;\n }\n if (claim.role < WORKSPACE_ROLE_LEVELS.OWNER) {\n return apiError(403, \"insufficient_role\", \"Only an owner can erase a workspace.\");\n }\n\n this.erased = true;\n this.erasurePending = true;\n if (this.invalidationTimer !== null) clearTimeout(this.invalidationTimer);\n this.invalidationTimer = null;\n this.pendingInvalidationNamespaces.clear();\n for (const ws of this.ctx.getWebSockets()) this.closeSocket(ws, 4410, \"workspace erased\");\n try {\n const erased = await this.finishErase();\n return json({ ok: true, erased });\n } catch (error) {\n // Keep the durable intent and refuse new work until cleanup succeeds.\n await this.ctx.storage.setAlarm(Date.now() + DURABILITY_ALARM_DELAY_MS);\n console.error(\"workspace_erase_failed\", { workspaceId: this.workspaceId, error: String(error) });\n return apiError(500, \"erase_failed\", `Erasing did not finish (${errorMessage(error)}); call it again.`);\n }\n }\n\n private async finishErase(): Promise<{ historyObjects: number; files: number }> {\n if (this.erasureRun) return this.erasureRun;\n this.erasureRun = this.eraseStorage();\n try { return await this.erasureRun; }\n finally { this.erasureRun = null; }\n }\n\n private async eraseStorage(): Promise<{ historyObjects: number; files: number }> {\n // Drain writes, snapshots and flushes that started before the erase gate.\n // No external deletion starts until this local intent is durably stored.\n await Promise.allSettled([...this.activeWork]);\n const sql = this.ctx.storage.sql;\n sql.exec(`CREATE TABLE IF NOT EXISTS \"${ERASING_TABLE}\" (at INTEGER NOT NULL)`);\n sql.exec(`INSERT INTO \"${ERASING_TABLE}\" (at) SELECT ? WHERE NOT EXISTS (SELECT 1 FROM \"${ERASING_TABLE}\")`, Date.now());\n await this.ctx.storage.sync?.();\n const workspaceId = this.workspaceId;\n await this.roomEnv.DATA.delete(manifestKey(workspaceId));\n const history = (await listAllR2(this.roomEnv.DATA, `${workspacePrefix(workspaceId)}/`)).map(object => object.key);\n await deleteR2Keys(this.roomEnv.DATA, history);\n await deleteR2Keys(this.roomEnv.DATA, (await listAllR2(this.roomEnv.DATA, personalKeyPrefix(workspaceId))).map(object => object.key));\n const files = this.roomEnv.FILES ? (await listAllR2(this.roomEnv.FILES, filesPrefix(workspaceId))).map(object => object.key) : [];\n if (this.roomEnv.FILES) await deleteR2Keys(this.roomEnv.FILES, files);\n await this.ctx.storage.deleteAlarm();\n // Clear application/engine tables and install the tombstone in ONE SQLite\n // transaction. deleteAll followed by CREATE leaves a crash window.\n this.ctx.storage.transactionSync(() => {\n // Defer checks until all referencing tables are removed by this\n // atomic transaction; retain Cloudflare-owned internal tables.\n sql.exec(\"PRAGMA defer_foreign_keys = ON\");\n for (const { name } of sql.exec<{ name: string }>(`SELECT name FROM sqlite_master WHERE type = 'trigger'`).toArray()) sql.exec(`DROP TRIGGER IF EXISTS \"${name.replaceAll('\"', '\"\"')}\"`);\n const tables = sql.exec<{ name: string }>(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT GLOB '_cf_*'`).toArray();\n // Empty rows while all referenced tables still exist. Otherwise DROP\n // can run cascade actions against a table already removed above it.\n for (const { name } of tables) sql.exec(`DELETE FROM \"${name.replaceAll('\"', '\"\"')}\"`);\n const children = new Map<string, string[]>();\n for (const { name } of tables) {\n for (const fk of sql.exec<{ table: string }>(`PRAGMA foreign_key_list(\"${name.replaceAll('\"', '\"\"')}\")`).toArray()) {\n if (fk.table !== name) children.set(fk.table, [...(children.get(fk.table) ?? []), name]);\n }\n }\n const visited = new Set<string>();\n const drop = (name: string): void => {\n if (visited.has(name)) return;\n visited.add(name);\n for (const child of children.get(name) ?? []) drop(child);\n sql.exec(`DROP TABLE IF EXISTS \"${name.replaceAll('\"', '\"\"')}\"`);\n };\n for (const { name } of tables) drop(name);\n sql.exec(`CREATE TABLE \"${ERASED_TABLE}\" (at INTEGER NOT NULL)`);\n sql.exec(`INSERT INTO \"${ERASED_TABLE}\" (at) VALUES (?)`, Date.now());\n });\n await this.ctx.storage.sync?.();\n this.erasurePending = false;\n this.personal?.clearPlaintext();\n this.subscriptionResults.clear();\n console.log(\"workspace_erased\", { workspaceId, objects: history.length + 1, files: files.length });\n return { historyObjects: history.length + 1, files: files.length };\n }\n\n private send(ws: WebSocket, message: unknown): void {\n try {\n ws.send(JSON.stringify(message));\n } catch {\n // A socket that is already closing is cleaned up by its close handler.\n }\n }\n\n private closeSocket(ws: WebSocket, code: number, reason: string): void {\n try {\n ws.close(code, reason);\n } catch {\n // Already closed.\n }\n }\n\n private resultsFor(clientId: string): Map<string, CachedResult> {\n let results = this.subscriptionResults.get(clientId);\n if (!results) {\n results = new Map<string, CachedResult>();\n this.subscriptionResults.set(clientId, results);\n }\n return results;\n }\n\n private dropSubscriptionResults(ws: WebSocket): void {\n const attachment = this.readSocket(ws);\n if (attachment) this.subscriptionResults.delete(attachment.clientId);\n }\n\n // ---- Invalidation --------------------------------------------------------\n\n private scheduleInvalidation(namespaces: Iterable<string>): void {\n if (this.erased) return;\n for (const namespace of namespaces) {\n this.pendingInvalidationNamespaces.add(namespace);\n }\n if (this.pendingInvalidationNamespaces.size === 0) return;\n if (this.invalidationTimer !== null) return;\n\n this.invalidationTimer = setTimeout(() => {\n this.invalidationTimer = null;\n const touched = this.pendingInvalidationNamespaces;\n this.pendingInvalidationNamespaces = new Set();\n const work = this.trackWork(() => this.flushInvalidations(touched)).catch(error => console.error(\"workspace_invalidation_failed\", error));\n this.ctx.waitUntil?.(work);\n }, DEFAULT_INVALIDATION_DEBOUNCE_MS);\n }\n\n private async flushInvalidations(touched: ReadonlySet<string>): Promise<void> {\n if (this.erased) return;\n // `getWebSockets` is part of the Durable Object runtime. Guard the call so\n // non-WebSocket harnesses (and older test doubles) do not crash a deferred\n // invalidation pass.\n const sockets = this.ctx.getWebSockets?.() ?? [];\n if (sockets.length === 0) return;\n\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const now = Math.floor(Date.now() / 1000);\n const runs = new Map<string, SubscriptionRun>();\n\n for (const ws of sockets) {\n const attachment = this.readSocket(ws);\n if (attachment === null) continue;\n\n if (attachment.exp <= now) {\n this.send(ws, {\n type: \"session:error\",\n code: \"claim_expired\",\n message: \"The role claim for this socket has expired.\",\n });\n this.removePresence(ws);\n this.closeSocket(ws, 1008, \"claim expired\");\n this.subscriptionResults.delete(attachment.clientId);\n continue;\n }\n\n const results = this.resultsFor(attachment.clientId);\n let attachmentChanged = false;\n\n for (const subscription of attachment.subscriptions) {\n const claim = claimFromAttachment(attachment, this.workspaceId);\n let compiled: CompiledQuery;\n try {\n compiled = compileQuery(subscription.query, viewAccess(claim));\n } catch {\n // A subscription stored by an older deployment may no longer\n // compile; leave it registered so the client can resubscribe.\n continue;\n }\n if (!queryMatchesTouched(compiled, touched)) continue;\n\n // Read rules see the caller's role and, for row rules, their subject.\n // Subscriptions with the same query and the same role (and subject,\n // when a row rule is involved) get the same answer, so it runs once\n // per flush and is shared.\n const bySubject = queriedNamespaces(compiled).some(viewDependsOnSubject);\n const key = `${bySubject ? attachment.sub : \"\"}\\u0000${attachment.role}\\u0000${stableStringify(subscription.query)}`;\n let run = runs.get(key);\n if (run === undefined) {\n run = await this.runSubscription(sql, compiled, claim);\n runs.set(key, run);\n }\n if (run.kind === \"error\") {\n this.send(ws, {\n type: \"query:error\",\n id: subscription.id,\n code: run.code,\n message: run.message,\n });\n results.delete(subscription.id);\n continue;\n }\n const { data, pageInfo } = run;\n\n const previous = results.get(subscription.id);\n results.set(subscription.id, { data, pageInfo });\n\n if (previous === undefined) {\n subscription.seq += 1;\n this.send(ws, {\n type: \"query:data\",\n id: subscription.id,\n seq: subscription.seq,\n data,\n pageInfo,\n });\n attachmentChanged = true;\n continue;\n }\n\n const diffs = diffQueryResults(previous.data, data);\n if (diffs === null) {\n subscription.seq += 1;\n this.send(ws, {\n type: \"query:data\",\n id: subscription.id,\n seq: subscription.seq,\n data,\n pageInfo,\n });\n attachmentChanged = true;\n continue;\n }\n\n // Page metadata moves without row changes too: a row inserted past\n // the window flips hasMore and moves nextCursor. It rides the first\n // diff, or an empty one when no row in the window changed.\n const pageInfoChanged =\n stableStringify(previous.pageInfo) !== stableStringify(pageInfo);\n if (diffs.length === 0 && !pageInfoChanged) continue;\n if (diffs.length === 0) {\n diffs.push({\n namespace: Object.keys(data)[0] ?? \"\",\n added: [],\n updated: [],\n removed: [],\n });\n }\n\n subscription.seq += 1;\n for (const [index, diff] of diffs.entries()) {\n const message: QueryDiffMessage = {\n type: \"query:diff\",\n id: subscription.id,\n seq: subscription.seq,\n namespace: diff.namespace,\n added: diff.added,\n updated: diff.updated,\n removed: diff.removed,\n ...(diff.order ? { order: diff.order } : {}),\n ...(index === 0 && pageInfoChanged ? { pageInfo } : {}),\n };\n this.send(ws, message);\n }\n attachmentChanged = true;\n }\n\n if (attachmentChanged) this.writeSocket(ws, attachment);\n }\n }\n\n /** One subscription's re-run for this flush: its result, or why it failed. */\n private async runSubscription(\n sql: ReturnType<typeof durableObjectSqlExecutor>,\n compiled: CompiledQuery,\n claim: RoleClaim\n ): Promise<SubscriptionRun> {\n try {\n const run = () => executeCompiledQueryWithPageInfo(this.personal?.sql(sql) ?? sql, compiled, claim);\n const result = this.personal ? await this.personal.read(run) : run();\n this.personal?.clearPlaintext();\n return { kind: \"result\", ...result };\n } catch (error) {\n const txError = error instanceof TxError ? error : null;\n return {\n kind: \"error\",\n code: txError?.code ?? \"internal_error\",\n message: txError?.message ?? errorMessage(error),\n };\n }\n }\n\n /**\n * Runs the durability pass (flush then snapshot) and schedules the next\n * pass only while there is work left. The 30s delay lets transactions\n * accumulate into fewer, larger log segments.\n */\n async alarm(): Promise<void> {\n if (!(await this.bootAgain())) return;\n if (this.erasurePending) {\n try { await this.finishErase(); }\n catch (error) {\n console.error(\"workspace_erase_failed\", { workspaceId: this.workspaceId, error: String(error) });\n await this.ctx.storage.setAlarm(Date.now() + DURABILITY_ALARM_DELAY_MS);\n }\n return;\n }\n if (this.erased) return;\n return this.trackWork(() => this.runAlarm());\n }\n\n private async runAlarm(): Promise<void> {\n if (this.limiter) return;\n if (this.erased || this.misplaced !== null) return;\n if (this.recovering) {\n try {\n await this.recoverStep(RECOVERY_STEP_BUDGET_MS);\n } catch (error) {\n console.error(\"workspace_recovery_failed\", { workspaceId: this.workspaceId, error: String(error) });\n await this.ctx.storage.setAlarm(Date.now() + DURABILITY_ALARM_DELAY_MS);\n }\n return;\n }\n const workspaceId = this.workspaceId;\n\n try {\n const tick = await durabilityTick(\n this.roomEnv.DATA,\n this.ctx.storage.sql,\n workspaceId,\n Date.now()\n );\n // A failed flush is retried with backoff; say so, or nobody knows the\n // log is not reaching R2.\n if (tick.flushError) console.error(\"workspace_flush_failed\", { workspaceId, error: tick.flushError });\n } catch (error) {\n console.error(\"workspace_durability_tick_failed\", {\n workspaceId,\n error: String(error),\n });\n await this.scheduleDurabilityAlarm(\n Date.now() + DURABILITY_ALARM_DELAY_MS\n );\n return;\n }\n\n // Re-read the clock: a chunked snapshot can take long enough that the\n // timestamp captured before the tick is already in the past.\n await this.scheduleNextDurabilityAlarm(Date.now());\n }\n\n /**\n * Schedules an alarm for the next due durability pass. An existing alarm is\n * never pushed later: a write must not delay a flush that is already due.\n */\n private async scheduleNextDurabilityAlarm(now: number): Promise<void> {\n const sql = this.ctx.storage.sql;\n const flushState = readFlushState(sql);\n\n let nextAt: number | null = null;\n if (flushState.hasPending) {\n nextAt = Math.max(\n now + DURABILITY_ALARM_DELAY_MS,\n flushState.nextAttemptAt ?? 0\n );\n }\n\n const later = (at: number) => {\n nextAt = nextAt === null ? at : Math.min(nextAt, at);\n };\n // Snapshots and age-based pruning keep history inside the retention,\n // so they are scheduled even when nothing else is pending.\n const snapshotAt = snapshotDueAt(sql);\n if (snapshotAt !== null) later(Math.max(snapshotAt, now + DURABILITY_ALARM_DELAY_MS));\n const pruneAt = historyPruneAt(sql);\n if (pruneAt !== null) later(Math.max(pruneAt, now + DURABILITY_ALARM_DELAY_MS));\n\n if (nextAt !== null) {\n await this.scheduleDurabilityAlarm(nextAt);\n }\n }\n\n private async scheduleDurabilityAlarm(at: number): Promise<void> {\n const existing = await this.ctx.storage.getAlarm();\n if (existing === null || at < existing) {\n await this.ctx.storage.setAlarm(at);\n }\n }\n\n /**\n * File metadata rows. Bytes live in R2 and never enter the transaction log;\n * this table is the queryable index over them.\n */\n private async listFiles(claim: RoleClaim): Promise<Response> {\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const rows = sql.all<Record<string, SqlValue>>(\n `SELECT \"id\", \"path\", \"r2_key\" AS \"r2Key\", \"size\",\n \"content_type\" AS \"contentType\", \"uploaded_by\" AS \"uploadedBy\",\n \"created_at\" AS \"createdAt\", \"updated_at\" AS \"updatedAt\"\n FROM \"${ENGINE_TABLES.files}\"\n ORDER BY \"path\"`\n ) as unknown as Array<FileInfo & Record<string, SqlValue>>;\n return json({ ok: true, data: fileRulesConfigured() ? await this.readPersonal(view => readableFiles(view, claim, rows)) : rows });\n }\n\n /** The stored file at `path`, as file rules see it. */\n private storedFile(sql: ReturnType<typeof durableObjectSqlExecutor>, path: string): FileInfo | undefined {\n return sql.one<FileInfo & Record<string, SqlValue>>(\n `SELECT \"path\", \"size\", \"content_type\" AS \"contentType\", \"uploaded_by\" AS \"uploadedBy\"\n FROM \"${ENGINE_TABLES.files}\" WHERE \"path\" = ?`,\n path\n );\n }\n\n /**\n * Decides one file operation for the Worker, before it touches bytes:\n * `{ path, action, size?, contentType? }`. A read of a file the caller may\n * not see answers 404, like a file that does not exist, so a rule does not\n * reveal what it hides.\n */\n private async authorizeFileRequest(request: Request, claim: RoleClaim): Promise<Response> {\n const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;\n const path = body?.path;\n const action = body?.action;\n if (typeof path !== \"string\" || path.length === 0) return apiError(400, \"invalid_path\", \"path is required.\");\n if (action !== \"read\" && action !== \"write\" && action !== \"delete\") {\n return apiError(400, \"invalid_action\", \"action must be read, write or delete.\");\n }\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const stored = this.storedFile(sql, path);\n if (action === \"write\") {\n const incoming: FileInfo = {\n path,\n size: typeof body?.size === \"number\" ? body.size : null,\n contentType: typeof body?.contentType === \"string\" ? body.contentType : null,\n uploadedBy: claim.sub,\n };\n return await this.readPersonal(view => authorizeFile(view, claim, \"write\", incoming, stored))\n ? json({ ok: true })\n : apiError(403, \"file_access_denied\", \"The file rules do not allow this write.\");\n }\n if (stored === undefined || !await this.readPersonal(view => authorizeFile(view, claim, action, stored))) {\n return stored === undefined || action === \"read\" || !await this.readPersonal(view => authorizeFile(view, claim, \"read\", stored))\n ? apiError(404, \"not_found\", \"No such file.\")\n : apiError(403, \"file_access_denied\", \"The file rules do not allow this delete.\");\n }\n return json({ ok: true });\n }\n\n private async recordFile(request: Request, claim: RoleClaim): Promise<Response> {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return apiError(400, \"invalid_body\", \"Request body must be a JSON object.\");\n }\n\n const record = (body ?? {}) as Record<string, unknown>;\n const path = record.path;\n const key = record.key;\n const size = record.size;\n const contentType = record.contentType;\n\n if (typeof path !== \"string\" || path.length === 0) {\n return apiError(400, \"invalid_path\", \"path is required.\");\n }\n // Bytes are stored under the file's own path in this workspace's prefix.\n // An index entry pointing anywhere else would serve, and later delete, an\n // object this workspace does not own.\n const own = `${filesPrefix(this.workspaceId)}${path}`;\n if (typeof key !== \"string\" || (key !== own && !key.startsWith(`${own}/.tapedb/`))) {\n return apiError(400, \"invalid_key\", \"key must be the stored object of this path in this workspace.\");\n }\n if (typeof size !== \"number\" || !Number.isFinite(size) || size < 0) {\n return apiError(400, \"invalid_size\", \"size must be a non-negative number.\");\n }\n\n // Logged, not written in place: a row outside the log is lost by a restore\n // from R2 (see file-index.ts).\n const sql = durableObjectSqlExecutor(this.ctx.storage);\n const commit = (view: SqlExecutor) => {\n const existing = this.storedFile(view, path);\n const incoming = { path, size, contentType: typeof contentType === \"string\" ? contentType : null, uploadedBy: claim.sub };\n if (!authorizeFile(view, claim, \"write\", incoming, existing)) return { denied: true as const };\n const previousKey = view.one<{ key: string }>(`SELECT r2_key AS key FROM \"_files\" WHERE path = ?`, path)?.key;\n recordFileEntry(sql, { ...incoming, key });\n return { denied: false as const, previousKey };\n };\n const decision = this.personal\n ? await this.ctx.storage.transaction(() => this.readPersonal(commit))\n : sql.transactionSync(() => commit(sql));\n if (decision.denied) return apiError(403, \"file_access_denied\", \"The file rules do not allow the completed upload.\");\n const previousKey = decision.previousKey;\n await this.scheduleFileFlush();\n\n return json({ ok: true, data: { path, size }, previousKey }, 201);\n }\n\n private async forgetFile(request: Request): Promise<Response> {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return apiError(400, \"invalid_body\", \"Request body must be a JSON object.\");\n }\n\n const path = ((body ?? {}) as Record<string, unknown>).path;\n if (typeof path !== \"string\" || path.length === 0) {\n return apiError(400, \"invalid_path\", \"path is required.\");\n }\n\n const removed = forgetFileEntry(\n durableObjectSqlExecutor(this.ctx.storage),\n path\n );\n if (removed > 0) await this.scheduleFileFlush();\n return json({ ok: true, removed });\n }\n\n /** File-index entries are log rows, so they ship to R2 like any write. */\n private async scheduleFileFlush(): Promise<void> {\n try {\n await this.scheduleNextDurabilityAlarm(Date.now());\n } catch (error) {\n // The entry is committed locally; the next write or boot reschedules.\n console.error(\"workspace_durability_schedule_failed\", {\n workspaceId: this.workspaceId,\n error: errorMessage(error),\n });\n }\n }\n\n /** Registry snapshot for tooling: API names, attribute types and links. */\n private schemaDocument(): Response {\n const namespaces = Object.values(NAMESPACES).map((namespace) => ({\n apiName: namespace.apiName,\n table: namespace.table,\n attributes: Object.fromEntries(\n Object.entries(namespace.attributes).map(([name, definition]) => [\n name,\n {\n type: definition.type,\n optional: definition.optional === true,\n indexed: definition.indexed === true,\n unique: definition.unique === true,\n },\n ])\n ),\n }));\n\n return json({\n ok: true,\n data: {\n namespaces,\n links: Object.values(LINKS).map((link) => ({\n apiName: link.apiName,\n kind: link.kind,\n forward: link.forward,\n reverse: link.reverse,\n })),\n },\n });\n }\n\n private status(): Response {\n const sql = this.ctx.storage.sql;\n const migrations = sql\n .exec<IdRow>(`SELECT id FROM \"_migrations\" ORDER BY id`)\n .toArray()\n .map((row) => row.id);\n const tables = sql\n .exec<NameRow>(\n `SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\n ORDER BY name`\n )\n .toArray()\n .map((row) => row.name);\n const txLog = sql\n .exec<CountRow>(`SELECT COUNT(*) AS total FROM \"_tx_log\"`)\n .one().total;\n const files = sql\n .exec<CountRow>(`SELECT COUNT(*) AS total FROM \"${ENGINE_TABLES.files}\"`)\n .one().total;\n\n // How far the log has reached R2: everything at or below `flushedSeq`\n // survives losing this object's storage.\n const flush = readFlushState(sql);\n const seq = sql.exec<{ seq: number | null }>(`SELECT high_water_seq AS seq FROM \"_tx_state\" WHERE \"id\" = 1`).toArray()[0]?.seq ?? 0;\n\n return json({\n ok: true,\n workspaceId: this.workspaceId,\n schemaVersion: migrations.at(-1) ?? null,\n migrations,\n tables,\n counts: { txLog, files },\n durability: {\n seq,\n flushedSeq: flush.lastSeq,\n snapshotSeq: readSnapshotState(sql).baseSeq,\n lastFlushError: flush.lastError,\n },\n });\n }\n}\n\n/** Every namespace a compiled query reads: its levels and their relation filters. */\nfunction queriedNamespaces(compiled: CompiledQuery): string[] {\n const namespaces = new Set<string>();\n const visit = (node: CompiledQuery[\"nodes\"][number]): void => {\n namespaces.add(node.namespace);\n for (const reference of node.references) namespaces.add(reference);\n for (const child of node.children) visit(child.node);\n };\n for (const node of compiled.nodes) visit(node);\n return [...namespaces];\n}\n\ntype SubscriptionRun =\n | { kind: \"error\"; code: string; message: string }\n | { kind: \"result\"; data: QueryResult; pageInfo: QueryPageInfo };\n\n/** Close codes the runtime refuses to send (reserved for local use). */\nconst RESERVED_CLOSE_CODES = new Set([1004, 1005, 1006, 1015]);\n\nfunction sendableCloseCode(code: number): number {\n return RESERVED_CLOSE_CODES.has(code) || code < 1000 || code > 4999 ? 1000 : code;\n}\n\n/**\n * Registers or replaces a subscription. A resubscribe keeps the per-socket\n * sequence climbing, so a client that reconnects cannot mistake a new result\n * for a replay.\n */\nfunction upsertSubscription(\n attachment: SocketAttachment,\n id: string,\n query: QueryDocument\n): StoredSubscription {\n const existing = attachment.subscriptions.find(\n (subscription) => subscription.id === id\n );\n if (existing) {\n existing.query = query;\n existing.seq += 1;\n return existing;\n }\n\n const created: StoredSubscription = { id, seq: 1, query };\n attachment.subscriptions.push(created);\n return created;\n}\n\n/** A subscription's last result, kept to diff the next one against. */\ninterface CachedResult {\n data: QueryResult;\n pageInfo: QueryPageInfo;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction statusForTxError(code: TxErrorCode): number {\n switch (code) {\n case \"permission_denied\":\n return 403;\n case \"conflict\":\n case \"not_found\":\n case \"unique_violation\":\n case \"foreign_key_violation\":\n return 409;\n case \"retry_expired\":\n return 410;\n case \"storage_error\":\n return 500;\n default:\n return 400;\n }\n}\n\n/** Read errors: permission 403, storage 500, every invalid query 400. */\nfunction statusForQueryError(code: TxErrorCode): number {\n switch (code) {\n case \"permission_denied\":\n return 403;\n case \"storage_error\":\n return 500;\n default:\n return 400;\n }\n}\n","/**\n * Canonical hashing for transaction ops.\n *\n * Two retries of the same optimistic write may serialise their object keys in\n * a different order. `stableStringify` sorts object keys recursively so the\n * log hash (and therefore client transaction deduplication) is order\n * independent. Array order is preserved because it is semantic.\n *\n * The digest is synchronous on purpose: it runs inside `transactionSync`,\n * where the async WebCrypto API cannot be awaited. FNV-1a 64-bit is enough for\n * deduplication keys (it is not used for authentication).\n */\n\n\n/** Stable JSON with recursively sorted object keys. */\nexport function stableStringify(value: unknown): string {\n const serialised = serialise(value, new Set<object>());\n return serialised ?? \"null\";\n}\n\n/** Stable, order-independent digest of an ops array. */\nexport function opsHash(ops: unknown): string {\n return fnv1a64(stableStringify(ops));\n}\n\nfunction serialise(value: unknown, seen: Set<object>): string | undefined {\n if (value === null) return \"null\";\n\n switch (typeof value) {\n case \"string\":\n return JSON.stringify(value);\n case \"number\":\n return Number.isFinite(value) ? JSON.stringify(value) : \"null\";\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n return undefined;\n case \"bigint\":\n return JSON.stringify(value.toString());\n default:\n break;\n }\n\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n throw new TypeError(\"Cannot serialise a circular structure.\");\n }\n seen.add(value);\n const items = value.map((item) => serialise(item, seen) ?? \"null\");\n seen.delete(value);\n return `[${items.join(\",\")}]`;\n }\n\n if (typeof value === \"object\") {\n if (seen.has(value)) {\n throw new TypeError(\"Cannot serialise a circular structure.\");\n }\n seen.add(value);\n\n const record = value as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const serialised = serialise(record[key], seen);\n if (serialised === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${serialised}`);\n }\n\n seen.delete(value);\n return `{${parts.join(\",\")}}`;\n }\n\n return undefined;\n}\n\nfunction fnv1a64(input: string): string {\n // 64-bit FNV-1a in four 16-bit limbs: the same digest as BigInt arithmetic,\n // without a BigInt multiply per byte (a bulk write hashes megabytes).\n const bytes = new TextEncoder().encode(input);\n let h0 = 0x2325;\n let h1 = 0x8422;\n let h2 = 0x9ce4;\n let h3 = 0xcbf2;\n for (let index = 0; index < bytes.length; index += 1) {\n h0 ^= bytes[index];\n // Multiply by the prime 2^40 + 0x1b3: 0x1b3 per limb, plus the 2^40 part\n // shifted into limbs 2 and 3.\n const t0 = h0 * 0x1b3;\n const t1 = h1 * 0x1b3;\n const t2 = h2 * 0x1b3 + (h0 << 8);\n const t3 = h3 * 0x1b3 + (h1 << 8);\n h1 = t1 + (t0 >>> 16);\n h0 = t0 & 0xffff;\n h2 = t2 + (h1 >>> 16);\n h1 &= 0xffff;\n h3 = (t3 + (h2 >>> 16)) & 0xffff;\n h2 &= 0xffff;\n }\n return [h3, h2, h1, h0].map((limb) => limb.toString(16).padStart(4, \"0\")).join(\"\");\n}\n","export function json(\n data: unknown,\n status = 200,\n headers: HeadersInit = {}\n): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n \"content-type\": \"application/json; charset=utf-8\",\n ...headers,\n },\n });\n}\n\nexport function apiError(\n status: number,\n code: string,\n message: string\n): Response {\n return json({ error: { code, message } }, status);\n}\n\n\n/**\n * Discards an unread request body before responding. Workers tear down a\n * connection whose body was never consumed once the response is sent.\n */\nexport async function discardBody(request: Request): Promise<void> {\n if (request.body && !request.bodyUsed) {\n await request.body.cancel().catch(() => undefined);\n }\n}\n","import { auditEnabled } from \"../audit\";\nimport type { SqlExecutor, SqlValue } from \"./sql\";\nimport type { LogSegment } from \"./types\";\n\n/**\n * One `_tx_log` row as stored by the transaction pipeline. `ops` stays a JSON\n * string in SQLite and is parsed back into the wire shape for the segment.\n */\ninterface TxLogRow extends Record<string, SqlValue> {\n ops_hash: string;\n seq: number;\n client_tx_id: string | null;\n ops: string;\n user_id: string | null;\n role: number | null;\n at: number;\n schema_version: string;\n}\n\nexport const DEFAULT_MAX_SEGMENT_ROWS = 5000;\nexport const DEFAULT_MAX_SEGMENT_BYTES = 1024 * 1024;\n\nconst textEncoder = new TextEncoder();\n\nfunction assertPositiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${label} must be a positive integer.`);\n }\n return value;\n}\n\n/** How many continuation parts a log entry has beyond part 0. */\nfunction extraParts(sql: SqlExecutor, seq: number): number {\n const row = sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_log_parts\" WHERE seq = ?`, seq).toArray()[0];\n return row?.n ?? 0;\n}\n\n/** The stored continuation parts of a log entry, as JSON text, in order. */\nexport function* storedParts(sql: SqlExecutor, seq: number): Generator<string> {\n let part = 0;\n for (;;) {\n const row = sql\n .exec<{ part: number; ops: string }>(\n `SELECT part, ops FROM \"_tx_log_parts\" WHERE seq = ? AND part > ? ORDER BY part LIMIT 1`,\n seq,\n part\n )\n .toArray()[0];\n if (row === undefined) return;\n part = row.part;\n yield row.ops;\n }\n}\n\nfunction parseOps(raw: string): unknown {\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // The pipeline writes valid JSON; keep a malformed row readable rather than\n // failing the whole flush.\n return raw;\n }\n}\n\n/**\n * Reads transactions after `afterSeq` in sequence order and renders one NDJSON\n * line per transaction.\n *\n * The returned segment never splits a transaction line: a single line larger\n * than `maxBytes` is still included on its own. Returns null when there is\n * nothing to flush.\n */\nexport function buildLogSegment(\n sql: SqlExecutor,\n afterSeq: number,\n maxRows: number = DEFAULT_MAX_SEGMENT_ROWS,\n maxBytes: number = DEFAULT_MAX_SEGMENT_BYTES\n): LogSegment | null {\n assertPositiveInteger(maxRows, \"maxRows\");\n assertPositiveInteger(maxBytes, \"maxBytes\");\n if (!Number.isSafeInteger(afterSeq) || afterSeq < 0) {\n throw new Error(\"afterSeq must be a non-negative integer.\");\n }\n\n const rows = sql\n .exec<TxLogRow>(\n `SELECT seq, client_tx_id, ops, ops_hash, user_id, role, at, schema_version\n FROM \"_tx_log\"\n WHERE seq > ?\n ORDER BY seq\n LIMIT ?`,\n afterSeq,\n maxRows\n )\n .toArray();\n\n const lines: string[] = [];\n const refs: Array<{ seq: number; first: string }> = [];\n let bytes = 0;\n\n for (const row of rows) {\n if (lines.length >= maxRows) break;\n\n const parts = extraParts(sql, row.seq);\n const entry = {\n seq: row.seq,\n ...(row.client_tx_id === null ? {} : { clientTxId: row.client_tx_id }),\n // An entry in parts keeps its ops in their own object, written part by\n // part, so neither the segment nor a later replay holds them at once.\n ...(parts > 0 ? { ops: [], opsParts: parts + 1 } : { ops: parseOps(row.ops) }),\n // The hash of what the client sent, which is not always the hash of the\n // ops stored beside it: a bulk write logs the rows it resolved. Carried\n // so a retry after a restore is still recognised.\n opsHash: row.ops_hash,\n // Present only when the deployment records an audit.\n ...(auditEnabled() && row.user_id !== null ? { userId: row.user_id } : {}),\n ...(auditEnabled() && row.role !== null ? { role: row.role } : {}),\n at: row.at,\n schemaVersion: row.schema_version,\n };\n const line = `${JSON.stringify(entry)}\\n`;\n const lineBytes = textEncoder.encode(line).byteLength;\n\n if (lines.length > 0 && bytes + lineBytes > maxBytes) break;\n\n lines.push(line);\n if (parts > 0) refs.push({ seq: row.seq, first: row.ops });\n bytes += lineBytes;\n }\n\n if (lines.length === 0) return null;\n\n return {\n fromSeq: rows[0].seq,\n toSeq: rows[lines.length - 1].seq,\n rows: lines.length,\n ndjson: lines.join(\"\"),\n refs,\n };\n}\n","/** Shared types for the workspace durability modules. */\n\nexport type SnapshotStatus = \"idle\" | \"running\" | \"completed\" | \"failed\";\n\nexport interface FlushState {\n lastSeq: number;\n attempts: number;\n nextAttemptAt: number | null;\n lastError: string | null;\n lastFlushAt: number | null;\n lastSegmentFrom: number | null;\n updatedAt: number;\n /** True when `_tx_log` has at least one row after `lastSeq`. */\n hasPending: boolean;\n}\n\nexport interface SnapshotState {\n baseSeq: number;\n status: SnapshotStatus;\n startedAt: number | null;\n completedAt: number | null;\n manifestKey: string | null;\n}\n\nexport interface LogSegment {\n fromSeq: number;\n toSeq: number;\n rows: number;\n ndjson: string;\n /**\n * Entries whose ops are in parts: their line says `opsParts` and carries no\n * ops, and the flusher uploads the parts to `logOpsKey(seq)` first.\n */\n refs: Array<{ seq: number; first: string }>;\n}\n\nexport interface FlushOptions {\n /** Maximum transactions in one segment. Defaults to 5000. */\n maxRows?: number;\n /** Maximum NDJSON bytes in one segment. Defaults to 1 MiB. */\n maxBytes?: number;\n}\n\nexport interface FlushResult {\n flushed: boolean;\n fromSeq?: number;\n toSeq?: number;\n rows?: number;\n key?: string;\n /** Set when the flush failed. */\n error?: string;\n code?: DurabilityErrorCode;\n}\n\nexport interface SnapshotOptions {\n /** Rows per chunk before gzip. Defaults to 500. */\n chunkRows?: number;\n /** Uncompressed NDJSON bytes per chunk. Defaults to 1 MiB. */\n chunkBytes?: number;\n /** Snapshot prefixes to keep, including the one just written. Defaults to 2. */\n retention?: number;\n /**\n * Covered replay-log sequences retained below a snapshot. Transaction\n * receipts are kept independently. Defaults to `LOG_RETENTION_SEQ`.\n */\n retainLogSequences?: number;\n}\n\nexport interface SnapshotResult {\n snapshotted: boolean;\n baseSeq?: number;\n logSeq?: number;\n manifestKey?: string;\n tables?: number;\n chunks?: number;\n rows?: number;\n bytes?: number;\n error?: string;\n /** Pruning is best-effort; failures are reported but do not fail the snapshot. */\n warnings?: string[];\n}\n\nexport interface DurabilityOptions {\n flush?: FlushOptions;\n snapshot?: SnapshotOptions;\n}\n\nexport interface HistoryPruneResult {\n /** R2 objects deleted. */\n objects: number;\n /** Local replay-log rows deleted. */\n localRows: number;\n /** Transaction receipts whose operation hash was removed; their IDs remain. */\n receipts: number;\n /** When the oldest remaining history becomes due, or null. */\n nextAt: number | null;\n}\n\nexport interface DurabilityTickResult {\n flushed: boolean;\n /** Why a due flush failed; it is retried with backoff. */\n flushError?: string;\n snapshot: SnapshotResult | null;\n /** Set when history was pruned by age on this pass. */\n history: HistoryPruneResult | null;\n}\n\nexport type DurabilityErrorCode =\n | \"r2_write_failed\"\n | \"manifest_conflict\"\n | \"snapshot_failed\"\n | \"invalid_state\";\n\nexport class DurabilityError extends Error {\n readonly code: DurabilityErrorCode;\n\n constructor(code: DurabilityErrorCode, message: string) {\n super(message);\n this.name = \"DurabilityError\";\n this.code = code;\n }\n}\n","import {\n MANIFEST_VERSION,\n putManifest,\n readManifest,\n type WorkspaceManifest,\n} from \"../r2-keys\";\nimport type { SqlExecutor, SqlValue } from \"./sql\";\nimport { DurabilityError } from \"./types\";\n\nconst textEncoder = new TextEncoder();\n\nexport const FALLBACK_ENGINE_VERSION = \"1\";\nconst MANIFEST_WRITE_ATTEMPTS = 2;\n\ninterface EngineVersionRow extends Record<string, SqlValue> {\n value: string;\n}\n\nexport function readEngineVersion(sql: SqlExecutor): string {\n const row = sql\n .exec<EngineVersionRow>(\n `SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'engine_version'`\n )\n .toArray()[0];\n return row?.value ?? FALLBACK_ENGINE_VERSION;\n}\n\nexport interface ManifestWriteResult {\n manifest: WorkspaceManifest;\n created: boolean;\n}\n\n/**\n * Conditional manifest write shared by the flusher and the snapshotter.\n *\n * `build` is called with the current manifest (or null when absent) so callers\n * can merge monotonic fields such as `logSeq`. On a precondition failure the\n * manifest is re-read and the write retried once; a second failure surfaces as\n * `DurabilityError(\"manifest_conflict\")` rather than overwriting another writer.\n */\nexport async function commitManifest(\n bucket: R2Bucket,\n workspaceId: string,\n build: (current: WorkspaceManifest | null) => WorkspaceManifest\n): Promise<ManifestWriteResult> {\n for (let attempt = 0; attempt < MANIFEST_WRITE_ATTEMPTS; attempt += 1) {\n const current = await readManifest(bucket, workspaceId);\n const manifest = build(current?.manifest ?? null);\n const written = await putManifest(\n bucket,\n workspaceId,\n manifest,\n current?.etag\n );\n if (written) {\n return { manifest, created: current === null };\n }\n }\n\n throw new DurabilityError(\n \"manifest_conflict\",\n `Could not write the manifest for workspace ${workspaceId}; another writer kept winning the ETag race.`\n );\n}\n\nexport function manifestCreatedAt(now: number): string {\n return new Date(now).toISOString();\n}\n\n/** UTF-8 byte length, used when estimating NDJSON chunk sizes. */\nexport function utf8Bytes(value: string): number {\n return textEncoder.encode(value).byteLength;\n}\n\n/** Fixed boundary for receipts already lost before an upgrade or restore. */\nexport function readReceiptFloor(sql: SqlExecutor): number {\n const row = sql.exec<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'receipts_since'`).toArray()[0];\n return row === undefined ? 0 : Number(row.value);\n}\n","import { logOpsKey, logSegmentKey, MANIFEST_VERSION } from \"../r2-keys\";\nimport { buildLogSegment, storedParts } from \"./log-segment\";\nimport {\n commitManifest,\n manifestCreatedAt,\n readEngineVersion,\n readReceiptFloor,\n} from \"./manifest\";\nimport type { SqlExecutor, SqlValue } from \"./sql\";\nimport type { FlushOptions, FlushResult, FlushState } from \"./types\";\nimport { DurabilityError } from \"./types\";\n\nexport const FLUSH_BACKOFF_BASE_MS = 30_000;\nexport const FLUSH_BACKOFF_MAX_MS = 60 * 60 * 1000;\nexport const MAX_FLUSH_ERROR_LENGTH = 500;\n\ninterface FlushStateRow extends Record<string, SqlValue> {\n last_seq: number;\n attempts: number;\n next_attempt_at: number | null;\n last_error: string | null;\n last_flush_at: number | null;\n last_segment_from: number | null;\n updated_at: number;\n}\n\ninterface PendingRow extends Record<string, SqlValue> {\n present: number;\n}\n\nfunction ensureFlushStateRow(sql: SqlExecutor): void {\n sql.exec(\n `INSERT OR IGNORE INTO \"_flush_state\"\n (id, last_seq, attempts, next_attempt_at, last_error, last_flush_at,\n last_segment_from, updated_at)\n VALUES (1, 0, 0, NULL, NULL, NULL, NULL, 0)`\n );\n}\n\n/** Reads `_flush_state` and whether `_tx_log` has rows after `lastSeq`. */\nexport function readFlushState(sql: SqlExecutor): FlushState {\n ensureFlushStateRow(sql);\n\n const row = sql\n .exec<FlushStateRow>(\n `SELECT last_seq, attempts, next_attempt_at, last_error, last_flush_at,\n last_segment_from, updated_at\n FROM \"_flush_state\"\n WHERE id = 1`\n )\n .toArray()[0];\n\n const lastSeq = row?.last_seq ?? 0;\n const pending =\n sql\n .exec<PendingRow>(\n `SELECT 1 AS present FROM \"_tx_log\" WHERE seq > ? ORDER BY seq LIMIT 1`,\n lastSeq\n )\n .toArray().length > 0;\n\n return {\n lastSeq,\n attempts: row?.attempts ?? 0,\n nextAttemptAt: row?.next_attempt_at ?? null,\n lastError: row?.last_error ?? null,\n lastFlushAt: row?.last_flush_at ?? null,\n lastSegmentFrom: row?.last_segment_from ?? null,\n updatedAt: row?.updated_at ?? 0,\n hasPending: pending,\n };\n}\n\n/** True when there is work and the backoff window has elapsed. */\nexport function shouldFlush(state: FlushState, now: number): boolean {\n return (\n state.hasPending &&\n (state.nextAttemptAt === null || now >= state.nextAttemptAt)\n );\n}\n\n/** Exponential backoff: 30s, 60s, 120s … capped at one hour. */\nexport function nextBackoffDelay(attempts: number): number {\n const exponent = Math.max(0, Math.min(attempts - 1, 20));\n return Math.min(FLUSH_BACKOFF_MAX_MS, FLUSH_BACKOFF_BASE_MS * 2 ** exponent);\n}\n\nfunction truncateError(message: string): string {\n return message.length > MAX_FLUSH_ERROR_LENGTH\n ? message.slice(0, MAX_FLUSH_ERROR_LENGTH)\n : message;\n}\n\nfunction recordFlushFailure(\n sql: SqlExecutor,\n state: FlushState,\n now: number,\n message: string\n): void {\n const attempts = state.attempts + 1;\n const nextAttemptAt = now + nextBackoffDelay(attempts);\n sql.exec(\n `UPDATE \"_flush_state\"\n SET attempts = ?, next_attempt_at = ?, last_error = ?, updated_at = ?\n WHERE id = 1`,\n attempts,\n nextAttemptAt,\n truncateError(message),\n now\n );\n}\n\n/**\n * Flushes pending `_tx_log` rows to R2.\n *\n * Ordering matters for recovery: the segment is uploaded first, then the\n * manifest is advanced, and only then is `_flush_state.last_seq` moved. If R2\n * or the manifest write fails, `last_seq` is untouched so the next attempt\n * re-uploads the same (idempotent) segment.\n */\n/** R2's smallest multipart part (except the last). */\nconst MIN_UPLOAD_PART = 5 * 1024 * 1024;\n\n/**\n * Uploads a log entry's parts as one NDJSON object, a JSON array per line,\n * through a multipart upload, so no more than about one upload part is in\n * memory however large the entry is.\n */\nasync function uploadParts(\n bucket: R2Bucket,\n workspaceId: string,\n sql: SqlExecutor,\n seq: number,\n first: string\n): Promise<void> {\n const key = logOpsKey(workspaceId, seq);\n const upload = await bucket.createMultipartUpload(key, {\n httpMetadata: { contentType: \"application/x-ndjson; charset=utf-8\" },\n });\n const uploaded: R2UploadedPart[] = [];\n // R2 wants every part but the last exactly the same size, so lines are cut\n // at byte boundaries into MIN_UPLOAD_PART-sized parts, not closed at a line.\n const encoder = new TextEncoder();\n const part = new Uint8Array(MIN_UPLOAD_PART);\n let filled = 0;\n const send = async (bytes: Uint8Array) => {\n uploaded.push(await upload.uploadPart(uploaded.length + 1, bytes.slice()));\n };\n try {\n const parts = (function* () {\n yield first;\n yield* storedParts(sql, seq);\n })();\n for (const text of parts) {\n const line = encoder.encode(`${text}\\n`);\n for (let offset = 0; offset < line.byteLength; ) {\n const take = Math.min(MIN_UPLOAD_PART - filled, line.byteLength - offset);\n part.set(line.subarray(offset, offset + take), filled);\n filled += take;\n offset += take;\n if (filled === MIN_UPLOAD_PART) {\n await send(part);\n filled = 0;\n }\n }\n }\n if (filled > 0 || uploaded.length === 0) await send(part.subarray(0, filled));\n await upload.complete(uploaded);\n } catch (error) {\n await upload.abort().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function flushPending(\n bucket: R2Bucket,\n sql: SqlExecutor,\n workspaceId: string,\n now: number,\n options: FlushOptions = {}\n): Promise<FlushResult> {\n const state = readFlushState(sql);\n\n if (!state.hasPending) {\n return { flushed: false };\n }\n\n const segment = buildLogSegment(\n sql,\n state.lastSeq,\n options.maxRows,\n options.maxBytes\n );\n\n if (!segment) {\n return { flushed: false };\n }\n\n const key = logSegmentKey(workspaceId, segment.fromSeq, segment.toSeq);\n\n try {\n // Entries in parts first: a segment line that refers to ops not yet in\n // R2 would be a replay that cannot finish.\n for (const ref of segment.refs) await uploadParts(bucket, workspaceId, sql, ref.seq, ref.first);\n\n const written = await bucket.put(key, segment.ndjson, {\n httpMetadata: { contentType: \"application/x-ndjson; charset=utf-8\" },\n });\n\n if (!written) {\n throw new DurabilityError(\n \"r2_write_failed\",\n `R2 did not acknowledge ${key}.`\n );\n }\n\n await commitManifest(bucket, workspaceId, (current) => ({\n version: MANIFEST_VERSION,\n workspaceId,\n baseSeq: current?.baseSeq ?? 0,\n logSeq: Math.max(current?.logSeq ?? 0, segment.toSeq),\n createdAt: current?.createdAt ?? manifestCreatedAt(now),\n engineVersion: readEngineVersion(sql),\n schemaVersion: current?.schemaVersion,\n receiptFloor: current && current.baseSeq > 0 ? current.receiptFloor : readReceiptFloor(sql),\n tables: current?.tables ?? [],\n totalRows: current?.totalRows ?? 0,\n totalBytes: current?.totalBytes ?? 0,\n }));\n\n sql.exec(\n `UPDATE \"_flush_state\"\n SET last_seq = ?, attempts = 0, next_attempt_at = NULL,\n last_error = NULL, last_flush_at = ?, last_segment_from = ?,\n updated_at = ?\n WHERE id = 1`,\n segment.toSeq,\n now,\n segment.fromSeq,\n now\n );\n\n return {\n flushed: true,\n fromSeq: segment.fromSeq,\n toSeq: segment.toSeq,\n rows: segment.rows,\n key,\n };\n } catch (cause) {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n recordFlushFailure(sql, state, now, error.message);\n\n return {\n flushed: false,\n error: error.message,\n code: cause instanceof DurabilityError ? cause.code : \"r2_write_failed\",\n };\n }\n}\n","/**\n * Shared R2 helpers.\n *\n * `listAll` was duplicated in `durability/snapshot.ts` and\n * `durability/recovery.ts`; both must paginate identically or pruning and\n * replay disagree about which objects exist. One implementation now serves\n * every caller, including the document room.\n */\n\n/** R2 accepts at most 1000 keys per delete call. */\nconst R2_DELETE_BATCH = 1000;\n\n/** Lists every object under `prefix`, following the cursor to the end. */\nexport async function listAllR2(\n bucket: R2Bucket,\n prefix: string\n): Promise<R2Object[]> {\n const objects: R2Object[] = [];\n let cursor: string | undefined;\n\n for (;;) {\n const page = await bucket.list({ prefix, cursor });\n objects.push(...page.objects);\n if (!page.truncated || !page.cursor) break;\n cursor = page.cursor;\n }\n\n return objects;\n}\n\n/** Deletes keys in batches, so a large prune stays within the R2 call limit. */\nexport async function deleteR2Keys(\n bucket: R2Bucket,\n keys: string[]\n): Promise<void> {\n for (let index = 0; index < keys.length; index += R2_DELETE_BATCH) {\n await bucket.delete(keys.slice(index, index + R2_DELETE_BATCH));\n }\n}\n","import { auditEnabled } from \"../audit\";\nimport { opsHash } from \"../tx-hash\";\nimport {\n MANIFEST_VERSION,\n manifestKey,\n workspacePrefix,\n type ManifestChunk,\n type ManifestTable,\n} from \"../r2-keys\";\nimport { deleteR2Keys, listAllR2 } from \"../r2-list\";\nimport { ENGINE_TABLES, namespaceTables } from \"../registry\";\nimport { readFlushState } from \"./flusher\";\nimport { historyAgeLimit, historyRetentionMs, SUPERSEDED_GRACE_MS } from \"./retention\";\nimport {\n commitManifest,\n manifestCreatedAt,\n readEngineVersion,\n readReceiptFloor,\n utf8Bytes,\n} from \"./manifest\";\nimport type { SqlExecutor, SqlValue } from \"./sql\";\nimport type {\n HistoryPruneResult,\n SnapshotOptions,\n SnapshotResult,\n SnapshotState,\n SnapshotStatus,\n} from \"./types\";\n\nexport const SNAPSHOT_SEQ_THRESHOLD = 1000;\nexport const DEFAULT_SNAPSHOT_CHUNK_ROWS = 500;\nexport const DEFAULT_SNAPSHOT_CHUNK_BYTES = 1024 * 1024;\nexport const DEFAULT_SNAPSHOT_RETENTION = 2;\n\nconst SAFE_TABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\ntype SqlRow = Record<string, SqlValue>;\n\ninterface HighWaterRow extends Record<string, SqlValue> {\n high_water_seq: number;\n}\n\ninterface SnapshotStateRow extends Record<string, SqlValue> {\n base_seq: number;\n status: string;\n started_at: number | null;\n completed_at: number | null;\n manifest_key: string | null;\n}\n\ninterface TableChunkAccumulator {\n chunks: ManifestChunk[];\n rows: number;\n bytes: number;\n}\n\nfunction assertPositiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${label} must be a positive integer.`);\n }\n return value;\n}\n\nfunction readSchemaVersion(sql: SqlExecutor): string | undefined {\n const row = sql\n .exec<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'schema_version'`)\n .toArray()[0];\n return row?.value;\n}\n\nexport function readHighWater(sql: SqlExecutor): number {\n const row = sql\n .exec<HighWaterRow>(`SELECT high_water_seq FROM \"_tx_state\" WHERE id = 1`)\n .toArray()[0];\n return row?.high_water_seq ?? 0;\n}\n\nexport function readSnapshotState(sql: SqlExecutor): SnapshotState {\n const row = sql\n .exec<SnapshotStateRow>(\n `SELECT base_seq, status, started_at, completed_at, manifest_key\n FROM \"_snapshot_state\"\n WHERE id = 1`\n )\n .toArray()[0];\n\n return {\n baseSeq: row?.base_seq ?? 0,\n status: (row?.status as SnapshotStatus | undefined) ?? \"idle\",\n startedAt: row?.started_at ?? null,\n completedAt: row?.completed_at ?? null,\n manifestKey: row?.manifest_key ?? null,\n };\n}\n\nfunction ensureSnapshotStateRow(sql: SqlExecutor): void {\n sql.exec(\n `INSERT OR IGNORE INTO \"_snapshot_state\" (id, base_seq, status)\n VALUES (1, 0, 'idle')`\n );\n}\n\nfunction markSnapshotRunning(sql: SqlExecutor, now: number): void {\n ensureSnapshotStateRow(sql);\n sql.exec(\n `UPDATE \"_snapshot_state\"\n SET status = 'running', started_at = ?, completed_at = NULL,\n manifest_key = NULL\n WHERE id = 1`,\n now\n );\n}\n\nfunction markSnapshotCompleted(\n sql: SqlExecutor,\n workspaceId: string,\n baseSeq: number,\n now: number\n): void {\n sql.exec(`DELETE FROM \"_engine_meta\" WHERE \"key\" = 'retention_snapshot_pending'`);\n sql.exec(\n `UPDATE \"_snapshot_state\"\n SET base_seq = ?, status = 'completed', completed_at = ?, manifest_key = ?\n WHERE id = 1`,\n baseSeq,\n now,\n manifestKey(workspaceId)\n );\n}\n\nfunction markSnapshotFailed(sql: SqlExecutor): void {\n ensureSnapshotStateRow(sql);\n sql.exec(\n `UPDATE \"_snapshot_state\"\n SET status = 'failed', completed_at = NULL, manifest_key = NULL\n WHERE id = 1`\n );\n}\n\n/**\n * True when a snapshot is due: sequence lag, a missing baseline, or changes\n * since a snapshot that has reached half the history retention (so values\n * deleted after it stop living in it; see retention.ts).\n */\nexport function shouldSnapshot(sql: SqlExecutor, now: number, retentionMs: number = historyRetentionMs()): boolean {\n const due = snapshotDueAt(sql, retentionMs);\n return due !== null && due <= now;\n}\n\n/** When the next snapshot is due, or null while none is needed. */\nexport function snapshotDueAt(sql: SqlExecutor, retentionMs: number = historyRetentionMs()): number | null {\n const highWater = readHighWater(sql);\n if (highWater <= 0) return null;\n\n const state = readSnapshotState(sql);\n if (sql.exec(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'retention_snapshot_pending'`).toArray().length) return Number.NEGATIVE_INFINITY;\n if (state.status !== \"completed\") return Number.NEGATIVE_INFINITY;\n if (highWater - state.baseSeq >= SNAPSHOT_SEQ_THRESHOLD) return Number.NEGATIVE_INFINITY;\n if (highWater > state.baseSeq) return (state.completedAt ?? 0) + historyAgeLimit(retentionMs);\n return null;\n}\n\nasync function gzipBytes(bytes: Uint8Array): Promise<Uint8Array> {\n // See recovery.ts: lib.dom and workers-types both declare these globals.\n const stream = new Response(bytes as unknown as BodyInit).body;\n if (!stream) {\n throw new Error(\"Failed to create a compression stream.\");\n }\n const compressed = stream.pipeThrough(new CompressionStream(\"gzip\"));\n return new Uint8Array(await new Response(compressed).arrayBuffer());\n}\n\nexport async function sha256Hex(bytes: Uint8Array): Promise<string> {\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n bytes as unknown as BufferSource\n );\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nasync function snapshotTable(\n bucket: R2Bucket,\n sql: SqlExecutor,\n workspaceId: string,\n baseSeq: number,\n table: string,\n chunkRows: number,\n chunkBytes: number,\n sourceTable: string = table\n): Promise<TableChunkAccumulator> {\n if (!SAFE_TABLE.test(table)) {\n throw new Error(`Unsafe table name in registry: ${table}`);\n }\n\n const prefix = `${workspacePrefix(workspaceId)}/snapshots/${baseSeq}/${table}`;\n const chunks: ManifestChunk[] = [];\n let totalRows = 0;\n let totalBytes = 0;\n\n let lines: string[] = [];\n let lineBytes = 0;\n let chunkIndex = 0;\n\n const flushChunk = async (): Promise<void> => {\n if (lines.length === 0) return;\n\n const key = `${prefix}/${chunkIndex}.ndjson.gz`;\n const raw = new TextEncoder().encode(lines.join(\"\"));\n const compressed = await gzipBytes(raw);\n const written = await bucket.put(key, compressed, {\n httpMetadata: { contentType: \"application/gzip\" },\n });\n if (!written) {\n throw new Error(`R2 did not acknowledge snapshot chunk ${key}.`);\n }\n\n chunks.push({\n key,\n rows: lines.length,\n bytes: compressed.byteLength,\n sha256: await sha256Hex(compressed),\n });\n totalRows += lines.length;\n totalBytes += compressed.byteLength;\n chunkIndex += 1;\n lines = [];\n lineBytes = 0;\n };\n\n let lastId: string | null = null;\n for (;;) {\n const rows: SqlRow[] =\n lastId === null\n ? sql\n .exec<SqlRow>(\n `SELECT * FROM \"${sourceTable}\" ORDER BY id LIMIT ?`,\n chunkRows\n )\n .toArray()\n : sql\n .exec<SqlRow>(\n `SELECT * FROM \"${sourceTable}\" WHERE id > ? ORDER BY id LIMIT ?`,\n lastId,\n chunkRows\n )\n .toArray();\n\n if (rows.length === 0) break;\n\n for (const row of rows) {\n const line = `${JSON.stringify(row)}\\n`;\n const bytes = utf8Bytes(line);\n\n if (\n lines.length > 0 &&\n (lines.length >= chunkRows || lineBytes + bytes > chunkBytes)\n ) {\n await flushChunk();\n }\n\n lines.push(line);\n lineBytes += bytes;\n\n if (lines.length >= chunkRows) {\n await flushChunk();\n }\n }\n\n lastId = String(rows[rows.length - 1].id);\n if (rows.length < chunkRows) break;\n }\n\n await flushChunk();\n\n return { chunks, rows: totalRows, bytes: totalBytes };\n}\n\nconst LOG_SEGMENT_NAME = /^(\\d+)-(\\d+)\\.ndjson$/;\n/** A log entry's ops, kept apart from its segment (`logOpsKey`). */\nconst LOG_OPS_NAME = /^ops\\/(\\d+)\\.ndjson$/;\n\n/** The last sequence a log object holds: a segment's `toSeq`, or an ops object's seq. */\nfunction logObjectEnd(name: string): number | null {\n const segment = LOG_SEGMENT_NAME.exec(name);\n if (segment) return Number(segment[2]);\n const ops = LOG_OPS_NAME.exec(name);\n return ops ? Number(ops[1]) : null;\n}\n\n/** Replay-log retention is independent of permanent transaction receipts. */\nexport const LOG_RETENTION_SEQ = 2 * SNAPSHOT_SEQ_THRESHOLD;\n\n/** Trim flushed replay rows after their checkpoint; receipts remain intact. */\nexport function trimLocalLog(\n sql: SqlExecutor,\n baseSeq: number,\n options: { retainLogSequences?: number } = {}\n): number {\n const horizon = options.retainLogSequences ?? LOG_RETENTION_SEQ;\n const flushed =\n sql\n .exec<{ last_seq: number }>(`SELECT last_seq FROM \"_flush_state\" WHERE id = 1`)\n .toArray()[0]?.last_seq ?? 0;\n const cut = Math.min(baseSeq, flushed) - horizon;\n if (cut <= 0) return 0;\n\n const removable =\n sql\n .exec<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_log\" WHERE seq <= ?`, cut)\n .toArray()[0]?.n ?? 0;\n if (removable === 0) return 0;\n\n sql.exec(`DELETE FROM \"_tx_log\" WHERE seq <= ?`, cut);\n sql.exec(`DELETE FROM \"_tx_log_parts\" WHERE seq <= ?`, cut);\n // Receipts are independent of the replay log and are never trimmed here.\n return Number(removable);\n}\n\n/**\n * Deletes log segments wholly covered by `baseSeq`, keeping those inside the\n * configured replay retention. Transaction receipts live in the snapshot.\n */\nexport async function pruneCoveredLogSegments(\n bucket: R2Bucket,\n workspaceId: string,\n baseSeq: number,\n options: { retainLogSequences?: number } = {}\n): Promise<number> {\n const prefix = `${workspacePrefix(workspaceId)}/log/`;\n const objects = await listAllR2(bucket, prefix);\n const keys: string[] = [];\n const horizon = options.retainLogSequences ?? LOG_RETENTION_SEQ;\n const retainFrom = baseSeq - horizon;\n\n for (const object of objects) {\n const end = logObjectEnd(object.key.slice(prefix.length));\n if (end === null) continue;\n // A segment that overlaps the horizon stays: its lines below the snapshot\n // base are the only remaining copy of their idempotency keys.\n if (end <= retainFrom) keys.push(object.key);\n }\n\n await deleteR2Keys(bucket, keys);\n return keys.length;\n}\n\nconst SNAPSHOT_OBJECT = /^(\\d+)\\//;\n\n/**\n * Keeps the newest `retention` snapshot prefixes (including the one just\n * written) and deletes older prefix contents.\n */\nexport async function pruneOldSnapshots(\n bucket: R2Bucket,\n workspaceId: string,\n currentBaseSeq: number,\n retention: number = DEFAULT_SNAPSHOT_RETENTION\n): Promise<number> {\n const prefix = `${workspacePrefix(workspaceId)}/snapshots/`;\n const objects = await listAllR2(bucket, prefix);\n\n const sequences = new Set<number>([currentBaseSeq]);\n const byObject: Array<{ key: string; seq: number | null }> = [];\n\n for (const object of objects) {\n const match = SNAPSHOT_OBJECT.exec(object.key.slice(prefix.length));\n const seq = match ? Number(match[1]) : null;\n if (seq !== null) sequences.add(seq);\n byObject.push({ key: object.key, seq });\n }\n\n const keep = new Set(\n [...sequences].sort((a, b) => b - a).slice(0, Math.max(1, retention))\n );\n const keys = byObject\n .filter((entry) => entry.seq !== null && !keep.has(entry.seq))\n .map((entry) => entry.key);\n\n await deleteR2Keys(bucket, keys);\n return keys.length;\n}\n\nasync function pruneSafely(\n bucket: R2Bucket,\n workspaceId: string,\n baseSeq: number,\n retention: number,\n retainLogSequences?: number\n): Promise<string[]> {\n const warnings: string[] = [];\n\n try {\n await pruneCoveredLogSegments(bucket, workspaceId, baseSeq, {\n retainLogSequences,\n });\n } catch (cause) {\n warnings.push(\n `log prune failed: ${cause instanceof Error ? cause.message : String(cause)}`\n );\n }\n\n try {\n await pruneOldSnapshots(bucket, workspaceId, baseSeq, retention);\n } catch (cause) {\n warnings.push(\n `snapshot prune failed: ${cause instanceof Error ? cause.message : String(cause)}`\n );\n }\n\n return warnings;\n}\n\n/**\n * Writes a full chunked snapshot of every entity table and then commits the v2\n * manifest. `_snapshot_state` only becomes `completed` after the manifest PUT\n * succeeds; pruning runs afterwards and never fails the snapshot.\n */\nexport async function snapshotWorkspace(\n bucket: R2Bucket,\n sql: SqlExecutor,\n workspaceId: string,\n now: number,\n options: SnapshotOptions = {}\n): Promise<SnapshotResult> {\n const chunkRows = assertPositiveInteger(\n options.chunkRows ?? DEFAULT_SNAPSHOT_CHUNK_ROWS,\n \"chunkRows\"\n );\n const chunkBytes = assertPositiveInteger(\n options.chunkBytes ?? DEFAULT_SNAPSHOT_CHUNK_BYTES,\n \"chunkBytes\"\n );\n const retention = assertPositiveInteger(\n options.retention ?? DEFAULT_SNAPSHOT_RETENTION,\n \"retention\"\n );\n\n const baseSeq = readHighWater(sql);\n const receiptFloor = readReceiptFloor(sql);\n const flushState = readFlushState(sql);\n\n markSnapshotRunning(sql, now);\n const sources = [\n ...namespaceTables(),\n ENGINE_TABLES.files,\n ENGINE_TABLES.txReceipts,\n ...(auditEnabled() ? [ENGINE_TABLES.txAudit] : []),\n ];\n const staged: string[] = [];\n try {\n // No await between reading baseSeq and copying every table: another\n // request cannot change the checkpoint halfway through its R2 upload.\n for (const table of sources) {\n const copy = `_tapedb_snapshot_${table}`;\n if (!SAFE_TABLE.test(table) || sources.includes(copy)) throw new Error(\"Snapshot staging table conflicts with an application table.\");\n sql.exec(`DROP TABLE IF EXISTS \"${copy}\"`);\n sql.exec(`CREATE TABLE \"${copy}\" AS SELECT * FROM \"${table}\"`);\n staged.push(copy);\n }\n const tables: ManifestTable[] = [];\n let totalRows = 0;\n let totalBytes = 0;\n let totalChunks = 0;\n\n // The file index is part of the workspace's state like any table: without\n // it a restore keeps only files written after the snapshot.\n for (const table of sources) {\n const snapshot = await snapshotTable(\n bucket,\n sql,\n workspaceId,\n baseSeq,\n table,\n chunkRows,\n chunkBytes,\n `_tapedb_snapshot_${table}`\n );\n tables.push({ name: table, chunks: snapshot.chunks });\n totalRows += snapshot.rows;\n totalBytes += snapshot.bytes;\n totalChunks += snapshot.chunks.length;\n }\n\n const logSeq = Math.max(baseSeq, flushState.lastSeq);\n\n const { manifest } = await commitManifest(\n bucket,\n workspaceId,\n (current) => ({\n version: MANIFEST_VERSION,\n workspaceId,\n baseSeq,\n logSeq: Math.max(logSeq, current?.logSeq ?? 0),\n createdAt: current?.createdAt ?? manifestCreatedAt(now),\n engineVersion: readEngineVersion(sql),\n schemaVersion: readSchemaVersion(sql),\n receiptFloor,\n tables,\n totalRows,\n totalBytes,\n })\n );\n\n markSnapshotCompleted(sql, workspaceId, baseSeq, now);\n // The superseded snapshot and the log it covers age out once its grace ends.\n setHistoryPruneAt(sql, now + SUPERSEDED_GRACE_MS);\n\n const warnings = await pruneSafely(\n bucket,\n workspaceId,\n baseSeq,\n retention,\n options.retainLogSequences\n );\n\n // The snapshot and its manifest are durable; the local log can shrink to\n // the same window R2 keeps.\n try {\n trimLocalLog(sql, baseSeq, { retainLogSequences: options.retainLogSequences });\n } catch (cause) {\n warnings.push(`trim_local_log_failed: ${cause instanceof Error ? cause.message : String(cause)}`);\n }\n\n return {\n snapshotted: true,\n baseSeq,\n logSeq: manifest.logSeq,\n manifestKey: manifestKey(workspaceId),\n tables: tables.length,\n chunks: totalChunks,\n rows: totalRows,\n bytes: totalBytes,\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n } catch (cause) {\n markSnapshotFailed(sql);\n return {\n snapshotted: false,\n baseSeq,\n error: cause instanceof Error ? cause.message : String(cause),\n };\n } finally {\n for (const table of staged) sql.exec(`DROP TABLE IF EXISTS \"${table}\"`);\n }\n}\n\nconst HISTORY_PRUNE_KEY = \"history_prune_at\";\n\nfunction setHistoryPruneAt(sql: SqlExecutor, at: number | null): void {\n sql.exec(\n `INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES (?, ?)`,\n HISTORY_PRUNE_KEY,\n at === null ? \"\" : String(at)\n );\n}\n\n/**\n * When history next needs pruning by age, or null when nothing is waiting.\n * A workspace that has never recorded one (new, upgraded or recovered) is\n * due as soon as it has a snapshot to rely on.\n */\nexport function historyPruneAt(sql: SqlExecutor): number | null {\n const state = readSnapshotState(sql);\n if (state.status !== \"completed\") return null;\n const row = sql\n .exec<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = ?`, HISTORY_PRUNE_KEY)\n .toArray()[0];\n if (row === undefined) return Number.NEGATIVE_INFINITY;\n return row.value === \"\" ? null : Number(row.value);\n}\n\n/**\n * Deletes history older than half the retention: superseded snapshots, the\n * log segments the newest snapshot covers, covered local log rows, and stale\n * staging left by a failed snapshot. The newest snapshot and the log after it\n * are what recovery needs, and are never touched here.\n */\nexport async function pruneHistory(\n bucket: R2Bucket,\n sql: SqlExecutor,\n workspaceId: string,\n now: number,\n retentionMs: number = historyRetentionMs()\n): Promise<HistoryPruneResult> {\n const state = readSnapshotState(sql);\n if (state.status !== \"completed\" || state.completedAt === null) {\n return { objects: 0, localRows: 0, receipts: 0, nextAt: null };\n }\n const age = historyAgeLimit(retentionMs);\n const graceEnds = state.completedAt + SUPERSEDED_GRACE_MS;\n let nextAt: number | null = null;\n const later = (at: number) => {\n nextAt = nextAt === null ? at : Math.min(nextAt, at);\n };\n const keys: string[] = [];\n const uploadedAt = (object: R2Object) => new Date(object.uploaded).getTime();\n\n const logPrefix = `${workspacePrefix(workspaceId)}/log/`;\n for (const object of await listAllR2(bucket, logPrefix)) {\n const end = logObjectEnd(object.key.slice(logPrefix.length));\n if (end === null || end > state.baseSeq) continue;\n const due = Math.max(uploadedAt(object) + age, graceEnds);\n if (due <= now) keys.push(object.key);\n else later(due);\n }\n\n const snapshotPrefix = `${workspacePrefix(workspaceId)}/snapshots/`;\n const prefixes = new Map<number, { keys: string[]; uploaded: number }>();\n for (const object of await listAllR2(bucket, snapshotPrefix)) {\n const match = SNAPSHOT_OBJECT.exec(object.key.slice(snapshotPrefix.length));\n if (!match) continue;\n const seq = Number(match[1]);\n if (seq === state.baseSeq) continue;\n const entry = prefixes.get(seq) ?? { keys: [], uploaded: 0 };\n entry.keys.push(object.key);\n entry.uploaded = Math.max(entry.uploaded, uploadedAt(object));\n prefixes.set(seq, entry);\n }\n for (const [seq, entry] of prefixes) {\n // An older snapshot is the fallback for the newest during its grace;\n // staging from a failed newer one is no one's fallback.\n const due = seq < state.baseSeq ? Math.max(entry.uploaded + age, graceEnds) : entry.uploaded + age;\n if (due <= now) keys.push(...entry.keys);\n else later(due);\n }\n await deleteR2Keys(bucket, keys);\n\n // Covered local rows: flushed to R2 and inside the newest snapshot.\n const flushed = readFlushState(sql).lastSeq;\n const cut = Math.min(state.baseSeq, flushed);\n const localRows =\n sql\n .exec<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_log\" WHERE seq <= ? AND at <= ?`, cut, now - age)\n .toArray()[0]?.n ?? 0;\n if (localRows > 0) {\n sql.exec(`DELETE FROM \"_tx_log\" WHERE seq <= ? AND at <= ?`, cut, now - age);\n // The audit's writer identities leave with the rest of the history.\n sql.exec(`DELETE FROM \"_tx_audit\" WHERE seq <= ? AND at <= ?`, cut, now - age);\n sql.exec(`DELETE FROM \"_tx_log_parts\" WHERE seq NOT IN (SELECT seq FROM \"_tx_log\")`);\n }\n const oldest = sql\n .exec<{ at: number | null }>(`SELECT MIN(at) AS at FROM \"_tx_log\" WHERE seq <= ?`, cut)\n .toArray()[0]?.at;\n if (oldest !== null && oldest !== undefined) later(oldest + age);\n\n // Keep the random id, sequence and time permanently for deduplication;\n // discard only the hash derived from the operation values.\n const receipts =\n sql\n .exec<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_receipts\" WHERE ops_hash IS NOT NULL AND at <= ?`, now - age)\n .toArray()[0]?.n ?? 0;\n if (receipts > 0) {\n sql.exec(`UPDATE \"_tx_receipts\" SET ops_hash = NULL WHERE ops_hash IS NOT NULL AND at <= ?`, now - age);\n // A new sequence gives the scrubbed snapshot a new immutable R2 prefix.\n // Otherwise the newest snapshot of a quiet workspace keeps hashes forever.\n const seq = Math.max(readHighWater(sql), Number(sql.exec<{ seq: number | null }>(`SELECT MAX(seq) AS seq FROM \"_tx_log\"`).toArray()[0]?.seq ?? 0)) + 1;\n sql.exec(`INSERT INTO \"_tx_log\" (seq, client_tx_id, ops, ops_hash, user_id, role, at, schema_version) VALUES (?, NULL, '[]', ?, NULL, NULL, ?, ?)`, seq, opsHash([]), now, readSchemaVersion(sql) ?? \"unknown\");\n sql.exec(`UPDATE \"_tx_state\" SET high_water_seq = ? WHERE id = 1`, seq);\n sql.exec(`INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES ('retention_snapshot_pending', '1')`);\n }\n const oldestReceipt = sql.exec<{ at: number | null }>(`SELECT MIN(at) AS at FROM \"_tx_receipts\" WHERE ops_hash IS NOT NULL`).toArray()[0]?.at;\n if (oldestReceipt !== null && oldestReceipt !== undefined) later(oldestReceipt + age);\n\n setHistoryPruneAt(sql, nextAt);\n return { objects: keys.length, localRows: Number(localRows), receipts: Number(receipts), nextAt };\n}\n","import { flushPending, readFlushState, shouldFlush } from \"./flusher\";\nimport { historyPruneAt, pruneHistory, shouldSnapshot, snapshotWorkspace } from \"./snapshot\";\nimport type { SqlExecutor } from \"./sql\";\nimport type { DurabilityOptions, DurabilityTickResult } from \"./types\";\n\n/** Segments one pass writes at most, and the time it spends writing them. */\nconst MAX_SEGMENTS_PER_TICK = 1000;\nconst FLUSH_BUDGET_MS = 20_000;\n\n/**\n * One durability pass: flush pending log rows first, take a snapshot when one\n * is due, then delete history past the retention.\n *\n * This module deliberately does not schedule alarms; the caller owns the\n * Durable Object alarm lifecycle.\n */\nexport async function durabilityTick(\n bucket: R2Bucket,\n sql: SqlExecutor,\n workspaceId: string,\n now: number,\n options: DurabilityOptions = {}\n): Promise<DurabilityTickResult> {\n // Drain the backlog, a segment at a time, rather than one segment per pass:\n // a segment holds about 1 MB, and a workspace writing faster than that per\n // alarm delay would otherwise fall further behind R2 with every write.\n const started = Date.now();\n let flushResult: Awaited<ReturnType<typeof flushPending>> | { flushed: false } = { flushed: false };\n let flushedAny = false;\n for (let segments = 0; segments < MAX_SEGMENTS_PER_TICK; segments += 1) {\n const flushState = readFlushState(sql);\n if (!shouldFlush(flushState, now)) break;\n flushResult = await flushPending(bucket, sql, workspaceId, now, options.flush);\n if (!flushResult.flushed) break;\n flushedAny = true;\n if (Date.now() - started > FLUSH_BUDGET_MS) break;\n }\n\n const snapshot = shouldSnapshot(sql, now)\n ? await snapshotWorkspace(bucket, sql, workspaceId, now, options.snapshot)\n : null;\n\n // History older than the retention allows, whether or not anything changed.\n const pruneAt = historyPruneAt(sql);\n const history = pruneAt !== null && pruneAt <= now ? await pruneHistory(bucket, sql, workspaceId, now) : null;\n\n const flushError = \"error\" in flushResult && typeof flushResult.error === \"string\" ? flushResult.error : undefined;\n return { flushed: flushedAny, ...(flushError ? { flushError } : {}), snapshot, history };\n}\n","/**\n * The transaction log's storage for transactions of any size.\n *\n * A transaction is one `_tx_log` row. Its ops are usually small enough to sit\n * in that row; a bulk write that touches many rows is not, and a Durable\n * Object row holds at most 8 MB. So a log entry's ops are a list of parts:\n * part 0 in `_tx_log.ops`, the rest in `_tx_log_parts`, each a JSON array of\n * ops of at most `LOG_PART_BYTES`. Every reader goes through `logParts`, one\n * part at a time, so no step holds more than one part in memory.\n *\n * Bulk writes log compactly: one `patchIds` / `deleteIds` op per chunk of\n * rows, carrying the ids and the values once, instead of one op per row.\n * `expandLogOps` turns them back into ordinary ops right before they are\n * validated, a chunk at a time. Clients cannot send these kinds: they exist\n * only in the log.\n */\n\nimport { stableStringify } from \"./tx-hash\";\nimport type { SqlExecutor, SqlValue } from \"./tx-sql\";\n\n/**\n * The most a stored part holds. Well under the 8 MB row limit, and small\n * enough that recovery applies one part (a few thousand rows) well inside a\n * Durable Object's 30 s of CPU, pausing between parts.\n */\nexport const LOG_PART_BYTES = 256 * 1024;\nlet logPartBytes = LOG_PART_BYTES;\n\n/** Tests only: a smaller part size, so a multi-part entry needs few rows. */\nexport function setLogPartBytesForTests(bytes: number | null): void {\n logPartBytes = bytes ?? LOG_PART_BYTES;\n}\n\n/** Rows per compact bulk op in the log. */\nexport const LOG_IDS_PER_OP = 1000;\n\ninterface PartRow extends Record<string, SqlValue> {\n ops: string;\n}\n\n/**\n * Collects a transaction's ops into parts as they are produced, so a bulk\n * write never builds its whole op list in memory.\n */\nexport class LogWriter {\n private readonly parts: string[] = [];\n private current: string[] = [];\n private size = 2;\n private stored = 0;\n\n constructor(\n private readonly sql: SqlExecutor,\n private readonly seq: number,\n private readonly partBytes: number = logPartBytes\n ) {}\n\n push(op: unknown): void {\n const text = stableStringify(op);\n if (this.current.length > 0 && this.size + text.length + 1 > this.partBytes) this.cut();\n this.current.push(text);\n this.size += text.length + 1;\n }\n\n private cut(): void {\n const json = `[${this.current.join(\",\")}]`;\n if (this.parts.length === 0 && this.stored === 0) {\n // Part 0 waits for `close`, which writes it into the log row.\n this.parts.push(json);\n } else {\n this.stored += 1;\n this.sql.exec(`INSERT INTO \"_tx_log_parts\" (seq, part, ops) VALUES (?, ?, ?)`, this.seq, this.stored, json);\n }\n this.current = [];\n this.size = 2;\n }\n\n /** Writes part 0 into the log row. Returns how many parts the entry has. */\n close(): number {\n if (this.current.length > 0 || (this.parts.length === 0 && this.stored === 0)) this.cut();\n this.sql.exec(`UPDATE \"_tx_log\" SET ops = ? WHERE seq = ?`, this.parts[0] ?? \"[]\", this.seq);\n return 1 + this.stored;\n }\n}\n\n/** Writes a whole op list (already in memory) as a log entry's parts. */\nexport function writeLogOps(sql: SqlExecutor, seq: number, ops: readonly unknown[]): void {\n const writer = new LogWriter(sql, seq);\n for (const op of ops) writer.push(op);\n writer.close();\n}\n\n/** How many continuation parts a log entry has beyond part 0. */\nexport function extraParts(sql: SqlExecutor, seq: number): number {\n return sql.one<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_log_parts\" WHERE seq = ?`, seq)?.n ?? 0;\n}\n\n/** A log entry's ops, one part at a time: part 0 (given), then the stored ones. */\nexport function* logParts(sql: SqlExecutor, seq: number, first: string): Generator<unknown[]> {\n yield parseArray(first);\n let part = 0;\n for (;;) {\n const row = sql.one<PartRow>(`SELECT ops FROM \"_tx_log_parts\" WHERE seq = ? AND part > ? ORDER BY part LIMIT 1`, seq, part);\n if (row === undefined) return;\n part += 1;\n yield parseArray(row.ops);\n }\n}\n\n/** Removes continuation parts whose log row is gone. */\nexport function deleteOrphanParts(sql: SqlExecutor): void {\n sql.exec(`DELETE FROM \"_tx_log_parts\" WHERE seq NOT IN (SELECT seq FROM \"_tx_log\")`);\n}\n\nfunction parseArray(text: string): unknown[] {\n const parsed: unknown = JSON.parse(text);\n if (!Array.isArray(parsed)) throw new Error(\"A log part is not a JSON array.\");\n return parsed;\n}\n\n/** One compact bulk op per chunk of ids. */\nexport function compactBulkOp(\n kind: \"patchMany\" | \"deleteMany\",\n namespace: string,\n ids: readonly string[],\n values: Record<string, unknown>\n): Record<string, unknown> {\n return kind === \"deleteMany\"\n ? { op: \"deleteIds\", namespace, ids: [...ids] }\n : { op: \"patchIds\", namespace, ids: [...ids], values };\n}\n\n/** Ordinary ops for a list that may hold compact bulk ops. */\nexport function expandLogOps(ops: readonly unknown[]): unknown[] {\n if (!ops.some(isCompact)) return [...ops];\n const out: unknown[] = [];\n for (const op of ops) {\n if (!isCompact(op)) {\n out.push(op);\n continue;\n }\n for (const id of op.ids) {\n out.push(\n op.op === \"deleteIds\"\n ? { op: \"delete\", namespace: op.namespace, id }\n : { op: \"patch\", namespace: op.namespace, id, values: op.values ?? {} }\n );\n }\n }\n return out;\n}\n\nfunction isCompact(\n op: unknown\n): op is { op: \"patchIds\" | \"deleteIds\"; namespace: string; ids: string[]; values?: Record<string, unknown> } {\n return (\n typeof op === \"object\" &&\n op !== null &&\n ((op as { op?: unknown }).op === \"patchIds\" || (op as { op?: unknown }).op === \"deleteIds\") &&\n Array.isArray((op as { ids?: unknown }).ids)\n );\n}\n","/**\n * Bulk writes, resolved to the rows they touch.\n *\n * `patchMany` and `deleteMany` arrive as a filter. The filter is evaluated\n * once, inside the transaction and before any op is applied, and its rows are\n * staged; the transaction then checks, applies and logs them a chunk at a\n * time, so one transaction writes any number of rows atomically. The log\n * records the rows, not the filter: re-running the filter during a replay,\n * against a database that has moved on, would change a different set.\n *\n * The rows are resolved through the query executor with the caller's claim,\n * so a bulk write touches exactly the rows that caller could have read and\n * patched one by one: `read` rules narrow the set, and the row rules for\n * `update` and `delete` still run per row afterwards.\n */\n\nimport type { RoleClaim } from \"../claims\";\nimport { compileQuery } from \"./query-compile\";\nimport { authorizeQuery, executeCompiledQueryWithPageInfo, viewAccess } from \"./query-execute\";\nimport { findNamespace } from \"./registry\";\nimport type { SqlExecutor } from \"./tx-sql\";\nimport { TxError } from \"./tx-types\";\nimport { validateEnvelope, type ValidatedBulkOp, type ValidatedOp } from \"./tx-validate\";\nimport { ensureScratch, SCRATCH_TABLE } from \"./query-stages\";\nimport { compactBulkOp, expandLogOps, LOG_IDS_PER_OP } from \"./tx-log\";\n\n/**\n * How many matching ids are resolved per query while staging a bulk op. A\n * bulk write is one transaction however many rows it matches; this only\n * bounds how many ids are in memory at once.\n */\nexport const BULK_BATCH_ROWS = 1000;\n\nfunction isBulk(op: ValidatedOp): op is ValidatedBulkOp {\n return op.kind === \"patchMany\" || op.kind === \"deleteMany\";\n}\n\n/**\n * The next batch of ids a bulk op's filter matches, for this caller, in id\n * order after `op.after`, and whether more match beyond it.\n *\n * Resuming by id rather than re-running the filter from the start is what\n * makes batching terminate: a patch that leaves rows matching would\n * otherwise match the same rows again.\n */\nfunction resolveIds(\n sql: SqlExecutor,\n claim: RoleClaim,\n op: ValidatedBulkOp\n): { ids: string[]; more: boolean } {\n const where =\n op.after === undefined ? op.where : { $and: [op.where, { id: { $gt: op.after } }] };\n const compiled = compileQuery(\n { [op.namespace]: { $: { where, order: { id: \"asc\" }, limit: BULK_BATCH_ROWS, select: [\"id\"] } } },\n viewAccess(claim)\n );\n authorizeQuery(claim, compiled);\n const { data, pageInfo } = executeCompiledQueryWithPageInfo(sql, compiled, claim);\n return {\n ids: (data[op.namespace] ?? []).map((row) => (row as { id: string }).id),\n more: pageInfo[op.namespace]?.hasMore === true,\n };\n}\n\nexport interface StagedBulk {\n /** Scratch key holding each bulk op's ids, keyed by the op's index. */\n keys: Map<number, string>;\n /** Rows matched, keyed by the op's index in the envelope. */\n matched: Record<number, number>;\n}\n\n/**\n * Resolves every bulk op's filter once, against the database as it is before\n * any op in the transaction is applied, and stages the matching ids in the\n * scratch table. The rows are found in id-ordered chunks through the query\n * executor, so the caller's read rules apply and no chunk holds more than\n * `BULK_BATCH_ROWS` ids in memory, however many rows match.\n */\nexport function stageBulkOps(sql: SqlExecutor, claim: RoleClaim, ops: readonly ValidatedOp[]): StagedBulk {\n const keys = new Map<number, string>();\n const matched: Record<number, number> = {};\n if (!ops.some(isBulk)) return { keys, matched };\n ensureScratch(sql);\n\n for (const [index, op] of ops.entries()) {\n if (!isBulk(op)) continue;\n if (!findNamespace(op.namespace)) {\n throw new TxError(\"unknown_namespace\", `Unknown namespace \"${op.namespace}\".`);\n }\n const key = globalThis.crypto.randomUUID();\n keys.set(index, key);\n let count = 0;\n let after = op.after;\n for (;;) {\n const batch = resolveIds(sql, claim, after === undefined ? op : { ...op, after });\n if (batch.ids.length > 0) {\n sql.exec(\n `INSERT OR IGNORE INTO \"${SCRATCH_TABLE}\" (\"k\", \"id\") SELECT ?, value FROM json_each(?)`,\n key,\n JSON.stringify(batch.ids)\n );\n count += batch.ids.length;\n after = batch.ids[batch.ids.length - 1];\n }\n if (!batch.more || batch.ids.length === 0) break;\n }\n matched[index] = count;\n }\n return { keys, matched };\n}\n\n/** A staged bulk op's ids, in id order, a chunk at a time. */\nexport function* stagedIds(sql: SqlExecutor, key: string): Generator<string[]> {\n let after = \"\";\n for (;;) {\n const rows = sql.all<{ id: string }>(\n `SELECT \"id\" FROM \"${SCRATCH_TABLE}\" WHERE \"k\" = ? AND \"id\" > ? ORDER BY \"id\" LIMIT ?`,\n key,\n after,\n LOG_IDS_PER_OP\n );\n if (rows.length === 0) return;\n yield rows.map((row) => row.id);\n if (rows.length < LOG_IDS_PER_OP) return;\n after = rows[rows.length - 1].id;\n }\n}\n\n/** Removes the staged ids. */\nexport function releaseStaged(sql: SqlExecutor, staged: StagedBulk): void {\n if (staged.keys.size === 0) return;\n sql.exec(`DELETE FROM \"${SCRATCH_TABLE}\" WHERE \"k\" IN (SELECT value FROM json_each(?))`, JSON.stringify([...staged.keys.values()]));\n}\n\n/**\n * One chunk of a bulk op as the log stores it (ids and values once) and as\n * validated per-row ops. The values are the client's own, not the\n * column-keyed ones: a replay validates them again, so they must be what a\n * client would have sent.\n */\nexport function bulkChunk(\n txId: string,\n op: ValidatedBulkOp,\n rawOp: unknown,\n ids: readonly string[]\n): { logged: Record<string, unknown>; ops: ValidatedOp[] } {\n const values = (rawOp as { values?: Record<string, unknown> }).values ?? {};\n const logged = compactBulkOp(op.kind, op.namespace, ids, values);\n return { logged, ops: validateEnvelope({ txId, ops: expandLogOps([logged]) }).ops };\n}\n\nexport { isBulk };\n","/**\n * Write-path transaction pipeline.\n *\n * Validation and authorization run before the transaction opens. Everything\n * else — deduplication, sequence allocation, log append, state advance and op\n * application — runs inside one `transactionSync`, so an error at any point\n * rolls back the log, the high-water mark and every row mutation together.\n */\n\nimport { auditEnabled } from \"./audit\";\nimport type { RoleClaim } from \"../claims\";\nimport { applyOps } from \"./tx-apply\";\nimport { bulkChunk, isBulk, releaseStaged, stageBulkOps, stagedIds } from \"./tx-bulk\";\nimport { LogWriter, writeLogOps } from \"./tx-log\";\nimport { opsHash, stableStringify } from \"./tx-hash\";\nimport { assertRowPermissions, authorizeOps } from \"./tx-permissions\";\nimport type { SqlExecutor } from \"./tx-sql\";\nimport { TxError, type TxResult } from \"./tx-types\";\nimport { validateEnvelope } from \"./tx-validate\";\n\nconst FALLBACK_SCHEMA_VERSION = \"0001_baseline\";\n\ntype TxLogRow = {\n seq: number;\n ops_hash: string | null;\n};\n\ntype TxStateRow = {\n high_water_seq: number;\n};\n\ntype TxLogMaxRow = {\n max_seq: number | null;\n};\n\ntype EngineMetaRow = {\n value: string;\n};\n\nexport function runTransaction(\n sql: SqlExecutor,\n workspaceId: string,\n claim: RoleClaim,\n envelope: unknown\n): TxResult {\n if (claim.workspaceId !== workspaceId) {\n throw new TxError(\n \"permission_denied\",\n \"Role claim does not belong to this workspace.\"\n );\n }\n\n const tx = validateEnvelope(envelope);\n authorizeOps(claim, tx.ops);\n\n // The hash is of what the client sent, so a retry of the same request is\n // recognised. What gets logged may differ: a bulk write logs the rows it\n // resolved.\n const hash = opsHash(tx.rawOps);\n\n return sql.transactionSync(() => {\n if (tx.clientTxId !== undefined) {\n const prior = sql.one<TxLogRow>(\n `SELECT seq, ops_hash FROM \"_tx_receipts\" WHERE id = ?`,\n tx.clientTxId\n );\n\n if (prior !== undefined) {\n if (prior.ops_hash === null || prior.ops_hash === hash) {\n return { txId: tx.txId, seq: prior.seq, applied: 0 };\n }\n throw new TxError(\n \"conflict\",\n `clientTxId \"${tx.clientTxId}\" was already used with different ops.`,\n { txId: tx.txId }\n );\n }\n // Receipts no longer expire. An older engine or snapshot may already\n // have discarded some: keep that fixed boundary, never a moving window.\n const since = receiptsSince(sql);\n if (since > 0 && tx.issuedAt !== undefined && tx.issuedAt <= since) {\n throw new TxError(\n \"retry_expired\",\n `clientTxId \"${tx.clientTxId}\" was issued before this workspace can recognise a retry because an earlier engine or snapshot did not retain every receipt, so it is not applied: it may already have been. Send the write again as a new transaction if it still applies.`,\n { txId: tx.txId }\n );\n }\n }\n\n if (!tx.ops.some(isBulk)) {\n // Row rules read the stored row, so they belong inside the transaction,\n // after the idempotency check (a replay of an applied tx must not\n // re-judge) and before the sequence is allocated (a denial burns nothing).\n const now = Date.now();\n const seq = appendLogEntry(sql, { clientTxId: tx.clientTxId ?? null, ops: \"[]\", opsHash: hash, at: now, userId: claim.sub, role: claim.role });\n // In parts when it is larger than a row holds (see tx-log.ts).\n writeLogOps(sql, seq, tx.rawOps);\n const applied = applyOps({ sql, seq, now, txId: tx.txId, beforeOp: op => assertRowPermissions(sql, claim, [op]) }, tx.ops);\n return { txId: tx.txId, seq, applied };\n }\n\n // A bulk write: its filter is resolved once, against the database before\n // any op here applies, and the rows are staged. Then every row's rules\n // run, then the ops apply in order, a chunk of rows at a time, so the\n // whole write is one atomic transaction however many rows it touches and\n // no step holds more than a chunk in memory.\n const staged = stageBulkOps(sql, claim, tx.ops);\n try {\n const matched = { matched: staged.matched };\n const chunks = (index: number) => {\n const op = tx.ops[index];\n const key = staged.keys.get(index)!;\n return (function* () {\n for (const ids of stagedIds(sql, key)) yield bulkChunk(tx.txId, op as never, tx.rawOps[index], ids);\n })();\n };\n\n const nothing = tx.ops.every((op, index) => isBulk(op) && staged.matched[index] === 0);\n if (nothing) {\n // A no-op is still a completed request: preserve its idempotency key so\n // retrying later cannot suddenly match newly-created rows.\n const state = sql.one<TxStateRow>(`SELECT high_water_seq FROM \"_tx_state\" WHERE \"id\" = 1`);\n const seq = tx.clientTxId === undefined ? (state?.high_water_seq ?? 0) : appendLogEntry(sql, {\n clientTxId: tx.clientTxId, ops: \"[]\", opsHash: hash, at: Date.now(), userId: claim.sub, role: claim.role,\n });\n return { txId: tx.txId, seq, applied: 0, ...matched };\n }\n\n const now = Date.now();\n const seq = appendLogEntry(sql, { clientTxId: tx.clientTxId ?? null, ops: \"[]\", opsHash: hash, at: now, userId: claim.sub, role: claim.role });\n const log = new LogWriter(sql, seq);\n const context = { sql, seq, now, txId: tx.txId, beforeOp: (op: typeof tx.ops[number]) => assertRowPermissions(sql, claim, [op]) };\n let applied = 0;\n for (const [index, op] of tx.ops.entries()) {\n if (!isBulk(op)) {\n log.push(tx.rawOps[index]);\n applied += applyOps(context, [op]);\n continue;\n }\n for (const chunk of chunks(index)) {\n log.push(chunk.logged);\n applied += applyOps(context, chunk.ops);\n }\n }\n log.close();\n return { txId: tx.txId, seq, applied, ...matched };\n } finally {\n releaseStaged(sql, staged);\n }\n });\n}\n\nexport interface LogEntry {\n clientTxId: string | null;\n /** Canonical JSON of the ops, exactly as replay will read them. */\n ops: string;\n opsHash: string;\n at: number;\n /** The writer, recorded only with `defineTapeDB({ audit: true })`. */\n userId?: string | null;\n role?: number | null;\n}\n\n/**\n * Allocates the next sequence and appends one `_tx_log` row. Must run inside\n * the caller's transaction, so the row, the high-water mark and whatever the\n * caller applies commit or roll back together.\n */\nexport function appendLogEntry(sql: SqlExecutor, entry: LogEntry): number {\n const state = sql.one<TxStateRow>(\n `SELECT high_water_seq FROM \"_tx_state\" WHERE \"id\" = 1`\n );\n const logMax = sql.one<TxLogMaxRow>(\n `SELECT MAX(seq) AS max_seq FROM \"_tx_log\"`\n );\n\n // Never hand out a sequence that already exists in the log. Recovery or a\n // partial restore can leave `_tx_state` behind `_tx_log`; repairing here\n // keeps the invariant even if that state was written by an older build.\n const previousSeq = Math.max(\n state?.high_water_seq ?? 0,\n logMax?.max_seq ?? 0\n );\n\n if (state === undefined) {\n sql.exec(\n `INSERT INTO \"_tx_state\" (\"id\", high_water_seq) VALUES (1, ?)`,\n previousSeq\n );\n }\n\n const seq = previousSeq + 1;\n\n sql.exec(\n `INSERT INTO \"_tx_log\"\n (seq, client_tx_id, ops, ops_hash, user_id, role, at, schema_version)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n seq,\n entry.clientTxId,\n entry.ops,\n entry.opsHash,\n // Who wrote what is recorded only when the deployment asks for an audit\n // (audit.ts): otherwise it would be personal data without a purpose.\n auditEnabled() ? entry.userId ?? null : null,\n auditEnabled() ? entry.role ?? null : null,\n entry.at,\n readSchemaVersion(sql)\n );\n\n if (entry.clientTxId !== null) {\n sql.exec(`INSERT INTO \"_tx_receipts\" (id, seq, ops_hash, at) VALUES (?, ?, ?, ?)`, entry.clientTxId, seq, entry.opsHash, entry.at);\n }\n sql.exec(`UPDATE \"_tx_state\" SET high_water_seq = ? WHERE \"id\" = 1`, seq);\n return seq;\n}\n\n/**\n * Receipts are complete only from this time: set when a workspace was\n * upgraded or restored from state that did not retain every receipt.\n * 0 when complete.\n */\nfunction receiptsSince(sql: SqlExecutor): number {\n const row = sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'receipts_since'`);\n return row === undefined ? 0 : Number(row.value);\n}\n\nfunction readSchemaVersion(sql: SqlExecutor): string {\n const row = sql.one<EngineMetaRow>(\n `SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'schema_version'`\n );\n return row?.value && row.value.length > 0\n ? row.value\n : FALLBACK_SCHEMA_VERSION;\n}\n","/**\n * The `_files` index, written through the transaction log.\n *\n * Bytes live in R2 and never enter the log. Their metadata rows do: a row that\n * changes outside the log exists only in the Durable Object's SQLite and in\n * the next snapshot, so a restore from R2 loses every upload since that\n * snapshot and resurrects every delete. Logging the change as an engine op\n * gives it a sequence, a segment, and a replay like any other write.\n *\n * File ops are engine-only. `validateEnvelope` refuses them, so a client\n * cannot forge one through `/transact`; only the room's `/files` route and\n * recovery apply them.\n */\n\nimport { ENGINE_TABLES } from \"./registry\";\nimport { opsHash, stableStringify } from \"./tx-hash\";\nimport { appendLogEntry } from \"./tx-pipeline\";\nimport type { SqlExecutor } from \"./tx-sql\";\n\nexport interface FilePutOp {\n op: \"file:put\";\n /** Row id, carried so a replay inserts the same id the original did. */\n id: string;\n path: string;\n key: string;\n size: number;\n contentType: string | null;\n /** The uploader's claim subject. */\n uploadedBy?: string | null;\n createdAt?: number;\n updatedAt?: number;\n}\n\nexport interface FileForgetOp {\n op: \"file:forget\";\n path: string;\n}\n\nexport type FileOp = FilePutOp | FileForgetOp;\n\nexport interface FileRecord {\n path: string;\n key: string;\n size: number;\n contentType: string | null;\n uploadedBy?: string | null;\n}\n\n/** True when a logged op list is a file-index entry rather than a client tx. */\nexport function isFileOpList(ops: readonly unknown[]): ops is FileOp[] {\n return (\n ops.length > 0 &&\n ops.every(\n (op) =>\n typeof op === \"object\" &&\n op !== null &&\n ((op as { op?: unknown }).op === \"file:put\" ||\n (op as { op?: unknown }).op === \"file:forget\")\n )\n );\n}\n\n/**\n * Applies file ops. Both are last-writer-wins on `path`, so applying them in\n * sequence order is enough for a replay to converge: no `updated_seq` guard is\n * needed, and replaying a line twice is harmless.\n *\n * Returns the number of rows changed.\n */\nexport function applyFileOps(\n sql: SqlExecutor,\n ops: readonly FileOp[],\n at: number\n): number {\n let changed = 0;\n for (const op of ops) {\n if (op.op === \"file:put\") {\n changed += sql.exec(\n `INSERT INTO \"${ENGINE_TABLES.files}\"\n (\"id\", \"path\", \"r2_key\", \"size\", \"content_type\", \"uploaded_by\", \"created_at\", \"updated_at\")\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(\"path\") DO UPDATE SET\n \"r2_key\" = excluded.\"r2_key\",\n \"size\" = excluded.\"size\",\n \"content_type\" = excluded.\"content_type\",\n \"uploaded_by\" = excluded.\"uploaded_by\",\n \"updated_at\" = excluded.\"updated_at\"`,\n op.id,\n op.path,\n op.key,\n op.size,\n op.contentType,\n op.uploadedBy ?? null,\n op.createdAt ?? at,\n op.updatedAt ?? at\n );\n } else {\n changed += sql.exec(\n `DELETE FROM \"${ENGINE_TABLES.files}\" WHERE \"path\" = ?`,\n op.path\n );\n }\n }\n return changed;\n}\n\n/** Logs and applies file ops in one transaction. Returns rows changed. */\nfunction commitFileOps(\n sql: SqlExecutor,\n ops: FileOp[],\n actor: { sub: string | null; role: number | null }\n): number {\n return sql.transactionSync(() => {\n const at = Date.now();\n appendLogEntry(sql, {\n clientTxId: null,\n ops: stableStringify(ops),\n opsHash: opsHash(ops),\n at,\n });\n return applyFileOps(sql, ops, at);\n });\n}\n\nexport function recordFileEntry(\n sql: SqlExecutor,\n record: FileRecord,\n actor: { sub: string | null; role: number | null } = { sub: null, role: null }\n): void {\n commitFileOps(\n sql,\n [\n {\n op: \"file:put\",\n id: crypto.randomUUID(),\n path: record.path,\n key: record.key,\n size: record.size,\n contentType: record.contentType,\n ...(record.uploadedBy ? { uploadedBy: record.uploadedBy } : {}),\n },\n ],\n actor\n );\n}\n\n/**\n * Forgets a path. A path that is not indexed burns no sequence: there is\n * nothing for a replay to undo.\n */\nexport function forgetFileEntry(\n sql: SqlExecutor,\n path: string,\n actor: { sub: string | null; role: number | null } = { sub: null, role: null }\n): number {\n const present = sql.one(\n `SELECT 1 AS \"present\" FROM \"${ENGINE_TABLES.files}\" WHERE \"path\" = ?`,\n path\n );\n if (present === undefined) return 0;\n return commitFileOps(sql, [{ op: \"file:forget\", path }], actor);\n}\n","/**\n * Cold-start recovery: rebuild a workspace Durable Object's SQLite from R2.\n *\n * The manifest names a chunked snapshot plus the highest flushed log sequence.\n * Recovery restores every entity table from that snapshot and then replays log\n * segments after the snapshot base. Replays never touch `_tx_log` or advance\n * `_tx_state` as they go; engine bookkeeping is written once, after the replay\n * finishes, so a crash mid-recovery cannot make the workspace look caught up.\n *\n * Every op is idempotent: an op is skipped when its target row already carries\n * `updated_seq >= line.seq`. A second recovery over the same R2 contents is\n * therefore safe.\n */\n\nimport { auditEnabled } from \"../audit\";\nimport { applyFileOps, isFileOpList } from \"../file-index\";\nimport {\n changesAfter,\n evolveColumn,\n evolveField,\n evolveModel,\n evolveTable,\n type SchemaChange,\n} from \"../schema-evolution\";\nimport {\n logOpsKey,\n manifestKey,\n readManifest,\n workspacePrefix,\n type ManifestTable,\n type WorkspaceManifest,\n} from \"../r2-keys\";\nimport { listAllR2 } from \"../r2-list\";\nimport {\n ENGINE_TABLES,\n findNamespace,\n LINKS,\n NAMESPACES,\n namespaceTables,\n registryGeneration,\n toSnakeCase,\n} from \"../registry\";\nimport { applyOps, quoteIdentifier } from \"../tx-apply\";\nimport { opsHash, stableStringify } from \"../tx-hash\";\nimport { expandLogOps } from \"../tx-log\";\nimport type {\n SqlExecutor as TxSqlExecutor,\n SqlRow as TxSqlRow,\n} from \"../tx-sql\";\nimport { acceptsValue, isBulkOp, isLinkOp, validateEnvelope, type ValidatedOp } from \"../tx-validate\";\nimport { sha256Hex } from \"./snapshot\";\nimport { readReceiptFloor } from \"./manifest\";\nimport { historyAgeLimit, historyRetentionMs } from \"./retention\";\nimport type { SqlCursor, SqlExecutor, SqlValue } from \"./sql\";\n\n/** Durability SQL plus the transaction primitive the restore/replay needs. */\nexport interface RecoverySqlExecutor extends SqlExecutor {\n settle?(): Promise<void>;\n transactionSync<T>(fn: () => T): T;\n}\n\nexport interface RecoverWorkspaceOptions {\n /**\n * Restore even when entity tables already contain rows. Existing rows are\n * left in place; snapshot rows replace rows with the same id.\n */\n force?: boolean;\n /** Clock override for deterministic tests; defaults to `Date.now()`. */\n now?: number;\n /**\n * Epoch ms after which recovery stops at the next chunk or segment, keeps\n * its progress, and returns `{ recovered: false, reason: \"paused\" }`. The\n * next call resumes. A Durable Object resets if its boot runs past 30 s,\n * so the room recovers in budgeted steps.\n */\n deadline?: number;\n /** Checked where `deadline` is; true pauses. */\n shouldPause?: () => boolean;\n /** Called as each unit (a chunk, a segment, a part of an entry) starts, with its name. */\n onUnit?: (unit: string) => void;\n}\n\n/** Thrown between steps when the time budget is spent; never escapes. */\nclass RecoveryPaused extends Error {}\n\n/** R2 could not be read. Nothing was applied from the failed read. */\nclass R2Unavailable extends Error {}\n\n/**\n * The bucket as recovery reads it: a failed get, list or whole-object read\n * becomes `R2Unavailable`, which keeps the progress made so far instead of\n * starting over. Streamed bodies are not wrapped: a parted entry applies\n * while it streams, so a failure there is not safe to resume from.\n */\nfunction resumableReads(bucket: R2Bucket): R2Bucket {\n const guard = async <T>(read: () => Promise<T>): Promise<T> => {\n try {\n return await read();\n } catch (error) {\n throw new R2Unavailable(messageOf(error));\n }\n };\n const wrapObject = (object: R2ObjectBody | null): R2ObjectBody | null =>\n object === null\n ? null\n : (new Proxy(object, {\n get(target, key) {\n if (key === \"arrayBuffer\" || key === \"text\" || key === \"json\") {\n const read = Reflect.get(target, key, target) as () => Promise<unknown>;\n return () => guard(() => read.call(target));\n }\n // Native getters (body, etag) need the object itself as `this`.\n const value = Reflect.get(target, key, target) as unknown;\n return typeof value === \"function\" ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n }) as R2ObjectBody);\n return new Proxy(bucket, {\n get(target, key) {\n if (key === \"get\") {\n return (...args: Parameters<R2Bucket[\"get\"]>) =>\n guard(() => target.get(...args)).then((object) => wrapObject(object as R2ObjectBody | null));\n }\n if (key === \"list\") return (...args: Parameters<R2Bucket[\"list\"]>) => guard(() => target.list(...args));\n const value = Reflect.get(target, key, target) as unknown;\n return typeof value === \"function\" ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n });\n}\n\nexport type RecoveryResult =\n | { recovered: false; reason: \"no_manifest\" | \"already_populated\" | \"paused\" }\n /** R2 could not be read; progress is kept and a later call resumes. */\n | { recovered: false; reason: \"unavailable\"; error: string }\n | {\n recovered: true;\n baseSeq: number;\n logSeq: number;\n /** Number of manifest tables restored (including empty ones). */\n tables: number;\n /** Snapshot rows inserted. */\n rows: number;\n /** Log transactions with at least one op applied. */\n replayed: number;\n /** Set when the restore could not carry everything forward. */\n warnings?: string[];\n };\n\ninterface PragmaColumn extends Record<string, SqlValue> {\n name: string;\n}\n\ninterface UpdatedSeqRow extends Record<string, SqlValue> {\n updated_seq: number;\n}\n\ninterface LogLine {\n /** The client's ops hash, when the segment carries one. */\n opsHash?: string;\n seq: number;\n at: number;\n ops: unknown[];\n /** The idempotency key. Present when the client supplied one. */\n clientTxId?: string;\n schemaVersion?: string;\n /** Present when the entry's ops are in their own object, in this many parts. */\n opsParts?: number;\n /** The writer, when the deployment records an audit. */\n userId?: string;\n role?: number;\n}\n\ninterface LogSegmentRef {\n key: string;\n fromSeq: number;\n toSeq: number;\n}\n\ninterface TargetRow {\n table: string;\n id: string;\n}\n\ntype RestorableRow = Record<string, SqlValue>;\n\n/**\n * Dependency-safe restore order, derived from the deployment registry.\n *\n * Parents come before children so the restore also works when\n * `PRAGMA foreign_keys` cannot be turned off (for example when recovery runs\n * inside an outer transaction). Computed rather than hardcoded, so a schema\n * change cannot silently reorder a restore.\n */\nexport function restoreOrder(): string[] {\n let remaining = Object.values(NAMESPACES);\n const emitted: string[] = [];\n const done = new Set<string>();\n\n while (remaining.length > 0) {\n const ready = remaining.filter((namespace) =>\n Object.values(namespace.attributes).every((attribute) => {\n const referenced = attribute.references?.table;\n if (!referenced || referenced === namespace.table) return true;\n if (!remaining.some((other) => other.table === referenced)) return true;\n return done.has(referenced);\n })\n );\n\n // A cycle cannot be ordered; emit the remainder rather than loop forever.\n const batch = ready.length > 0 ? ready : remaining;\n for (const namespace of batch) {\n emitted.push(namespace.table);\n done.add(namespace.table);\n }\n\n // Drop what was emitted. Without this the loop never terminates: `ready` is\n // derived from `remaining`, and re-selecting the same tables grows\n // `emitted` until the array overflows.\n remaining = remaining.filter((namespace) => !done.has(namespace.table));\n }\n\n emitted.push(ENGINE_TABLES.files, ENGINE_TABLES.txReceipts, ENGINE_TABLES.txAudit);\n return emitted;\n}\n\n/** Tables whose rows reference another row in the same chunk. */\nfunction selfReferential(): Record<string, string> {\n const map: Record<string, string> = {};\n for (const namespace of Object.values(NAMESPACES)) {\n for (const [name, attribute] of Object.entries(namespace.attributes)) {\n if (attribute.references?.table === namespace.table) {\n map[namespace.table] = toSnakeCase(name);\n }\n }\n }\n return map;\n}\n\nconst LOG_SEGMENT_NAME = /^(\\d+)-(\\d+)\\.ndjson$/;\nconst MAX_ERROR_LENGTH = 2000;\n\n/**\n * Tables recovery may touch. Computed lazily and rebuilt when the registry is\n * configured, which happens after this module loads: a module-level snapshot\n * would be fixed to the empty pre-configuration state and reject every\n * namespace.\n */\nlet allowedTableCache: { generation: number; tables: Set<string> } | null = null;\n\nexport function allowedTables(): Set<string> {\n const generation = registryGeneration();\n if (allowedTableCache === null || allowedTableCache.generation !== generation) {\n allowedTableCache = {\n generation,\n tables: new Set<string>([...namespaceTables(), ENGINE_TABLES.files, ENGINE_TABLES.txReceipts, ENGINE_TABLES.txAudit]),\n };\n }\n return allowedTableCache.tables;\n}\n\nconst textDecoder = new TextDecoder();\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Engine tables include `$files`, which `quoteIdentifier` intentionally\n * rejects. Callers only pass names from `allowedTables()`, so quoting here is\n * a guard rail rather than an input sanitizer.\n */\nfunction quoteTable(table: string): string {\n if (!allowedTables().has(table)) {\n throw new Error(`Unknown table \"${table}\".`);\n }\n return `\"${table}\"`;\n}\n\nfunction truncate(message: string): string {\n return message.length > MAX_ERROR_LENGTH\n ? message.slice(0, MAX_ERROR_LENGTH)\n : message;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction setMeta(sql: RecoverySqlExecutor, key: string, value: string): void {\n sql.exec(\n `INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES (?, ?)`,\n key,\n value\n );\n}\n\nfunction getMeta(sql: RecoverySqlExecutor, key: string): string | undefined {\n try {\n const row = sql.exec<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = ?`, key).toArray()[0];\n return row?.value;\n } catch {\n return undefined;\n }\n}\n\nconst PROGRESS_KEYS = [\n \"recovery_manifest\",\n \"recovery_phase\",\n \"recovery_chunks_done\",\n \"recovery_segments_done\",\n \"recovery_lines_done\",\n \"recovery_entry_parts\",\n];\n\nfunction deleteMeta(sql: RecoverySqlExecutor, key: string): void {\n sql.exec(`DELETE FROM \"_engine_meta\" WHERE \"key\" = ?`, key);\n}\n\nfunction markRunning(sql: RecoverySqlExecutor, now: number): void {\n setMeta(sql, \"recovery_status\", \"running\");\n setMeta(sql, \"recovery_started_at\", String(now));\n deleteMeta(sql, \"recovery_error\");\n deleteMeta(sql, \"recovery_completed_at\");\n deleteMeta(sql, \"recovery_failed_at\");\n}\n\nfunction markFailed(\n sql: RecoverySqlExecutor,\n now: number,\n error: unknown\n): void {\n setMeta(sql, \"recovery_status\", \"failed\");\n for (const key of PROGRESS_KEYS) deleteMeta(sql, key);\n setMeta(sql, \"recovery_error\", truncate(messageOf(error)));\n setMeta(sql, \"recovery_failed_at\", String(now));\n deleteMeta(sql, \"recovery_completed_at\");\n}\n\nfunction markComplete(\n sql: RecoverySqlExecutor,\n manifest: WorkspaceManifest,\n now: number\n): void {\n setMeta(sql, \"recovery_status\", \"complete\");\n for (const key of PROGRESS_KEYS) deleteMeta(sql, key);\n setMeta(sql, \"recovery_completed_at\", String(now));\n setMeta(sql, \"recovery_base_seq\", String(manifest.baseSeq));\n setMeta(sql, \"recovery_log_seq\", String(manifest.logSeq));\n deleteMeta(sql, \"recovery_error\");\n deleteMeta(sql, \"recovery_failed_at\");\n}\n\n/** True when any entity table contains at least one row. */\nfunction hasEntityRows(sql: RecoverySqlExecutor): boolean {\n for (const table of restoreOrder()) {\n const rows = sql\n .exec(`SELECT 1 AS \"present\" FROM ${quoteTable(table)} LIMIT 1`)\n .toArray();\n if (rows.length > 0) return true;\n }\n return false;\n}\n\n/**\n * True when this Durable Object has ever committed a transaction, even if\n * every row has since been deleted.\n *\n * `hasEntityRows` alone cannot tell a freshly-wiped DO from a workspace that\n * legitimately emptied itself: deletes are hard deletes, so a workspace whose\n * last row was removed looks identical to one that lost its SQLite. The\n * high-water mark survives both cases, and only the wipe resets it.\n */\nfunction hasWriteHistory(sql: RecoverySqlExecutor): boolean {\n try {\n const row = sql\n .exec<{\n high_water_seq: number;\n }>(`SELECT high_water_seq FROM \"_tx_state\" WHERE \"id\" = 1`)\n .toArray()[0];\n return (row?.high_water_seq ?? 0) > 0;\n } catch {\n // Migrations have not run yet, so there is no local history to protect.\n return false;\n }\n}\n\n/**\n * Drops the rows a failed restore managed to insert.\n *\n * `recoverWorkspace` only runs when the entity tables were empty, so everything\n * in these tables at this point came from the failed attempt. Removing it stops\n * the next boot from treating a partial restore as real local state and\n * returning `already_populated` forever.\n */\nfunction clearRestoredRows(sql: RecoverySqlExecutor): void {\n // Children first: attachment foreign keys deliberately restrict task deletion.\n for (const table of [...restoreOrder()].reverse()) {\n sql.exec(`DELETE FROM ${quoteTable(table)}`);\n }\n}\n\nfunction orderedTables(manifest: WorkspaceManifest): ManifestTable[] {\n const byName = new Map(manifest.tables.map((table) => [table.name, table]));\n const ordered: ManifestTable[] = [];\n\n for (const name of restoreOrder()) {\n const table = byName.get(name);\n if (table) {\n ordered.push(table);\n byName.delete(name);\n }\n }\n\n // Table names are validated against the registry before this point, so\n // anything left over cannot be restored with this schema.\n if (byName.size > 0) {\n throw new Error(\n `Manifest contains unknown table(s): ${[...byName.keys()].join(\", \")}.`\n );\n }\n\n return ordered;\n}\n\nfunction validateManifestTables(manifest: WorkspaceManifest): void {\n const snapshotPrefix = `${workspacePrefix(\n manifest.workspaceId\n )}/snapshots/${manifest.baseSeq}/`;\n\n const changes = changesAfter(manifest.schemaVersion);\n for (const table of manifest.tables) {\n const current = evolveTable(table.name, changes);\n if (current !== null && !allowedTables().has(current)) {\n throw new Error(`Manifest contains unknown table \"${table.name}\".`);\n }\n\n const tablePrefix = `${snapshotPrefix}${table.name}/`;\n for (const chunk of table.chunks) {\n if (!chunk.key.startsWith(tablePrefix)) {\n throw new Error(\n `Snapshot chunk ${chunk.key} is outside the manifest's table prefix.`\n );\n }\n }\n }\n}\n\nfunction readColumns(sql: RecoverySqlExecutor, table: string): Set<string> {\n const columns = sql\n .exec<PragmaColumn>(`PRAGMA table_info(${quoteTable(table)})`)\n .toArray()\n .map((row) => row.name);\n\n if (columns.length === 0) {\n throw new Error(\n `Table \"${table}\" has no columns; workspace migrations have not run.`\n );\n }\n\n return new Set(columns);\n}\n\nasync function gunzipBytes(bytes: Uint8Array): Promise<Uint8Array> {\n // `lib.dom` and workers-types both declare Response/BodyInit, and their\n // intersection rejects Uint8Array<ArrayBufferLike>. Same bytes either way.\n const stream = new Response(bytes as unknown as BodyInit).body;\n if (!stream) {\n throw new Error(\"Failed to create a decompression stream.\");\n }\n const decompressed = stream.pipeThrough(new DecompressionStream(\"gzip\"));\n return new Uint8Array(await new Response(decompressed).arrayBuffer());\n}\n\nfunction parseNdjson(text: string, source: string): RestorableRow[] {\n const rows: RestorableRow[] = [];\n\n for (const [index, line] of text.split(\"\\n\").entries()) {\n if (line.length === 0) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(line) as unknown;\n } catch {\n throw new Error(`Invalid NDJSON in ${source} at line ${index + 1}.`);\n }\n\n if (!isPlainRecord(parsed)) {\n throw new Error(\n `Snapshot row in ${source} at line ${index + 1} is not an object.`\n );\n }\n\n rows.push(parsed as RestorableRow);\n }\n\n return rows;\n}\n\n/**\n * Puts parents before children so self-referential foreign keys hold even when\n * `PRAGMA foreign_keys = OFF` is unavailable. Rows in a cycle are appended in\n * their original order and left for `PRAGMA foreign_key_check` to reject.\n */\nfunction orderParentsFirst(\n rows: RestorableRow[],\n parentColumn: string\n): RestorableRow[] {\n const knownIds = new Set(rows.map((row) => String(row.id)));\n const emitted = new Set<string>();\n const pending = [...rows];\n const ordered: RestorableRow[] = [];\n\n while (pending.length > 0) {\n let progressed = false;\n\n for (let index = 0; index < pending.length;) {\n const row = pending[index];\n const parent = row[parentColumn];\n const parentReady =\n parent === null ||\n parent === undefined ||\n !knownIds.has(String(parent)) ||\n emitted.has(String(parent));\n\n if (parentReady) {\n ordered.push(row);\n emitted.add(String(row.id));\n pending.splice(index, 1);\n progressed = true;\n } else {\n index += 1;\n }\n }\n\n if (!progressed) {\n ordered.push(...pending);\n break;\n }\n }\n\n return ordered;\n}\n\n/** Snapshot rows from an older schema, with dropped columns removed and renamed ones moved. */\nfunction evolveRows(\n rows: RestorableRow[],\n table: string,\n changes: SchemaChange[]\n): RestorableRow[] {\n if (changes.length === 0) return rows;\n return rows.map((row) => {\n const out: RestorableRow = {};\n for (const [column, value] of Object.entries(row)) {\n const current = evolveColumn(table, column, changes);\n if (current !== null) out[current] = value;\n }\n return out;\n });\n}\n\n/**\n * Log ops from an older schema, read through the changes made since. A model\n * or link a migration dropped drops the op; a dropped field drops the value;\n * renames are followed; a retyped value that no longer fits is dropped.\n */\nfunction evolveOps(ops: unknown[], changes: SchemaChange[]): unknown[] {\n if (changes.length === 0) return ops;\n const out: unknown[] = [];\n for (const raw of ops) {\n if (!isPlainRecord(raw) || typeof raw.namespace !== \"string\") {\n out.push(raw);\n continue;\n }\n const namespace = evolveModel(raw.namespace, changes);\n if (namespace === null) continue;\n const op: Record<string, unknown> = { ...raw, namespace };\n\n if (raw.op === \"link\" || raw.op === \"unlink\") {\n if (typeof raw.link === \"string\" && !(raw.link in LINKS)) {\n // Model-API link names are \"<model>.<field>\"; follow their renames.\n const [model, field] = raw.link.split(\".\");\n const evolved = field === undefined ? null : evolveField(model, field, changes);\n const owner = evolveModel(model, changes);\n if (evolved === null || owner === null) continue;\n op.link = `${owner}.${evolved.field}`;\n }\n out.push(op);\n continue;\n }\n\n for (const key of [\"values\", \"create\"] as const) {\n const values = raw[key];\n if (!isPlainRecord(values)) continue;\n const projected: Record<string, unknown> = {};\n for (const [attribute, value] of Object.entries(values)) {\n const evolved = evolveField(raw.namespace, attribute, changes);\n if (evolved === null) continue;\n if (evolved.retyped && !acceptsValue(namespace, evolved.field, value)) continue;\n projected[evolved.field] = value;\n }\n op[key] = projected;\n }\n out.push(op);\n }\n return out;\n}\n\nfunction insertChunk(\n sql: RecoverySqlExecutor,\n table: string,\n rows: RestorableRow[],\n allowedColumns: Set<string>\n): number {\n if (rows.length === 0) return 0;\n\n const columns = Object.keys(rows[0]).sort();\n const columnSet = new Set(columns);\n\n for (const row of rows) {\n const keys = Object.keys(row);\n if (keys.length !== columns.length) {\n throw new Error(\n `Snapshot rows for \"${table}\" have inconsistent column sets.`\n );\n }\n for (const key of keys) {\n if (!columnSet.has(key)) {\n throw new Error(\n `Snapshot rows for \"${table}\" have inconsistent column sets.`\n );\n }\n if (!allowedColumns.has(key)) {\n throw new Error(\n `Snapshot row for \"${table}\" contains unknown column \"${key}\".`\n );\n }\n }\n }\n\n const statement = `INSERT OR REPLACE INTO ${quoteTable(table)} (${columns\n .map(quoteIdentifier)\n .join(\", \")}) VALUES (${columns.map(() => \"?\").join(\", \")})`;\n\n for (const row of rows) {\n sql.exec(statement, ...columns.map((column) => row[column]));\n }\n\n return rows.length;\n}\n\nasync function restoreTable(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n table: ManifestTable & { sourceName?: string },\n allowedColumns: Set<string>,\n changes: SchemaChange[],\n progress: { index: number; done: number; pause: (unit: string) => void }\n): Promise<number> {\n let inserted = 0;\n\n for (const chunk of table.chunks) {\n // Chunks committed by an earlier, interrupted attempt stay committed.\n const index = progress.index;\n progress.index += 1;\n if (index < progress.done) continue;\n progress.pause(`chunk ${table.name} ${index}`);\n const object = await bucket.get(chunk.key);\n if (!object) {\n throw new Error(`Snapshot chunk ${chunk.key} is missing from R2.`);\n }\n\n const compressed = new Uint8Array(await object.arrayBuffer());\n\n if (compressed.byteLength !== chunk.bytes) {\n throw new Error(\n `Snapshot chunk ${chunk.key} is ${compressed.byteLength} bytes; manifest says ${chunk.bytes}.`\n );\n }\n\n const digest = await sha256Hex(compressed);\n if (digest.toLowerCase() !== chunk.sha256.toLowerCase()) {\n throw new Error(\n `Snapshot chunk ${chunk.key} failed checksum verification.`\n );\n }\n\n const rows = evolveRows(\n parseNdjson(textDecoder.decode(await gunzipBytes(compressed)), chunk.key),\n table.sourceName ?? table.name,\n changes\n );\n\n if (rows.length !== chunk.rows) {\n throw new Error(\n `Snapshot chunk ${chunk.key} has ${rows.length} rows; manifest says ${chunk.rows}.`\n );\n }\n\n const parentColumn = selfReferential()[table.name];\n const ordered =\n parentColumn === undefined ? rows : orderParentsFirst(rows, parentColumn);\n\n // The chunk and its checkpoint commit together.\n inserted += sql.transactionSync(() => {\n const count = insertChunk(sql, table.name, ordered, allowedColumns);\n setMeta(sql, \"recovery_chunks_done\", String(index + 1));\n return count;\n });\n }\n\n return inserted;\n}\n\nasync function restoreSnapshot(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n manifest: WorkspaceManifest,\n pause: (unit: string) => void\n): Promise<{ tables: number; rows: number }> {\n const changes = changesAfter(manifest.schemaVersion);\n const tables = orderedTables(manifest);\n let rows = 0;\n const progress = { index: 0, done: Number(getMeta(sql, \"recovery_chunks_done\") ?? 0), pause };\n\n for (const table of tables) {\n const columns = readColumns(sql, table.name);\n rows += await restoreTable(bucket, sql, table, columns, changes, progress);\n }\n\n return { tables: tables.length, rows };\n}\n\nfunction foreignKeyCheck(sql: RecoverySqlExecutor): void {\n const violations = sql\n .exec<Record<string, SqlValue>>(`PRAGMA foreign_key_check`)\n .toArray();\n\n if (violations.length === 0) return;\n\n const sample = violations\n .slice(0, 5)\n .map(\n (row) =>\n `${String(row.table)}#${String(row.rowid)} -> ${String(row.parent)}`\n )\n .join(\", \");\n\n throw new Error(\n `Foreign key check failed after restore (${violations.length} violation(s): ${sample}).`\n );\n}\n\nasync function listLogSegments(\n bucket: R2Bucket,\n workspaceId: string\n): Promise<LogSegmentRef[]> {\n const prefix = `${workspacePrefix(workspaceId)}/log/`;\n const objects = await listAllR2(bucket, prefix);\n const segments: LogSegmentRef[] = [];\n\n for (const object of objects) {\n const match = LOG_SEGMENT_NAME.exec(object.key.slice(prefix.length));\n if (!match) continue;\n\n const fromSeq = Number(match[1]);\n const toSeq = Number(match[2]);\n\n if (\n !Number.isSafeInteger(fromSeq) ||\n !Number.isSafeInteger(toSeq) ||\n toSeq < fromSeq\n ) {\n throw new Error(`Invalid log segment name \"${object.key}\".`);\n }\n\n segments.push({ key: object.key, fromSeq, toSeq });\n }\n\n return segments.sort((a, b) => a.fromSeq - b.fromSeq || a.toSeq - b.toSeq);\n}\n\nfunction parseLogLines(text: string, source: string): LogLine[] {\n const lines: LogLine[] = [];\n\n for (const [index, line] of text.split(\"\\n\").entries()) {\n if (line.length === 0) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(line) as unknown;\n } catch {\n throw new Error(`Invalid NDJSON in ${source} at line ${index + 1}.`);\n }\n\n if (!isPlainRecord(parsed)) {\n throw new Error(\n `Log line in ${source} at line ${index + 1} is not an object.`\n );\n }\n\n const seq = parsed.seq;\n const at = parsed.at;\n const ops = parsed.ops;\n\n if (typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0) {\n throw new Error(\n `Log line in ${source} at line ${index + 1} has an invalid seq.`\n );\n }\n if (typeof at !== \"number\" || !Number.isFinite(at)) {\n throw new Error(\n `Log line in ${source} at line ${index + 1} has an invalid timestamp.`\n );\n }\n const opsParts = parsed.opsParts;\n const inParts = typeof opsParts === \"number\" && Number.isSafeInteger(opsParts) && opsParts > 0;\n if (!Array.isArray(ops) || (ops.length === 0 && !inParts && !(typeof parsed.clientTxId === \"string\" && parsed.clientTxId.length > 0 && typeof parsed.opsHash === \"string\" && parsed.opsHash.length > 0))) {\n throw new Error(`Log line in ${source} at line ${index + 1} has no ops.`);\n }\n\n // The segment carries the idempotency key too, so recovery rebuilds\n // `_tx_log` instead of forgetting every transaction it restored. The\n // writer's identity is restored only when the deployment records an\n // audit (recordReplayedLine).\n const clientTxId = parsed.clientTxId;\n const opsHashValue = parsed.opsHash;\n const schemaVersion = parsed.schemaVersion;\n\n lines.push({\n seq,\n at,\n ops,\n ...(typeof clientTxId === \"string\" && clientTxId.length > 0\n ? { clientTxId }\n : {}),\n ...(typeof opsHashValue === \"string\" && opsHashValue.length > 0\n ? { opsHash: opsHashValue }\n : {}),\n schemaVersion:\n typeof schemaVersion === \"string\" ? schemaVersion : \"unknown\",\n ...(inParts ? { opsParts: opsParts as number } : {}),\n ...(typeof parsed.userId === \"string\" ? { userId: parsed.userId } : {}),\n ...(typeof parsed.role === \"number\" ? { role: parsed.role } : {}),\n });\n }\n\n return lines;\n}\n\nfunction targetFor(op: ValidatedOp): TargetRow {\n if (isBulkOp(op)) {\n // The log holds the rows a bulk write resolved, never the filter.\n throw new Error(`A log line holds an unresolved \"${op.kind}\".`);\n }\n if (isLinkOp(op)) {\n const child = findNamespace(op.childNamespace);\n if (!child) {\n throw new Error(`Unknown link child namespace \"${op.childNamespace}\".`);\n }\n return { table: child.table, id: op.childId };\n }\n\n const namespace = findNamespace(op.namespace);\n if (!namespace) {\n throw new Error(`Unknown namespace \"${op.namespace}\".`);\n }\n return { table: namespace.table, id: op.id };\n}\n\nfunction alreadyApplied(\n sql: RecoverySqlExecutor,\n target: TargetRow,\n seq: number,\n op: ValidatedOp\n): boolean {\n const row = sql\n .exec<UpdatedSeqRow>(\n `SELECT \"updated_seq\" FROM ${quoteTable(target.table)} WHERE \"id\" = ? LIMIT 1`,\n target.id\n )\n .toArray()[0];\n\n if (row === undefined) {\n // A delete that finds nothing has nothing left to do. A missing target for\n // any other op means the transaction was not applied yet.\n return op.kind === \"delete\";\n }\n\n return Number(row.updated_seq) >= seq;\n}\n\nfunction toTxSql(sql: RecoverySqlExecutor): TxSqlExecutor {\n return {\n exec(query, ...params) {\n const cursor = sql.exec(query, ...params) as SqlCursor<\n Record<string, SqlValue>\n > & { rowsWritten?: number };\n return cursor.rowsWritten ?? 1;\n },\n all<T extends TxSqlRow = TxSqlRow>(\n query: string,\n ...params: SqlValue[]\n ): T[] {\n return sql.exec<T>(query, ...params).toArray();\n },\n one<T extends TxSqlRow = TxSqlRow>(\n query: string,\n ...params: SqlValue[]\n ): T | undefined {\n return sql.exec<T>(query, ...params).toArray()[0];\n },\n transactionSync(fn) {\n return sql.transactionSync(fn);\n },\n };\n}\n\nfunction replayLine(\n sql: RecoverySqlExecutor,\n txSql: TxSqlExecutor,\n line: LogLine\n): boolean {\n // File-index entries are engine ops, not client transactions: they are\n // last-writer-wins on path, so applying them in order is the whole replay.\n if (isFileOpList(line.ops)) {\n recordReplayedLine(sql, line);\n applyFileOps(txSql, line.ops, line.at);\n return true;\n }\n\n if (line.ops.some(op => isPlainRecord(op) && (op.op === \"import:row\" || typeof op.op === \"string\" && op.op.startsWith(\"state:\") || op.op === \"import:begin\" || op.op === \"import:end\"))) {\n recordReplayedLine(sql, line);\n for (const raw of line.ops as Array<{ op: string; table: string; row: RestorableRow; id?: string }>) {\n if (raw.op === \"file:put\" || raw.op === \"file:forget\") { applyFileOps(txSql, [raw as never], line.at); continue; }\n if (raw.op === \"state:delete\") {\n const changes = changesAfter(line.schemaVersion), table = evolveTable(raw.table, changes);\n if (typeof raw.id !== \"string\") throw new Error(\"Invalid state deletion.\");\n if (table && namespaceTables().includes(table)) txSql.exec(`DELETE FROM \"${table}\" WHERE id = ? AND updated_seq <= ?`, raw.id, line.seq);\n continue;\n }\n if (raw.op !== \"import:row\" && raw.op !== \"state:row\") continue;\n const changes = changesAfter(line.schemaVersion);\n const table = evolveTable(raw.table, changes);\n if (table === null || !namespaceTables().includes(table)) continue;\n const row = evolveRows([raw.row], raw.table, changes)[0];\n const old = sql.exec<{ updated_seq: number }>(`SELECT updated_seq FROM \"${table}\" WHERE id = ?`, String(row.id)).toArray()[0];\n if (old && old.updated_seq >= line.seq) continue;\n const allowed = new Set(sql.exec<{ name: string }>(`PRAGMA table_info(\"${table}\")`).toArray().map(column => column.name));\n insertChunk(sql, table, [row], allowed);\n }\n return true;\n }\n\n const ops = evolveOps(expandLogOps(line.ops), changesAfter(line.schemaVersion));\n // Receipts survive even when a migration removed every referenced model.\n if (ops.length === 0) {\n recordReplayedLine(sql, line);\n return false;\n }\n const tx = validateEnvelope({ txId: \"recovery\", ops });\n const touched = new Set<string>();\n let applied = false;\n\n // Rebuild the local log as we replay, so `clientTxId` dedupe survives the\n // cold start for as long as the segments are retained. Without this the\n // engine forgets every transaction it just restored, and a client retrying\n // across an eviction re-applies its write.\n recordReplayedLine(sql, line);\n\n for (const op of tx.ops) {\n const target = targetFor(op);\n const key = `${target.table}:${target.id}`;\n\n if (!touched.has(key) && alreadyApplied(sql, target, line.seq, op)) {\n continue;\n }\n\n applyOps(\n {\n sql: txSql,\n seq: line.seq,\n now: line.at,\n txId: \"recovery\",\n replay: true,\n },\n [op]\n );\n\n touched.add(key);\n applied = true;\n }\n\n return applied;\n}\n\n/**\n * Writes one replayed segment line back into `_tx_log`.\n *\n * `ops_hash` is recomputed rather than carried in the segment: the segment\n * stores the ops themselves, and the hash is a canonical function of them, so\n * recomputing keeps the idempotency check byte-identical to the original\n * insert.\n */\nfunction recordReplayedLine(sql: RecoverySqlExecutor, line: LogLine): void {\n const ops = line.ops as readonly unknown[];\n if (line.clientTxId) {\n sql.exec(`INSERT OR IGNORE INTO \"_tx_receipts\" (id, seq, ops_hash, at) VALUES (?, ?, ?, ?)`,\n line.clientTxId, line.seq, line.opsHash ?? opsHash(ops), line.at);\n }\n\n sql.exec(\n `INSERT OR IGNORE INTO \"_tx_log\"\n (seq, client_tx_id, ops, ops_hash, user_id, role, at, schema_version)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n line.seq,\n line.clientTxId ?? null,\n stableStringify(ops),\n // Older segments carry no hash, so it is recomputed from the ops; a bulk\n // write's stored ops are the rows it resolved, whose hash is not the\n // client's, which is why newer segments carry the original.\n line.opsHash ?? opsHash(ops),\n auditEnabled() && typeof line.userId === \"string\" ? line.userId : null,\n auditEnabled() && typeof line.role === \"number\" ? line.role : null,\n line.at,\n line.schemaVersion ?? \"unknown\"\n );\n}\n\nfunction startsImport(ops: unknown[]): boolean {\n return isPlainRecord(ops[0]) && (ops[0].op === \"import:begin\" || ops[0].op === \"state:begin\");\n}\nasync function importForeignKeys(sql: RecoverySqlExecutor, enabled: boolean): Promise<void> {\n await sql.settle?.();\n sql.exec(`PRAGMA foreign_keys = ${enabled ? \"ON\" : \"OFF\"}`);\n}\n\nasync function replayLogs(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n txSql: TxSqlExecutor,\n workspaceId: string,\n baseSeq: number,\n logSeq: number,\n snapshotHasFiles: boolean,\n pause: (unit: string) => void\n): Promise<{ replayed: number; maxSeq: number }> {\n const segments = await listLogSegments(bucket, workspaceId);\n let replayed = 0;\n let maxSeq = 0;\n const done = Number(getMeta(sql, \"recovery_segments_done\") ?? 0);\n\n // A segment that is present in R2 is durable even when the manifest write\n // that would have advanced `logSeq` lost the ETag race (crash between the\n // segment PUT and the manifest PUT). The manifest is a lower bound, not the\n // authority: replay everything the listed segments can cover.\n const durableToSeq = segments.reduce(\n (max, segment) => Math.max(max, segment.toSeq),\n logSeq\n );\n\n for (const [index, segment] of segments.entries()) {\n // Segments an interrupted attempt finished; replaying them again would\n // be harmless (rows carry their seq), only slower.\n if (index < done) continue;\n if (segment.fromSeq > durableToSeq) continue;\n pause(`segment ${segment.fromSeq}-${segment.toSeq}`);\n\n const object = await bucket.get(segment.key);\n if (!object) {\n // A segment the snapshot already covers may have been pruned once it\n // fell outside the idempotency horizon. Rows are safe in the snapshot;\n // its keys are simply outside the retry window we promise.\n if (segment.toSeq <= baseSeq) continue;\n throw new Error(`Log segment ${segment.key} is missing from R2.`);\n }\n\n const lines = parseLogLines(await object.text(), segment.key);\n // Lines of this segment an earlier step finished, when it stopped\n // between the parts of a large entry.\n const linesDone = getMeta(sql, \"recovery_lines_done\")?.split(\":\").map(Number);\n const skipTo = linesDone !== undefined && linesDone[0] === index ? linesDone[1] : 0;\n const markLine = (seq: number) => setMeta(sql, \"recovery_lines_done\", `${index}:${seq}`);\n\n let pending: LogLine[] = [];\n let worked = false;\n const applyPending = () => sql.transactionSync(() => {\n const batch = pending;\n pending = [];\n if (batch.length > 0) worked = true;\n if (batch.length > 0) markLine(batch[batch.length - 1].seq);\n for (const line of batch) {\n // The snapshot already reflects everything at or below its base, so\n // those ops must not be applied again (a delete-then-insert history\n // would resurrect rows the snapshot correctly omits). Their\n // idempotency keys are another matter: the snapshot does not carry\n // them, so this line is the only copy left.\n if (line.seq <= baseSeq) {\n recordReplayedLine(sql, line);\n // Snapshots taken before the file index was snapshotted do not\n // hold it, so the segments are its only copy below the base. File\n // ops are last-writer-wins on path, so applying them is safe.\n if (!snapshotHasFiles && isFileOpList(line.ops)) {\n applyFileOps(txSql, line.ops, line.at);\n }\n continue;\n }\n\n maxSeq = Math.max(maxSeq, line.seq);\n if (line.ops.length === 0) recordReplayedLine(sql, line);\n else if (replayLine(sql, txSql, line)) replayed += 1;\n }\n });\n\n // Entries that write whole rows (imports, and every write to a model\n // with personal fields) are applied with foreign keys off, then checked.\n // Consecutive ones share one switch and one check: per entry, the two\n // storage syncs and a full check made a segment of them take minutes.\n let rowRun: LogLine[] = [];\n const applyRowRun = async () => {\n if (rowRun.length === 0) return;\n const run = rowRun;\n rowRun = [];\n worked = true;\n await importForeignKeys(sql, false);\n try {\n sql.transactionSync(() => {\n for (const line of run) replayLine(sql, txSql, line);\n markLine(run[run.length - 1].seq);\n });\n foreignKeyCheck(sql);\n } finally {\n await importForeignKeys(sql, true);\n }\n for (const line of run) maxSeq = Math.max(maxSeq, line.seq);\n replayed += run.length;\n };\n\n for (const line of lines) {\n if (line.seq <= skipTo) continue;\n // At or below the base there is nothing to apply, only the line to\n // record, which needs no switch.\n if (line.opsParts === undefined && line.seq > baseSeq && startsImport(line.ops)) {\n applyPending();\n rowRun.push(line);\n continue;\n }\n if (line.opsParts === undefined) {\n await applyRowRun();\n pending.push(line);\n continue;\n }\n applyPending();\n await applyRowRun();\n // Each entry stored in parts is read from R2 on its own: a unit, once\n // this step applied something (or a resumed step could not move on).\n if (worked) pause(`entry ${line.seq}`);\n worked = true;\n if (await replayParts(bucket, sql, txSql, workspaceId, line, baseSeq, pause)) replayed += 1;\n markLine(line.seq);\n if (line.seq > baseSeq) maxSeq = Math.max(maxSeq, line.seq);\n }\n applyPending();\n await applyRowRun();\n setMeta(sql, \"recovery_segments_done\", String(index + 1));\n }\n\n return { replayed, maxSeq };\n}\n\n/**\n * Replays an entry whose ops are in their own object, a part at a time: each\n * part is read from the stream, recorded in the local log (part 0 in the log\n * row, the rest in `_tx_log_parts`) and, above the snapshot base, applied, in\n * its own transaction. Applying a row is idempotent, so a recovery cut off\n * between parts finishes them on the next attempt.\n */\nasync function replayParts(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n txSql: TxSqlExecutor,\n workspaceId: string,\n line: LogLine,\n baseSeq: number,\n pause: (unit: string) => void\n): Promise<boolean> {\n const object = await bucket.get(logOpsKey(workspaceId, line.seq));\n if (!object) throw new Error(`The ops of log entry ${line.seq} are missing from R2.`);\n // Parts an earlier step applied: each commits with its progress.\n const progress = getMeta(sql, \"recovery_entry_parts\")?.split(\":\").map(Number);\n const done = progress !== undefined && progress[0] === line.seq ? progress[1] : 0;\n let part = 0;\n let appliedHere = 0;\n let applied = false;\n let importing = false;\n if (done > 0) {\n const first = sql.exec<{ ops: string }>(`SELECT ops FROM \"_tx_log\" WHERE seq = ?`, line.seq).toArray()[0];\n if (first && line.seq > baseSeq && startsImport(JSON.parse(first.ops) as unknown[])) { importing = true; await importForeignKeys(sql, false); }\n }\n try {\n for await (const text of objectLines(object)) {\n const current = part;\n part += 1;\n if (current < done) continue;\n // Between parts a step may stop, once it applied one here. A whole-row\n // entry switches its foreign keys back on when it stops and off again\n // when it resumes; its check runs once, after its last part. Nothing is\n // served in between: the workspace answers 503 until the restore ends.\n if (appliedHere > 0) pause(`entry ${line.seq} part ${current}`);\n appliedHere += 1;\n const ops = JSON.parse(text) as unknown[];\n if (current === 0 && line.seq > baseSeq && startsImport(ops)) { importing = true; await importForeignKeys(sql, false); }\n sql.transactionSync(() => {\n if (current === 0) recordReplayedLine(sql, { ...line, ops });\n else sql.exec(`INSERT OR IGNORE INTO \"_tx_log_parts\" (seq, part, ops) VALUES (?, ?, ?)`, line.seq, current, text);\n if (line.seq > baseSeq && ops.length > 0 && replayLine(sql, txSql, { ...line, ops })) applied = true;\n setMeta(sql, \"recovery_entry_parts\", `${line.seq}:${current + 1}`);\n });\n }\n if (importing) foreignKeyCheck(sql);\n } finally { if (importing) await importForeignKeys(sql, true); }\n if (part !== line.opsParts) {\n throw new Error(`Log entry ${line.seq} has ${part} parts in R2; its segment says ${line.opsParts}.`);\n }\n return applied;\n}\n\n/** An object's lines, read from its body stream without holding it whole. */\nasync function* objectLines(object: R2ObjectBody): AsyncGenerator<string> {\n const reader = object.body.pipeThrough(new TextDecoderStream()).getReader();\n let buffered = \"\";\n let finished = false;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffered += value;\n let newline = buffered.indexOf(\"\\n\");\n while (newline !== -1) {\n const lineText = buffered.slice(0, newline);\n buffered = buffered.slice(newline + 1);\n if (lineText.length > 0) yield lineText;\n newline = buffered.indexOf(\"\\n\");\n }\n }\n if (buffered.length > 0) yield buffered;\n finished = true;\n } finally {\n // A step that stops between parts leaves the rest of the body unread.\n if (!finished) await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction writeFinalState(\n sql: RecoverySqlExecutor,\n manifest: WorkspaceManifest,\n maxReplayedSeq: number,\n now: number\n): void {\n const highWater = Math.max(manifest.logSeq, maxReplayedSeq);\n\n sql.exec(\n `INSERT OR IGNORE INTO \"_tx_state\" (\"id\", high_water_seq) VALUES (1, 0)`\n );\n sql.exec(\n `UPDATE \"_tx_state\" SET high_water_seq = ? WHERE \"id\" = 1`,\n highWater\n );\n\n sql.exec(\n `INSERT OR IGNORE INTO \"_flush_state\"\n (id, last_seq, attempts, updated_at)\n VALUES (1, 0, 0, ?)`,\n now\n );\n sql.exec(\n `UPDATE \"_flush_state\"\n SET last_seq = MAX(last_seq, ?), attempts = 0, next_attempt_at = NULL,\n last_error = NULL, updated_at = ?\n WHERE id = 1`,\n manifest.logSeq,\n now\n );\n\n sql.exec(\n `INSERT OR IGNORE INTO \"_snapshot_state\"\n (id, base_seq, status)\n VALUES (1, ?, 'completed')`,\n manifest.baseSeq\n );\n sql.exec(\n `UPDATE \"_snapshot_state\"\n SET base_seq = ?, status = 'completed', started_at = ?,\n completed_at = ?, manifest_key = ?\n WHERE id = 1`,\n manifest.baseSeq,\n now,\n now,\n manifestKey(manifest.workspaceId)\n );\n}\n\n/**\n * Rebuilds `workspaceId` from its R2 manifest, snapshot chunks and log\n * segments.\n *\n * Returns `{ recovered: false, reason }` when there is no manifest or when the\n * workspace already has entity rows and `force` is not set. On a restore or\n * replay failure the `_engine_meta` recovery marker is left as `failed` with\n * the error text and the error is rethrown, so the caller can fail the boot.\n */\nexport async function recoverWorkspace(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n workspaceId: string,\n options: RecoverWorkspaceOptions = {}\n): Promise<RecoveryResult> {\n const now = options.now ?? Date.now();\n bucket = resumableReads(bucket);\n // Every call does at least one chunk or segment, so a slow first read can\n // never keep a recovery from moving forward.\n let started = false;\n const pause = (unit: string) => {\n options.onUnit?.(unit);\n const first = !started;\n started = true;\n if (first) return;\n if (options.shouldPause?.() ?? (options.deadline !== undefined && Date.now() >= options.deadline)) {\n throw new RecoveryPaused();\n }\n };\n\n // A run that was cut off (a reset past the boot's 30 s, an eviction, a\n // crash) left \"running\" behind with its progress: resume it. Its rows are\n // partial, so they never count as a populated workspace. Neither do the\n // rows of a run that failed: the workspace never served them.\n const status = getMeta(sql, \"recovery_status\");\n const interrupted = status === \"running\" || status === \"failed\";\n const pinned = interrupted ? getMeta(sql, \"recovery_manifest\") : undefined;\n if (pinned !== undefined) {\n return runRecovery(bucket, sql, workspaceId, JSON.parse(pinned) as WorkspaceManifest, now, pause);\n }\n if (interrupted) {\n // Failed, or cut off by a version that kept no progress: start over.\n try {\n sql.exec(\"PRAGMA foreign_keys = OFF\");\n } catch {\n // Children are deleted first either way.\n }\n clearRestoredRows(sql);\n }\n\n // A normal boot must not touch R2. Only a genuinely fresh DO is a recovery\n // candidate: no entity rows AND no local write history. A workspace that\n // deliberately emptied its tables still owns that state, and restoring it\n // would resurrect deleted rows and rewind `_tx_state`.\n if (!options.force && !interrupted && (hasEntityRows(sql) || hasWriteHistory(sql))) {\n return { recovered: false, reason: \"already_populated\" };\n }\n\n const stored = await readManifest(bucket, workspaceId);\n if (!stored) {\n return { recovered: false, reason: \"no_manifest\" };\n }\n\n if (stored.manifest.workspaceId !== workspaceId) {\n throw new Error(\n `Manifest for workspace ${stored.manifest.workspaceId} cannot restore ${workspaceId}.`\n );\n }\n // Chunk keys keep the table names of the schema the snapshot was taken\n // under, so they are checked first; the rows then restore into today's\n // tables. A table a later migration dropped is skipped.\n validateManifestTables(stored.manifest);\n const changes = changesAfter(stored.manifest.schemaVersion);\n const manifest: WorkspaceManifest = {\n ...stored.manifest,\n tables: stored.manifest.tables.flatMap((table) => {\n const current = evolveTable(table.name, changes);\n return current === null ? [] : [{ ...table, name: current, sourceName: table.name }];\n }),\n };\n\n // Drop any stale log rows before replaying. The replay rebuilds `_tx_log`\n // from the durable segments, so a row here belongs to a database that is\n // about to be replaced. The manifest is pinned, so every resumed step\n // restores the same snapshot.\n sql.transactionSync(() => {\n markRunning(sql, now);\n sql.exec(`DELETE FROM \"_tx_log\"`);\n sql.exec(`DELETE FROM \"_tx_log_parts\"`);\n sql.exec(`DELETE FROM \"_tx_receipts\"`);\n sql.exec(`DELETE FROM \"_tx_audit\"`);\n setMeta(sql, \"recovery_manifest\", JSON.stringify(manifest));\n setMeta(sql, \"recovery_phase\", \"restore\");\n setMeta(sql, \"recovery_chunks_done\", \"0\");\n setMeta(sql, \"recovery_segments_done\", \"0\");\n });\n return runRecovery(bucket, sql, workspaceId, manifest, now, pause);\n}\n\n/** Restore, then replay, from wherever an earlier attempt got to. */\nasync function runRecovery(\n bucket: R2Bucket,\n sql: RecoverySqlExecutor,\n workspaceId: string,\n manifest: WorkspaceManifest,\n now: number,\n pause: (unit: string) => void\n): Promise<RecoveryResult> {\n try {\n // Foreign keys are disabled for the restore so chunk order cannot break\n // self-references; `PRAGMA foreign_key_check` below is the safety net.\n // When the pragma cannot change (for example inside an outer transaction)\n // `RESTORE_ORDER` and `orderParentsFirst` keep the restore valid.\n try {\n sql.exec(\"PRAGMA foreign_keys = OFF\");\n } catch {\n // Fall back to dependency ordering.\n }\n\n let restored: { tables: number; rows: number } = { tables: manifest.tables.length, rows: 0 };\n try {\n if (getMeta(sql, \"recovery_phase\") !== \"replay\") {\n restored = await restoreSnapshot(bucket, sql, manifest, pause);\n foreignKeyCheck(sql);\n setMeta(sql, \"recovery_phase\", \"replay\");\n }\n } finally {\n try {\n sql.exec(\"PRAGMA foreign_keys = ON\");\n } catch {\n // The caller owns the connection; nothing else we can do here.\n }\n }\n\n const txSql = toTxSql(sql);\n const replay = await replayLogs(\n bucket,\n sql,\n txSql,\n workspaceId,\n manifest.baseSeq,\n manifest.logSeq,\n manifest.tables.some((table) => table.name === ENGINE_TABLES.files),\n pause\n );\n // Lines replayed by earlier attempts count too.\n const replayedTo = Number(\n sql.exec<{ seq: number | null }>(`SELECT MAX(seq) AS seq FROM \"_tx_log\" WHERE seq > ?`, manifest.baseSeq).toArray()[0]?.seq ?? 0\n );\n\n // Older snapshots may omit receipts or contain ones whose siblings were\n // expired. Carry their safety boundary through every later snapshot.\n const incomplete = manifest.baseSeq > 0 && (\n manifest.receiptFloor === undefined ||\n !manifest.tables.some((table) => table.name === ENGINE_TABLES.txReceipts)\n );\n const floor = Math.max(readReceiptFloor(sql), manifest.receiptFloor ?? 0, incomplete ? now : 0);\n\n // Bookkeeping and the success marker commit together so the workspace can\n // never look caught up while its sequence state is only half written.\n sql.transactionSync(() => {\n writeFinalState(sql, manifest, Math.max(replay.maxSeq, replayedTo), now);\n // Receipts without a stored timestamp take the restore time.\n sql.exec(`UPDATE \"_tx_receipts\" SET at = ? WHERE at = 0`, now);\n // Written by engines that tracked missing receipts; nothing reads it.\n sql.exec(`DELETE FROM \"_engine_meta\" WHERE \"key\" = 'dedupe_floor_seq'`);\n sql.exec(`UPDATE \"_tx_receipts\" SET ops_hash = NULL WHERE ops_hash IS NOT NULL AND at <= ?`, now - historyAgeLimit(historyRetentionMs()));\n sql.exec(`INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES ('receipts_since', ?)`, String(floor));\n markComplete(sql, manifest, now);\n });\n\n if (incomplete) {\n console.warn(\"workspace_recovered_without_complete_receipts\", { workspaceId, baseSeq: manifest.baseSeq });\n }\n\n return {\n recovered: true,\n baseSeq: manifest.baseSeq,\n logSeq: manifest.logSeq,\n tables: restored.tables,\n rows: restored.rows,\n replayed: replay.replayed,\n ...(incomplete\n ? {\n warnings: [\n `The snapshot does not guarantee complete transaction receipts: unknown retries first issued before this restore are refused as retry_expired.`,\n ],\n }\n : {}),\n };\n } catch (error) {\n if (error instanceof RecoveryPaused) {\n // Progress is committed; the next call resumes.\n return { recovered: false, reason: \"paused\" };\n }\n if (error instanceof R2Unavailable) {\n return { recovered: false, reason: \"unavailable\", error: error.message };\n }\n try {\n markFailed(sql, now, error);\n } catch {\n // Preserve the restore/replay error even if the marker cannot be written.\n }\n try {\n // Leave no half-restored dataset behind: without this the next boot sees\n // rows, reports `already_populated`, and serves a systematically\n // incomplete workspace forever.\n clearRestoredRows(sql);\n } catch {\n // Preserve the original failure; the retry will fail the same way.\n }\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n","/**\n * Adapts a Durable Object's storage to the recovery SQL contract.\n *\n * `DurableObjectStorage.sql` provides the query cursor surface and\n * `DurableObjectStorage.transactionSync` provides the transaction primitive;\n * recovery needs both on one object.\n */\n\nimport { fitBindings } from \"../sql-binding\";\nimport type { RecoverySqlExecutor } from \"./recovery\";\nimport type { SqlValue } from \"./sql\";\n\nexport function durableObjectRecoverySqlExecutor(\n storage: DurableObjectStorage\n): RecoverySqlExecutor {\n return {\n settle: async () => { await storage.sync?.(); },\n exec<T extends Record<string, SqlValue>>(\n query: string,\n ...bindings: SqlValue[]\n ) {\n const fitted = fitBindings(query, bindings);\n return storage.sql.exec<T>(fitted.sql, ...fitted.params);\n },\n transactionSync<T>(fn: () => T): T {\n return storage.transactionSync(fn);\n },\n };\n}\n","import { BASELINE_MIGRATION_ID, isEngineMigration } from \"./migrations-bundle\";\nimport {\n WORKSPACE_MIGRATIONS,\n type BundledWorkspaceMigration,\n} from \"./migrations-bundle\";\n\nexport const MIGRATIONS_TABLE_SQL = `\nCREATE TABLE IF NOT EXISTS \"_migrations\" (\n id TEXT PRIMARY KEY NOT NULL,\n checksum TEXT NOT NULL,\n applied_at INTEGER NOT NULL\n)\n`;\n\nexport interface AppliedMigration {\n id: string;\n checksum: string;\n}\n\nexport function migrationIds(\n migrations: ReadonlyArray<BundledWorkspaceMigration> = WORKSPACE_MIGRATIONS\n): string[] {\n return migrations.map((migration) => migration.id);\n}\n\nexport function pendingMigrations(\n applied: ReadonlySet<string>,\n migrations: ReadonlyArray<BundledWorkspaceMigration> = WORKSPACE_MIGRATIONS\n): BundledWorkspaceMigration[] {\n return migrations.filter((migration) => !applied.has(migration.id));\n}\n\nexport function assertMigrationOrder(\n migrations: ReadonlyArray<BundledWorkspaceMigration> = WORKSPACE_MIGRATIONS\n): void {\n if (migrations.length === 0) {\n throw new Error(\"No workspace migrations are bundled.\");\n }\n\n if (migrations[0].id !== BASELINE_MIGRATION_ID) {\n throw new Error(`The first workspace migration must be ${BASELINE_MIGRATION_ID}.`);\n }\n\n // Each track is sorted on its own; the engine track comes first.\n const seen = new Set<string>();\n const previous = { engine: \"\", app: \"\" };\n let appStarted = false;\n for (const migration of migrations) {\n if (!/^(tapedb_)?\\d{4}_[a-z0-9_]+$/.test(migration.id)) {\n throw new Error(`Invalid workspace migration id \"${migration.id}\".`);\n }\n if (seen.has(migration.id)) {\n throw new Error(`Duplicate workspace migration id \"${migration.id}\".`);\n }\n const track = isEngineMigration(migration.id) ? \"engine\" : \"app\";\n if (track === \"engine\" && appStarted) {\n throw new Error(`Engine migration \"${migration.id}\" must come before app migrations.`);\n }\n if (track === \"app\") appStarted = true;\n if (previous[track] && migration.id <= previous[track]) {\n throw new Error(\n `Workspace migrations must be sorted; \"${migration.id}\" follows \"${previous[track]}\".`\n );\n }\n seen.add(migration.id);\n previous[track] = migration.id;\n }\n}\n\nexport function latestMigrationId(\n migrations: ReadonlyArray<BundledWorkspaceMigration> = WORKSPACE_MIGRATIONS\n): string | null {\n return migrations.length > 0 ? migrations[migrations.length - 1].id : null;\n}\n\nexport async function migrationChecksum(sql: string): Promise<string> {\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(sql)\n );\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * What applying a migration needs from the database it runs on. `settle`\n * resolves once no transaction is open: SQLite ignores a foreign-key pragma\n * inside one, and a Durable Object holds an implicit one after any write\n * until its writes are synced.\n */\nexport interface MigrationHost {\n /** Runs one or more statements. */\n run(statements: string): void;\n /** Runs one statement and returns its rows. */\n all(query: string): Array<Record<string, unknown>>;\n transaction(fn: () => void): void;\n settle(): Promise<void>;\n}\n\nfunction foreignKeysOn(host: MigrationHost): boolean {\n return Number(host.all(\"PRAGMA foreign_keys\")[0]?.foreign_keys) === 1;\n}\n\n/**\n * Applies one migration the way SQLite documents for schema changes: foreign\n * keys off around the transaction, `foreign_key_check` before it commits,\n * foreign keys back on after.\n *\n * Off is what lets a migration rebuild a table other tables reference. With\n * foreign keys on, dropping the old copy of the table would run every\n * child's ON DELETE action, cascading deletes into child rows or nulling\n * their keys, before the rebuilt table took its place. The check is what\n * keeps that safe: a migration that would leave a row pointing at nothing\n * rolls back, and the object refuses to boot rather than serve it.\n *\n * Throws, without serving with enforcement off, if foreign keys cannot be\n * switched back on.\n */\nexport async function applyMigrationWithoutCascades(\n host: MigrationHost,\n migration: BundledWorkspaceMigration,\n record: () => void\n): Promise<void> {\n await host.settle();\n host.run(\"PRAGMA foreign_keys = OFF\");\n if (foreignKeysOn(host)) {\n throw new Error(\n `Workspace migration ${migration.id} was not applied: foreign keys could not be switched off around it, so a table rebuild could cascade.`\n );\n }\n\n try {\n host.transaction(() => {\n host.run(migration.sql);\n record();\n const violations = host.all(\"PRAGMA foreign_key_check\");\n if (violations.length > 0) {\n const first = violations[0];\n throw new Error(\n `Workspace migration ${migration.id} was not applied: it leaves ${violations.length} row(s) pointing at rows that do not exist (first: \"${String(first.table)}\" row ${String(first.rowid)} -> \"${String(first.parent)}\").`\n );\n }\n });\n } finally {\n await host.settle();\n host.run(\"PRAGMA foreign_keys = ON\");\n }\n\n if (!foreignKeysOn(host)) {\n throw new Error(\"Foreign keys could not be switched back on after a migration; refusing to serve without them.\");\n }\n}\n","/**\n * Live-query invalidation and diffing.\n *\n * The workspace DO keeps one subscription per client query. After a commit we\n * derive the namespaces a transaction touched, re-run only the subscriptions\n * whose compiled query references one of them, and push the smallest update\n * that is safe.\n *\n * Diffs are per top-level namespace and entity-level: an `updated` entity is\n * the full new entity, including any nested linked data that changed. This is\n * deliberate — nested arrays/objects do not have a stable identity contract,\n * so diffing them field by field would be guesswork.\n *\n * `removed` is a list of entity ids; `added` and `updated` carry full entities.\n */\n\nimport type { CompiledNode, CompiledQuery } from \"./query-compile\";\nimport type { QueryResult } from \"./query-types\";\nimport {\n findNamespace,\n LINKS,\n NAMESPACES,\n type LinkDefinition,\n} from \"./registry\";\nimport { stableStringify } from \"./tx-hash\";\n\n/** One flush per namespace every 50ms gives the plan's ~20 re-runs/second. */\nexport const DEFAULT_INVALIDATION_DEBOUNCE_MS = 50;\n\n/**\n * Minimal shape accepted by `touchedNamespaces`. Validated ops expose `kind`,\n * while raw wire ops expose `op`; both are accepted so the room can derive\n * invalidation from the envelope it already parsed.\n */\nexport interface TouchableOp {\n namespace?: unknown;\n kind?: unknown;\n op?: unknown;\n link?: unknown;\n childNamespace?: unknown;\n}\n\nexport interface EntityDiff {\n added: unknown[];\n /** Full replacement entities; nested changes are entity-level. */\n updated: unknown[];\n /** Ids that disappeared from the result. */\n removed: string[];\n /**\n * Every id of the new result in order, when applying the diff the simple\n * way — survivors keep their places, `added` is appended — would not\n * reproduce it.\n */\n order?: string[];\n}\n\nexport interface NamespaceDiff extends EntityDiff {\n namespace: string;\n}\n\n/**\n * Namespaces whose content a transaction touched.\n *\n * `update`/`merge`/`delete` touch their own namespace. `link`/`unlink` write\n * the child's foreign key, so they touch both the op namespace and the\n * namespace that owns the FK.\n */\n/**\n * Namespaces the database rewrites when rows of `namespace` are deleted.\n *\n * A `CASCADE` removes child rows and a `SET NULL` clears their foreign key, so\n * a subscriber to the child namespace sees its data change even though no op\n * ever named it. Resolved transitively: folders -> documents -> blocks.\n */\nexport function dependentNamespaces(namespace: string): Set<string> {\n const dependents = new Set<string>();\n const queue = [namespace];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n const target = findNamespace(current);\n if (!target) continue;\n\n for (const [apiName, definition] of Object.entries(NAMESPACES)) {\n if (apiName === current || dependents.has(apiName)) continue;\n\n const references = Object.values(definition.attributes).some(\n (attribute) =>\n attribute.references?.table === target.table &&\n attribute.references.onDelete !== \"RESTRICT\"\n );\n if (!references) continue;\n\n dependents.add(apiName);\n queue.push(apiName);\n }\n }\n\n return dependents;\n}\n\nexport function touchedNamespaces(ops: readonly TouchableOp[]): Set<string> {\n const touched = new Set<string>();\n\n for (const op of ops) {\n if (typeof op.namespace === \"string\" && op.namespace.length > 0) {\n touched.add(op.namespace);\n }\n\n const kind = typeof op.kind === \"string\" ? op.kind : op.op;\n\n // Deleting a row rewrites FK-dependent rows, so their namespaces must be\n // invalidated too or subscribers keep stale children forever.\n if (kind === \"delete\" && typeof op.namespace === \"string\") {\n for (const dependent of dependentNamespaces(op.namespace)) {\n touched.add(dependent);\n }\n }\n\n if (kind !== \"link\" && kind !== \"unlink\") continue;\n\n if (typeof op.childNamespace === \"string\" && op.childNamespace.length > 0) {\n touched.add(op.childNamespace);\n }\n\n if (typeof op.link === \"string\") {\n const link = (LINKS as Record<string, LinkDefinition>)[op.link];\n if (link) touched.add(link.foreignKey.namespace);\n }\n }\n\n return touched;\n}\n\n/** Reads `ops` from a validated transaction envelope. */\nexport function touchedNamespacesFromEnvelope(envelope: unknown): Set<string> {\n if (!isRecord(envelope) || !Array.isArray(envelope.ops)) {\n return new Set();\n }\n\n return touchedNamespaces(envelope.ops.filter(isRecord));\n}\n\n/**\n * True when any node of the compiled query — top-level or nested traversal —\n * reads one of the touched namespaces, as rows or through a relation filter.\n */\nexport function queryMatchesTouched(\n compiled: CompiledQuery,\n touched: ReadonlySet<string>\n): boolean {\n if (touched.size === 0) return false;\n\n const visit = (node: CompiledNode): boolean =>\n touched.has(node.namespace) ||\n (node.references ?? []).some((namespace) => touched.has(namespace)) ||\n node.children.some((child) => visit(child.node));\n\n return compiled.nodes.some(visit);\n}\n\n/** True when the compiled query references `namespace` at any depth. */\nexport function queryReferencesNamespace(\n compiled: CompiledQuery,\n namespace: string\n): boolean {\n const visit = (node: CompiledNode): boolean =>\n node.namespace === namespace ||\n (node.references ?? []).includes(namespace) ||\n node.children.some((child) => visit(child.node));\n\n return compiled.nodes.some(visit);\n}\n\n/**\n * Compares two entity lists by id.\n *\n * Returns `null` when the payload is not a list of uniquely identified\n * entities; callers then send a full `query:data` payload instead of a diff.\n */\n/**\n * Each entity's canonical JSON, computed once per object. A result object is\n * the next flush's previous result, and identical subscriptions share one, so\n * without this every entity was serialised twice per subscriber per flush.\n */\nconst entityJson = new WeakMap<object, string>();\n\nfunction canonical(entity: unknown): string {\n if (typeof entity !== \"object\" || entity === null) return stableStringify(entity);\n let json = entityJson.get(entity);\n if (json === undefined) {\n json = stableStringify(entity);\n entityJson.set(entity, json);\n }\n return json;\n}\n\nexport function diffEntityList(\n previous: unknown,\n next: unknown\n): EntityDiff | null {\n const previousById = indexEntities(previous);\n const nextById = indexEntities(next);\n if (previousById === null || nextById === null) return null;\n\n const added: unknown[] = [];\n const updated: unknown[] = [];\n const removed: string[] = [];\n\n for (const [id, entity] of nextById) {\n const before = previousById.get(id);\n if (before === undefined) {\n added.push(entity);\n continue;\n }\n if (canonical(before) !== canonical(entity)) {\n updated.push(entity);\n }\n }\n\n for (const id of previousById.keys()) {\n if (!nextById.has(id)) removed.push(id);\n }\n\n const nextIds = [...nextById.keys()];\n const merged = [\n ...[...previousById.keys()].filter((id) => nextById.has(id)),\n ...added.map((entity) => (entity as { id: string }).id),\n ];\n const inPlace = merged.every((id, index) => id === nextIds[index]);\n\n return inPlace ? { added, updated, removed } : { added, updated, removed, order: nextIds };\n}\n\n/**\n * Diffs every top-level namespace in a query result.\n *\n * Returns `null` when a namespace is missing from either side or when its\n * value cannot be indexed by entity id, so the caller falls back to full data.\n * Returns an empty array when both results are identical.\n */\nexport function diffQueryResults(\n previous: QueryResult,\n next: QueryResult\n): NamespaceDiff[] | null {\n const namespaces = new Set([...Object.keys(previous), ...Object.keys(next)]);\n\n const diffs: NamespaceDiff[] = [];\n\n for (const namespace of namespaces) {\n const before = previous[namespace];\n const after = next[namespace];\n // A query's top-level namespace set is fixed. A difference means the\n // result shape changed underneath us; do not risk a partial diff.\n if (before === undefined || after === undefined) return null;\n\n const diff = diffEntityList(before, after);\n if (diff === null) return null;\n\n if (diff.added.length + diff.updated.length + diff.removed.length > 0 || diff.order) {\n diffs.push({ namespace, ...diff });\n }\n }\n\n return diffs;\n}\n\nfunction indexEntities(value: unknown): Map<string, unknown> | null {\n if (!Array.isArray(value)) return null;\n\n const entities = new Map<string, unknown>();\n for (const entity of value) {\n if (!isRecord(entity)) return null;\n\n const id = entity.id;\n if (typeof id !== \"string\" || id.length === 0) return null;\n // Duplicate ids make \"updated\" ambiguous, so refuse to diff.\n if (entities.has(id)) return null;\n\n entities.set(id, entity);\n }\n\n return entities;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/** R2 file operations run inside the owning room's tracked request. */\nimport { WORKSPACE_ROLE_LEVELS } from \"../claims\";\nimport { apiError, discardBody, json } from \"../http\";\nimport type { Env } from \"../types\";\nimport { fileRulesConfigured } from \"./file-access\";\nimport { filesPrefix } from \"./r2-keys\";\n\nexport const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;\nexport type StorageDispatch = (env: Env, workspaceId: string, path: string, init: RequestInit, trustedClaim: string) => Promise<Response>;\n\n/** Metadata dispatch is local to the same room, never another binding fetch. */\nexport function storageHandler(callRoom: StorageDispatch) {\n function storageKey(workspaceId: string, objectKey: string): string {\n return `${filesPrefix(workspaceId)}${objectKey}`;\n }\n/**\n * Reads a request body without ever holding more than `limit` bytes. A\n * content-length check is not enough: a chunked request can omit or lie about\n * it, and buffering the whole body first would turn an oversized upload into a\n * Worker memory problem.\n */\nasync function readBodyWithinLimit(\n request: Request,\n limit: number\n): Promise<Uint8Array | null> {\n if (request.body === null) return new Uint8Array();\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n total += value.byteLength;\n if (total > limit) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Records stored bytes in the workspace's file index. A failure is reported\n * rather than swallowed, and the bytes are taken back out: an object nobody\n * can list is an orphan that costs storage forever. If that delete fails too,\n * the 502 still tells the caller to retry, and a retry overwrites the key.\n */\nasync function recordUpload(\n env: Env,\n bucket: R2Bucket,\n workspaceId: string,\n objectKey: string,\n key: string,\n size: number,\n contentType: string,\n trustedClaim: string\n): Promise<Response> {\n let recorded: Response;\n try { recorded = await callRoom(\n env,\n workspaceId,\n \"/files\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ path: objectKey, key, size, contentType }),\n },\n trustedClaim\n ); } catch {\n try { await bucket.delete(key); } catch { /* Erasure also removes unindexed versions. */ }\n return apiError(502, \"file_index_failed\", \"Could not record the upload in the workspace index.\");\n }\n if (!recorded.ok) {\n try {\n await bucket.delete(key);\n } catch {\n // Best effort.\n }\n if (recorded.status === 403) return recorded;\n return apiError(502, \"file_index_failed\", \"Could not record the upload in the workspace index; nothing was stored.\");\n }\n const indexed = await recorded.json() as { previousKey?: string };\n if (indexed.previousKey && indexed.previousKey !== key) await bucket.delete(indexed.previousKey);\n return json({ key, size }, 201);\n}\n\n/**\n * Uploads of any size, as R2 multipart uploads on the file's own URL:\n *\n * - `POST ?uploads` starts one (the request's content type is the file's)\n * and answers `{ uploadId }`.\n * - `PUT ?uploadId=…&partNumber=n` stores part n (1-10000), at most\n * `MAX_UPLOAD_BYTES`; every part but the last must be at least 5 MiB, and\n * all but the last the same size. Answers `{ partNumber, etag }`.\n * - `POST ?uploadId=…` with `{ parts: [{ partNumber, etag }] }` completes it\n * and records the file in the index, like a single PUT.\n * - `DELETE ?uploadId=…` abandons it; R2 also drops unfinished ones itself.\n *\n * Nothing is listed until the upload completes.\n */\nasync function handleMultipart(\n request: Request,\n env: Env,\n bucket: R2Bucket,\n workspaceId: string,\n objectKey: string,\n key: string,\n query: URLSearchParams,\n trustedClaim: string\n): Promise<Response> {\n if (request.method === \"POST\" && query.has(\"uploads\")) {\n await discardBody(request);\n const contentType = request.headers.get(\"content-type\") ?? \"application/octet-stream\";\n const version = crypto.randomUUID();\n const upload = await bucket.createMultipartUpload(`${key}/.tapedb/${version}`, { httpMetadata: { contentType } });\n return json({ uploadId: `${version}:${upload.uploadId}` }, 201);\n }\n\n const uploadId = query.get(\"uploadId\");\n if (!uploadId) {\n await discardBody(request);\n return apiError(400, \"invalid_upload\", \"A multipart request needs ?uploads or ?uploadId=.\");\n }\n const separator = uploadId.indexOf(\":\");\n if (separator >= 0 && /^[0-9a-f-]{36}$/.test(uploadId.slice(0, separator))) {\n key = `${key}/.tapedb/${uploadId.slice(0, separator)}`;\n }\n const upload = bucket.resumeMultipartUpload(key, separator >= 0 ? uploadId.slice(separator + 1) : uploadId);\n\n try {\n if (request.method === \"PUT\") {\n const partNumber = Number(query.get(\"partNumber\"));\n if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 10_000) {\n await discardBody(request);\n return apiError(400, \"invalid_upload\", \"partNumber must be an integer from 1 to 10000.\");\n }\n const body = await readBodyWithinLimit(request, MAX_UPLOAD_BYTES);\n if (body === null) {\n return apiError(413, \"upload_too_large\", `A part is at most ${MAX_UPLOAD_BYTES} bytes; send the file in more parts.`);\n }\n const part = await upload.uploadPart(partNumber, body);\n return json({ partNumber: part.partNumber, etag: part.etag });\n }\n\n if (request.method === \"POST\") {\n const input = (await request.json().catch(() => null)) as { parts?: unknown } | null;\n const parts = Array.isArray(input?.parts) ? input.parts : null;\n if (\n parts === null ||\n parts.length === 0 ||\n !parts.every(\n (part) =>\n typeof part === \"object\" &&\n part !== null &&\n Number.isInteger((part as { partNumber?: unknown }).partNumber) &&\n typeof (part as { etag?: unknown }).etag === \"string\"\n )\n ) {\n return apiError(400, \"invalid_upload\", \"Completing an upload needs { parts: [{ partNumber, etag }] }.\");\n }\n const object = await upload.complete(parts as R2UploadedPart[]);\n const contentType = object.httpMetadata?.contentType ?? \"application/octet-stream\";\n return recordUpload(env, bucket, workspaceId, objectKey, key, object.size, contentType, trustedClaim);\n }\n\n if (request.method === \"DELETE\") {\n await discardBody(request);\n await upload.abort();\n return new Response(null, { status: 204 });\n }\n } catch (error) {\n // R2 refuses an unknown upload id, a part out of shape, or a part list\n // that does not match what was uploaded: the caller's mistake.\n return apiError(400, \"invalid_upload\", `R2 refused the upload: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n await discardBody(request);\n return apiError(405, \"method_not_allowed\", `${request.method} is not part of a multipart upload.`);\n}\n\nasync function handleStorage(\n request: Request,\n env: Env,\n workspaceId: string,\n objectKey: string,\n role: number,\n trustedClaim: string\n): Promise<Response> {\n const bucket = env.FILES;\n if (!bucket) {\n await discardBody(request);\n return apiError(501, \"storage_not_configured\", \"Bind an FILES R2 bucket to use storage.\");\n }\n\n // Without file rules, roles decide here. With rules, the workspace decides\n // each operation before any byte moves (see engine/file-access.ts).\n const ruled = fileRulesConfigured();\n if (!ruled) {\n const required =\n request.method === \"GET\" || request.method === \"HEAD\"\n ? WORKSPACE_ROLE_LEVELS.MEMBER\n : WORKSPACE_ROLE_LEVELS.EDITOR;\n if (role < required) {\n await discardBody(request);\n return apiError(403, \"insufficient_role\", \"Insufficient role for this file operation.\");\n }\n }\n const authorize = async (action: \"read\" | \"write\" | \"delete\", details: { size?: number; contentType?: string } = {}) => {\n if (!ruled) return null;\n const decision = await callRoom(\n env,\n workspaceId,\n \"/files/authorize\",\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ path: objectKey, action, ...details }),\n },\n trustedClaim\n );\n if (decision.ok) {\n await decision.body?.cancel();\n return null;\n }\n await discardBody(request);\n return new Response(decision.body, { status: decision.status, headers: { \"content-type\": \"application/json\" } });\n };\n\n let key = storageKey(workspaceId, objectKey);\n const query = new URL(request.url).searchParams;\n\n if (query.has(\"uploads\") || query.has(\"uploadId\")) {\n // Starting and completing an upload are writes; its parts and its abort\n // need only the upload id, which only an authorized start handed out.\n const decides = request.method === \"POST\";\n const refused = decides\n ? await authorize(\"write\", query.has(\"uploads\") ? { contentType: request.headers.get(\"content-type\") ?? \"application/octet-stream\" } : {})\n : null;\n if (refused) return refused;\n return handleMultipart(request, env, bucket, workspaceId, objectKey, key, query, trustedClaim);\n }\n\n if (request.method === \"PUT\") {\n const refused = await authorize(\"write\", {\n ...(Number.isFinite(Number(request.headers.get(\"content-length\") ?? \"\")) && request.headers.has(\"content-length\")\n ? { size: Number(request.headers.get(\"content-length\")) }\n : {}),\n contentType: request.headers.get(\"content-type\") ?? \"application/octet-stream\",\n });\n if (refused) return refused;\n const declared = Number(request.headers.get(\"content-length\") ?? \"\");\n if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES) {\n await discardBody(request);\n return apiError(413, \"upload_too_large\", `One request carries at most ${MAX_UPLOAD_BYTES} bytes; send a larger file as a multipart upload (?uploads), as the client does.`);\n }\n const body = await readBodyWithinLimit(request, MAX_UPLOAD_BYTES);\n if (body === null) {\n return apiError(413, \"upload_too_large\", `One request carries at most ${MAX_UPLOAD_BYTES} bytes; send a larger file as a multipart upload (?uploads), as the client does.`);\n }\n const contentType =\n request.headers.get(\"content-type\") ?? \"application/octet-stream\";\n\n key = `${key}/.tapedb/${crypto.randomUUID()}`;\n await bucket.put(key, body, { httpMetadata: { contentType } });\n\n // Bytes are stored; now record them where the database can see them. A\n // failure here is reported rather than swallowed: an object nobody can\n // list is worse than a failed upload.\n return recordUpload(env, bucket, workspaceId, objectKey, key, body.byteLength, contentType, trustedClaim);\n }\n\n const locate = async (action: \"read\" | \"delete\") => {\n const response = await callRoom(env, workspaceId, \"/files/locate\", { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ path: objectKey, action }) }, trustedClaim);\n if (!response.ok) return null;\n const data = await response.json() as { key?: string };\n return typeof data.key === \"string\" ? data.key : null;\n };\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n const refused = await authorize(\"read\");\n if (refused) return refused;\n const storedKey = await locate(\"read\");\n if (!storedKey) return apiError(404, \"not_found\", \"No such object.\");\n const object = request.method === \"HEAD\" ? await bucket.head(storedKey) : await bucket.get(storedKey);\n if (!object) return apiError(404, \"not_found\", \"No such object.\");\n const headers = new Headers();\n headers.set(\"etag\", object.httpEtag);\n if (object.httpMetadata?.contentType) {\n headers.set(\"content-type\", object.httpMetadata.contentType);\n }\n // Uploaded bytes and the content type are user-controlled. Keep a\n // same-origin HTML or SVG upload from becoming script execution.\n headers.set(\"x-content-type-options\", \"nosniff\");\n headers.set(\"content-security-policy\", \"default-src 'none'; sandbox\");\n const body = \"body\" in object ? (object.body as BodyInit) : null;\n return new Response(body, { headers });\n }\n\n if (request.method === \"DELETE\") {\n const refused = await authorize(\"delete\");\n if (refused) return refused;\n const storedKey = await locate(\"delete\");\n\n const forgotten = await callRoom(\n env,\n workspaceId,\n \"/files\",\n {\n method: \"DELETE\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ path: objectKey }),\n },\n trustedClaim\n );\n if (!forgotten.ok) {\n return apiError(\n 502,\n \"file_index_failed\",\n \"Deleted the object but could not remove it from the workspace index.\"\n );\n }\n\n if (storedKey) await bucket.delete(storedKey);\n return new Response(null, { status: 204 });\n }\n\n await discardBody(request);\n return apiError(405, \"method_not_allowed\", `${request.method} is not supported for storage.`);\n}\n\n return handleStorage;\n}\n","/**\n * Workspace export: every row the caller may read, as NDJSON.\n *\n * {\"type\":\"header\",\"format\":\"tapedb-export\",\"version\":1,\"workspaceId\":…,\"seq\":…,\"models\":[…],\"skipped\":[…]}\n * {\"type\":\"row\",\"model\":\"task\",\"data\":{…}} one per row, model by model, in id order\n * {\"type\":\"file\",\"file\":{\"path\":…,\"size\":…,…}} the file index (bytes stay in R2)\n * {\"type\":\"end\",\"seq\":…,\"rows\":…,\"counts\":{…},\"consistent\":true}\n *\n * Rows go through the same query path as any read, so read rules apply, a\n * model the caller cannot read is skipped and named in the header, and rows\n * come back in the API shape a client would see.\n *\n * The stream is pulled: each pull reads one chunk of up to 1000 rows, keyset\n * by id, so a large workspace never sits in memory at once. Writes are not\n * held off for the length of an export, so one can land between chunks; the\n * end line reports the sequence at the start and at the end, and\n * `consistent` is true when no write landed in between: the export is then\n * exactly the workspace at that sequence. An export that stops early ends\n * with an `error` line and no `end`.\n */\n\nimport type { PersonalRuntime } from \"./personal\";\nimport type { QueryPageInfo, QueryResult } from \"./query-types\";\nimport type { RoleClaim } from \"../claims\";\nimport { compileQuery } from \"./query-compile\";\nimport { authorizeQuery, executeCompiledQueryWithPageInfo, viewAccess } from \"./query-execute\";\nimport { QUERY_CHUNK_ROWS } from \"./query-types\";\nimport { ENGINE_TABLES, NAMESPACES } from \"./registry\";\nimport type { SqlExecutor, SqlRow } from \"./tx-sql\";\nimport { readableFiles } from \"./file-access\";\nimport { TxError } from \"./tx-types\";\n\ntype ExportFile = SqlRow & { id: string; path: string; size: number; contentType: string | null; uploadedBy: string | null; r2Key: string; createdAt: number; updatedAt: number };\ntype StepResult = { data: QueryResult; pageInfo: QueryPageInfo; files?: ExportFile[] };\n\nexport const EXPORT_FORMAT = \"tapedb-export\";\nexport const EXPORT_VERSION = 1;\n\nfunction highWater(sql: SqlExecutor): number {\n const row = sql.one<{ seq: number | null }>(`SELECT high_water_seq AS \"seq\" FROM \"_tx_state\" WHERE \"id\" = 1`);\n return Number(row?.seq ?? 0);\n}\n\nfunction schemaVersion(sql: SqlExecutor): string | null {\n const row = sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'schema_version'`);\n return row?.value ?? null;\n}\n\n/** The readable models, in registry order, and the ones the caller may not read. */\nfunction plan(claim: RoleClaim): { models: string[]; skipped: Array<{ model: string; reason: string }> } {\n const models: string[] = [];\n const skipped: Array<{ model: string; reason: string }> = [];\n for (const apiName of Object.keys(NAMESPACES)) {\n try {\n authorizeQuery(claim, compileQuery({ [apiName]: { $: { limit: 1 } } }, viewAccess(claim)));\n models.push(apiName);\n } catch (error) {\n skipped.push({ model: apiName, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return { models, skipped };\n}\n\n/**\n * Lines of the export, produced lazily. Each `next()` reads at most one\n * chunk from SQLite.\n */\nfunction* exportSteps(\n sql: SqlExecutor,\n claim: RoleClaim,\n workspaceId: string,\n now: () => number = Date.now\n): Generator<string | (() => StepResult), void, StepResult> {\n const startSeq = highWater(sql);\n const { models, skipped } = plan(claim);\n yield JSON.stringify({\n type: \"header\",\n format: EXPORT_FORMAT,\n version: EXPORT_VERSION,\n workspaceId,\n seq: startSeq,\n exportedAt: now(),\n schemaVersion: schemaVersion(sql),\n models,\n skipped,\n });\n\n const counts: Record<string, number> = {};\n let rows = 0;\n try {\n for (const model of models) {\n counts[model] = 0;\n let after: string | undefined;\n for (;;) {\n const compiled = compileQuery(\n {\n [model]: {\n $: { order: { id: \"asc\" }, limit: QUERY_CHUNK_ROWS, ...(after === undefined ? {} : { after }) },\n },\n },\n viewAccess(claim)\n );\n const { data, pageInfo } = yield () => executeCompiledQueryWithPageInfo(sql, compiled, claim);\n for (const row of data[model] ?? []) {\n yield JSON.stringify({ type: \"row\", model, data: row });\n counts[model] += 1;\n rows += 1;\n }\n const next = pageInfo[model]?.nextCursor;\n if (pageInfo[model]?.hasMore !== true || next === undefined) break;\n after = next;\n }\n }\n\n let lastPath: string | null = null;\n for (;;) {\n const files: ExportFile[] = sql.all<ExportFile>(\n `SELECT \"id\", \"path\", \"r2_key\" AS \"r2Key\", \"size\", \"content_type\" AS \"contentType\",\n \"uploaded_by\" AS \"uploadedBy\", \"created_at\" AS \"createdAt\", \"updated_at\" AS \"updatedAt\"\n FROM \"${ENGINE_TABLES.files}\"\n ${lastPath === null ? \"\" : `WHERE \"path\" > ?`}\n ORDER BY \"path\" LIMIT ?`,\n ...((lastPath === null ? [] : [lastPath]) as string[]),\n QUERY_CHUNK_ROWS\n );\n const visible = (yield () => {\n const ids = new Set(readableFiles(sql, claim, files.map(file => ({ ...file, uploadedBy: file.uploadedBy ?? \"\" }))).map(file => file.id));\n return { data: {}, pageInfo: {}, files: files.filter(file => ids.has(file.id)) };\n }).files ?? [];\n for (const file of visible) yield JSON.stringify({ type: \"file\", file });\n if (files.length < QUERY_CHUNK_ROWS) break;\n lastPath = String(files[files.length - 1].path);\n }\n } catch (error) {\n yield JSON.stringify({\n type: \"error\",\n code: error instanceof TxError ? error.code : \"storage_error\",\n message: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n const endSeq = highWater(sql);\n yield JSON.stringify({\n type: \"end\",\n startSeq,\n seq: endSeq,\n rows,\n counts,\n consistent: endSeq === startSeq,\n });\n}\n\n/** Synchronous export for engines without encrypted fields. */\nexport function* exportLines(sql: SqlExecutor, claim: RoleClaim, workspaceId: string, now: () => number = Date.now): Generator<string> {\n const steps = exportSteps(sql, claim, workspaceId, now);\n let next = steps.next();\n try {\n while (!next.done) {\n if (typeof next.value === \"string\") { yield next.value; next = steps.next(); }\n else {\n try { next = steps.next(next.value()); } catch (error) { next = steps.throw(error); }\n }\n }\n } finally { steps.return(); }\n}\n\nasync function* personalExportLines(sql: SqlExecutor, claim: RoleClaim, workspaceId: string, personal: PersonalRuntime): AsyncGenerator<string> {\n const steps = exportSteps(personal.sql(sql), claim, workspaceId);\n let next = steps.next();\n try {\n while (!next.done) {\n if (typeof next.value === \"string\") { yield next.value; next = steps.next(); }\n else {\n try { const result = await personal.read(next.value); personal.clearPlaintext(); next = steps.next(result); } catch (error) { next = steps.throw(error); }\n }\n }\n } finally { steps.return(); }\n}\n\n/** The export as a byte stream that reads one chunk per pull. */\nexport function exportStream(\n sql: SqlExecutor,\n claim: RoleClaim,\n workspaceId: string,\n personal?: PersonalRuntime\n): ReadableStream<Uint8Array> {\n const lines = personal ? personalExportLines(sql, claim, workspaceId, personal) : exportLines(sql, claim, workspaceId);\n const encoder = new TextEncoder();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n // A few lines per pull keeps the stream moving without reading ahead\n // more than one chunk of rows.\n let text = \"\";\n for (let count = 0; count < 256; count += 1) {\n const next = await lines.next();\n if (next.done) {\n if (text) controller.enqueue(encoder.encode(text));\n controller.close();\n return;\n }\n text += next.value + \"\\n\";\n }\n controller.enqueue(encoder.encode(text));\n },\n cancel() {\n lines.return(undefined);\n },\n });\n}\n","import type { PersonalRuntime } from \"./personal\";\nimport type { RoleClaim } from \"../claims\";\nimport { NAMESPACES } from \"./registry\";\nimport { filesPrefix } from \"./r2-keys\";\nimport { validateEnvelope } from \"./tx-validate\";\nimport { appendLogEntry } from \"./tx-pipeline\";\nimport { LogWriter } from \"./tx-log\";\nimport { opsHash, stableStringify } from \"./tx-hash\";\nimport { applyFileOps, type FilePutOp } from \"./file-index\";\nimport { TxError } from \"./tx-types\";\nimport type { SqlExecutor, SqlRow } from \"./tx-sql\";\n\nexport function assertEmpty(sql: SqlExecutor): void {\n if ((sql.one<{ seq: number }>(`SELECT high_water_seq AS seq FROM \"_tx_state\" WHERE id = 1`)?.seq ?? 0) > 0 ||\n sql.one<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_tx_log\"`)!.n > 0 ||\n sql.one<{ n: number }>(`SELECT COUNT(*) AS n FROM \"_files\"`)!.n > 0 ||\n Object.values(NAMESPACES).some(model => sql.one<{ n: number }>(`SELECT COUNT(*) AS n FROM \"${model.table}\"`)!.n > 0))\n throw new TxError(\"conflict\", \"Import requires an empty workspace without history.\");\n}\n\n/** A checked stream is staged in SQLite, then applied and logged atomically. */\nexport async function importWorkspace(sql: SqlExecutor, request: Request, claim: RoleClaim, workspaceId: string, personal?: PersonalRuntime): Promise<number> {\n assertEmpty(sql);\n sql.exec(`CREATE TABLE IF NOT EXISTS \"_tapedb_import\" (n INTEGER PRIMARY KEY, data TEXT NOT NULL)`);\n sql.exec(`DELETE FROM \"_tapedb_import\"`);\n let n = 0, rows = 0, header: Record<string, unknown> | null = null, end: Record<string, unknown> | null = null;\n const stage = async (text: string) => {\n if (!text.trim()) return;\n const value = JSON.parse(text) as Record<string, unknown>;\n if (end) throw new Error(\"The export has data after its end line.\");\n if (!header) {\n if (value.type !== \"header\" || value.format !== \"tapedb-export\" || value.version !== 1 || value.workspaceId !== workspaceId ||\n !Array.isArray(value.skipped) || value.skipped.length) throw new Error(\"Import requires a complete export of this workspace.\");\n header = value; return;\n }\n if (value.type === \"end\") { end = value; return; }\n if (value.type !== \"row\" && value.type !== \"file\") throw new Error(\"Unexpected export line.\");\n if (value.type === \"row\") {\n rows++;\n if (personal) {\n const record = value.data as Record<string, unknown>;\n const namespace = NAMESPACES[String(value.model)];\n if (!namespace || !record || typeof record.id !== \"string\") throw new Error(\"Invalid exported model row.\");\n const { id, createdAt, updatedAt, updatedSeq, $erased, ...values } = record;\n const parsed = validateEnvelope({ txId: \"import\", ops: [{ op: \"insert\", namespace: value.model, id, values }] }).ops[0];\n if (parsed.kind !== \"insert\") throw new Error(\"Invalid import operation.\");\n const encoded = await personal.prepare(sql, namespace, id, parsed.values, true, Array.isArray($erased) && $erased.every(field => typeof field === \"string\") ? $erased : []);\n const row = { id, ...encoded, created_at: createdAt ? new Date(createdAt as string).getTime() : Date.now(), updated_at: updatedAt ? new Date(updatedAt as string).getTime() : Date.now(), updated_seq: updatedSeq ?? 0 };\n text = JSON.stringify({ type: \"stored\", table: namespace.table, row });\n }\n }\n sql.exec(`INSERT INTO \"_tapedb_import\" (n, data) VALUES (?, ?)`, ++n, text);\n };\n try {\n if (!request.body) throw new Error(\"Import needs an NDJSON body.\");\n const reader = request.body.pipeThrough(new TextDecoderStream()).getReader();\n let tail = \"\";\n try {\n for (;;) {\n const { value, done } = await reader.read(); if (done) break;\n tail += value;\n for (let at = tail.indexOf(\"\\n\"); at >= 0; at = tail.indexOf(\"\\n\")) { await stage(tail.slice(0, at)); tail = tail.slice(at + 1); }\n }\n } finally { await reader.cancel().catch(() => undefined); reader.releaseLock(); }\n if (tail.trim()) await stage(tail);\n const finish = end as Record<string, unknown> | null;\n const start = header as Record<string, unknown> | null;\n if (!start || !finish || finish.consistent !== true || finish.rows !== rows || finish.startSeq !== start.seq || finish.seq !== start.seq)\n throw new Error(\"The export is incomplete or inconsistent.\");\n return sql.transactionSync(() => {\n assertEmpty(sql);\n if (!Number.isSafeInteger(start.seq) || (start.seq as number) < 0) throw new Error(\"Invalid export sequence.\");\n sql.exec(`UPDATE \"_tx_state\" SET high_water_seq = ? WHERE id = 1`, start.seq as number);\n sql.exec(\"PRAGMA defer_foreign_keys = ON\");\n const seq = appendLogEntry(sql, { clientTxId: null, ops: \"[]\", opsHash: opsHash([]), at: Date.now() });\n const log = new LogWriter(sql, seq);\n log.push({ op: \"import:begin\" });\n for (let at = 0;;) {\n const batch = sql.all<{ n: number; data: string }>(`SELECT n, data FROM \"_tapedb_import\" WHERE n > ? ORDER BY n LIMIT 100`, at);\n if (!batch.length) break;\n for (const staged of batch) {\n at = staged.n;\n const line = JSON.parse(staged.data);\n const now = Date.now();\n if (line.type === \"file\") {\n const file = line.file;\n if (!file || typeof file.path !== \"string\" || typeof file.id !== \"string\" || typeof file.r2Key !== \"string\" || !file.r2Key.startsWith(filesPrefix(workspaceId)) || !Number.isSafeInteger(file.size) || file.size < 0)\n throw new Error(\"Invalid file index entry.\");\n const op: FilePutOp = { op: \"file:put\", id: file.id, path: file.path, key: file.r2Key, size: file.size, contentType: file.contentType ?? null, uploadedBy: file.uploadedBy ?? null, createdAt: file.createdAt, updatedAt: file.updatedAt };\n log.push(op);\n applyFileOps(sql, [op], file.createdAt ?? now);\n sql.exec(`UPDATE \"_files\" SET updated_at = ? WHERE id = ?`, file.updatedAt ?? now, file.id);\n continue;\n }\n if (line.type === \"stored\") {\n const columns = Object.keys(line.row);\n log.push({ op: \"import:row\", table: line.table, row: line.row });\n sql.exec(`INSERT INTO \"${line.table}\" (${columns.map(column => '\"' + column + '\"').join(',')}) VALUES (${columns.map(() => '?').join(',')})`, ...columns.map(column => line.row[column]));\n continue;\n }\n const namespace = NAMESPACES[line.model];\n if (!namespace || !line.data || typeof line.data.id !== \"string\") throw new Error(\"Invalid exported model row.\");\n const { id, createdAt, updatedAt, updatedSeq, $erased, ...values } = line.data;\n const parsed = validateEnvelope({ txId: \"import\", ops: [{ op: \"insert\", namespace: line.model, id, values }] }).ops[0];\n if (parsed.kind !== \"insert\") throw new Error(\"Invalid import operation.\");\n const row: SqlRow = { id, ...parsed.values, created_at: createdAt ? new Date(createdAt).getTime() : now,\n updated_at: updatedAt ? new Date(updatedAt).getTime() : now, updated_seq: updatedSeq ?? 0 };\n if (!Number.isFinite(row.created_at) || !Number.isFinite(row.updated_at)) throw new Error(\"Invalid row timestamp.\");\n const op = { op: \"import:row\", table: namespace.table, row };\n log.push(op);\n const columns = Object.keys(row);\n sql.exec(`INSERT INTO \"${namespace.table}\" (${columns.map(column => '\"' + column + '\"').join(',')}) VALUES (${columns.map(() => '?').join(',')})`, ...columns.map(column => row[column]));\n }\n }\n log.push({ op: \"import:end\" });\n log.close();\n sql.exec(`INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES ('receipts_since', ?)`, String(Date.now()));\n return rows;\n });\n } finally { sql.exec(`DROP TABLE IF EXISTS \"_tapedb_import\"`); }\n}\n","import { personalKeyPrefix } from \"./personal\";\nimport type { Env } from \"../types\";\nimport { filesPrefix, manifestKey, workspacePrefix } from \"./r2-keys\";\nimport { listAllR2 } from \"./r2-list\";\n\nexport type MoveState = { state: \"frozen\" | \"copying\" | \"copied\" | \"ready\" | \"moved\"; to: string };\nexport const moveKey = (id: string) => `moves/${id}.json`;\nexport const jurisdiction = (value: string | undefined) => value === \"none\" || value === \"\" ? undefined : value;\nexport async function readMove(bucket: R2Bucket, id: string): Promise<MoveState | null> {\n const object = await bucket.get(moveKey(id));\n return object ? object.json<MoveState>() : null;\n}\n/** `readMove` with two more tries, for a read that fails in passing. */\nexport async function readMoveWithRetries(bucket: R2Bucket, id: string): Promise<MoveState | null> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await readMove(bucket, id);\n } catch (error) {\n if (attempt >= 2) throw error;\n await new Promise((resolve) => setTimeout(resolve, 100 * 4 ** attempt));\n }\n }\n}\nexport async function writeMove(bucket: R2Bucket, id: string, state: MoveState): Promise<void> {\n await bucket.put(moveKey(id), JSON.stringify(state));\n}\n\n/** Bindings for the source side of a configured move. */\nexport function sourceEnvironment(env: Env): Env {\n if (env.TAPEDB_MOVE_FROM === undefined || !env.DATA_FROM) throw new Error(\"Configure TAPEDB_MOVE_FROM and DATA_FROM before moving workspaces.\");\n return { ...env, WORKSPACE: env.WORKSPACE_FROM ?? env.WORKSPACE, DATA: env.DATA_FROM, FILES: env.FILES_FROM,\n TAPEDB_JURISDICTION: jurisdiction(env.TAPEDB_MOVE_FROM), TAPEDB_MOVE_FROM: undefined };\n}\n\n/** Copy with bounded memory and R2's equal-sized multipart parts. */\nexport async function copyObject(from: R2Bucket, to: R2Bucket, key: string): Promise<void> {\n if (await to.head(key)) return;\n const info = await from.head(key);\n if (!info) throw new Error(`Move source object disappeared: ${key}`);\n const metadata = { httpMetadata: info.httpMetadata, customMetadata: info.customMetadata };\n if (info.size <= 8 * 1024 * 1024) {\n const object = await from.get(key);\n if (!object) throw new Error(`Move source object disappeared: ${key}`);\n await to.put(key, object.body, { ...metadata, onlyIf: { etagDoesNotMatch: \"*\" } }); return;\n }\n // At most 10,000 parts, streamed directly from native R2 range bodies.\n const size = Math.max(8 * 1024 * 1024, Math.ceil(info.size / 10_000));\n const upload = await to.createMultipartUpload(key, metadata);\n const parts: R2UploadedPart[] = [];\n try {\n for (let offset = 0; offset < info.size; offset += size) {\n const object = await from.get(key, { range: { offset, length: Math.min(size, info.size - offset) } });\n if (!object) throw new Error(`Move source object disappeared: ${key}`);\n parts.push(await upload.uploadPart(parts.length + 1, object.body));\n }\n await upload.complete(parts);\n } catch (error) { await upload.abort().catch(() => undefined); throw error; }\n}\n\nexport async function copyWorkspace(source: Env, target: Env, id: string, fileKeys: ReadableStream<Uint8Array>): Promise<void> {\n const manifest = manifestKey(id);\n const objects = [...await listAllR2(source.DATA, `${workspacePrefix(id)}/`), ...await listAllR2(source.DATA, personalKeyPrefix(id))];\n for (const object of objects) if (object.key !== manifest) await copyObject(source.DATA, target.DATA, object.key);\n const reader = fileKeys.getReader();\n const decoder = new TextDecoder();\n let tail = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read(); if (done) break;\n tail += decoder.decode(value, { stream: true });\n for (let end = tail.indexOf(\"\\n\"); end >= 0; end = tail.indexOf(\"\\n\")) {\n const key = JSON.parse(tail.slice(0, end)) as string; tail = tail.slice(end + 1);\n if (!source.FILES || !target.FILES) throw new Error(\"A FILES binding is missing.\");\n if (!key.startsWith(filesPrefix(id))) throw new Error(\"File key is outside this workspace.\");\n await copyObject(source.FILES, target.FILES, key);\n }\n }\n if (tail.trim()) throw new Error(\"File listing was incomplete.\");\n } finally { reader.releaseLock(); }\n // Publish the recovery checkpoint only after all referenced objects exist.\n if (objects.some(object => object.key === manifest)) await copyObject(source.DATA, target.DATA, manifest);\n}\n","/**\n * Built-in limits for the claim route: exact token buckets, global per key.\n *\n * Each bucket lives in one of `LIMITER_SHARDS` Durable Objects of the\n * workspace class, addressed by a name that is not a workspace id, so a\n * deployment needs no extra binding or migration. A Durable Object is one\n * place in the world and runs one request at a time, so a count is exact and\n * shared by every location, unlike Cloudflare's rate-limit binding, which\n * counts per location and approximately.\n *\n * Keys are HMACs of the caller's IP or subject under the claim secret: the\n * limiter never stores an address or a user id. A bucket that has refilled\n * is indistinguishable from none and is deleted.\n */\n\nimport { apiError, json } from \"../http\";\nimport type { SqlExecutor } from \"./tx-sql\";\n\nexport interface ClaimLimit {\n /** Requests a caller may make in a burst; the bucket's size. */\n requests: number;\n /** Seconds the bucket takes to refill from empty. */\n perSeconds: number;\n}\n\n/**\n * Limits on `POST /_tapedb/claim`. `ip` is checked before the session lookup\n * (it protects your identity system from floods), `subject` after it.\n * `false` turns one off.\n */\nexport interface ClaimLimits {\n ip?: ClaimLimit | false;\n subject?: ClaimLimit | false;\n}\n\n/**\n * Defaults: a signed-in user rarely needs more than a claim per connect and\n * per renewal, while one office or mobile carrier can put hundreds of users\n * behind one address, hence the larger per-IP bucket.\n */\nexport const DEFAULT_CLAIM_LIMITS: Required<{ [K in keyof ClaimLimits]: ClaimLimit }> = {\n ip: { requests: 300, perSeconds: 60 },\n subject: { requests: 30, perSeconds: 60 },\n};\n\nexport const LIMITER_SHARDS = 32;\nconst LIMITER_PREFIX = \"tapedb-limits-\";\nexport const BUCKETS_TABLE = \"_claim_buckets\";\n\nexport function limiterName(shard: number): string {\n return `${LIMITER_PREFIX}${shard}`;\n}\n\nexport function isLimiterName(name: string | undefined): boolean {\n return typeof name === \"string\" && new RegExp(`^${LIMITER_PREFIX}\\\\d+$`).test(name);\n}\n\nexport function resolveClaimLimits(limits: ClaimLimits | false | undefined): Required<ClaimLimits> {\n if (limits === false) return { ip: false, subject: false };\n const pick = (kind: keyof ClaimLimits): ClaimLimit | false => {\n const given = limits?.[kind];\n if (given === false) return false;\n const limit = given ?? DEFAULT_CLAIM_LIMITS[kind];\n if (!(Number.isInteger(limit.requests) && limit.requests > 0 && limit.perSeconds > 0)) {\n throw new Error(`identity.limits.${kind} needs a positive integer \\`requests\\` and a positive \\`perSeconds\\`.`);\n }\n return limit;\n };\n return { ip: pick(\"ip\"), subject: pick(\"subject\") };\n}\n\n/** The bucket key for a caller, and the shard that holds it. */\nexport async function limiterKey(secret: string, value: string): Promise<{ key: string; shard: number }> {\n const hmacKey = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(`tapedb-claim-limits:${secret}`),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n const digest = new Uint8Array(await crypto.subtle.sign(\"HMAC\", hmacKey, new TextEncoder().encode(value)));\n const key = [...digest.slice(0, 16)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return { key, shard: digest[16] % LIMITER_SHARDS };\n}\n\nexport interface LimitDecision {\n allowed: boolean;\n /** Whole seconds until one more request is allowed; 0 when allowed. */\n retryAfterSeconds: number;\n}\n\n/** Takes one token from `key`'s bucket, exactly. */\nexport function takeToken(sql: SqlExecutor, key: string, limit: ClaimLimit, now: number): LimitDecision {\n sql.exec(\n `CREATE TABLE IF NOT EXISTS \"${BUCKETS_TABLE}\" (key TEXT PRIMARY KEY, tokens REAL NOT NULL, at INTEGER NOT NULL, refill_ms INTEGER NOT NULL) WITHOUT ROWID`\n );\n const refillMs = limit.perSeconds * 1000;\n const row = sql.one<{ tokens: number; at: number }>(`SELECT tokens, at FROM \"${BUCKETS_TABLE}\" WHERE key = ?`, key);\n const elapsed = row ? Math.max(0, now - Number(row.at)) : refillMs;\n const tokens = Math.min(limit.requests, (row ? Number(row.tokens) : limit.requests) + (elapsed * limit.requests) / refillMs);\n const allowed = tokens >= 1;\n const left = allowed ? tokens - 1 : tokens;\n sql.exec(\n `INSERT INTO \"${BUCKETS_TABLE}\" (key, tokens, at, refill_ms) VALUES (?, ?, ?, ?)\n ON CONFLICT(key) DO UPDATE SET tokens = excluded.tokens, at = excluded.at, refill_ms = excluded.refill_ms`,\n key,\n left,\n now,\n refillMs\n );\n // Buckets that have refilled hold nothing worth keeping.\n sql.exec(\n `DELETE FROM \"${BUCKETS_TABLE}\" WHERE key IN (SELECT key FROM \"${BUCKETS_TABLE}\" WHERE at + refill_ms < ? LIMIT 100)`,\n now\n );\n return {\n allowed,\n retryAfterSeconds: allowed ? 0 : Math.ceil(((1 - left) * refillMs) / limit.requests / 1000),\n };\n}\n\n/** The limiter object's one route: `POST { key, requests, perSeconds }`. */\nexport async function handleLimitRequest(request: Request, sql: SqlExecutor, now = Date.now()): Promise<Response> {\n const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;\n const key = body?.key;\n const requests = body?.requests;\n const perSeconds = body?.perSeconds;\n if (\n request.method !== \"POST\" ||\n typeof key !== \"string\" || !/^[0-9a-f]{32}$/.test(key) ||\n !Number.isInteger(requests) || (requests as number) <= 0 ||\n typeof perSeconds !== \"number\" || perSeconds <= 0\n ) {\n return apiError(400, \"invalid_limit\", \"A limit request is POST { key, requests, perSeconds }.\");\n }\n return json(takeToken(sql, key, { requests: requests as number, perSeconds }, now));\n}\n","/**\n * Per-socket state of any size, and messages of any size.\n *\n * A socket's attachment survives hibernation but holds at most 16 KiB\n * (Cloudflare's limit), while its live queries, presence and topics have no\n * natural bound. While they are small they stay in the attachment, so a\n * cursor move costs no storage write. Past `INLINE_STATE_BYTES` they move to\n * `_socket_state` in parts, and the attachment keeps only who the socket is.\n *\n * Messages: Cloudflare closes a socket on a received frame over 32 MiB. The\n * client sends a larger message as `part` frames, which wait in\n * `_socket_parts` (so hibernation between frames loses nothing) until the\n * last arrives, then run as the whole message. Topic messages are relayed\n * part by part instead (see the room), so the room never holds one whole.\n *\n * Both tables are ephemeral, like the sockets they belong to: never logged,\n * snapshotted or exported, and cleared for sockets that are gone.\n */\n\nimport { MAX_SOCKET_MESSAGE_BYTES, MAX_SOCKET_PENDING_BYTES, MAX_ROOM_PENDING_BYTES, MAX_SOCKET_PENDING_MESSAGES, MAX_SOCKET_MESSAGE_PARTS } from \"../socket-protocol\";\nimport type { SqlExecutor } from \"./tx-sql\";\nimport type { SocketAttachment } from \"./ws-types\";\n\n/** Attachment bytes kept inline; the platform allows 16 KiB. */\nexport const INLINE_STATE_BYTES = 12 * 1024;\n/** Characters per stored part: 256 Ki UTF-16 units is at most 768 KiB of UTF-8. */\nconst STATE_PART_CHARS = 256 * 1024;\n\nexport class SocketLimitError extends Error {}\n\nexport const SOCKET_STATE_TABLE = \"_socket_state\";\nexport const SOCKET_PARTS_TABLE = \"_socket_parts\";\n\n/** What stays in the attachment when the rest is stored. */\ntype CoreAttachment = Pick<SocketAttachment, \"clientId\" | \"sub\" | \"role\" | \"exp\"> & { spilled: true };\n\ntype Spillable = Omit<SocketAttachment, \"clientId\" | \"sub\" | \"role\" | \"exp\">;\n\nconst encoder = new TextEncoder();\n\nfunction byteLength(value: unknown): number {\n return encoder.encode(JSON.stringify(value)).byteLength;\n}\n\n/** Splits text into parts without cutting a surrogate pair. */\nexport function splitText(text: string, size: number): string[] {\n const parts: string[] = [];\n for (let start = 0; start < text.length; ) {\n let end = Math.min(start + size, text.length);\n const last = text.charCodeAt(end - 1);\n if (end < text.length && last >= 0xd800 && last <= 0xdbff) end -= 1;\n parts.push(text.slice(start, end));\n start = end;\n }\n return parts.length > 0 ? parts : [\"\"];\n}\n\n/** True when the stored attachment points at state kept in `_socket_state`. */\nexport function isSpilled(raw: unknown): raw is CoreAttachment {\n return typeof raw === \"object\" && raw !== null && (raw as { spilled?: unknown }).spilled === true;\n}\n\n/** The full attachment: inline as stored, or core plus the stored state. */\nexport function loadAttachment(sql: SqlExecutor, raw: unknown): unknown {\n if (!isSpilled(raw)) return raw;\n const rows = sql.all<{ data: string }>(\n `SELECT data FROM \"${SOCKET_STATE_TABLE}\" WHERE client_id = ? ORDER BY part`,\n raw.clientId\n );\n if (rows.length === 0) return null;\n const rest = JSON.parse(rows.map((row) => row.data).join(\"\")) as Spillable;\n const { spilled: _spilled, ...core } = raw;\n return { ...core, ...rest };\n}\n\n/**\n * The value to hand `serializeAttachment`: the attachment itself when it\n * fits, or its core with the rest stored. Clears stored state it no longer\n * needs.\n */\nexport function storeAttachment(sql: SqlExecutor, attachment: SocketAttachment, wasSpilled: boolean): unknown {\n const size = byteLength(attachment);\n if (size > MAX_SOCKET_MESSAGE_BYTES) throw new SocketLimitError(\"Socket state exceeds its memory budget.\");\n if (size <= INLINE_STATE_BYTES) {\n if (wasSpilled) sql.exec(`DELETE FROM \"${SOCKET_STATE_TABLE}\" WHERE client_id = ?`, attachment.clientId);\n return attachment;\n }\n const { clientId, sub, role, exp, ...rest } = attachment;\n sql.transactionSync(() => {\n sql.exec(`DELETE FROM \"${SOCKET_STATE_TABLE}\" WHERE client_id = ?`, clientId);\n splitText(JSON.stringify(rest), STATE_PART_CHARS).forEach((data, part) => {\n sql.exec(`INSERT INTO \"${SOCKET_STATE_TABLE}\" (client_id, part, data) VALUES (?, ?, ?)`, clientId, part, data);\n });\n });\n const core: CoreAttachment = { clientId, sub, role, exp, spilled: true };\n return core;\n}\n\n/**\n * Takes one part of a multi-frame message. Returns the whole message text\n * once the last part is in, null while more are expected, or an error code\n * for a part out of order (the parts so far are dropped).\n */\nexport function acceptPart(\n sql: SqlExecutor,\n clientId: string,\n part: { id: string; index: number; last: boolean; data: string },\n assemble = true\n): { text: string } | { pending: true } | { complete: true } | { error: string } {\n const stored = sql.one<{ n: number }>(\n `SELECT COUNT(*) AS n FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ?`,\n clientId,\n part.id\n )?.n ?? 0;\n if (Number(stored) !== part.index) {\n sql.exec(`DELETE FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ?`, clientId, part.id);\n return { error: \"part_out_of_order\" };\n }\n const bytes = part.data.length > MAX_SOCKET_MESSAGE_BYTES ? MAX_SOCKET_MESSAGE_BYTES + 1 : encoder.encode(part.data).byteLength;\n const totals = sql.one<{ message: number; socket: number; room: number; messages: number }>(\n `SELECT COALESCE(SUM(CASE WHEN client_id = ? AND id = ? THEN length(CAST(data AS BLOB)) ELSE 0 END), 0) AS message,\n COALESCE(SUM(CASE WHEN client_id = ? THEN length(CAST(data AS BLOB)) + 128 ELSE 0 END), 0) AS socket,\n COALESCE(SUM(length(CAST(data AS BLOB)) + 128), 0) AS room,\n COUNT(DISTINCT CASE WHEN client_id = ? THEN id END) AS messages\n FROM \"${SOCKET_PARTS_TABLE}\"`, clientId, part.id, clientId, clientId\n )!;\n if (bytes + totals.message > MAX_SOCKET_MESSAGE_BYTES ||\n bytes + 128 + totals.socket > MAX_SOCKET_PENDING_BYTES ||\n bytes + 128 + totals.room > MAX_ROOM_PENDING_BYTES ||\n (stored === 0 && !part.last && totals.messages >= MAX_SOCKET_PENDING_MESSAGES) ||\n part.index >= MAX_SOCKET_MESSAGE_PARTS) {\n sql.exec(`DELETE FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ?`, clientId, part.id);\n return { error: \"message_limit_exceeded\" };\n }\n if (!part.last) {\n sql.exec(\n `INSERT INTO \"${SOCKET_PARTS_TABLE}\" (client_id, id, idx, data) VALUES (?, ?, ?, ?)`,\n clientId,\n part.id,\n part.index,\n part.data\n );\n return { pending: true };\n }\n if (!assemble) {\n sql.exec(`DELETE FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ?`, clientId, part.id);\n return { complete: true };\n }\n const earlier = sql.all<{ data: string }>(\n `SELECT data FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ? ORDER BY idx`,\n clientId,\n part.id\n );\n sql.exec(`DELETE FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ? AND id = ?`, clientId, part.id);\n return { text: earlier.map((row) => row.data).join(\"\") + part.data };\n}\n\n/** Drops everything stored for one socket. */\nexport function forgetSocket(sql: SqlExecutor, clientId: string): void {\n sql.exec(`DELETE FROM \"${SOCKET_STATE_TABLE}\" WHERE client_id = ?`, clientId);\n sql.exec(`DELETE FROM \"${SOCKET_PARTS_TABLE}\" WHERE client_id = ?`, clientId);\n}\n\n/** Drops state of sockets that are gone (closed while the object was evicted). */\nexport function forgetOtherSockets(sql: SqlExecutor, live: readonly string[]): void {\n const keep = JSON.stringify(live);\n for (const table of [SOCKET_STATE_TABLE, SOCKET_PARTS_TABLE]) {\n sql.exec(`DELETE FROM \"${table}\" WHERE client_id NOT IN (SELECT value FROM json_each(?))`, keep);\n }\n}\n","import {\n WORKSPACE_ROLE_LEVELS,\n claimSecretProblem,\n type RoleClaim,\n type WorkspaceRole,\n} from \"./claims\";\nimport { claimFromProtocols } from \"./socket-protocol\";\n\n/**\n * Engine role-claim verification.\n *\n * The platform mints a short-lived HS256 JWT whose payload matches the frozen\n * `RoleClaim` contract in `./claims.ts`. This module is the Worker half: it\n * validates the signature and the claim before any request reaches a\n * `WorkspaceRoom` Durable Object.\n *\n * There is deliberately no JWKS path: the agreed contract is a shared HS256\n * secret (`TAPEDB_CLAIM_SECRET`), not an asymmetric key set.\n */\n\n/** Trusted header forwarded to the Durable Object after verification. */\nexport const TRUSTED_CLAIM_HEADER = \"x-tapedb-claims\";\n\nexport type ClaimErrorCode =\n | \"missing_token\"\n | \"invalid_format\"\n | \"invalid_signature\"\n | \"expired\"\n | \"wrong_workspace\"\n | \"invalid_claim\";\n\n/** Typed verification failure; `code` is safe to return to the caller. */\nexport class ClaimError extends Error {\n readonly code: ClaimErrorCode;\n\n constructor(code: ClaimErrorCode, message: string) {\n super(message);\n this.name = \"ClaimError\";\n this.code = code;\n }\n}\n\n/** Minimal env view needed to verify a claim. */\nexport interface ClaimVerificationEnv {\n TAPEDB_CLAIM_SECRET: string;\n TAPEDB_CLAIM_ISSUER?: string;\n TAPEDB_CLAIM_AUDIENCE?: string;\n}\n\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;\nconst BEARER_PATTERN = /^Bearer[ \\t]+(.+)$/i;\nconst MAX_IAT_SKEW_SECONDS = 60;\n\n/**\n * Reads a claim token from the request.\n *\n * - `Authorization: Bearer <jwt>` for HTTP requests.\n * - A `tapedb.claim.<jwt>` entry in `Sec-WebSocket-Protocol` for WebSocket\n * upgrades, where browsers cannot set `Authorization`.\n *\n * Never the URL: a token in a query string ends up in request logs and\n * browser history. A `?claim=` parameter is ignored.\n *\n * A present-but-non-Bearer `Authorization` header returns `null` instead of\n * falling back to the protocol header, so the two transports cannot be confused.\n */\nexport function extractClaimToken(request: Request): string | null {\n const authorization = request.headers.get(\"authorization\");\n if (authorization !== null) {\n const match = BEARER_PATTERN.exec(authorization.trim());\n const token = match?.[1]?.trim() ?? \"\";\n return token.length > 0 ? token : null;\n }\n\n return claimFromProtocols(request.headers.get(\"sec-websocket-protocol\"));\n}\n\n/**\n * Verifies a compact JWS against the frozen `RoleClaim` contract.\n *\n * Throws `ClaimError` for malformed tokens, bad signatures, expiry, workspace\n * mismatches and invalid claim values. A missing server secret throws a plain\n * `Error`: that is a deployment problem, not a client failure.\n */\nexport async function verifyRoleClaim(\n token: string,\n env: ClaimVerificationEnv,\n expectedWorkspaceId: string\n): Promise<RoleClaim> {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new ClaimError(\"invalid_format\", \"Token is not a compact JWS.\");\n }\n\n const [headerSegment, payloadSegment, signatureSegment] = parts;\n\n const header = decodeJsonSegment(headerSegment, \"header\");\n if (header.alg !== \"HS256\") {\n throw new ClaimError(\"invalid_format\", \"Token algorithm must be HS256.\");\n }\n // `typ` is optional, but when present it must be exactly JWT.\n if (header.typ !== undefined && header.typ !== \"JWT\") {\n throw new ClaimError(\"invalid_format\", \"Token type must be JWT.\");\n }\n\n const signature = decodeBase64Url(signatureSegment, \"signature\");\n const secret = env.TAPEDB_CLAIM_SECRET;\n const problem = claimSecretProblem(secret);\n if (problem !== null) throw new Error(problem);\n\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"verify\"]\n );\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n key,\n signature as unknown as BufferSource,\n new TextEncoder().encode(`${headerSegment}.${payloadSegment}`)\n );\n if (!valid) {\n throw new ClaimError(\"invalid_signature\", \"Token signature is invalid.\");\n }\n\n const payload = decodeJsonSegment(payloadSegment, \"payload\");\n const now = Math.floor(Date.now() / 1000);\n\n const sub = payload.sub;\n if (typeof sub !== \"string\" || sub.trim().length === 0) {\n throw new ClaimError(\"invalid_claim\", \"Claim subject must be non-empty.\");\n }\n\n const workspaceId = payload.workspaceId;\n if (typeof workspaceId !== \"string\" || workspaceId.length === 0) {\n throw new ClaimError(\"invalid_claim\", \"Claim workspace id must be set.\");\n }\n if (workspaceId !== expectedWorkspaceId) {\n throw new ClaimError(\n \"wrong_workspace\",\n \"Token is valid for a different workspace.\"\n );\n }\n\n const role = payload.role;\n if (\n typeof role !== \"number\" ||\n !Number.isInteger(role) ||\n role < WORKSPACE_ROLE_LEVELS.GUEST ||\n role > WORKSPACE_ROLE_LEVELS.DEVELOPER\n ) {\n throw new ClaimError(\n \"invalid_claim\",\n \"Claim role must be an integer from 0 to 8.\"\n );\n }\n\n const exp = payload.exp;\n const iat = payload.iat;\n if (\n typeof exp !== \"number\" ||\n !Number.isInteger(exp) ||\n typeof iat !== \"number\" ||\n !Number.isInteger(iat)\n ) {\n throw new ClaimError(\n \"invalid_claim\",\n \"Claim exp and iat must be integer seconds.\"\n );\n }\n\n if (exp <= now) {\n throw new ClaimError(\"expired\", \"Token has expired.\");\n }\n if (iat > now + MAX_IAT_SKEW_SECONDS) {\n throw new ClaimError(\n \"invalid_claim\",\n \"Claim iat is too far in the future.\"\n );\n }\n\n const issuer = payload.iss;\n const audience = payload.aud;\n if (issuer !== undefined && typeof issuer !== \"string\") {\n throw new ClaimError(\"invalid_claim\", \"Claim issuer must be a string.\");\n }\n if (audience !== undefined && typeof audience !== \"string\") {\n throw new ClaimError(\"invalid_claim\", \"Claim audience must be a string.\");\n }\n\n if (env.TAPEDB_CLAIM_ISSUER && issuer !== env.TAPEDB_CLAIM_ISSUER) {\n throw new ClaimError(\"invalid_claim\", \"Claim issuer is not accepted.\");\n }\n if (env.TAPEDB_CLAIM_AUDIENCE && audience !== env.TAPEDB_CLAIM_AUDIENCE) {\n throw new ClaimError(\"invalid_claim\", \"Claim audience is not accepted.\");\n }\n\n const claim: RoleClaim = {\n sub,\n workspaceId,\n role: role as WorkspaceRole,\n exp,\n iat,\n };\n if (issuer !== undefined) claim.iss = issuer;\n if (audience !== undefined) claim.aud = audience;\n return claim;\n}\n\n/** Extracts and verifies the claim attached to an engine request. */\nexport async function authenticateEngineRequest(\n request: Request,\n env: ClaimVerificationEnv,\n workspaceId: string\n): Promise<RoleClaim> {\n const token = extractClaimToken(request);\n if (token === null) {\n throw new ClaimError(\"missing_token\", \"Missing engine claim token.\");\n }\n return verifyRoleClaim(token, env, workspaceId);\n}\n\n/**\n * Serialises the verified claim for the Durable Object. Only the fields the\n * engine needs are forwarded; signature material is never re-sent.\n */\nexport function encodeTrustedRoleClaim(claim: RoleClaim): string {\n const forwarded = {\n sub: claim.sub,\n workspaceId: claim.workspaceId,\n role: claim.role,\n exp: claim.exp,\n };\n return encodeBase64Url(new TextEncoder().encode(JSON.stringify(forwarded)));\n}\n\nfunction decodeJsonSegment(\n segment: string,\n label: string\n): Record<string, unknown> {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", {\n fatal: true,\n ignoreBOM: false,\n }).decode(decodeBase64Url(segment, label));\n } catch (error) {\n if (error instanceof ClaimError) throw error;\n throw new ClaimError(\n \"invalid_format\",\n `Token ${label} is not valid UTF-8.`\n );\n }\n\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new ClaimError(\"invalid_format\", `Token ${label} is not valid JSON.`);\n }\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ClaimError(\n \"invalid_format\",\n `Token ${label} must be a JSON object.`\n );\n }\n return value as Record<string, unknown>;\n}\n\n/** Strict base64url: URL-safe alphabet only, no padding, canonical length. */\nfunction decodeBase64Url(segment: string, label: string): Uint8Array {\n if (\n segment.length === 0 ||\n !BASE64URL_PATTERN.test(segment) ||\n segment.length % 4 === 1\n ) {\n throw new ClaimError(\n \"invalid_format\",\n `Token ${label} is not valid base64url.`\n );\n }\n\n const base64 =\n segment.replace(/-/g, \"+\").replace(/_/g, \"/\") +\n \"=\".repeat((4 - (segment.length % 4)) % 4);\n\n let binary: string;\n try {\n binary = atob(base64);\n } catch {\n throw new ClaimError(\n \"invalid_format\",\n `Token ${label} is not valid base64url.`\n );\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n // Reject non-canonical encodings that `atob` would otherwise accept.\n if (encodeBase64Url(bytes) !== segment) {\n throw new ClaimError(\n \"invalid_format\",\n `Token ${label} is not valid base64url.`\n );\n }\n return bytes;\n}\n\nfunction encodeBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n","/**\n * Reads the role claim the Worker attaches after verifying the client JWT.\n *\n * The client-supplied `x-tapedb-claims` header is replaced before forwarding, so this\n * header is trusted. Nothing here reads a client header directly, verifies a\n * signature, or logs token material. A missing, malformed, expired or\n * wrong-workspace claim is a permission failure.\n */\n\nimport {\n WORKSPACE_ROLE_LEVELS,\n type RoleClaim,\n type WorkspaceRole,\n} from \"../claims\";\nimport { TRUSTED_CLAIM_HEADER } from \"../verify\";\nimport { TxError } from \"./tx-types\";\n\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;\n\nexport function readTrustedRoleClaim(\n request: Request,\n workspaceId: string\n): RoleClaim {\n const claim = readTrustedRoleClaimAnyWorkspace(request);\n if (claim.workspaceId !== workspaceId) {\n throw denied(\"Verified role claim is for a different workspace.\");\n }\n return claim;\n}\n\n/**\n * Reads the verified claim without comparing it to a workspace id.\n *\n * For Durable Objects addressed by something other than a workspace (the app\n * registry), the workspace check is the caller's job: the binding is what\n * decides which workspace the claim must match.\n */\nexport function readTrustedRoleClaimAnyWorkspace(request: Request): RoleClaim {\n const header = request.headers.get(TRUSTED_CLAIM_HEADER);\n if (header === null || header.length === 0) {\n throw denied(\"Missing verified role claim.\");\n }\n\n const payload = decodeClaim(header);\n if (payload === null) {\n throw denied(\"Verified role claim is malformed.\");\n }\n\n const sub = payload.sub;\n if (typeof sub !== \"string\" || sub.trim().length === 0) {\n throw denied(\"Verified role claim has no subject.\");\n }\n\n const claimedWorkspace = payload.workspaceId;\n if (typeof claimedWorkspace !== \"string\" || claimedWorkspace.length === 0) {\n throw denied(\"Verified role claim has no workspace.\");\n }\n\n const role = payload.role;\n if (\n typeof role !== \"number\" ||\n !Number.isInteger(role) ||\n role < WORKSPACE_ROLE_LEVELS.GUEST ||\n role > WORKSPACE_ROLE_LEVELS.DEVELOPER\n ) {\n throw denied(\"Verified role claim has an invalid role.\");\n }\n\n const exp = payload.exp;\n if (typeof exp !== \"number\" || !Number.isInteger(exp)) {\n throw denied(\"Verified role claim has no expiry.\");\n }\n if (exp <= Math.floor(Date.now() / 1000)) {\n throw denied(\"Verified role claim has expired.\");\n }\n\n const iat = payload.iat;\n const claim: RoleClaim = {\n sub,\n workspaceId: claimedWorkspace,\n role: role as WorkspaceRole,\n exp,\n // The Worker does not forward `iat`; 0 keeps the shape stable.\n iat: typeof iat === \"number\" && Number.isInteger(iat) ? iat : 0,\n };\n\n return claim;\n}\n\nfunction decodeClaim(header: string): Record<string, unknown> | null {\n if (!BASE64URL_PATTERN.test(header) || header.length % 4 === 1) {\n return null;\n }\n\n const base64 =\n header.replace(/-/g, \"+\").replace(/_/g, \"/\") +\n \"=\".repeat((4 - (header.length % 4)) % 4);\n\n let binary: string;\n try {\n binary = atob(base64);\n } catch {\n return null;\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n // Reject non-canonical encodings that atob accepts.\n if (encodeBase64Url(bytes) !== header) return null;\n\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(\n bytes\n );\n } catch {\n return null;\n }\n\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\nfunction encodeBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\nfunction denied(message: string): TxError {\n return new TxError(\"permission_denied\", message);\n}\n","import { NAMESPACES, toSnakeCase } from \"./registry\";\nimport { isPersonalCiphertext, type PersonalRuntime } from \"./personal\";\nimport type { SqlExecutor, SqlRow, SqlValue } from \"./tx-sql\";\nimport { appendLogEntry } from \"./tx-pipeline\";\nimport { opsHash } from \"./tx-hash\";\nimport { LogWriter } from \"./tx-log\";\n\n/** Encrypt existing values in bounded, restartable transactions before reads. */\nexport async function migratePersonal(sql: SqlExecutor, personal: PersonalRuntime, transaction: <T>(fn: () => Promise<T>) => Promise<T>, deadline: number): Promise<boolean> {\n const signature = JSON.stringify(Object.values(NAMESPACES).map(model => [model.table, Object.entries(model.attributes).filter(([, field]) => field.personal).map(([field, definition]) => [field, definition.personal])]));\n const stateKey = \"personal_migration\";\n const stored = sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = ?`, stateKey);\n let state = stored ? JSON.parse(stored.value) as { signature: string; table: number; after: string } : { signature, table: 0, after: \"\" };\n if (state.signature !== signature) state = { signature, table: 0, after: \"\" };\n const models = Object.values(NAMESPACES);\n while (state.table < models.length) {\n if (Date.now() >= deadline) return false;\n const model = models[state.table];\n const fields = Object.entries(model.attributes).filter(([, definition]) => definition.personal);\n await transaction(async () => {\n const rows = fields.length ? sql.all<SqlRow>(`SELECT * FROM \"${model.table}\" WHERE id > ? ORDER BY id LIMIT 100`, state.after) : [];\n let log: LogWriter | undefined;\n const version = sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'schema_version'`)?.value ?? null;\n for (const row of rows) {\n const values: Record<string, SqlValue> = {};\n for (const [field, definition] of fields) {\n const column = toSnakeCase(field), value = row[column];\n if (value === null || isPersonalCiphertext(value)) continue;\n const subject = definition.personal!.subject === \"self\" ? row.id : row[toSnakeCase(definition.personal!.subject)];\n if (typeof subject !== \"string\") throw new Error(`Personal field ${model.apiName}.${field} needs a string subject.`);\n values[column] = await personal.seal(model, String(row.id), field, value, subject, version);\n }\n if (Object.keys(values).length) {\n if (!log) {\n const seq = appendLogEntry(sql, { clientTxId: null, ops: \"[]\", opsHash: opsHash([]), at: Date.now() });\n log = new LogWriter(sql, seq); log.push({ op: \"state:begin\" });\n }\n sql.exec(`UPDATE \"${model.table}\" SET ${Object.keys(values).map(column => `\"${column}\" = ?`).join(\", \")} WHERE id = ?`, ...Object.values(values), row.id);\n log.push({ op: \"state:row\", table: model.table, row: { ...row, ...values } });\n }\n state.after = String(row.id);\n }\n if (log) { log.push({ op: \"state:end\" }); log.close(); }\n if (rows.length < 100) { state.table++; state.after = \"\"; }\n sql.exec(`INSERT OR REPLACE INTO \"_engine_meta\" (\"key\", value) VALUES (?, ?)`, stateKey, JSON.stringify(state));\n sql.exec(`DELETE FROM \"_personal_changes\"`);\n });\n personal.clearPlaintext();\n }\n return true;\n}\n","import type { RoleClaim } from \"../claims\";\nimport { NAMESPACES, findNamespace } from \"./registry\";\nimport type { SqlExecutor, SqlRow } from \"./tx-sql\";\nimport { validateEnvelope, isLinkOp } from \"./tx-validate\";\nimport { authorizeOps, assertRowPermissions } from \"./tx-permissions\";\nimport { appendLogEntry } from \"./tx-pipeline\";\nimport { applyOps } from \"./tx-apply\";\nimport { stageBulkOps, isBulk, bulkChunk, stagedIds, releaseStaged } from \"./tx-bulk\";\nimport { LogWriter } from \"./tx-log\";\nimport { TxError, type TxResult } from \"./tx-types\";\nimport type { PersonalRuntime } from \"./personal\";\n\n/** Capture SQL side effects too: cascades and foreign-key nulling. */\nexport function installPersonalCapture(sql: SqlExecutor): void {\n sql.exec(`CREATE TABLE IF NOT EXISTS \"_personal_changes\" (table_name TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY (table_name, id)) WITHOUT ROWID`);\n for (const model of Object.values(NAMESPACES)) for (const action of [\"INSERT\", \"UPDATE\", \"DELETE\"]) {\n const row = action === \"DELETE\" ? \"OLD\" : \"NEW\";\n sql.exec(`CREATE TRIGGER IF NOT EXISTS \"_personal_capture_${model.table}_${action}\" AFTER ${action} ON \"${model.table}\"\n BEGIN INSERT OR REPLACE INTO \"_personal_changes\" (table_name, id) VALUES ('${model.table}', ${row}.id); END`);\n }\n}\n\n/** The caller wraps this async pipeline in storage.transaction(). */\nexport async function runPersonalTransaction(sql: SqlExecutor, personal: PersonalRuntime, workspace: string, claim: RoleClaim, envelope: unknown): Promise<TxResult> {\n if (claim.workspaceId !== workspace) throw new TxError(\"permission_denied\", \"The claim belongs to another workspace.\");\n const tx = validateEnvelope(envelope); authorizeOps(claim, tx.ops);\n // Keyed: the raw ops carry plaintext personal values.\n const hash = await personal.receiptHash(tx.rawOps);\n if (tx.clientTxId !== undefined) {\n const prior = sql.one<{ seq: number; ops_hash: string | null }>(`SELECT seq, ops_hash FROM \"_tx_receipts\" WHERE id = ?`, tx.clientTxId);\n if (prior) {\n if (prior.ops_hash === null || prior.ops_hash === hash) return { txId: tx.txId, seq: prior.seq, applied: 0 };\n throw new TxError(\"conflict\", \"The transaction id was already used with different ops.\");\n }\n const floor = Number(sql.one<{ value: string }>(`SELECT value FROM \"_engine_meta\" WHERE \"key\" = 'receipts_since'`)?.value ?? 0);\n if (floor > 0 && tx.issuedAt !== undefined && tx.issuedAt <= floor) throw new TxError(\"retry_expired\", \"This write predates the workspace's retained receipts.\");\n }\n const viewSql = personal.sql(sql);\n const staged = await personal.read(() => sql.transactionSync(() => stageBulkOps(viewSql, claim, tx.ops)));\n const chunks = (index: number) => (function* () {\n for (const ids of stagedIds(sql, staged.keys.get(index)!)) yield bulkChunk(tx.txId, tx.ops[index] as never, tx.rawOps[index], ids);\n })();\n try {\n const nothing = tx.ops.every((op, index) => isBulk(op) && staged.matched[index] === 0);\n if (nothing && tx.clientTxId === undefined) return { txId: tx.txId, seq: sql.one<{ seq: number }>(`SELECT high_water_seq AS seq FROM \"_tx_state\" WHERE id = 1`)?.seq ?? 0, applied: 0, matched: staged.matched };\n const now = Date.now();\n const seq = appendLogEntry(sql, { clientTxId: tx.clientTxId ?? null, ops: \"[]\", opsHash: hash, at: now, userId: claim.sub, role: claim.role });\n sql.exec(`DELETE FROM \"_personal_changes\"`);\n let applied = 0;\n for (const [index, op] of tx.ops.entries()) {\n const batches = isBulk(op) ? chunks(index) : [{ ops: [op] }];\n for (const batch of batches) for (let item of batch.ops) {\n await personal.read(() => assertRowPermissions(viewSql, claim, [item]));\n if (\"values\" in item && \"id\" in item) {\n const model = findNamespace(item.namespace)!;\n const inserting = !sql.one(`SELECT id FROM \"${model.table}\" WHERE id = ?`, item.id);\n const incoming = item.kind === \"upsert\" && inserting && item.createValues !== undefined ? item.createValues : item.values;\n const values = await personal.prepare(sql, model, item.id, incoming, inserting);\n item = { ...item, values, ...(item.kind === \"upsert\" && inserting ? { createValues: values } : {}) };\n }\n if (isLinkOp(item)) {\n const model = findNamespace(item.childNamespace)!;\n const current = sql.one<SqlRow>(`SELECT * FROM \"${model.table}\" WHERE id = ?`, item.childId);\n if (current && (item.kind === \"link\" || current[item.foreignKeyColumn] === item.parentId)) {\n const values = await personal.prepare(sql, model, item.childId, { [item.foreignKeyColumn]: item.kind === \"link\" ? item.parentId : null }, false);\n applied += applyOps({ sql, seq, now, txId: tx.txId }, [item]);\n const fields = Object.keys(values).filter(column => column !== item.foreignKeyColumn);\n if (fields.length) sql.exec(`UPDATE \"${model.table}\" SET ${fields.map(column => `\"${column}\" = ?`).join(\", \")} WHERE id = ?`, ...fields.map(column => values[column]), item.childId);\n continue;\n }\n }\n applied += applyOps({ sql, seq, now, txId: tx.txId }, [item]);\n }\n }\n const log = new LogWriter(sql, seq); log.push({ op: \"state:begin\" });\n let afterTable = \"\", afterId = \"\";\n for (;;) {\n const changed = sql.all<{ table_name: string; id: string }>(`SELECT table_name, id FROM \"_personal_changes\" WHERE table_name > ? OR (table_name = ? AND id > ?) ORDER BY table_name, id LIMIT 100`, afterTable, afterTable, afterId);\n if (!changed.length) break;\n for (const change of changed) {\n const row = sql.one<SqlRow>(`SELECT * FROM \"${change.table_name}\" WHERE id = ?`, change.id);\n log.push(row ? { op: \"state:row\", table: change.table_name, row } : { op: \"state:delete\", table: change.table_name, id: change.id });\n afterTable = change.table_name; afterId = change.id;\n }\n }\n log.push({ op: \"state:end\" }); log.close();\n sql.exec(`DELETE FROM \"_personal_changes\"`);\n return { txId: tx.txId, seq, applied, ...(tx.ops.some(isBulk) ? { matched: staged.matched } : {}) };\n } finally { releaseStaged(sql, staged); }\n}\n","/**\n * Minimal synchronous SQL surface used by the transaction pipeline.\n *\n * The Durable Object exposes a synchronous SQLite API plus `transactionSync`;\n * tests run the same pipeline against `bun:sqlite`. Keeping the contract here\n * lets the apply/pipeline code stay independent of either driver.\n *\n * Booleans are normalised to 0/1 by validation before they reach a binding.\n */\n\nimport { fitBindings } from \"./sql-binding\";\n\nexport type SqlValue = string | number | null | ArrayBuffer;\n\nexport type SqlRow = Record<string, SqlValue>;\n\nexport interface SqlExecutor {\n decodeRows?(namespace: string, rows: SqlRow[]): SqlRow[];\n /** Runs a statement and returns the number of rows it changed. */\n exec(sql: string, ...params: SqlValue[]): number;\n /** Runs a query and returns every row. */\n all<T extends SqlRow = SqlRow>(sql: string, ...params: SqlValue[]): T[];\n /** Runs a query and returns the first row, if any. */\n one<T extends SqlRow = SqlRow>(\n sql: string,\n ...params: SqlValue[]\n ): T | undefined;\n /** Runs `fn` atomically; any thrown error rolls the transaction back. */\n transactionSync<T>(fn: () => T): T;\n}\n\n/**\n * Adapts a Durable Object's SQLite storage to `SqlExecutor`. Every statement\n * goes through `fitBindings`, which keeps it within the object's limit of 100\n * bound parameters.\n */\nexport function durableObjectSqlExecutor(\n storage: DurableObjectStorage\n): SqlExecutor {\n const run = <T extends SqlRow>(sql: string, params: SqlValue[]) => {\n const fitted = fitBindings(sql, params);\n return storage.sql.exec<T>(fitted.sql, ...fitted.params);\n };\n return {\n exec(sql, ...params) {\n return run(sql, params).rowsWritten;\n },\n all<T extends SqlRow = SqlRow>(sql: string, ...params: SqlValue[]): T[] {\n return run<T>(sql, params).toArray();\n },\n one<T extends SqlRow = SqlRow>(\n sql: string,\n ...params: SqlValue[]\n ): T | undefined {\n return run<T>(sql, params).toArray()[0];\n },\n transactionSync<T>(fn: () => T): T {\n return storage.transactionSync(fn);\n },\n };\n}\n","import type { RoleClaim } from \"../claims\";\nimport { apiError } from \"../http\";\nimport { readTrustedRoleClaim } from \"./trusted-claim\";\nimport { TxError } from \"./tx-types\";\n\n/**\n * The WebSocket accept path shared by `WorkspaceRoom` and `DocumentRoom`.\n *\n * Both accepted a socket, verified the trusted role claim and reported a\n * rejection with `session:error` + close 1008 in copy-pasted code. This is the\n * authorization path for both objects, so it lives in one place: drift between\n * two copies would mean one socket class accepting a claim the other rejects.\n *\n * Callers own what happens after the accept (session handshake payload,\n * subscription state, document sync).\n */\n\nexport interface AcceptSocketOptions<Attachment> {\n ctx: DurableObjectState;\n request: Request;\n workspaceId: string;\n /** Builds the attachment persisted across hibernation. */\n buildAttachment: (claim: RoleClaim, clientId: string) => Attachment;\n /**\n * Optional authorization floor applied after the claim is verified.\n * Return a rejection to refuse the socket.\n */\n authorize?: (claim: RoleClaim) => { code: string; message: string } | null;\n}\n\nexport type AcceptSocketResult<Attachment> =\n | {\n accepted: true;\n client: WebSocket;\n server: WebSocket;\n claim: RoleClaim;\n attachment: Attachment;\n }\n | { accepted: false; response: Response };\n\nfunction rejectSocket(\n client: WebSocket,\n server: WebSocket,\n code: string,\n message: string\n): Response {\n try {\n server.send(JSON.stringify({ type: \"session:error\", code, message }));\n } catch {\n // A socket that cannot be written to is closed below anyway.\n }\n try {\n server.close(1008, \"role claim rejected\");\n } catch {\n // Already closed.\n }\n return new Response(null, { status: 101, webSocket: client });\n}\n\nexport function acceptVerifiedSocket<Attachment>(\n options: AcceptSocketOptions<Attachment>\n): AcceptSocketResult<Attachment> {\n const { ctx, request, workspaceId } = options;\n\n if (request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") {\n return {\n accepted: false,\n response: apiError(\n 426,\n \"upgrade_required\",\n \"Connect with a WebSocket upgrade request.\"\n ),\n };\n }\n\n const pair = new WebSocketPair();\n const client = pair[0];\n const server = pair[1];\n\n // Hibernation-friendly accept: the object can be evicted while the socket\n // stays open, so the verified claim lives in the serialized attachment.\n ctx.acceptWebSocket(server);\n\n let claim: RoleClaim;\n try {\n claim = readTrustedRoleClaim(request, workspaceId);\n } catch (error) {\n const txError = error instanceof TxError ? error : null;\n return {\n accepted: false,\n response: rejectSocket(\n client,\n server,\n txError?.code ?? \"permission_denied\",\n txError?.message ?? \"A verified role claim is required.\"\n ),\n };\n }\n\n const refusal = options.authorize?.(claim) ?? null;\n if (refusal !== null) {\n return {\n accepted: false,\n response: rejectSocket(client, server, refusal.code, refusal.message),\n };\n }\n\n const attachment = options.buildAttachment(claim, crypto.randomUUID());\n server.serializeAttachment(attachment);\n\n return { accepted: true, client, server, claim, attachment };\n}\n","/**\n * WebSocket wire contract for workspace live queries.\n *\n * Client -> server: `ping`, `query:subscribe`, `query:unsubscribe`, the\n * presence messages, `topic:join`, `topic:leave`, `topic:send`.\n * Server -> client: `session:ready`, `session:error`, `pong`, `query:data`,\n * `query:diff`, `query:unsubscribed`, `query:error`, the presence updates,\n * `topic:message`, `topic:error`, `error`.\n *\n * The socket attachment is the only durable copy of a subscription, so it is\n * persisted with `serializeAttachment` and re-read after hibernation.\n */\n\nimport {\n WORKSPACE_ROLE_LEVELS,\n type RoleClaim,\n type WorkspaceRole,\n} from \"../claims\";\nimport type { QueryDocument, QueryPageInfo, QueryResult } from \"./query-types\";\nimport { isTopic } from \"./topics\";\n\nexport interface StoredSubscription {\n id: string;\n /** Monotonic per-subscription sequence; persisted so wake does not rewind. */\n seq: number;\n query: QueryDocument;\n}\n\nexport interface PresenceState {\n /** Presence target, e.g. a diagram id. */\n target: string;\n /** Arbitrary JSON presence (name, colour, ...); never persisted. */\n presence?: unknown;\n cursor?: unknown;\n drag?: unknown;\n}\n\nexport interface PresencePeer {\n clientId: string;\n presence: unknown;\n cursor?: unknown;\n drag?: unknown;\n}\n\nexport const PRESENCE_TARGET_PATTERN = /^[A-Za-z0-9:_-]{1,128}$/;\n\nexport function isPresenceTarget(value: unknown): value is string {\n return typeof value === \"string\" && PRESENCE_TARGET_PATTERN.test(value);\n}\n\nexport interface SocketAttachment {\n clientId: string;\n sub: string;\n role: WorkspaceRole;\n /** Claim expiry, seconds since epoch. */\n exp: number;\n subscriptions: StoredSubscription[];\n /** Current ephemeral presence target and values for this socket. */\n presence?: PresenceState;\n /** Broadcast topics this socket has joined. */\n topics?: string[];\n}\n\nexport interface PingMessage {\n type: \"ping\";\n at?: unknown;\n}\n\nexport interface QuerySubscribeMessage {\n type: \"query:subscribe\";\n id: string;\n query: unknown;\n}\n\nexport interface QueryUnsubscribeMessage {\n type: \"query:unsubscribe\";\n id: string;\n}\n\nexport interface PresenceSetMessage {\n type: \"presence:set\";\n target: string;\n presence: unknown;\n}\n\nexport interface PresenceClearMessage {\n type: \"presence:clear\";\n target: string;\n}\n\nexport interface CursorSetMessage {\n type: \"cursor:set\";\n target: string;\n cursor: unknown;\n}\n\nexport interface DragSetMessage {\n type: \"drag:set\";\n target: string;\n drag: unknown;\n}\n\nexport interface DragClearMessage {\n type: \"drag:clear\";\n target: string;\n}\n\nexport interface TopicJoinMessage {\n type: \"topic:join\";\n topic: string;\n}\n\nexport interface TopicLeaveMessage {\n type: \"topic:leave\";\n topic: string;\n}\n\nexport interface TopicSendMessage {\n type: \"topic:send\";\n topic: string;\n message: unknown;\n}\n\nexport type ClientMessage =\n | TopicJoinMessage\n | TopicLeaveMessage\n | TopicSendMessage\n | PingMessage\n | QuerySubscribeMessage\n | QueryUnsubscribeMessage\n | PresenceSetMessage\n | PresenceClearMessage\n | CursorSetMessage\n | DragSetMessage\n | DragClearMessage;\n\nexport interface SessionReadyMessage {\n type: \"session:ready\";\n workspaceId: string;\n connections: number;\n}\n\nexport interface SessionErrorMessage {\n type: \"session:error\";\n code: string;\n message: string;\n}\n\nexport interface PongMessage {\n type: \"pong\";\n at?: unknown;\n now: number;\n}\n\nexport interface QueryDataMessage {\n type: \"query:data\";\n id: string;\n seq: number;\n data: QueryResult;\n pageInfo?: QueryPageInfo;\n}\n\nexport interface QueryDiffMessage {\n type: \"query:diff\";\n id: string;\n seq: number;\n /** Top-level namespace this diff applies to. */\n namespace: string;\n added: unknown[];\n updated: unknown[];\n removed: string[];\n /**\n * Every id in the namespace's result, in the query's order. Present when\n * keeping surviving rows in place and appending `added` would not give\n * that order: a row arrived mid-list, or an update moved one.\n */\n order?: string[];\n /** Present when the subscription's page metadata changed. */\n pageInfo?: QueryPageInfo;\n}\n\nexport interface QueryUnsubscribedMessage {\n type: \"query:unsubscribed\";\n id: string;\n}\n\nexport interface QueryErrorMessage {\n type: \"query:error\";\n id: string | null;\n code: string;\n message: string;\n}\n\nexport interface PresenceUpdateMessage {\n type: \"presence:update\";\n target: string;\n peers: PresencePeer[];\n}\n\nexport interface CursorUpdateMessage {\n type: \"cursor:update\";\n target: string;\n clientId: string;\n cursor: unknown;\n}\n\nexport interface DragUpdateMessage {\n type: \"drag:update\";\n target: string;\n clientId: string;\n drag: unknown;\n}\n\nexport interface TopicMessage {\n type: \"topic:message\";\n topic: string;\n message: unknown;\n /** The sending socket's client id and the claim subject behind it. */\n from: { clientId: string; sub: string };\n}\n\nexport interface TopicErrorMessage {\n type: \"topic:error\";\n topic: string | null;\n code: string;\n message: string;\n}\n\nexport interface ErrorMessage {\n type: \"error\";\n code: string;\n message?: string;\n}\n\nexport type ServerMessage =\n | SessionReadyMessage\n | SessionErrorMessage\n | PongMessage\n | QueryDataMessage\n | QueryDiffMessage\n | QueryUnsubscribedMessage\n | QueryErrorMessage\n | PresenceUpdateMessage\n | CursorUpdateMessage\n | DragUpdateMessage\n | TopicMessage\n | TopicErrorMessage\n | ErrorMessage;\n\n/**\n * Validates a deserialized attachment. Returns `null` for a socket accepted\n * before its claim was verified, or for any value that does not match the\n * persisted contract.\n */\nexport function parseSocketAttachment(value: unknown): SocketAttachment | null {\n if (!isRecord(value)) return null;\n\n const { clientId, sub, role, exp, subscriptions, presence, topics } = value;\n if (typeof clientId !== \"string\" || clientId.length === 0) return null;\n if (typeof sub !== \"string\" || sub.length === 0) return null;\n if (\n typeof role !== \"number\" ||\n !Number.isInteger(role) ||\n role < WORKSPACE_ROLE_LEVELS.GUEST ||\n role > WORKSPACE_ROLE_LEVELS.DEVELOPER\n ) {\n return null;\n }\n if (typeof exp !== \"number\" || !Number.isFinite(exp)) return null;\n if (!Array.isArray(subscriptions)) return null;\n\n const stored: StoredSubscription[] = [];\n for (const entry of subscriptions) {\n const subscription = parseSubscription(entry);\n if (subscription === null) return null;\n stored.push(subscription);\n }\n\n const parsedPresence = parsePresenceState(presence);\n if (parsedPresence === null) return null;\n\n if (topics !== undefined && (!Array.isArray(topics) || !topics.every(isTopic))) {\n return null;\n }\n\n return {\n clientId,\n sub,\n role: role as WorkspaceRole,\n exp,\n subscriptions: stored,\n ...(parsedPresence ? { presence: parsedPresence } : {}),\n ...(Array.isArray(topics) && topics.length > 0 ? { topics: [...topics] } : {}),\n };\n}\n\nfunction parsePresenceState(value: unknown): PresenceState | undefined | null {\n if (value === undefined) return undefined;\n if (!isRecord(value)) return null;\n if (!isPresenceTarget(value.target)) return null;\n return {\n target: value.target,\n presence: value.presence,\n cursor: value.cursor,\n drag: value.drag,\n };\n}\n\n/** Rebuilds the claim used for permission checks on an accepted socket. */\nexport function claimFromAttachment(\n attachment: SocketAttachment,\n workspaceId: string\n): RoleClaim {\n return {\n sub: attachment.sub,\n workspaceId,\n role: attachment.role,\n exp: attachment.exp,\n iat: 0,\n };\n}\n\nfunction parseSubscription(value: unknown): StoredSubscription | null {\n if (!isRecord(value)) return null;\n\n const { id, seq, query } = value;\n if (typeof id !== \"string\" || id.length === 0) return null;\n if (typeof seq !== \"number\" || !Number.isInteger(seq) || seq < 0) {\n return null;\n }\n if (!isRecord(query)) return null;\n\n return { id, seq, query: query as QueryDocument };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/**\n * Claim minting.\n *\n * The engine consumes a short-lived signed claim and never issues one. This\n * module is the other half: it turns a session into that claim, and it is\n * deliberately identity-agnostic. Bring BetterAuth, your own JWT, a session\n * cookie or an API key and implement two methods.\n *\n * Wire format matches the verifier exactly: compact JWS, HS256, base64url with\n * no padding, payload `{ sub, workspaceId, role, iat, exp, iss?, aud? }`.\n */\n\nimport type { ClaimLimits, LimitDecision } from \"./engine/claim-limits\";\nimport { WORKSPACE_ROLE_LEVELS, claimSecretProblem, type RoleClaim, type WorkspaceRole } from \"./claims\";\nimport { apiError, discardBody, json } from \"./http\";\n\nexport const DEFAULT_CLAIM_TTL_SECONDS = 300;\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport interface MintClaimInput {\n sub: string;\n workspaceId: string;\n role: WorkspaceRole;\n iss?: string;\n aud?: string;\n ttlSeconds?: number;\n}\n\nexport interface MintedClaim {\n token: string;\n expiresAt: number;\n expiresIn: number;\n}\n\nfunction base64UrlFromBytes(bytes: Uint8Array): string {\n let binary = \"\";\n for (let index = 0; index < bytes.length; index += 1) {\n binary += String.fromCharCode(bytes[index]);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction encodeJson(value: unknown): string {\n return base64UrlFromBytes(new TextEncoder().encode(JSON.stringify(value)));\n}\n\n/** Signs the compact HS256 claim the engine verifier accepts. */\nexport async function signRoleClaim(\n secret: string,\n input: MintClaimInput,\n now: number = Date.now()\n): Promise<MintedClaim> {\n const problem = claimSecretProblem(secret);\n if (problem !== null) throw new Error(problem);\n\n const ttlSeconds = input.ttlSeconds ?? DEFAULT_CLAIM_TTL_SECONDS;\n const issuedAt = Math.floor(now / 1000);\n const expiresAt = issuedAt + ttlSeconds;\n\n const payload: RoleClaim = {\n sub: input.sub,\n workspaceId: input.workspaceId,\n role: input.role,\n iat: issuedAt,\n exp: expiresAt,\n ...(input.iss ? { iss: input.iss } : {}),\n ...(input.aud ? { aud: input.aud } : {}),\n };\n\n const header = encodeJson({ alg: \"HS256\", typ: \"JWT\" });\n const body = encodeJson(payload);\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n key,\n new TextEncoder().encode(`${header}.${body}`)\n );\n\n return {\n token: `${header}.${body}.${base64UrlFromBytes(new Uint8Array(signature))}`,\n expiresAt: expiresAt * 1000,\n expiresIn: ttlSeconds,\n };\n}\n\n/**\n * The two methods a deployment implements, and an optional rate limit.\n * Everything else about identity (passwords, magic codes, OAuth, cookies)\n * stays in the host application.\n */\nexport interface ClaimIdentity {\n /** Resolve the caller's subject from the request. Null means \"not signed in\". */\n getSubject(headers: Headers): Promise<{ sub: string } | null>;\n /** Resolve the caller's role in a workspace. Null means \"not a member\". */\n getRole(workspaceId: string, sub: string): Promise<WorkspaceRole | null>;\n /**\n * Optional per-caller limit for the claim route, checked before anything\n * else. `key` is `claim:<cf-connecting-ip>`. Return false to refuse with\n * 429 `rate_limited`; a throw refuses with 500 `rate_limit_unavailable`.\n * Back it with a Cloudflare rate-limit binding when the route is public.\n */\n allowRequest?(key: string): Promise<boolean>;\n /**\n * Built-in limits, on by default: exact, global token buckets per caller\n * IP (before the session lookup) and per subject (after it). Defaults: 300\n * requests per IP and 30 per subject, refilling over 60 seconds. Set a\n * limit to `false`, or `limits: false`, to turn it off.\n */\n limits?: ClaimLimits | false;\n}\n\nexport interface MintClaimDependencies {\n identity: ClaimIdentity;\n secret: string;\n issuer?: string;\n audience?: string;\n ttlSeconds?: number;\n now?: () => number;\n /** Optional per-caller limiter; return false to reject with 429. */\n allowRequest?: (key: string) => Promise<boolean>;\n /** The built-in limits: one token for this IP or subject. */\n limit?: (kind: \"ip\" | \"subject\", value: string) => Promise<LimitDecision>;\n}\n\nfunction rateLimited(retryAfterSeconds: number): Response {\n const response = apiError(429, \"rate_limited\", \"Too many claim requests. Try again shortly.\");\n if (retryAfterSeconds > 0) response.headers.set(\"retry-after\", String(retryAfterSeconds));\n return response;\n}\n\n/**\n * `POST /_tapedb/claim`: session to workspace role to a short-lived claim.\n *\n * Rate limiting is the deployment's call. If you expose this on the public\n * internet, back `allowRequest` with a Cloudflare rate-limit binding.\n */\nexport async function mintClaim(\n request: Request,\n deps: MintClaimDependencies\n): Promise<Response> {\n if (request.method !== \"POST\") {\n await discardBody(request);\n return apiError(405, \"method_not_allowed\", \"Use POST.\");\n }\n\n const ip = request.headers.get(\"cf-connecting-ip\") ?? \"unknown\";\n if (deps.limit) {\n const decision = await deps.limit(\"ip\", ip);\n if (!decision.allowed) {\n await discardBody(request);\n return rateLimited(decision.retryAfterSeconds);\n }\n }\n\n if (deps.allowRequest) {\n const key = `claim:${ip}`;\n let allowed: boolean;\n try {\n allowed = await deps.allowRequest(key);\n } catch {\n return apiError(500, \"rate_limit_unavailable\", \"Could not apply the claim rate limit.\");\n }\n if (!allowed) {\n await discardBody(request);\n return apiError(429, \"rate_limited\", \"Too many claim requests. Try again shortly.\");\n }\n }\n\n let subject: { sub: string } | null;\n try {\n subject = await deps.identity.getSubject(request.headers);\n } catch {\n return apiError(500, \"session_lookup_failed\", \"Could not resolve the session.\");\n }\n\n if (subject === null || subject.sub.trim().length === 0) {\n await discardBody(request);\n return apiError(401, \"unauthenticated\", \"Sign in first.\");\n }\n\n if (deps.limit) {\n const decision = await deps.limit(\"subject\", subject.sub);\n if (!decision.allowed) {\n await discardBody(request);\n return rateLimited(decision.retryAfterSeconds);\n }\n }\n\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return apiError(400, \"invalid_body\", \"Request body must be a JSON object.\");\n }\n\n const workspaceId =\n typeof body === \"object\" && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>).workspaceId\n : undefined;\n\n if (typeof workspaceId !== \"string\" || !UUID_PATTERN.test(workspaceId)) {\n return apiError(400, \"invalid_workspace_id\", \"workspaceId must be a UUID.\");\n }\n\n const secretProblem = claimSecretProblem(deps.secret);\n if (secretProblem !== null) {\n return apiError(500, \"claim_secret_missing\", secretProblem);\n }\n\n let role: WorkspaceRole | null;\n try {\n role = await deps.identity.getRole(workspaceId, subject.sub);\n } catch {\n return apiError(500, \"membership_lookup_failed\", \"Could not resolve workspace membership.\");\n }\n\n if (role === null) {\n return apiError(403, \"not_a_member\", \"You are not a member of this workspace.\");\n }\n\n const minted = await signRoleClaim(\n deps.secret,\n {\n sub: subject.sub,\n workspaceId,\n role,\n iss: deps.issuer,\n aud: deps.audience,\n ttlSeconds: deps.ttlSeconds,\n },\n deps.now?.() ?? Date.now()\n );\n\n return json({\n token: minted.token,\n workspaceId,\n roleLevel: role,\n expiresAt: minted.expiresAt,\n expiresIn: minted.expiresIn,\n });\n}\n\n/**\n * Development-only issuer. Mints an OWNER claim for any workspace without a\n * session so `tapedb dev` works with zero configuration.\n *\n * The caller is responsible for refusing this in production; `defineTapeDB`\n * enforces that before this function is reachable.\n */\nexport async function mintDevClaim(\n workspaceId: string,\n secret: string\n): Promise<MintedClaim> {\n return signRoleClaim(secret, {\n sub: \"dev-user\",\n workspaceId,\n role: WORKSPACE_ROLE_LEVELS.OWNER,\n });\n}\n","/**\n * `POST /_tapedb/claim` routing.\n *\n * Kept out of the Worker entry so it can be tested without the Workers runtime:\n * a claim either mints a token or refuses. The built-in limits come in as a\n * function, so the route itself never addresses a Durable Object.\n */\n\nimport { apiError, discardBody, json } from \"./http\";\nimport { isWorkspaceId } from \"./engine/r2-keys\";\nimport { claimSecretProblem } from \"./claims\";\nimport { mintClaim, mintDevClaim, type ClaimIdentity } from \"./mint\";\nimport type { LimitDecision } from \"./engine/claim-limits\";\n\nexport interface ClaimRouteEnv {\n ENVIRONMENT?: string;\n TAPEDB_CLAIM_SECRET: string;\n TAPEDB_CLAIM_ISSUER?: string;\n TAPEDB_CLAIM_AUDIENCE?: string;\n TAPEDB_DEV_CLAIMS?: string;\n /**\n * When set, the development route mints only for requests that carry it in\n * `x-tapedb-dev-token`. For a deployed test Worker reachable by anyone:\n * without it, the route hands an owner claim for any workspace to anyone.\n */\n TAPEDB_DEV_CLAIMS_TOKEN?: string;\n}\n\n/** Header a gated development route expects TAPEDB_DEV_CLAIMS_TOKEN in. */\nexport const DEV_TOKEN_HEADER = \"x-tapedb-dev-token\";\n\nexport interface ClaimRouteOptions {\n env: ClaimRouteEnv;\n identity?: ClaimIdentity;\n devClaims?: boolean;\n /** Takes one token from a built-in limit (claim-limits.ts); absent when limits are off. */\n limit?: (kind: \"ip\" | \"subject\", value: string) => Promise<LimitDecision>;\n}\n\n/**\n * Order matters and is the security property: the development issuer is\n * checked first, but two independent conditions must both hold:\n *\n * 1. the code opted in (`devClaims: true`), and\n * 2. the deployment opted in (`TAPEDB_DEV_CLAIMS=true`), and\n * 3. `ENVIRONMENT` is not `production`.\n *\n * With `TAPEDB_DEV_CLAIMS_TOKEN` set, the request must also carry that token\n * (compared in constant time); without it the route answers 401 and mints\n * nothing.\n *\n * The env-var condition is the one that makes a plain `wrangler deploy` safe:\n * `tapedb dev` passes the var on the command line, so a deployed Worker never\n * has it, even if `ENVIRONMENT` is left at the generated default.\n */\nexport async function handleClaimRequest(\n request: Request,\n options: ClaimRouteOptions\n): Promise<Response> {\n const { env, identity, devClaims = false, limit } = options;\n const isProduction = env.ENVIRONMENT === \"production\";\n const devEnabled = devClaims && env.TAPEDB_DEV_CLAIMS === \"true\";\n\n if (devEnabled && !isProduction) {\n const required = env.TAPEDB_DEV_CLAIMS_TOKEN;\n if (required && !sameToken(request.headers.get(DEV_TOKEN_HEADER) ?? \"\", required)) {\n await discardBody(request);\n return apiError(401, \"dev_token_required\", `This development claim route needs the ${DEV_TOKEN_HEADER} header.`);\n }\n if (request.method !== \"POST\") {\n await discardBody(request);\n return apiError(405, \"method_not_allowed\", \"Use POST.\");\n }\n\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return apiError(400, \"invalid_body\", \"Request body must be a JSON object.\");\n }\n\n const workspaceId =\n typeof body === \"object\" && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>).workspaceId\n : undefined;\n\n if (typeof workspaceId !== \"string\" || !isWorkspaceId(workspaceId)) {\n return apiError(400, \"invalid_workspace_id\", \"workspaceId must be a UUID.\");\n }\n\n const secretProblem = claimSecretProblem(env.TAPEDB_CLAIM_SECRET);\n if (secretProblem !== null) {\n return apiError(500, \"claim_secret_missing\", secretProblem);\n }\n\n const minted = await mintDevClaim(workspaceId, env.TAPEDB_CLAIM_SECRET);\n return json({ token: minted.token, workspaceId, expiresIn: minted.expiresIn });\n }\n\n if (!identity) {\n await discardBody(request);\n return apiError(\n 501,\n \"identity_not_configured\",\n \"Pass defineTapeDB({ identity }) to serve claims.\"\n );\n }\n\n return mintClaim(request, {\n identity,\n ...(identity.allowRequest ? { allowRequest: (key: string) => identity.allowRequest!(key) } : {}),\n ...(limit ? { limit } : {}),\n secret: env.TAPEDB_CLAIM_SECRET,\n issuer: env.TAPEDB_CLAIM_ISSUER,\n audience: env.TAPEDB_CLAIM_AUDIENCE,\n });\n}\n\n/** Constant-time comparison, so the token cannot be guessed byte by byte from timing. */\nfunction sameToken(given: string, expected: string): boolean {\n const a = new TextEncoder().encode(given);\n const b = new TextEncoder().encode(expected);\n let diff = a.length ^ b.length;\n for (let i = 0; i < b.length; i += 1) diff |= (a[i] ?? 0) ^ b[i];\n return diff === 0;\n}\n","/**\n * Worker entry.\n *\n * `defineTapeDB()` installs the deployment schema and returns the Durable\n * Object class plus the fetch handler. The consumer's Worker is then two\n * exports and nothing else:\n *\n * const tapedb = defineTapeDB({ schema });\n * export const WorkspaceRoom = tapedb.WorkspaceRoom;\n * export default tapedb.worker;\n */\n\nimport { configureRegistry, registryConfigured } from \"../engine/registry\";\nimport { configureMigrations } from \"../engine/migrations-bundle\";\nimport { configurePermissions } from \"../engine/tx-permissions\";\nimport { configureTopics, type TopicOptions } from \"../engine/topics\";\nimport { configureAudit } from \"../engine/audit\";\nimport { configureFileAccess, fileRulesConfigured } from \"../engine/file-access\";\nimport { configureRetention, type RetentionOptions } from \"../engine/durability/retention\";\nimport { isWorkspaceId } from \"../engine/r2-keys\";\nimport { WorkspaceRoom } from \"../engine/workspace-room\";\nimport { sourceEnvironment, readMove } from \"../engine/workspace-move\";\nimport { apiError, discardBody, json } from \"../http\";\nimport { handleClaimRequest } from \"../claim-route\";\nimport { limiterKey, limiterName, resolveClaimLimits, type ClaimLimits, type LimitDecision } from \"../engine/claim-limits\";\nimport { mintClaim, mintDevClaim, type ClaimIdentity } from \"../mint\";\nimport type { TapeDBSchema } from \"../schema\";\nimport type { BundledWorkspaceMigration } from \"../engine/migrations-bundle\";\nimport type { Env } from \"../types\";\nimport {\n authenticateEngineRequest,\n ClaimError,\n encodeTrustedRoleClaim,\n extractClaimToken,\n TRUSTED_CLAIM_HEADER,\n verifyRoleClaim,\n} from \"../verify\";\nimport { WORKSPACE_ROLE_LEVELS } from \"../claims\";\n\n/**\n * The most one upload request carries: a whole small file in one PUT, or one\n * part of a multipart upload. A file of any size goes up as parts (R2 keeps\n * objects up to 5 TB), so this bounds a request, not a file; it stays well\n * inside the request body size every Workers plan accepts.\n */\nexport { MAX_UPLOAD_BYTES } from \"../engine/storage-routes\";\n\nconst ENGINE_PREFIX = \"/engine/workspaces\";\n\n/** One app migration, as `tapedb migrate` bundles it. */\nexport type AppMigration = BundledWorkspaceMigration;\n\nexport interface DefineTapeDBOptions {\n schema: TapeDBSchema;\n /**\n * The app's committed migrations, from `tapedb/migrations.gen.ts`. Omit\n * only before the first `tapedb migrate dev`: the schema's generated SQL\n * is used, which cannot evolve.\n */\n migrations?: readonly AppMigration[];\n /**\n * Identity adapter. Implement `getSubject` and `getRole` to serve\n * `POST /_tapedb/claim`. Without it that route returns 501 and the consumer\n * must supply tokens to the client itself.\n */\n identity?: ClaimIdentity;\n /**\n * Development-only issuer: mints an OWNER claim for any workspace with no\n * session. Always refused when `ENVIRONMENT` is `production`.\n */\n devClaims?: boolean;\n /**\n * Broadcast topics. `authorize` decides whether a caller may join a topic\n * or send to it; without it anyone with a claim for the workspace may,\n * guests included, as with presence. `replaySeconds` (default 60) is how\n * much of each topic the room keeps for clients that reconnect.\n *\n * @experimental May change in a minor release.\n */\n topics?: TopicOptions;\n /**\n * Records who changed each row: the claim's subject and role on every log\n * entry (also in R2), and a per-row history read with `db.$history`.\n * Off by default; the history is pruned with `retention`.\n */\n audit?: boolean;\n /**\n * How long deleted or overwritten values may remain in the workspace's\n * history (R2 log segments, older snapshots, the local replay log).\n * Defaults to 30 days; at least 2.\n */\n retention?: RetentionOptions;\n}\n\nexport interface TapeDBWorker {\n /** The database room class. Export it from the Worker entry. */\n WorkspaceRoom: typeof WorkspaceRoom;\n worker: { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> };\n}\n\n/**\n * Headers the Worker forwards to a room: the client's, minus every\n * `x-tapedb-*` header. Only the Worker sets those (the verified claim).\n */\nfunction forwardableHeaders(source: HeadersInit | undefined): Headers {\n const headers = new Headers(source);\n for (const name of [...headers.keys()]) {\n if (name.startsWith(\"x-tapedb-\")) headers.delete(name);\n }\n return headers;\n}\n\n/** A room URL with exactly this path; never resolved relative to anything. */\nfunction roomUrl(path: string, search = \"\"): URL {\n const url = new URL(\"https://room.internal/\");\n url.pathname = path;\n url.search = search;\n return url;\n}\n\nfunction roomRequest(request: Request, path: string): Request {\n const init: RequestInit = { method: request.method, headers: forwardableHeaders(request.headers) };\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n init.body = request.body;\n }\n return new Request(roomUrl(path, new URL(request.url).search), init);\n}\n\n/** The workspace's Durable Object, inside TAPEDB_JURISDICTION when set. */\n/**\n * One token from a built-in claim limit. A limiter that cannot be reached\n * lets the request through and logs it: a limiter outage should not lock\n * every user out of every workspace.\n */\nasync function takeClaimToken(\n env: Env,\n limits: Required<ClaimLimits>,\n kind: \"ip\" | \"subject\",\n value: string\n): Promise<LimitDecision> {\n const limit = limits[kind];\n if (!limit || !env.TAPEDB_CLAIM_SECRET) return { allowed: true, retryAfterSeconds: 0 };\n try {\n const { key, shard } = await limiterKey(env.TAPEDB_CLAIM_SECRET, `${kind}:${value}`);\n const response = await workspaceStub(env, limiterName(shard)).fetch(\"https://tapedb.limits/limit\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ key, requests: limit.requests, perSeconds: limit.perSeconds }),\n });\n if (!response.ok) throw new Error(`limiter answered ${response.status}`);\n return (await response.json()) as LimitDecision;\n } catch (error) {\n console.warn(JSON.stringify({ event: \"claim_limit_unavailable\", kind, message: error instanceof Error ? error.message : String(error) }));\n return { allowed: true, retryAfterSeconds: 0 };\n }\n}\n\nfunction workspaceStub(env: Env, workspaceId: string): DurableObjectStub<WorkspaceRoom> {\n let namespace = env.WORKSPACE;\n if (env.TAPEDB_JURISDICTION) {\n try {\n namespace = env.WORKSPACE.jurisdiction(env.TAPEDB_JURISDICTION as DurableObjectJurisdiction);\n } catch (error) {\n // Plain `wrangler dev`: workerd has no jurisdictions. `tapedb dev` clears the var.\n throw new Error(`TAPEDB_JURISDICTION is \"${env.TAPEDB_JURISDICTION}\" but this runtime has no jurisdictions (${error instanceof Error ? error.message : String(error)}). Run locally with \\`tapedb dev\\`, which leaves it out.`);\n }\n }\n return namespace.get(namespace.idFromName(workspaceId));\n}\n\n/**\n * Calls the Durable Object directly with a trusted claim. Used for the file\n * metadata index, which lives in the workspace's SQLite next to the data, not\n * in R2.\n */\nasync function callRoom(\n env: Env,\n workspaceId: string,\n path: string,\n init: RequestInit,\n trustedClaim: string\n): Promise<Response> {\n const headers = forwardableHeaders(init.headers);\n headers.set(TRUSTED_CLAIM_HEADER, trustedClaim);\n\n const queryAt = path.indexOf(\"?\");\n const request = new Request(queryAt === -1 ? roomUrl(path) : roomUrl(path.slice(0, queryAt), path.slice(queryAt)), {\n ...init,\n headers,\n });\n\n return workspaceStub(env, workspaceId).fetch(request);\n}\n\nexport function defineTapeDB(options: DefineTapeDBOptions): TapeDBWorker {\n const { schema, identity, devClaims = false, migrations } = options;\n // Validated once, when the Worker is defined.\n const claimLimits = resolveClaimLimits(identity?.limits);\n\n // One schema per Worker instance. Installed at module evaluation, before any\n // request or Durable Object is constructed.\n configureRegistry(schema.registry);\n configureMigrations(\n migrations === undefined ? schema.migrations : [schema.migrations[0], ...migrations]\n );\n configurePermissions(schema.permissions);\n configureTopics(options.topics);\n configureAudit(options.audit);\n configureFileAccess(schema.files);\n configureRetention(options.retention);\n\n const worker = {\n async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {\n if (!registryConfigured()) {\n return apiError(500, \"engine_not_configured\", \"Call defineTapeDB({ schema }) first.\");\n }\n\n const url = new URL(request.url);\n\n if (url.pathname === \"/status\" || url.pathname === \"/health\") {\n return json({ ok: true, service: \"tapedb\" });\n }\n\n if (url.pathname === \"/_tapedb/claim\") {\n return handleClaimRequest(request, {\n env,\n identity,\n devClaims,\n ...(claimLimits.ip || claimLimits.subject ? { limit: (kind, value) => takeClaimToken(env, claimLimits, kind, value) } : {}),\n });\n }\n\n if (!url.pathname.startsWith(`${ENGINE_PREFIX}/`)) {\n await discardBody(request);\n return apiError(404, \"no_route\", `No route for ${request.method} ${url.pathname}.`);\n }\n\n const rest = url.pathname.slice(ENGINE_PREFIX.length + 1);\n const slash = rest.indexOf(\"/\");\n const workspaceId = slash === -1 ? rest : rest.slice(0, slash);\n const roomPath = slash === -1 ? \"/\" : rest.slice(slash);\n\n if (!isWorkspaceId(workspaceId)) {\n await discardBody(request);\n return apiError(400, \"invalid_workspace_id\", \"Workspace id must be a UUID.\");\n }\n // An empty segment (\"//\") would let one route stand in for another\n // that the Worker keeps internal. No room route has one; a file path\n // may, and is passed to the byte routes as data, never as the path.\n if (!roomPath.startsWith(\"/files/\") && roomPath.includes(\"//\")) {\n await discardBody(request);\n return apiError(404, \"no_route\", `No route for ${request.method} ${url.pathname}.`);\n }\n\n // Every engine route needs a verified claim before a Durable Object is\n // touched: addressing one by name creates it, runs its migrations and\n // checks R2 for a recovery, so an open route would let anyone create\n // objects for any UUID. The Worker's own /status answers health checks.\n let trustedClaim: string | null = null;\n let role: number = WORKSPACE_ROLE_LEVELS.GUEST;\n\n {\n try {\n const claim = await authenticateEngineRequest(request, env, workspaceId);\n role = claim.role;\n trustedClaim = encodeTrustedRoleClaim(claim);\n if (roomPath === \"/move\") {\n if (request.method !== \"POST\") return apiError(405, \"method_not_allowed\", \"Move a workspace with POST.\");\n if (role < WORKSPACE_ROLE_LEVELS.OWNER) return apiError(403, \"insufficient_role\", \"Only an owner can move a workspace.\");\n return callRoom(env, workspaceId, \"/move/run\", { method: \"POST\", body: request.body, duplex: \"half\" } as RequestInit, trustedClaim);\n }\n\n if (roomPath.startsWith(\"/move/\") || roomPath.startsWith(\"/storage/\")) return apiError(404, \"not_found\", \"No public route.\");\n if (env.TAPEDB_MOVE_FROM !== undefined && (await readMove(env.DATA, workspaceId))?.state !== \"ready\") {\n env = sourceEnvironment(env);\n const state = await readMove(env.DATA, workspaceId);\n const read = request.method === \"GET\" || request.method === \"HEAD\" || roomPath === \"/query\";\n if (state?.state === \"frozen\" && !read) return apiError(409, \"workspace_moving\", \"Writes resume after the move.\");\n }\n\n\n // The file index is written only by the byte routes below, which\n // check roles and keep index and bytes in step. A client may list\n // it with the role that reads files, and nothing else.\n if (roomPath === \"/files\") {\n if (request.method !== \"GET\") {\n await discardBody(request);\n return apiError(405, \"method_not_allowed\", \"The file index changes only through uploads and deletes under /files/<path>.\");\n }\n // With file rules the room lists only what the caller may read.\n if (!fileRulesConfigured() && role < WORKSPACE_ROLE_LEVELS.MEMBER) {\n return apiError(403, \"insufficient_role\", \"Insufficient role to list files.\");\n }\n }\n\n if (roomPath.startsWith(\"/files/\")) {\n return callRoom(env, workspaceId, `/storage/${roomPath.slice(\"/files/\".length)}${url.search}`, {\n method: request.method,\n headers: request.headers,\n ...(request.method === \"GET\" || request.method === \"HEAD\" ? {} : { body: request.body }),\n }, trustedClaim);\n }\n } catch (error) {\n await discardBody(request);\n if (error instanceof ClaimError) {\n const status = error.code === \"wrong_workspace\" ? 403 : 401;\n return apiError(status, error.code, error.message);\n }\n throw error;\n }\n }\n\n const forwarded = roomRequest(request, roomPath);\n if (trustedClaim !== null) forwarded.headers.set(TRUSTED_CLAIM_HEADER, trustedClaim);\n\n return workspaceStub(env, workspaceId).fetch(forwarded);\n },\n };\n\n return { WorkspaceRoom, worker };\n}\n\n// The public surface of `@tapedb/tapedb/worker`; see API.md. Everything else in this\n// module (trusted-claim plumbing, dev claims, the room class itself) is\n// internal: the Durable Object class reaches the Worker as\n// `defineTapeDB(...).WorkspaceRoom`.\nexport { ClaimError, verifyRoleClaim };\nexport { signRoleClaim } from \"../mint\";\nexport type { ClaimIdentity } from \"../mint\";\nexport type { ClaimLimit, ClaimLimits } from \"../engine/claim-limits\";\nexport type { TopicAction, TopicAuthorizer, TopicOptions } from \"../engine/topics\";\nexport { WORKSPACE_ROLE_LEVELS };\nexport type { Env, TapeDBSchema, BundledWorkspaceMigration };\n\n// A named type for downstream declaration emission; no runtime room export.\nexport type { WorkspaceRoom as TapeDBRoom };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,SAAS,gBACd,MACA,OACS;AACT,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAElD,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AAAA,IACzD,KAAK;AACH,aAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AAAA,IACzD,KAAK;AACH,aAAO,UAAU;AAAA,IACnB,KAAK;AACH,aAAO,oBAAoB,KAAK;AAAA,IAClC,KAAK;AAAA,IACL,KAAK;AACH,aAAO,OAAO,UAAU,WAAW,UAAU,KAAK,IAAI;AAAA,EAC1D;AACF;AAEA,SAAS,oBAAoB,OAAgC;AAC3D,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,EAC1C;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,SAAS,OAAO,KAAK;AAC3B,WAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,UAAU,OAAwB;AACzC,MAAI;AACF,WAAO,KAAK,MAAM,KAAK;AAAA,EACzB,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;;;ACsIO,IAAM,UAAN,cAAsB,MAAM;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,UAA0B,CAAC,GAC3B;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,OAAO,QAAQ;AACpB,SAAK,UAAU,QAAQ;AAAA,EACzB;AAAA,EAEA,SAAuB;AACrB,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,GAAI,KAAK,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AO,QAAQ,WAAW,SAAS,QAAQ,WAAW,UAAU,aAAa;AACnF,gBAAI,OAAO,UAAU,YAAY,CAAC,KAAM,QAAO,SAAS,KAAK,oBAAoB,+BAA+B;AAAA,UAClH;AAMA,cAAI,aAAa,UAAU;AACzB,gBAAI,QAAQ,WAAW,OAAO;AAC5B,oBAAM,YAAY,OAAO;AACzB,qBAAO,SAAS,KAAK,sBAAsB,8EAA8E;AAAA,YAC3H;AAEA,gBAAI,CAAC,oBAAoB,KAAK,OAAO,sBAAsB,QAAQ;AACjE,qBAAO,SAAS,KAAK,qBAAqB,kCAAkC;AAAA,YAC9E;AAAA,UACF;AAEA,cAAI,SAAS,WAAW,SAAS,GAAG;AAClC,mBAAO,SAAS,KAAK,aAAa,YAAY,SAAS,MAAM,UAAU,MAAM,CAAC,GAAG,IAAI,MAAM,IAAI;AAAA,cAC7F,QAAQ,QAAQ;AAAA,cAChB,SAAS,QAAQ;AAAA,cACjB,GAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,SAAS,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;AAAA,YACxF,GAAG,YAAY;AAAA,UACjB;AAAA,QACF,SAAS,OAAO;AACd,gBAAM,YAAY,OAAO;AACzB,cAAI,iBAAiB,YAAY;AAC/B,kBAAM,SAAS,MAAM,SAAS,oBAAoB,MAAM;AACxD,mBAAO,SAAS,QAAQ,MAAM,MAAM,MAAM,OAAO;AAAA,UACnD;AACA,gBAAM;AAAA,QACR;AAAA,MACF;AAEA,YAAM,YAAY,YAAY,SAAS,QAAQ;AAC/C,UAAI,iBAAiB,KAAM,WAAU,QAAQ,IAAI,sBAAsB,YAAY;AAEnF,aAAO,cAAc,KAAK,WAAW,EAAE,MAAM,SAAS;AAAA,IACxD;AAAA,EACF;AAEA,SAAO,EAAE,eAAe,OAAO;AACjC;","names":["namespace","raw","subject","ISO_DATE_PATTERN","isPlainObject","invalidOp","invalidValue","isPlainObject","invalidOp","invalidValue","isPlainObject","invalidOp","invalidValue","envelope","count","authOf","bytes","bytes","textEncoder","encoder","bytes","assertPositiveInteger","highWater","bytes","json","envelope","seq","readSchemaVersion","LOG_SEGMENT_NAME","bytes","schemaVersion","changes","table","enabled","highWater","envelope","json","callRoom","bytes","upload","locate","encoder","op","columns","resolve","decoder","encoder","bytes","bytes","BASE64URL_PATTERN","bytes","encodeBase64Url","fields","envelope","fields","isRecord","resolve","errorMessage","encoder","envelope","isPlainObject","previousKey","UUID_PATTERN","bytes"]}
|