@sudobility/screenwriter_types 0.1.5 → 0.1.7

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/api/envelope.ts","../src/api/pagination.ts","../src/api/routes.ts","../src/tenancy/index.ts","../src/sharing/index.ts","../src/projects/index.ts","../src/lifecycle/index.ts","../src/me/index.ts","../src/account/index.ts","../src/templates/index.ts","../src/versions/index.ts","../src/commands/index.ts","../src/formats/index.ts","../src/reads/index.ts","../src/io/index.ts","../src/ai/index.ts","../src/ai/actions.ts","../src/jobs/index.ts","../src/reports/index.ts","../src/packets/index.ts","../src/assets/index.ts","../src/collab/index.ts","../src/credits/index.ts","../src/public/index.ts","../src/admin/index.ts","../src/sync/permissions.ts","../src/sync/index.ts","../node_modules/lib0/binary.js","../node_modules/lib0/math.js","../node_modules/lib0/number.js","../node_modules/lib0/string.js","../node_modules/lib0/error.js","../node_modules/lib0/encoding.js","../node_modules/lib0/decoding.js","../src/sync/codec.ts"],"sourcesContent":["/**\n * Response envelope, error vocabulary (spec 05 §12) and pagination shape.\n * Platform-free: no clock is read here, so the envelope carries no timestamp.\n */\n\n/** Every REST error code and its fixed HTTP status (spec 05 §12). */\nconst ERROR_TABLE = [\n ['UNAUTHORIZED', 401],\n ['REAUTH_REQUIRED', 401],\n ['API_KEY_FORBIDDEN', 403],\n ['FORBIDDEN', 403],\n ['ROLE_ESCALATION', 403],\n ['NOT_FOUND', 404],\n ['PROJECT_NOT_FOUND', 404],\n ['DOCUMENT_NOT_FOUND', 404],\n ['SNAPSHOT_NOT_FOUND', 404],\n ['TEMPLATE_NOT_FOUND', 404],\n ['ITEM_NOT_FOUND', 404],\n ['ANCHOR_NOT_FOUND', 404],\n ['TARGET_NOT_FOUND', 404],\n ['VALIDATION', 400],\n ['COMMAND_INVALID', 422],\n ['TEMPLATE_INVALID', 422],\n ['CONFIRMATION_MISMATCH', 400],\n ['EPOCH_MISMATCH', 409],\n ['DOCUMENT_LOCKED', 423],\n ['DOCUMENT_BUSY', 409],\n ['JOB_ALREADY_RUNNING', 409],\n ['JOB_FINISHED', 409],\n ['JOB_NOT_FINISHED', 409],\n ['LAST_OWNER', 409],\n ['ALREADY_MEMBER', 409],\n ['NOT_A_MEMBER', 409],\n ['PERSONAL_WORKSPACE_IMMUTABLE', 409],\n ['OWNS_TEAM_WORKSPACE', 409],\n ['NOT_IN_TRASH', 409],\n ['PARENT_IN_TRASH', 409],\n ['FOLDER_DEPTH', 409],\n ['FOLDER_CYCLE', 409],\n ['MOVE_FORBIDDEN', 403],\n ['BUILTIN_IMMUTABLE', 409],\n ['LOCATOR_AMBIGUOUS', 409],\n ['INVITATION_INVALID', 410],\n ['INVITATION_EXPIRED', 410],\n ['INVITATION_CLOSED', 410],\n ['EMAIL_MISMATCH', 403],\n ['SHARE_LINK_INVALID', 404],\n ['SHARE_LINK_PASSWORD_REQUIRED', 401],\n ['WATERMARK_REQUIRED', 403],\n ['EDIT_WINDOW_CLOSED', 409],\n ['ASSET_TOO_LARGE', 413],\n ['IMPORT_TOO_LARGE', 413],\n ['UNSUPPORTED_FORMAT', 400],\n ['IMPORT_FAILED', 400],\n ['IMPORT_INVALID', 422],\n ['ASSET_TYPE_REJECTED', 415],\n ['ASSET_CHECKSUM_MISMATCH', 422],\n ['ASSET_NOT_READY', 409],\n ['ASSET_IN_USE', 409],\n ['UPLOAD_INCOMPLETE', 409],\n ['UPLOAD_EXPIRED', 410],\n ['STORAGE_QUOTA_EXCEEDED', 507],\n ['STORAGE_UNAVAILABLE', 503],\n ['IMPORT_FORMAT_UNSUPPORTED', 415],\n ['EXPORT_FORMAT_UNSUPPORTED', 415],\n ['COMPARE_TOO_LARGE', 413],\n ['LIMIT_EXCEEDED', 409],\n ['RATE_LIMITED', 429],\n ['QUOTA_EXCEEDED', 429],\n ['INSUFFICIENT_CREDITS', 402],\n ['AI_UNAVAILABLE', 503],\n ['AI_INPUT_TOO_LARGE', 413],\n ['AI_GENERATION_FAILED', 502],\n ['AI_OUTPUT_INVALID', 502],\n ['CONFIG_MISSING', 503],\n ['CLIENT_TOO_OLD', 426],\n ['CONTENT_CHANGED', 409],\n ['STYLE_NOT_IN_TEMPLATE', 422],\n ['NOT_CONTIGUOUS', 422],\n ['LOCKED_CONTENT', 409],\n ['NAME_COLLISION', 409],\n ['KIND_MISMATCH', 422],\n ['OVERLAPPING_SHOTS', 422],\n ['OVERLAPPING_NODE', 422],\n ['SCENES_LOCKED', 409],\n ['NOT_LOCKED', 409],\n ['RANGE_OUT_OF_BOUNDS', 422],\n ['INVALID_TARGET', 422],\n ['INVALID_DUAL_DIALOGUE', 422],\n ['FOUNTAIN_PARSE_ERROR', 422],\n ['UNMAPPED_STYLES', 422],\n ['RANGE_TOO_LARGE', 413],\n ['PAYLOAD_TOO_LARGE', 413],\n ['INVALID_REGEX', 400],\n ['REPORT_OPTIONS_INVALID', 400],\n ['REPORT_KIND_UNAVAILABLE', 501],\n ['ENTITY_IN_USE', 409],\n ['VARIANT_IN_USE', 409],\n ['SNAPSHOT_NOT_IN_DOCUMENT', 404],\n ['ITEM_NOT_IN_SNAPSHOT', 404],\n ['INVALID_LOCATOR', 400],\n ['LOCATOR_NOT_FOUND', 404],\n ['ROLE_NOT_ALLOWED_FOR_TARGET', 422],\n ['ID_CONFLICT', 409],\n ['IDEMPOTENCY_KEY_REUSED', 409],\n ['IDEMPOTENCY_IN_PROGRESS', 409],\n ['DEVICE_REVOKED', 403],\n ['MACRO_TRIGGER_TAKEN', 409],\n ['STALE_WRITE', 409],\n ['HANDOFF_INVALID', 410],\n ['WATERMARK_NOT_FOUND', 404],\n ['OCR_UNAVAILABLE', 503],\n ['GRAMMAR_UNAVAILABLE', 503],\n ['AI_CONSENT_REQUIRED', 403],\n ['AI_DISABLED_FOR_WORKSPACE', 403],\n ['AI_EXCLUDED_DOCUMENT', 403],\n ['AI_KEY_NOT_PERMITTED', 403],\n ['QUOTE_EXCEEDS_MAX', 402],\n ['AI_CONTENT_REFUSED', 422],\n ['SCOPE_TOO_LARGE', 413],\n ['SUGGESTION_UNAVAILABLE', 409],\n ['JOB_KIND_DISABLED', 501],\n ['JOB_KIND_NOT_GENERIC', 400],\n ['JOB_FAILED', 409],\n ['JOB_TIMEOUT', 504],\n ['LIKENESS_CONSENT_REQUIRED', 422],\n ['CONTENT_REJECTED', 422],\n ['INTERNAL', 500],\n] as const;\n\ntype ErrorTable = typeof ERROR_TABLE;\nexport type ApiErrorCode = ErrorTable[number][0];\n\nexport const API_ERROR_CODES = Object.fromEntries(\n ERROR_TABLE.map(([code]) => [code, code])\n) as { readonly [C in ApiErrorCode]: C };\n\n/** HTTP status per error code. */\nexport const ERROR_STATUS = Object.fromEntries(ERROR_TABLE) as Record<\n ApiErrorCode,\n number\n>;\n\nexport interface ApiSuccess<T> {\n success: true;\n data: T;\n}\n\nexport interface ApiFailure {\n success: false;\n /** Human-readable message. */\n error: string;\n code: ApiErrorCode;\n /** Code-specific details (e.g. `issues`, `index`, `ids`). */\n details?: Record<string, unknown>;\n}\n\nexport type ApiResponse<T> = ApiSuccess<T> | ApiFailure;\n\nexport function successResponse<T>(data: T): ApiSuccess<T> {\n return { success: true, data };\n}\n\n/** The only constructor for failure envelopes. */\nexport function errorResponse(\n message: string,\n code: ApiErrorCode,\n details?: Record<string, unknown>\n): ApiFailure {\n return details === undefined\n ? { success: false, error: message, code }\n : { success: false, error: message, code, details };\n}\n\n/** Cursor page: `nextCursor` is null on the last page. */\nexport interface Paginated<T> {\n items: T[];\n nextCursor: string | null;\n}\n","import { z } from 'zod';\n\n/** `limit` 1-200 (default 50); `cursor` is an opaque base64url string. */\nexport const cursorQuerySchema = z.object({\n limit: z.coerce.number().int().min(1).max(200).default(50),\n cursor: z\n .string()\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n});\nexport type CursorQuery = z.infer<typeof cursorQuerySchema>;\n","/**\n * Route table for slices B1-B5 (spec 05 §6). Paths are relative to API_BASE_PATH.\n * `auth` uses the spec legend: U user, K key (r/rw scope), L link, P public.\n * `permission` is the spec 05 §5.2 permission checked on the resolved object.\n */\nexport const API_BASE_PATH = '/api/v1';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\nexport interface RouteSpec {\n method: HttpMethod;\n path: string;\n auth: string;\n permission: string | null;\n}\n\nconst r = (\n method: HttpMethod,\n path: string,\n auth: string,\n permission: string | null = null\n): RouteSpec => ({ method, path, auth, permission });\n\nexport const API_ROUTES = {\n // B1\n health: r('GET', '/health', 'P'),\n meGet: r('GET', '/me', 'U,Kr'),\n mePatch: r('PATCH', '/me', 'U'),\n // B2 workspaces\n workspacesList: r('GET', '/workspaces', 'U,Kr'),\n workspaceGet: r('GET', '/workspaces/:wid', 'U,Kr', 'workspace.read'),\n // B2 projects\n projectsList: r('GET', '/workspaces/:wid/projects', 'U,Kr', 'project.read'),\n projectCreate: r(\n 'POST',\n '/workspaces/:wid/projects',\n 'U,Krw',\n 'project.create'\n ),\n projectGet: r('GET', '/projects/:pid', 'U,Kr,L', 'project.read'),\n projectUpdate: r('PATCH', '/projects/:pid', 'U,Krw', 'project.update'),\n projectTrash: r('POST', '/projects/:pid/trash', 'U,Krw', 'project.trash'),\n projectRestore: r(\n 'POST',\n '/projects/:pid/restore',\n 'U,Krw',\n 'project.restore'\n ),\n // B2 documents\n documentsList: r(\n 'GET',\n '/projects/:pid/documents',\n 'U,Kr,L',\n 'document.read'\n ),\n documentCreate: r(\n 'POST',\n '/projects/:pid/documents',\n 'U,Krw',\n 'document.create'\n ),\n documentGet: r('GET', '/documents/:did', 'U,Kr,L', 'document.read'),\n documentUpdate: r('PATCH', '/documents/:did', 'U,Krw', 'document.edit'),\n documentTrash: r('POST', '/documents/:did/trash', 'U,Krw', 'document.trash'),\n documentRestore: r(\n 'POST',\n '/documents/:did/restore',\n 'U,Krw',\n 'document.restore'\n ),\n documentState: r('GET', '/documents/:did/state', 'U,Kr,L', 'document.read'),\n documentContent: r(\n 'GET',\n '/documents/:did/content',\n 'U,Kr,L',\n 'document.read'\n ),\n // B2 templates\n templatesList: r('GET', '/templates', 'U,Kr'),\n templateGet: r('GET', '/templates/:tid', 'U,Kr'),\n // B3 sync (WebSocket upgrade, credentials travel in the first `auth` frame)\n sync: r('GET', '/sync', 'P'),\n // B4 versions and snapshots\n versionsList: r('GET', '/documents/:did/versions', 'U,Kr,L', 'document.read'),\n versionState: r(\n 'GET',\n '/documents/:did/versions/:vid/state',\n 'U,Kr,L',\n 'document.read'\n ),\n versionRestore: r(\n 'POST',\n '/documents/:did/versions/:vid/restore',\n 'U,Krw',\n 'document.restore'\n ),\n versionSnapshot: r(\n 'POST',\n '/documents/:did/versions/:vid/snapshot',\n 'U,Krw',\n 'snapshot.create'\n ),\n snapshotsList: r(\n 'GET',\n '/documents/:did/snapshots',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotCreate: r(\n 'POST',\n '/documents/:did/snapshots',\n 'U,Krw',\n 'snapshot.create'\n ),\n snapshotGet: r('GET', '/snapshots/:sid', 'U,Kr,L', 'snapshot.read'),\n snapshotState: r('GET', '/snapshots/:sid/state', 'U,Kr,L', 'snapshot.read'),\n snapshotContent: r(\n 'GET',\n '/snapshots/:sid/content',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotOpen: r('POST', '/snapshots/:sid/open', 'U,Krw', 'snapshot.open'),\n snapshotFork: r('POST', '/snapshots/:sid/fork', 'U,Krw', 'snapshot.read'),\n // B15 versions, snapshots and sync completion (spec 05 §6.7.1, §6.9-6.11)\n elementHistory: r(\n 'GET',\n '/documents/:did/elements/:elementId/history',\n 'U,Kr',\n 'document.read'\n ),\n documentPresence: r(\n 'GET',\n '/documents/:did/presence',\n 'U,Kr',\n 'document.read'\n ),\n versionRestoreAsCopy: r(\n 'POST',\n '/documents/:did/versions/:vid/restore-as-copy',\n 'U,Krw',\n 'version.restoreAsCopy'\n ),\n snapshotPrefs: r('PUT', '/snapshots/:sid/prefs', 'U', 'snapshot.hideForSelf'),\n snapshotNotesList: r(\n 'GET',\n '/snapshots/:sid/notes',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotNoteCreate: r(\n 'POST',\n '/snapshots/:sid/notes',\n 'U,Krw',\n 'snapshot.appendNote'\n ),\n snapshotCommentsList: r(\n 'GET',\n '/snapshots/:sid/comments',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotCommentCreate: r(\n 'POST',\n '/snapshots/:sid/comments',\n 'U,L',\n 'document.comment'\n ),\n snapshotCommentCopyToLive: r(\n 'POST',\n '/snapshot-comments/:cid/copy-to-live',\n 'U',\n 'document.edit'\n ),\n snapshotCommentResolve: r(\n 'POST',\n '/snapshot-comments/:cid/resolve',\n 'U',\n 'document.comment'\n ),\n documentCompare: r(\n 'POST',\n '/documents/:did/compare',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n // Import and export (synchronous, no jobs)\n documentImport: r(\n 'POST',\n '/projects/:pid/documents/import',\n 'U,Krw',\n 'document.create'\n ),\n documentExport: r('POST', '/documents/:did/export', 'U,Kr', 'document.read'),\n formatsList: r('GET', '/formats', 'U,Kr'),\n // B5 commands and reads\n commands: r('POST', '/documents/:did/commands', 'U,Krw', 'document.edit'),\n outline: r('GET', '/documents/:did/outline', 'U,Kr,L', 'document.read'),\n scene: r('GET', '/documents/:did/scenes/:sceneId', 'U,Kr,L', 'document.read'),\n scenesBatch: r(\n 'POST',\n '/documents/:did/scenes/batch',\n 'U,Kr,L',\n 'document.read'\n ),\n elementsBatch: r(\n 'POST',\n '/documents/:did/elements/batch',\n 'U,Kr,L',\n 'document.read'\n ),\n // B6 personal API keys (user principals only; a key gets 403 API_KEY_FORBIDDEN)\n apiKeysList: r('GET', '/api-keys', 'U'),\n apiKeyCreate: r('POST', '/api-keys', 'U', 'apiKeys.use'),\n apiKeyUpdate: r('PATCH', '/api-keys/:kid', 'U'),\n apiKeyRevoke: r('DELETE', '/api-keys/:kid', 'U'),\n // B7 AI: script review and polish. Keys need the `ai` flag (403 AI_KEY_NOT_PERMITTED) and, to start\n // jobs or decide suggestions, read_write scope.\n aiStatus: r('GET', '/ai/status', 'U,Kr'),\n // Synchronous AI actions (`ai/actions.ts`): user principals only, gated by AI consent, a daily limit and credits.\n aiGenerateCharacterSkeleton: r(\n 'POST',\n '/ai/generate-character-skeleton',\n 'U'\n ),\n aiGenerateScript: r('POST', '/ai/generate-script', 'U'),\n aiPolishCharacterDialogue: r('POST', '/ai/polish-character-dialogue', 'U'),\n aiPolishScene: r('POST', '/ai/polish-scene', 'U'),\n aiJobCreate: r('POST', '/documents/:did/ai/jobs', 'U,Krw', 'ai.run'),\n aiJobsList: r('GET', '/documents/:did/ai/jobs', 'U,Kr', 'document.read'),\n aiJobGet: r('GET', '/ai/jobs/:jobId', 'U,Kr', 'document.read'),\n aiJobCancel: r('POST', '/ai/jobs/:jobId/cancel', 'U,Krw', 'ai.review'),\n aiSuggestionSetsList: r(\n 'GET',\n '/documents/:did/ai/suggestion-sets',\n 'U,Kr',\n 'document.read'\n ),\n aiSuggestionSetGet: r(\n 'GET',\n '/ai/suggestion-sets/:ssid',\n 'U,Kr',\n 'document.read'\n ),\n aiSuggestionSetAccept: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/accept',\n 'U,Krw',\n 'document.edit'\n ),\n aiSuggestionSetReject: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/reject',\n 'U,Krw',\n 'document.edit'\n ),\n // B8 tenancy, roles, sharing. Keys (K) only read members and /me/shared; everything else is user-only (403 API_KEY_FORBIDDEN).\n workspaceCreate: r('POST', '/workspaces', 'U'),\n workspaceUpdate: r('PATCH', '/workspaces/:wid', 'U', 'workspace.update'),\n workspaceDelete: r('DELETE', '/workspaces/:wid', 'U', 'workspace.delete'),\n workspaceTransfer: r(\n 'POST',\n '/workspaces/:wid/transfer',\n 'U',\n 'workspace.transfer'\n ),\n workspaceLeave: r('POST', '/workspaces/:wid/leave', 'U', 'workspace.leave'),\n workspaceUsage: r('GET', '/workspaces/:wid/usage', 'U', 'workspace.read'),\n workspaceAudit: r(\n 'GET',\n '/workspaces/:wid/audit.csv',\n 'U',\n 'workspace.audit'\n ),\n membersList: r('GET', '/workspaces/:wid/members', 'U,Kr', 'members.read'),\n memberUpdate: r(\n 'PATCH',\n '/workspaces/:wid/members/:uid',\n 'U',\n 'members.updateRole'\n ),\n memberRemove: r(\n 'DELETE',\n '/workspaces/:wid/members/:uid',\n 'U',\n 'members.remove'\n ),\n invitationCreateWorkspace: r(\n 'POST',\n '/workspaces/:wid/invitations',\n 'U',\n 'members.invite'\n ),\n invitationCreateProject: r(\n 'POST',\n '/projects/:pid/invitations',\n 'U',\n 'share.manage'\n ),\n invitationCreateDocument: r(\n 'POST',\n '/documents/:did/invitations',\n 'U',\n 'share.manage'\n ),\n workspaceInvitationsList: r(\n 'GET',\n '/workspaces/:wid/invitations',\n 'U',\n 'members.invite'\n ),\n myInvitations: r('GET', '/me/invitations', 'U'),\n invitationRenew: r('POST', '/invitations/:iid/renew', 'U'),\n invitationCancel: r('DELETE', '/invitations/:iid', 'U'),\n invitationAccept: r('POST', '/invitations/accept', 'U'),\n invitationDecline: r('POST', '/invitations/:iid/decline', 'U'),\n sharedWithMe: r('GET', '/me/shared', 'U,Kr'),\n documentLock: r('POST', '/documents/:did/lock', 'U', 'document.lock'),\n documentUnlock: r('DELETE', '/documents/:did/lock', 'U', 'document.lock'),\n documentUnlockSession: r(\n 'POST',\n '/documents/:did/unlock-session',\n 'U',\n 'document.read'\n ),\n shareLinkCreateDocument: r(\n 'POST',\n '/documents/:did/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkCreateProject: r(\n 'POST',\n '/projects/:pid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkCreateSnapshot: r(\n 'POST',\n '/snapshots/:sid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinksListDocument: r(\n 'GET',\n '/documents/:did/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinksListProject: r(\n 'GET',\n '/projects/:pid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkUpdate: r('PATCH', '/share-links/:lid', 'U', 'share.manage'),\n shareLinkRevoke: r('DELETE', '/share-links/:lid', 'U', 'share.manage'),\n grantsListDocument: r('GET', '/documents/:did/grants', 'U', 'share.manage'),\n grantsListProject: r('GET', '/projects/:pid/grants', 'U', 'share.manage'),\n grantUpdate: r('PATCH', '/grants/:gid', 'U', 'share.manage'),\n grantRemove: r('DELETE', '/grants/:gid', 'U', 'share.manage'),\n // B8 public link routes: the token in the path is the credential; an optional Bearer is a user or a link session (`fls_`).\n publicShareResolve: r('GET', '/public/share/:token', 'P'),\n shareUnlock: r('POST', '/share/:token/unlock', 'P'),\n shareState: r('GET', '/share/:token/state', 'P,L', 'document.read'),\n // B9 generic jobs (spec 05 §6.19). Jobs are visible to their owner, or to anyone who can read the job's document;\n // cancel, outputs and recipients are owner-only. `/ai/jobs*` stays as the AI facade over the same rows.\n jobsList: r('GET', '/jobs', 'U,Kr', 'document.read'),\n jobGet: r('GET', '/jobs/:jobId', 'U,Kr,L', 'document.read'),\n jobCreate: r('POST', '/jobs', 'U,Krw', 'document.read'),\n jobCancel: r('POST', '/jobs/:jobId/cancel', 'U,Krw', 'document.read'),\n jobOutputs: r('GET', '/jobs/:jobId/outputs', 'U,K,L', 'document.export'),\n jobRecipients: r('GET', '/jobs/:jobId/recipients', 'U', 'document.export'),\n // Provider webhook: unauthenticated, HMAC-signed with JOB_WEBHOOK_SECRET_<ADAPTER> (fails closed: 401 when unset).\n jobWebhook: r('POST', '/webhooks/jobs/:adapterId', 'W'),\n // B10 projection-backed reads, search, reports, packets (spec 05 §6.7.1, §6.7.2, §6.12, §6.14, §6.15, §6.17, §6.18, §6.22).\n // `?source=live|snapshot:<id>|version:<id>` selects the state a read answers from. Keys (K) read all of these; the report\n // and resolve POSTs are reads, so a read-only key may send them.\n entitiesList: r('GET', '/documents/:did/entities', 'U,Kr,L', 'document.read'),\n entityGet: r(\n 'GET',\n '/documents/:did/entities/:eid',\n 'U,Kr,L',\n 'document.read'\n ),\n entityUsage: r(\n 'GET',\n '/documents/:did/entities/:eid/usage',\n 'U,Kr,L',\n 'document.read'\n ),\n entityDialogue: r(\n 'GET',\n '/documents/:did/entities/:eid/dialogue',\n 'U,Kr,L',\n 'document.read'\n ),\n tagCategoriesList: r(\n 'GET',\n '/documents/:did/tag-categories',\n 'U,Kr,L',\n 'document.read'\n ),\n tagsList: r('GET', '/documents/:did/tags', 'U,Kr,L', 'document.read'),\n notesList: r('GET', '/documents/:did/notes', 'U,Kr,L', 'document.read'),\n beatsList: r('GET', '/documents/:did/beats', 'U,Kr,L', 'document.read'),\n binList: r('GET', '/documents/:did/bin', 'U,Kr,L', 'document.read'),\n revisionsGet: r(\n 'GET',\n '/documents/:did/revisions',\n 'U,Kr,L',\n 'document.read'\n ),\n changesList: r('GET', '/documents/:did/changes', 'U,Kr,L', 'document.read'),\n alternatesGet: r(\n 'GET',\n '/documents/:did/alternates/:elementId',\n 'U,Kr,L',\n 'document.read'\n ),\n titlePageGet: r(\n 'GET',\n '/documents/:did/title-page',\n 'U,Kr,L',\n 'document.read'\n ),\n statsGet: r('GET', '/documents/:did/stats', 'U,Kr,L', 'document.read'),\n fountainGet: r('GET', '/documents/:did/fountain', 'U,Kr,L', 'document.read'),\n sceneShotsList: r(\n 'GET',\n '/documents/:did/scenes/:sceneId/shots',\n 'U,Kr,L',\n 'document.read'\n ),\n resolveBatch: r('POST', '/documents/:did/resolve', 'U,Kr,L', 'document.read'),\n resolveOne: r('GET', '/documents/:did/resolve', 'U,Kr,L', 'document.read'),\n documentSearch: r('GET', '/documents/:did/search', 'U,Kr,L', 'document.read'),\n workspaceSearch: r(\n 'GET',\n '/workspaces/:wid/search',\n 'U,Kr',\n 'workspace.read'\n ),\n search: r('GET', '/search', 'U,Kr'),\n reportKinds: r('GET', '/reports/kinds', 'U,Kr'),\n reportGet: r('GET', '/documents/:did/reports/:kind', 'U,Kr,L', 'reports.run'),\n reportCreate: r('POST', '/documents/:did/reports', 'U,Kr,L', 'reports.run'),\n packetScene: r(\n 'GET',\n '/documents/:did/packets/scene/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetCharacter: r(\n 'GET',\n '/documents/:did/packets/character/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetLocation: r(\n 'GET',\n '/documents/:did/packets/location/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetShot: r(\n 'GET',\n '/documents/:did/packets/shot/:locator',\n 'U,Kr',\n 'document.read'\n ),\n // B13 account and per-user data (spec 05 §6.1, §6.1.1, §6.26). User-only (a key gets 403 API_KEY_FORBIDDEN) except the macro list (Kr).\n meDictionaryGet: r('GET', '/me/dictionary', 'U'),\n meDictionaryUpdate: r('PUT', '/me/dictionary', 'U'),\n mePreferencesGet: r('GET', '/me/preferences', 'U'),\n mePreferencesSet: r('PUT', '/me/preferences', 'U'),\n meMacrosList: r('GET', '/me/macros', 'U,Kr'),\n meMacroCreate: r('POST', '/me/macros', 'U'),\n meMacroUpdate: r('PATCH', '/me/macros/:mid', 'U'),\n meMacroDelete: r('DELETE', '/me/macros/:mid', 'U'),\n meWritingStats: r('GET', '/me/writing-stats', 'U'),\n meWritingSessionCreate: r('POST', '/me/writing-sessions', 'U'),\n meWritingGoalsGet: r('GET', '/me/writing-goals', 'U'),\n meWritingGoalsSet: r('PUT', '/me/writing-goals', 'U'),\n meExport: r('POST', '/me/export', 'U'),\n meDelete: r('DELETE', '/me', 'U'),\n meRestore: r('POST', '/me/restore', 'U'),\n documentMyStateGet: r(\n 'GET',\n '/documents/:did/my-state',\n 'U',\n 'document.read'\n ),\n documentMyStateSet: r(\n 'PUT',\n '/documents/:did/my-state',\n 'U',\n 'document.read'\n ),\n documentStar: r('PUT', '/documents/:did/star', 'U', 'document.read'),\n documentUnstar: r('DELETE', '/documents/:did/star', 'U', 'document.read'),\n // B14 project, document and template lifecycle, workspace settings (spec 05 §6.2, §6.6-§6.8, §6.26). Writes are `Krw`; purge,\n // trash-empty, workspace defaults and contacts are user-only (a key gets 403 API_KEY_FORBIDDEN).\n workspaceDocuments: r(\n 'GET',\n '/workspaces/:wid/documents',\n 'U,Kr',\n 'project.read'\n ),\n workspaceTrash: r('GET', '/workspaces/:wid/trash', 'U,Kr', 'project.read'),\n workspaceTrashEmpty: r(\n 'POST',\n '/workspaces/:wid/trash/empty',\n 'U',\n 'project.purge'\n ),\n projectPurge: r('DELETE', '/projects/:pid', 'U', 'project.purge'),\n projectDuplicate: r(\n 'POST',\n '/projects/:pid/duplicate',\n 'U,Krw',\n 'project.create'\n ),\n projectFolderCreate: r(\n 'POST',\n '/projects/:pid/folders',\n 'U,Krw',\n 'project.update'\n ),\n projectFolderUpdate: r(\n 'PATCH',\n '/project-folders/:fid',\n 'U,Krw',\n 'project.update'\n ),\n projectFolderDelete: r(\n 'DELETE',\n '/project-folders/:fid',\n 'U,Krw',\n 'project.update'\n ),\n documentMove: r('POST', '/documents/:did/move', 'U,Krw', 'document.move'),\n documentPurge: r('DELETE', '/documents/:did', 'U', 'project.purge'),\n documentDuplicate: r(\n 'POST',\n '/documents/:did/duplicate',\n 'U,Krw',\n 'document.create'\n ),\n documentApplyTemplate: r(\n 'POST',\n '/documents/:did/template',\n 'U,Krw',\n 'document.lock'\n ),\n templateCreate: r('POST', '/templates', 'U,Krw', 'templates.manage'),\n templateVersionCreate: r(\n 'POST',\n '/templates/:tid/versions',\n 'U,Krw',\n 'templates.manage'\n ),\n templateUpdate: r('PATCH', '/templates/:tid', 'U,Krw', 'templates.manage'),\n templateDelete: r('DELETE', '/templates/:tid', 'U,Krw', 'templates.manage'),\n templateImport: r('POST', '/templates/import', 'U,Krw', 'templates.manage'),\n templateExport: r('GET', '/templates/:tid/export', 'U,Kr'),\n projectBinList: r('GET', '/projects/:pid/bin', 'U,Kr', 'project.read'),\n projectBinCreate: r('POST', '/projects/:pid/bin', 'U,Krw', 'document.edit'),\n projectBinDelete: r(\n 'DELETE',\n '/project-bin-items/:id',\n 'U,Krw',\n 'document.edit'\n ),\n workspaceDefaultsGet: r(\n 'GET',\n '/workspaces/:wid/defaults',\n 'U,Kr',\n 'workspace.read'\n ),\n workspaceDefaultsSet: r(\n 'PUT',\n '/workspaces/:wid/defaults',\n 'U',\n 'workspace.update'\n ),\n workspaceContactsList: r(\n 'GET',\n '/workspaces/:wid/contacts',\n 'U',\n 'workspace.read'\n ),\n workspaceContactsCreate: r(\n 'POST',\n '/workspaces/:wid/contacts',\n 'U',\n 'workspace.update'\n ),\n workspaceContactUpdate: r(\n 'PATCH',\n '/workspace-contacts/:cid',\n 'U',\n 'workspace.update'\n ),\n workspaceContactDelete: r(\n 'DELETE',\n '/workspace-contacts/:cid',\n 'U',\n 'workspace.update'\n ),\n // B16 imports, exports and watermark as jobs (spec 05 §6.18). `POST /imports*` and `/uploads/state` are `Krw`; exports are `Kr` (a read key may\n // export what it can read); the watermark lookup is user-only (403 API_KEY_FORBIDDEN for a key). The synchronous\n // `documentImport`/`documentExport`/`formatsList` stay until the app moves to these (see the plan's B16 \"Deferred\" list).\n uploadState: r('POST', '/uploads/state', 'U,Krw'),\n importCreate: r('POST', '/imports', 'U,Krw', 'document.create'),\n importStart: r('POST', '/imports/:importId/start', 'U,Krw'),\n documentImportOver: r(\n 'POST',\n '/documents/:did/import-over',\n 'U,Krw',\n 'document.edit'\n ),\n documentExportCreate: r(\n 'POST',\n '/documents/:did/exports',\n 'U,Kr',\n 'document.export'\n ),\n documentExportCombined: r(\n 'POST',\n '/documents/export-combined',\n 'U,Kr',\n 'document.export'\n ),\n watermarkLookup: r(\n 'POST',\n '/workspaces/:wid/watermark-lookup',\n 'U',\n 'workspace.audit'\n ),\n // B11 assets and R2 (spec 05 §6.13). Bytes go to object storage through presigned URLs, never through the API. Writes are `Krw`, reads `Kr`;\n // share-link readers (`L`) are not built (no `/share/:token/assets` route yet). The uploader routes check the caller is the uploader.\n assetUploadCreate: r(\n 'POST',\n '/workspaces/:wid/assets/uploads',\n 'U,Krw',\n 'assets.upload'\n ),\n assetUploadGet: r('GET', '/assets/uploads/:uploadId', 'U,Krw'),\n assetUploadParts: r('POST', '/assets/uploads/:uploadId/parts', 'U,Krw'),\n assetUploadComplete: r('POST', '/assets/uploads/:uploadId/complete', 'U,Krw'),\n assetUploadAbort: r('DELETE', '/assets/uploads/:uploadId', 'U,Krw'),\n assetsList: r('GET', '/assets', 'U,Kr', 'assets.read'),\n assetGet: r('GET', '/assets/:aid', 'U,Kr', 'assets.read'),\n assetUrl: r('GET', '/assets/:aid/versions/:vid/url', 'U,Kr', 'assets.read'),\n assetUpdate: r('PATCH', '/assets/:aid', 'U,Krw', 'assets.upload'),\n assetDelete: r('DELETE', '/assets/:aid', 'U,Krw', 'assets.upload'),\n assetRestore: r('POST', '/assets/:aid/restore', 'U,Krw', 'assets.upload'),\n assetLinkCreate: r('POST', '/asset-links', 'U,Krw', 'assets.link'),\n documentAssetLinks: r(\n 'GET',\n '/documents/:did/asset-links',\n 'U,Kr',\n 'assets.read'\n ),\n assetLinkUpdate: r('PATCH', '/asset-links/:lid', 'U,Krw', 'assets.link'),\n assetLinkDelete: r('DELETE', '/asset-links/:lid', 'U,Krw', 'assets.link'),\n documentStaleness: r(\n 'GET',\n '/documents/:did/staleness',\n 'U,Kr',\n 'document.read'\n ),\n assetLinkStaleness: r(\n 'GET',\n '/asset-links/:lid/staleness',\n 'U,Kr',\n 'assets.read'\n ),\n // B12 collaboration, notifications, devices, email (spec 05 §6.15, §6.16, §6.24, §6.26). Most of this slice is\n // user-only (a key gets 403 API_KEY_FORBIDDEN): personal notifications and devices, and chat/activity writes are\n // never for a key. `documentChatList` and `documentActivity` are the two exceptions (`Kr`, a read key may read them).\n meNotificationPrefsGet: r('GET', '/me/notification-prefs', 'U'),\n meNotificationPrefsSet: r('PUT', '/me/notification-prefs', 'U'),\n documentMentionsWithoutAccess: r(\n 'GET',\n '/documents/:did/mentions-without-access',\n 'U',\n 'share.manage'\n ),\n documentChatList: r('GET', '/documents/:did/chat', 'U,Kr,L', 'document.chat'),\n documentChatCreate: r('POST', '/documents/:did/chat', 'U,L', 'document.chat'),\n chatMessageUpdate: r('PATCH', '/chat-messages/:mid', 'U', 'document.chat'),\n chatMessageDelete: r('DELETE', '/chat-messages/:mid', 'U', 'document.chat'),\n documentActivity: r(\n 'GET',\n '/documents/:did/activity',\n 'U,Kr',\n 'document.activity'\n ),\n workspaceActivity: r(\n 'GET',\n '/workspaces/:wid/activity',\n 'U',\n 'workspace.read'\n ),\n notificationsList: r('GET', '/notifications', 'U'),\n notificationsRead: r('POST', '/notifications/read', 'U'),\n notificationDelete: r('DELETE', '/notifications/:nid', 'U'),\n notificationsStream: r('GET', '/notifications/stream', 'U'),\n devicesList: r('GET', '/devices', 'U'),\n deviceCreate: r('POST', '/devices', 'U'),\n deviceUpdate: r('PATCH', '/devices/:devid', 'U'),\n deviceRevoke: r('POST', '/devices/:devid/revoke', 'U'),\n devicePushTokenSet: r('PUT', '/devices/:devid/push-token', 'U'),\n devicePushTokenDelete: r('DELETE', '/devices/:devid/push-token', 'U'),\n // B17 AI completion and credits (spec 05 §6.3, §6.19, §6.20, §6.21; spec 06 §9-10). AI routes need the key's `ai`\n // flag (403 AI_KEY_NOT_PERMITTED); `decide` needs read_write. Consent, activity and credits are user-only except\n // the balance/products reads (Kr; a key spends its own workspace's credits so it may read them) — `consumables/products`\n // is also public (unauthenticated pricing display). `GET .../suggestion-sets` and `GET /suggestion-sets/:ssid` are\n // already built (B7, under `/ai/` — kept as-is rather than duplicated at the bare path spec 05 Appendix A also lists).\n meAiConsentGet: r('GET', '/me/ai-consents', 'U'),\n meAiConsentAccept: r('POST', '/me/ai-consents', 'U'),\n meAiActivity: r('GET', '/me/ai-activity', 'U'),\n workspaceAiActivity: r(\n 'GET',\n '/workspaces/:wid/ai-activity',\n 'U',\n 'workspace.audit'\n ),\n aiEstimate: r('POST', '/documents/:did/ai/estimate', 'U,Kr', 'document.read'),\n aiReportsList: r(\n 'GET',\n '/documents/:did/ai/reports',\n 'U,Kr',\n 'document.read'\n ),\n aiReportGet: r(\n 'GET',\n '/documents/:did/ai/reports/:jobId',\n 'U,Kr',\n 'document.read'\n ),\n aiReportNoteConvert: r(\n 'POST',\n '/documents/:did/ai/reports/:jobId/notes/:noteId/convert',\n 'U,Krw',\n 'document.comment'\n ),\n aiSuggestionSetDecide: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/decide',\n 'U,Krw',\n 'document.edit'\n ),\n consumablesBalance: r('GET', '/consumables/balance', 'U,Kr'),\n consumablesPurchases: r('GET', '/consumables/purchases', 'U'),\n consumablesUsages: r('GET', '/consumables/usages', 'U'),\n consumablesProducts: r('GET', '/consumables/products', 'U,Kr,P'),\n consumablesWebhook: r('POST', '/consumables/webhook', 'W'),\n purchaseHandoffCreate: r('POST', '/purchases/handoff', 'U'),\n // B18 public, admin, telemetry (spec 05 §6.21, §6.23, §6.24; `/language/*` skipped by decision, see the plan's\n // B18 note). Public routes need no session at all. Admin needs `siteAdmin` on a USER principal specifically —\n // never an API key, whatever its scope — enforced in the handler (there is no per-object permission to check).\n publicTemplatesList: r('GET', '/public/templates', 'P'),\n publicTemplateGet: r('GET', '/public/templates/:builtinKey', 'P'),\n publicConfig: r('GET', '/public/config', 'P'),\n publicNamesDb: r('GET', '/public/names-db/:version', 'P'),\n publicHealthDeep: r('GET', '/public/health/deep', 'P'),\n publicWatermarkedGet: r('GET', '/public/watermarked/:exportId/:token', 'P'),\n purchaseHandoffRedeem: r('POST', '/public/purchases/handoff/redeem', 'P'),\n telemetryCreate: r('POST', '/telemetry', 'U,P'),\n adminUsersLookup: r('GET', '/admin/users', 'U'),\n adminUserRestore: r('POST', '/admin/users/:uid/restore', 'U'),\n adminUserPurge: r('DELETE', '/admin/users/:uid', 'U'),\n adminJobsList: r('GET', '/admin/jobs', 'U'),\n adminJobRetry: r('POST', '/admin/jobs/:id/retry', 'U'),\n adminJobRefund: r('POST', '/admin/jobs/:id/refund', 'U'),\n adminJobKindUpdate: r('PATCH', '/admin/job-kinds/:kind', 'U'),\n adminDocumentMeta: r('GET', '/admin/documents/:did/meta', 'U'),\n} as const satisfies Record<string, RouteSpec>;\n\nexport type ApiRouteName = keyof typeof API_ROUTES;\n","import { z } from 'zod';\n\nexport const WORKSPACE_KINDS = ['personal', 'team'] as const;\nexport type WorkspaceKind = (typeof WORKSPACE_KINDS)[number];\n\n/** Ordered by authority (spec 05 §5.2). */\nexport const ROLES = [\n 'owner',\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const workspaceKindSchema = z.enum(WORKSPACE_KINDS);\nexport const roleSchema = z.enum(ROLES);\n\nexport interface WorkspaceSummary {\n id: string;\n kind: WorkspaceKind;\n name: string;\n avatarAssetId: string | null;\n}\n\nexport interface Workspace extends WorkspaceSummary {\n defaultTemplateId: string | null;\n defaultLanguage: string;\n aiEnabled: boolean;\n /** F-SET-009: false disables every existing `anyone with the link` share link of the workspace and refuses new ones. */\n allowPublicLinks: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/** `GET /workspaces` item: summary plus the caller's role. */\nexport type WorkspaceListItem = WorkspaceSummary & { role: Role };\n\n/** `GET /workspaces/:wid` */\nexport type WorkspaceDetail = Workspace & {\n role: Role;\n memberCount: number;\n storageBytes: number;\n};\n\n// ─── Permissions (spec 05 §5.2) ─────────────────────────────────────────────\n\n/**\n * Every permission with the LOWEST role that holds it. The matrix is monotonic (a higher role has\n * everything a lower one has), so `ROLE_PERMISSIONS` is derived from this table.\n * Notes on the two permissions with a condition beyond the role:\n * - `share.manage` for a writer only applies to documents/projects they created (checked by the API).\n * - `project.trash` / `project.restore` for a writer only applies to projects they created.\n */\nexport const PERMISSION_MIN_ROLE = {\n 'workspace.read': 'viewer',\n 'workspace.update': 'admin',\n 'workspace.aiToggle': 'owner',\n 'workspace.audit': 'admin',\n 'workspace.delete': 'owner',\n 'workspace.transfer': 'owner',\n 'workspace.leave': 'viewer',\n 'members.read': 'viewer',\n 'members.invite': 'admin',\n 'members.updateRole': 'admin',\n 'members.remove': 'admin',\n 'project.create': 'writer',\n 'project.read': 'viewer',\n 'project.update': 'writer',\n 'project.trash': 'writer',\n 'project.restore': 'writer',\n 'project.purge': 'admin',\n 'document.create': 'writer',\n 'document.read': 'viewer',\n 'document.export': 'viewer',\n 'document.edit': 'writer',\n 'document.comment': 'commenter',\n 'document.chat': 'commenter',\n 'document.activity': 'viewer',\n 'document.trash': 'writer',\n 'document.restore': 'writer',\n 'document.move': 'writer',\n 'document.lock': 'writer',\n 'document.aiExclude': 'writer',\n 'snapshot.create': 'writer',\n 'snapshot.open': 'writer',\n 'snapshot.fork': 'writer',\n 'snapshot.cherryPick': 'writer',\n 'snapshot.appendNote': 'writer',\n 'snapshot.read': 'viewer',\n 'snapshot.compare': 'viewer',\n 'snapshot.hideForSelf': 'viewer',\n 'version.restore': 'writer',\n 'version.restoreAsCopy': 'writer',\n 'share.manage': 'writer',\n 'assets.upload': 'writer',\n 'assets.link': 'writer',\n 'assets.read': 'viewer',\n 'ai.run': 'writer',\n 'ai.review': 'commenter',\n 'jobs.media': 'writer',\n 'templates.manage': 'writer',\n 'reports.run': 'viewer',\n 'apiKeys.use': 'viewer',\n} as const satisfies Record<string, Role>;\n\nexport type Permission = keyof typeof PERMISSION_MIN_ROLE;\nexport const PERMISSIONS = Object.keys(PERMISSION_MIN_ROLE) as Permission[];\n\n/** 0 = owner ... 4 = viewer; a smaller number is more authority. */\nconst RANK: Record<Role, number> = {\n owner: 0,\n admin: 1,\n writer: 2,\n commenter: 3,\n viewer: 4,\n};\n\n/** True when `a` has at least the authority of `b`. */\nexport const roleAtLeast = (a: Role, b: Role): boolean => RANK[a] <= RANK[b];\n\n/** The higher-authority of the given roles (nulls ignored); null when there are none. */\nexport function maxRole(...roles: (Role | null | undefined)[]): Role | null {\n let best: Role | null = null;\n for (const r of roles)\n if (r && (best === null || RANK[r] < RANK[best])) best = r;\n return best;\n}\n\n/** The lower-authority of two roles (used to cap an API key by its scope). */\nexport const minRole = (a: Role, b: Role): Role => (RANK[a] >= RANK[b] ? a : b);\n\nexport const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> =\n Object.fromEntries(\n ROLES.map((role) => [\n role,\n PERMISSIONS.filter((p) => roleAtLeast(role, PERMISSION_MIN_ROLE[p])),\n ])\n ) as unknown as Record<Role, readonly Permission[]>;\n\n/** The only check routes call. */\nexport const hasPermission = (role: Role, permission: Permission): boolean =>\n roleAtLeast(role, PERMISSION_MIN_ROLE[permission]);\n\n/** Lowest role that holds `permission` (goes in a 403's `details.requiredRole`). */\nexport const requiredRoleFor = (permission: Permission): Role =>\n PERMISSION_MIN_ROLE[permission];\n\n/** Roles a share grant or a project/document invitation may carry: `owner` is never granted by share. */\nexport const SHARE_ROLES = ['admin', 'writer', 'commenter', 'viewer'] as const;\nexport type ShareRole = (typeof SHARE_ROLES)[number];\n","/**\n * Tenancy management and sharing DTOs (spec 05 §5.3, §5.4, §6.2-6.4, §6.7, §6.21, §8.3), slice B8.\n */\nimport { z } from 'zod';\nimport { roleSchema, type Role } from '../tenancy/index.js';\n\n// ─── Workspaces ─────────────────────────────────────────────────────────────\n\nexport const TEAM_WORKSPACE_LIMIT = 50;\n\nexport const workspaceCreateSchema = z.object({\n name: z.string().trim().min(1).max(80),\n avatarAssetId: z.string().min(1).nullable().optional(),\n});\nexport type WorkspaceCreateRequest = z.infer<typeof workspaceCreateSchema>;\n\nexport const workspaceUpdateSchema = z.object({\n name: z.string().trim().min(1).max(80).optional(),\n avatarAssetId: z.string().min(1).nullable().optional(),\n defaultTemplateId: z.string().min(1).nullable().optional(),\n defaultLanguage: z.string().min(2).max(35).optional(),\n aiEnabled: z.boolean().optional(),\n allowPublicLinks: z.boolean().optional(),\n});\nexport type WorkspaceUpdateRequest = z.infer<typeof workspaceUpdateSchema>;\n\nexport const workspaceDeleteSchema = z.object({ confirmName: z.string() });\nexport type WorkspaceDeleteRequest = z.infer<typeof workspaceDeleteSchema>;\n/** `DELETE /workspaces/:wid` response (soft delete). */\nexport interface WorkspaceDeleteResponse {\n deletedAt: string;\n}\n\nexport const workspaceTransferSchema = z.object({\n toUserId: z.string().min(1),\n});\nexport type WorkspaceTransferRequest = z.infer<typeof workspaceTransferSchema>;\n\n/** `GET /workspaces/:wid/audit.csv` query: an ISO-8601 range of at most one year. */\nexport const workspaceAuditQuerySchema = z.object({\n from: z.iso.datetime({ offset: true }).optional(),\n to: z.iso.datetime({ offset: true }).optional(),\n});\nexport type WorkspaceAuditQuery = z.infer<typeof workspaceAuditQuerySchema>;\nexport const AUDIT_CSV_COLUMNS = [\n 'created_at',\n 'actor',\n 'action',\n 'target_type',\n 'target_id',\n 'ip',\n] as const;\nexport const AUDIT_MAX_RANGE_DAYS = 366;\n\nexport interface WorkspaceUsage {\n storageBytes: number;\n quotaBytes: number;\n documentCount: number;\n assetCount: number;\n}\n\n// ─── Members ────────────────────────────────────────────────────────────────\n\nexport interface Member {\n userId: string;\n email: string | null;\n displayName: string | null;\n role: Role;\n invitedBy: string | null;\n joinedAt: string;\n}\n\nexport const memberUpdateSchema = z.object({ role: roleSchema });\nexport type MemberUpdateRequest = z.infer<typeof memberUpdateSchema>;\n\n// ─── Invitations ────────────────────────────────────────────────────────────\n\nexport const INVITATION_TARGETS = ['workspace', 'project', 'document'] as const;\nexport type InvitationTarget = (typeof INVITATION_TARGETS)[number];\nexport const INVITATION_TTL_DAYS = 14;\nexport const INVITATION_STATUSES = [\n 'pending',\n 'accepted',\n 'declined',\n 'cancelled',\n 'expired',\n] as const;\nexport type InvitationStatus = (typeof INVITATION_STATUSES)[number];\n\n/** `role` for a workspace invitation is `admin|writer|commenter|viewer` (never `owner`); for a project or document it is a grant role. */\nexport const invitationCreateSchema = z.object({\n email: z.email().max(254),\n role: roleSchema,\n});\nexport type InvitationCreateRequest = z.infer<typeof invitationCreateSchema>;\n\n/** The token is never in this shape: it travels only in the invitation email (`notifyInvitation`, slice B12). */\nexport interface Invitation {\n id: string;\n targetType: InvitationTarget;\n workspaceId: string;\n projectId: string | null;\n documentId: string | null;\n email: string;\n role: Role;\n invitedBy: string;\n /** Inviter's display name or email, and the target's name, so an invitee can recognise it. */\n invitedByName: string | null;\n targetName: string | null;\n status: InvitationStatus;\n expiresAt: string;\n createdAt: string;\n}\n\nexport const invitationAcceptSchema = z.object({ token: z.string().min(1) });\nexport type InvitationAcceptRequest = z.infer<typeof invitationAcceptSchema>;\nexport interface InvitationAcceptResult {\n workspaceId?: string;\n projectId?: string;\n documentId?: string;\n}\n\n/** Where an invitation, grant list or link list points. */\nexport type ShareTarget =\n | { type: 'workspace'; id: string }\n | { type: 'project'; id: string }\n | { type: 'document'; id: string };\n\n// ─── Grants ─────────────────────────────────────────────────────────────────\n\nexport interface ShareGrant {\n id: string;\n targetType: 'project' | 'document';\n projectId: string | null;\n documentId: string | null;\n userId: string;\n email: string | null;\n displayName: string | null;\n role: Role;\n grantedBy: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport const grantUpdateSchema = z.object({ role: roleSchema });\nexport type GrantUpdateRequest = z.infer<typeof grantUpdateSchema>;\n\n/** `GET /me/shared` item: a project or document reached through a grant, not through a workspace membership. */\nexport interface SharedItem {\n type: 'project' | 'document';\n id: string;\n title: string;\n role: Role;\n workspaceId: string;\n /** For a document: its project. */\n projectId: string | null;\n projectName: string | null;\n sharedBy: string | null;\n grantedAt: string;\n}\n\n// ─── Share links ────────────────────────────────────────────────────────────\n\nexport const SHARE_LINK_ACCESS = ['view', 'comment'] as const;\nexport type ShareLinkAccess = (typeof SHARE_LINK_ACCESS)[number];\n/** `anyone`: the URL alone opens it at `access`. `restricted`: only people on the access list (grants/membership). */\nexport const SHARE_LINK_GENERAL_ACCESS = ['anyone', 'restricted'] as const;\nexport type ShareLinkGeneralAccess = (typeof SHARE_LINK_GENERAL_ACCESS)[number];\nexport const SHARE_LINK_TARGETS = ['project', 'document', 'snapshot'] as const;\nexport type ShareLinkTarget = (typeof SHARE_LINK_TARGETS)[number];\nexport const SHARE_LINK_TOKEN_PREFIX = 'fws_';\n/** Link session (`fls_...`) lifetime, seconds (spec 05 §5.4). */\nexport const LINK_SESSION_TTL_S = 900;\nexport const LINK_SESSION_PREFIX = 'fls_';\n\nexport const shareLinkCreateSchema = z.object({\n access: z.enum(SHARE_LINK_ACCESS),\n generalAccess: z.enum(SHARE_LINK_GENERAL_ACCESS).default('anyone'),\n expiresAt: z.iso.datetime({ offset: true }).nullable().optional(),\n password: z.string().min(1).max(200).optional(),\n allowDownload: z.boolean().default(true),\n watermarkText: z.string().max(200).nullable().optional(),\n});\nexport type ShareLinkCreateRequest = z.input<typeof shareLinkCreateSchema>;\n\nexport const shareLinkUpdateSchema = z\n .object({\n access: z.enum(SHARE_LINK_ACCESS).optional(),\n generalAccess: z.enum(SHARE_LINK_GENERAL_ACCESS).optional(),\n expiresAt: z.iso.datetime({ offset: true }).nullable().optional(),\n password: z.string().min(1).max(200).optional(),\n clearPassword: z.boolean().optional(),\n allowDownload: z.boolean().optional(),\n watermarkText: z.string().max(200).nullable().optional(),\n })\n .refine((v) => !(v.password !== undefined && v.clearPassword), {\n message: 'password and clearPassword are exclusive',\n });\nexport type ShareLinkUpdateRequest = z.infer<typeof shareLinkUpdateSchema>;\n\nexport interface ShareLink {\n id: string;\n targetType: ShareLinkTarget;\n projectId: string | null;\n documentId: string | null;\n snapshotId: string | null;\n access: ShareLinkAccess;\n generalAccess: ShareLinkGeneralAccess;\n /** Last 4 characters of the token, for the UI list. */\n tokenHint: string;\n hasPassword: boolean;\n allowDownload: boolean;\n watermarkText: string | null;\n expiresAt: string | null;\n revokedAt: string | null;\n accessCount: number;\n lastAccessedAt: string | null;\n createdBy: string | null;\n createdAt: string;\n}\n/** The full token (and so the URL) is returned once, at creation. */\nexport type ShareLinkCreated = ShareLink & { url: string; token: string };\nexport interface ShareLinkRevokeResponse {\n revokedAt: string;\n}\n\n/** `GET /public/share/:token` (no content, no auth). A restricted link hides the title. */\nexport interface PublicShareInfo {\n targetType: ShareLinkTarget;\n title: string | null;\n access: ShareLinkAccess;\n generalAccess: ShareLinkGeneralAccess;\n requiresPassword: boolean;\n /** True for a `comment` link: adding a note needs a signed-in user. */\n requiresSignInToComment: boolean;\n expiresAt: string | null;\n allowDownload: boolean;\n}\n\nexport const shareUnlockSchema = z.object({\n password: z.string().max(200).optional(),\n});\nexport type ShareUnlockRequest = z.infer<typeof shareUnlockSchema>;\n/** Also the way to obtain (and renew) a session for a password-less link. Send `linkSession` as `Authorization: Bearer` on `/share/:token/*` and as the sync `link` auth token. */\nexport interface ShareUnlockResponse {\n linkSession: string;\n expiresAt: string;\n /** What the session allows: `comment` only for a comment link opened by a signed-in user. */\n access: ShareLinkAccess;\n}\n\n// ─── Document lock ──────────────────────────────────────────────────────────\n\nexport const UNLOCK_SESSION_TTL_S = 1800;\nexport const REAUTH_MAX_AGE_S = 300;\nexport interface DocumentLockResponse {\n locked: boolean;\n}\nexport interface UnlockSession {\n sessionToken: string;\n expiresAt: string;\n}\n","import { z } from 'zod';\nimport { DOCUMENT_KINDS } from '@sudobility/writing_core';\nimport type { DocumentKind } from '@sudobility/writing_core';\nimport type { Role } from '../tenancy/index.js';\n\nexport { DOCUMENT_KINDS };\nexport type { DocumentKind };\n\nexport const documentKindSchema = z.enum(DOCUMENT_KINDS);\n\nexport const SORT_OPTIONS = ['updated', 'name', 'created'] as const;\n\n/** Spec 05 §6.26: a `series` project orders its episodes by `(season, episode)` (F-COL-006). */\nexport const PROJECT_KINDS = ['feature', 'series', 'play', 'other'] as const;\nexport type ProjectKind = (typeof PROJECT_KINDS)[number];\nexport const projectKindSchema = z.enum(PROJECT_KINDS);\n\n/** Document labels (F-COL-006): at most 20 per document, each 1-40 characters. */\nexport const DOCUMENT_LABELS_MAX = 20;\nexport const DOCUMENT_LABEL_MAX_CHARS = 40;\nexport const documentLabelsSchema = z\n .array(z.string().trim().min(1).max(DOCUMENT_LABEL_MAX_CHARS))\n .max(DOCUMENT_LABELS_MAX);\n\n// ─── Projects (spec 05 §6.6) ────────────────────────────────────────────────\n\nexport interface ProjectSummary {\n id: string;\n workspaceId: string;\n name: string;\n description: string | null;\n color: string | null;\n coverAssetId: string | null;\n kind: ProjectKind;\n logline: string | null;\n documentCount: number;\n createdAt: string;\n updatedAt: string;\n trashedAt: string | null;\n}\n\nexport interface DocumentMeta {\n id: string;\n projectId: string;\n workspaceId: string;\n folderId: string | null;\n kind: DocumentKind;\n title: string;\n logline: string | null;\n color: string | null;\n labels: string[];\n /** Series projects: episodes order by `(season, episode)`. */\n season: number | null;\n episode: number | null;\n position: number;\n language: string;\n templateId: string | null;\n templateVersion: number | null;\n epoch: number;\n excludeFromAi: boolean;\n locked: boolean;\n pageCount: number;\n sceneCount: number;\n wordCount: number;\n parentSnapshotId: string | null;\n createdBy: string | null;\n createdAt: string;\n updatedAt: string;\n lastEditedAt: string | null;\n trashedAt: string | null;\n}\n\nexport interface ProjectFolder {\n id: string;\n projectId: string;\n parentFolderId: string | null;\n name: string;\n position: number;\n}\n\n/** `GET /projects/:pid` */\nexport interface Project extends ProjectSummary {\n role: Role;\n folders: ProjectFolder[];\n documents: DocumentMeta[];\n}\n\nexport const projectCreateSchema = z.object({\n name: z.string().trim().min(1).max(200),\n description: z.string().max(2000).optional(),\n coverAssetId: z.string().optional(),\n color: z.string().max(32).optional(),\n kind: projectKindSchema.optional(),\n logline: z.string().max(2000).optional(),\n});\nexport type ProjectCreateRequest = z.infer<typeof projectCreateSchema>;\n\nexport const projectUpdateSchema = z.object({\n name: z.string().trim().min(1).max(200).optional(),\n description: z.string().max(2000).nullable().optional(),\n coverAssetId: z.string().nullable().optional(),\n color: z.string().max(32).nullable().optional(),\n kind: projectKindSchema.optional(),\n logline: z.string().max(2000).nullable().optional(),\n workspaceId: z.string().optional(),\n});\nexport type ProjectUpdateRequest = z.infer<typeof projectUpdateSchema>;\n\nexport const projectListQuerySchema = z.object({\n trashed: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n q: z.string().optional(),\n sort: z.enum(SORT_OPTIONS).optional(),\n});\nexport type ProjectListQuery = z.infer<typeof projectListQuerySchema>;\n\n// ─── Documents (spec 05 §6.7) ───────────────────────────────────────────────\n\nexport const documentCreateSchema = z.object({\n /** Client-generated `doc_...`; creation is idempotent on it. */\n id: z.string().startsWith('doc_').optional(),\n title: z.string().trim().min(1).max(200),\n kind: documentKindSchema,\n folderId: z.string().optional(),\n templateId: z.string().optional(),\n templateVersion: z.number().int().positive().optional(),\n language: z.string().max(16).optional(),\n labels: documentLabelsSchema.optional(),\n season: z.number().int().min(0).max(9999).optional(),\n episode: z.number().int().min(0).max(99999).optional(),\n});\nexport type DocumentCreateRequest = z.infer<typeof documentCreateSchema>;\n\nexport const documentUpdateSchema = z.object({\n title: z.string().trim().min(1).max(200).optional(),\n folderId: z.string().nullable().optional(),\n position: z.number().optional(),\n color: z.string().max(32).nullable().optional(),\n language: z.string().max(16).optional(),\n logline: z.string().max(2000).nullable().optional(),\n excludeFromAi: z.boolean().optional(),\n labels: documentLabelsSchema.optional(),\n season: z.number().int().min(0).max(9999).nullable().optional(),\n episode: z.number().int().min(0).max(99999).nullable().optional(),\n});\nexport type DocumentUpdateRequest = z.infer<typeof documentUpdateSchema>;\n\nexport const documentListQuerySchema = z.object({\n trashed: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n folderId: z.string().optional(),\n kind: documentKindSchema.optional(),\n /** `episode` = `(season, episode)` with unnumbered documents last; the default for a `series` project. */\n order: z.enum(['position', 'episode']).optional(),\n});\nexport type DocumentListQuery = z.infer<typeof documentListQuerySchema>;\n\n/** Style row in `DocumentDetail.template` (`code` = shortcut digit, `enter`/`tab` = next style ids). */\nexport interface DocumentTemplateStyle {\n id: string;\n name: string;\n code: number | null;\n enter: string | null;\n tab: string | null;\n}\n\nexport interface DocumentTemplateInfo {\n id: string;\n version: number;\n name: string;\n layoutMode: 'flow' | 'panels';\n styles: DocumentTemplateStyle[];\n}\n\n/** `GET /documents/:did` (metadata plus live-state facts, no content). */\nexport interface DocumentDetail extends DocumentMeta {\n role: Role;\n schemaVersion: number;\n template: DocumentTemplateInfo | null;\n}\n\n// ─── Trash ──────────────────────────────────────────────────────────────────\n\nexport interface TrashResult {\n trashedAt: string;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\nimport { documentKindSchema } from '../projects/index.js';\nimport type { Job } from '../jobs/index.js';\n\n/**\n * Project, document and template lifecycle, workspace settings (slice B14; spec 05 §6.2, §6.6, §6.7, §6.26).\n * Folders, move / duplicate / purge / apply template, the workspace documents list and trash, the Shared Bin, the workspace\n * defaults and the batch-watermark contacts. Template CRUD types live in `templates/`.\n */\n\n/** Trashed items are purged (`system.purge`) this many days after they were trashed (spec 05 §17). */\nexport const TRASH_RETENTION_DAYS = 30;\n\nexport interface PurgeScheduledResponse {\n purgeScheduled: true;\n}\n\n// ─── project folders (`pfd_`, §6.6) ───────────────────────────────────────────\n\n/** A folder may sit at most this deep (`FOLDER_DEPTH`): the root's children are depth 1. */\nexport const FOLDER_MAX_DEPTH = 8;\n\nexport const projectFolderCreateSchema = z.object({\n name: z.string().trim().min(1).max(120),\n parentFolderId: z.string().min(1).optional(),\n});\nexport type ProjectFolderCreateRequest = z.infer<\n typeof projectFolderCreateSchema\n>;\n\nexport const projectFolderUpdateSchema = z.object({\n name: z.string().trim().min(1).max(120).optional(),\n /** `null` moves the folder to the project root. */\n parentFolderId: z.string().min(1).nullable().optional(),\n position: z.number().finite().optional(),\n});\nexport type ProjectFolderUpdateRequest = z.infer<\n typeof projectFolderUpdateSchema\n>;\n\n/** `DELETE /project-folders/:fid?moveContentsTo=<fid>|root`; without it the contents move up to the folder's own parent. */\nexport const projectFolderDeleteQuerySchema = z.object({\n moveContentsTo: z.string().min(1).optional(),\n});\nexport type ProjectFolderDeleteQuery = z.infer<\n typeof projectFolderDeleteQuerySchema\n>;\n\nexport interface ProjectFolderDeleteResponse {\n deleted: true;\n}\n\n// ─── projects: purge and duplicate ────────────────────────────────────────────\n\nexport const projectPurgeSchema = z.object({ confirmName: z.string() });\nexport type ProjectPurgeRequest = z.infer<typeof projectPurgeSchema>;\n\nexport const projectDuplicateSchema = z.object({\n name: z.string().trim().min(1).max(200),\n targetWorkspaceId: z.string().min(1).optional(),\n includeSnapshots: z.boolean().default(false),\n /** Re-links the source's asset links onto the copy (B11); a no-op when the target is a different workspace. */\n includeAssets: z.boolean().default(false),\n});\nexport type ProjectDuplicateRequest = z.input<typeof projectDuplicateSchema>;\n\n/** `job.result` of a finished `project.duplicate` job. */\nexport interface ProjectDuplicateResult {\n projectId: string;\n documents: number;\n snapshots: number;\n /** Documents that were not copied: a locked document needs a re-authentication a job cannot give. */\n skipped: { documentId: string; reason: 'locked' }[];\n}\n\n// ─── documents: move, duplicate, apply template ───────────────────────────────\n\nexport const documentMoveSchema = z.object({\n targetProjectId: z.string().min(1),\n folderId: z.string().min(1).nullable().optional(),\n});\nexport type DocumentMoveRequest = z.infer<typeof documentMoveSchema>;\n\nexport const documentDuplicateSchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().min(1).optional(),\n includeSnapshots: z.boolean().default(false),\n includeAssets: z.boolean().default(false),\n});\nexport type DocumentDuplicateRequest = z.input<typeof documentDuplicateSchema>;\n\n/** `POST /documents/:did/template`. `templateVersion` defaults to the template's latest. */\nexport const documentApplyTemplateSchema = z.object({\n templateId: z.string().min(1),\n templateVersion: z.number().int().min(1).optional(),\n /** Old style id -> style id of the new template, for styles the new template has no counterpart of. */\n mapping: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type DocumentApplyTemplateRequest = z.infer<\n typeof documentApplyTemplateSchema\n>;\n\nexport interface ApplyTemplateDryRunResponse {\n /** Style ids used by elements that have no counterpart (same id, same role or explicit `mapping`) in the new template. */\n unmappedStyles: string[];\n /** Pages of the document after minus before. */\n pageDelta: number;\n}\nexport type ApplyTemplateResponse = Job | ApplyTemplateDryRunResponse;\n\n/** `job.result` of a finished `doc.applyTemplate` job. */\nexport interface ApplyTemplateResult {\n templateId: string;\n templateVersion: number;\n remapped: number;\n preTemplateSnapshotId: string;\n}\n\n// ─── workspace documents and trash ────────────────────────────────────────────\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\n\n/** `GET /workspaces/:wid/documents`: across every project; `starred` is the caller's own stars (`document_stars`). */\nexport const workspaceDocumentsQuerySchema = cursorQuerySchema.extend({\n q: z.string().max(200).optional(),\n kind: documentKindSchema.optional(),\n trashed: boolQuery.optional(),\n starred: boolQuery.optional(),\n label: z.string().max(40).optional(),\n});\nexport type WorkspaceDocumentsQuery = z.output<\n typeof workspaceDocumentsQuerySchema\n>;\n\nexport const TRASH_ITEM_TYPES = ['project', 'document', 'asset'] as const;\nexport type TrashItemType = (typeof TRASH_ITEM_TYPES)[number];\n\n/** `GET /workspaces/:wid/trash`. A document trashed together with its project is not listed on its own (restore the project). */\nexport interface TrashItem {\n type: TrashItemType;\n id: string;\n title: string;\n /** A document's project, for the \"in <project>\" line. */\n projectId: string | null;\n trashedAt: string;\n trashedBy: string | null;\n /** `trashedAt` + `TRASH_RETENTION_DAYS`. */\n purgeAt: string;\n}\n\n/** `confirm` must be `EMPTY`: anything else is the server's `CONFIRMATION_MISMATCH`, not a schema error. */\nexport const trashEmptySchema = z.object({ confirm: z.string() });\nexport type TrashEmptyRequest = z.infer<typeof trashEmptySchema>;\n\n/** The `system.purge` job's input (also what a purge job row shows in its `requestSummary`). */\nexport const purgeInputSchema = z.object({\n workspaceId: z.string().optional(),\n projectId: z.string().optional(),\n documentId: z.string().optional(),\n});\nexport type PurgeInput = z.infer<typeof purgeInputSchema>;\nexport interface PurgeResult {\n projects: number;\n documents: number;\n}\n\n// ─── Shared Bin (`bin_`, §6.26) ───────────────────────────────────────────────\n\n/** Serialised size cap of one snippet (`LIMIT_EXCEEDED`). */\nexport const PROJECT_BIN_ITEM_MAX_BYTES = 2 * 1024 * 1024;\n\nexport interface ProjectBinItem {\n id: string;\n projectId: string;\n title: string;\n /** Frozen `ElementJSON[]`: notes and tags are stripped. */\n elements: Record<string, unknown>[];\n sourceDocumentId: string | null;\n createdBy: string | null;\n createdAt: string;\n}\n\nexport const projectBinCreateSchema = z.object({\n id: z.string().startsWith('bin_').optional(),\n title: z.string().trim().min(1).max(200).optional(),\n elements: z.array(z.record(z.string(), z.unknown())).min(1),\n sourceDocumentId: z.string().min(1).optional(),\n});\nexport type ProjectBinCreateRequest = z.input<typeof projectBinCreateSchema>;\n\nexport interface ProjectBinDeleteResponse {\n deleted: true;\n}\n\n// ─── workspace defaults (§6.26) ───────────────────────────────────────────────\n\nexport const DEFAULT_PROJECT_ROLES = [\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n] as const;\nexport type DefaultProjectRole = (typeof DEFAULT_PROJECT_ROLES)[number];\n\nconst looseItems = (max: number) => z.array(z.looseObject({})).max(max);\n\n/**\n * What *New document* copies into a document of the workspace (then the two diverge, spec 01 §5.4) and *Save as workspace\n * worksheet* writes to. The lists are open objects owned by spec 09 features.\n */\nexport const workspaceDefaultsSchema = z.object({\n tagCategories: looseItems(200).default([]),\n revisionColourSets: looseItems(100).default([]),\n noteTypes: looseItems(100).default([]),\n worksheets: looseItems(200).default([]),\n /** The role newly created projects grant workspace members who have none (F-SET-009). */\n defaultProjectRole: z.enum(DEFAULT_PROJECT_ROLES).nullable().default(null),\n});\nexport type WorkspaceDefaultsInput = z.input<typeof workspaceDefaultsSchema>;\nexport type WorkspaceDefaultsDoc = z.output<typeof workspaceDefaultsSchema>;\nexport interface WorkspaceDefaults extends WorkspaceDefaultsDoc {\n updatedAt: string;\n}\n/** Serialised size cap of the defaults document (`LIMIT_EXCEEDED`). */\nexport const WORKSPACE_DEFAULTS_MAX_BYTES = 256 * 1024;\n\nexport const workspaceDefaultsPutSchema = workspaceDefaultsSchema.extend({\n baseUpdatedAt: z.string().min(1),\n});\nexport type WorkspaceDefaultsPutRequest = z.input<\n typeof workspaceDefaultsPutSchema\n>;\nexport interface WorkspaceDefaultsPutResponse {\n updatedAt: string;\n}\n\n// ─── contacts (`ctc_`, §6.26) ─────────────────────────────────────────────────\n\nexport const WORKSPACE_CONTACTS_BATCH_MAX = 500;\n\nexport interface WorkspaceContact {\n id: string;\n name: string;\n company: string | null;\n email: string | null;\n}\n\nconst contactFields = {\n name: z.string().trim().min(1).max(200),\n company: z.string().trim().max(200).nullable().optional(),\n email: z.string().trim().max(320).nullable().optional(),\n};\nexport const workspaceContactInputSchema = z.object({\n id: z.string().startsWith('ctc_').optional(),\n ...contactFields,\n});\n/** More than `WORKSPACE_CONTACTS_BATCH_MAX` entries is the server's `LIMIT_EXCEEDED`, not a schema error. */\nexport const workspaceContactsCreateSchema = z.object({\n contacts: z.array(workspaceContactInputSchema).min(1),\n});\nexport type WorkspaceContactsCreateRequest = z.input<\n typeof workspaceContactsCreateSchema\n>;\nexport const workspaceContactPatchSchema = z.object({\n name: contactFields.name.optional(),\n company: contactFields.company,\n email: contactFields.email,\n});\nexport type WorkspaceContactPatchRequest = z.infer<\n typeof workspaceContactPatchSchema\n>;\nexport const workspaceContactsQuerySchema = cursorQuerySchema.extend({\n q: z.string().max(200).optional(),\n});\nexport type WorkspaceContactsQuery = z.output<\n typeof workspaceContactsQuerySchema\n>;\nexport interface WorkspaceContactDeleteResponse {\n deleted: true;\n}\n\n// ─── job inputs (`project.duplicate`, `doc.applyTemplate`, `template.thumbnail`; `system.purge` is `purgeInputSchema`) ───\n\nexport const projectDuplicateJobInputSchema = z.object({\n projectId: z.string().min(1),\n name: z.string().min(1),\n targetWorkspaceId: z.string().min(1),\n includeSnapshots: z.boolean(),\n includeAssets: z.boolean(),\n});\nexport type ProjectDuplicateJobInput = z.infer<\n typeof projectDuplicateJobInputSchema\n>;\n\nexport const applyTemplateJobInputSchema = z.object({\n templateId: z.string().min(1),\n templateVersion: z.number().int().min(1),\n mapping: z.record(z.string(), z.string()).optional(),\n});\nexport type ApplyTemplateJobInput = z.infer<typeof applyTemplateJobInputSchema>;\n\nexport const templateThumbnailInputSchema = z.object({\n templateId: z.string().min(1),\n version: z.number().int().min(1),\n});\nexport type TemplateThumbnailInput = z.infer<\n typeof templateThumbnailInputSchema\n>;\n","import { z } from 'zod';\n\nexport const UI_LANGUAGES = [\n 'en',\n 'es',\n 'fr',\n 'de',\n 'pt',\n 'it',\n 'ja',\n 'zh',\n] as const;\nexport type UiLanguage = (typeof UI_LANGUAGES)[number];\n\n/** `GET /me` (spec 05 §6.1). */\nexport interface Me {\n userId: string;\n email: string | null;\n displayName: string | null;\n avatarUrl: string | null;\n locale: string;\n uiLanguage: string;\n timeZone: string;\n siteAdmin: boolean;\n personalWorkspaceId: string;\n createdAt: string;\n /** Set while an account deletion is scheduled (`DELETE /me`); `POST /me/restore` clears it. */\n deletionScheduledFor?: string | null;\n}\n\nexport const meUpdateSchema = z.object({\n displayName: z.string().trim().min(1).max(120).optional(),\n avatarAssetId: z.string().nullable().optional(),\n locale: z.string().min(2).max(35).optional(),\n uiLanguage: z.enum(UI_LANGUAGES).optional(),\n timeZone: z.string().min(1).max(64).optional(),\n});\nexport type MeUpdateRequest = z.infer<typeof meUpdateSchema>;\n","import { z } from 'zod';\n\n/**\n * Account and per-user data (slice B13; spec 05 §6.1, §6.1.1, §6.26, §8.1, §17).\n * Everything here belongs to one user: preferences, spelling dictionary, macros, writing sessions, stats, goals, the\n * per-document view state (`my-state`) and stars. All are user-only routes (an API key gets 403 `API_KEY_FORBIDDEN`),\n * except the macro list, which a key may read.\n */\n\n// ─── user preferences (§6.1.1) ────────────────────────────────────────────────\n\nexport const USER_PREFERENCES_VERSION = 1;\n/** Serialised size cap of `PUT /me/preferences` (`LIMIT_EXCEEDED`). */\nexport const USER_PREFERENCES_MAX_BYTES = 256 * 1024;\nexport const AUTOCORRECT_MAX_PAIRS = 5000;\nexport const RECENT_SEARCHES_MAX = 20;\n\nexport const DEVICE_CLASSES = ['phone', 'tablet', 'desktop'] as const;\nexport type DeviceClass = (typeof DEVICE_CLASSES)[number];\n\n/** A section is an open object: its keys are owned by spec 09/10 features and grow without a types release. */\nconst section = z.looseObject({});\n\nconst appearanceSchema = z.looseObject({\n theme: z.enum(['system', 'light', 'dark']).optional(),\n pageTheme: z\n .enum(['paper', 'night', 'midnight', 'sepia', 'custom'])\n .optional(),\n custom: section.optional(),\n density: z.string().max(40).optional(),\n largeIcons: z.boolean().optional(),\n reducedMotion: z.boolean().optional(),\n});\n\nconst keymapSchema = z.looseObject({\n preset: z.enum(['fadewright', 'finalDraft', 'fadeIn']).optional(),\n overrides: z.record(z.string(), z.string().nullable()).optional(),\n byPlatform: section.optional(),\n});\n\nconst autocorrectSchema = z.looseObject({\n options: section.optional(),\n pairs: z\n .array(\n z.object({ from: z.string().min(1).max(200), to: z.string().max(200) })\n )\n .max(AUTOCORRECT_MAX_PAIRS)\n .optional(),\n});\n\nconst languageSchema = z.looseObject({\n scriptDefault: z.string().max(35).optional(),\n installedDictionaries: z.array(z.string().max(35)).max(50).optional(),\n ignoreLists: section.optional(),\n lookups: z\n .array(z.object({ label: z.string().max(80), url: z.string().max(500) }))\n .max(50)\n .optional(),\n});\n\nconst tableReadSchema = z.looseObject({\n narratorVoiceByLanguage: z.record(z.string(), section).optional(),\n rate: z.number().optional(),\n actors: z\n .array(z.looseObject({ id: z.string(), name: z.string() }))\n .max(200)\n .optional(),\n});\n\n/**\n * `UserPreferences`: one JSON document per user, closed at the top level (an unknown top-level key is `VALIDATION`),\n * open inside each section. `version` is `USER_PREFERENCES_VERSION`; a higher version from a newer client is stored as is.\n */\nexport const userPreferencesSchema = z.strictObject({\n version: z.number().int().min(1).max(1000).default(USER_PREFERENCES_VERSION),\n appearance: appearanceSchema.optional(),\n editor: section.optional(),\n deviceClasses: z\n .strictObject({\n phone: section.optional(),\n tablet: section.optional(),\n desktop: section.optional(),\n })\n .optional(),\n keymap: keymapSchema.optional(),\n autocorrect: autocorrectSchema.optional(),\n language: languageSchema.optional(),\n tableRead: tableReadSchema.optional(),\n toolbar: section.optional(),\n recentSearches: z\n .array(z.string().max(500))\n .max(RECENT_SEARCHES_MAX)\n .optional(),\n revisionColourSets: z.array(section).max(100).optional(),\n offline: section.optional(),\n});\nexport type UserPreferences = z.output<typeof userPreferencesSchema>;\nexport type UserPreferencesInput = z.input<typeof userPreferencesSchema>;\nexport const USER_PREFERENCES_KEYS = [\n 'version',\n 'appearance',\n 'editor',\n 'deviceClasses',\n 'keymap',\n 'autocorrect',\n 'language',\n 'tableRead',\n 'toolbar',\n 'recentSearches',\n 'revisionColourSets',\n 'offline',\n] as const;\n\n/** `GET /me/preferences` (and `details.current` of a `STALE_WRITE`): the document plus its optimistic-concurrency token. */\nexport type UserPreferencesResponse = UserPreferences & { updatedAt: string };\n\n/** `PUT /me/preferences`: a whole-document replace; `baseUpdatedAt` is the `updatedAt` of the last GET/PUT. */\nexport const userPreferencesPutSchema = userPreferencesSchema.extend({\n baseUpdatedAt: z.string().min(1).max(40),\n});\nexport type UserPreferencesPutRequest = z.input<\n typeof userPreferencesPutSchema\n>;\nexport interface UserPreferencesPutResponse {\n updatedAt: string;\n}\n\n// ─── dictionary ───────────────────────────────────────────────────────────────\n\nexport const DICTIONARY_MAX_WORDS = 50_000;\nconst dictionaryWord = z.string().trim().min(1).max(100);\nexport const dictionaryUpdateSchema = z.object({\n add: z.array(dictionaryWord).max(5000).optional(),\n remove: z.array(dictionaryWord).max(5000).optional(),\n});\nexport type DictionaryUpdateRequest = z.infer<typeof dictionaryUpdateSchema>;\nexport interface DictionaryResponse {\n words: string[];\n}\nexport interface DictionaryUpdateResponse {\n count: number;\n}\n\n// ─── macros ───────────────────────────────────────────────────────────────────\n\nexport const USER_MACRO_MAX = 500;\nexport const MACRO_TRIGGER_KINDS = ['shortcut', 'alias'] as const;\n\nconst macroOptionFields = {\n smartReplace: z.boolean(),\n confirm: z.boolean(),\n wordOnly: z.boolean(),\n matchCase: z.boolean(),\n activeInStyles: z.array(z.string().max(80)).max(100),\n};\n/** Create: every option defaulted. */\nconst macroOptionsSchema = z.object({\n smartReplace: macroOptionFields.smartReplace.default(false),\n confirm: macroOptionFields.confirm.default(false),\n wordOnly: macroOptionFields.wordOnly.default(true),\n matchCase: macroOptionFields.matchCase.default(false),\n activeInStyles: macroOptionFields.activeInStyles.default([]),\n});\n/** Patch: no defaults (a default would overwrite the stored value of an option the request did not mention). */\nconst macroOptionsPatchSchema = z.object(macroOptionFields).partial();\n\nexport const userMacroSchema = z.object({\n name: z.string().trim().min(1).max(120),\n trigger: z.object({\n kind: z.enum(MACRO_TRIGGER_KINDS),\n value: z.string().trim().min(1).max(80),\n }),\n insertText: z.string().max(10_000),\n setElementStyle: z.string().max(80).nullable().optional(),\n nextElementStyle: z.string().max(80).nullable().optional(),\n options: macroOptionsSchema.prefault({}),\n});\nexport type UserMacroCreateRequest = z.input<typeof userMacroSchema>;\n\n/** `PATCH /me/macros/:mid`: any subset; `options` and `trigger` merge into the stored ones. */\nexport const userMacroPatchSchema = z.object({\n name: userMacroSchema.shape.name.optional(),\n trigger: z\n .object({\n kind: z.enum(MACRO_TRIGGER_KINDS).optional(),\n value: userMacroSchema.shape.trigger.shape.value.optional(),\n })\n .optional(),\n insertText: userMacroSchema.shape.insertText.optional(),\n setElementStyle: userMacroSchema.shape.setElementStyle,\n nextElementStyle: userMacroSchema.shape.nextElementStyle,\n options: macroOptionsPatchSchema.optional(),\n});\nexport type UserMacroPatchRequest = z.input<typeof userMacroPatchSchema>;\n\nexport interface UserMacro {\n id: string;\n name: string;\n trigger: { kind: (typeof MACRO_TRIGGER_KINDS)[number]; value: string };\n insertText: string;\n setElementStyle: string | null;\n nextElementStyle: string | null;\n options: z.output<typeof macroOptionsSchema>;\n createdAt: string;\n updatedAt: string;\n}\nexport interface DeleteResponse {\n deleted: true;\n}\n\n// ─── writing sessions, stats, goals ───────────────────────────────────────────\n\nexport const WRITING_GOAL_KINDS = [\n 'wordsPerDay',\n 'pagesPerDay',\n 'minutesPerDay',\n 'wordsPerWeek',\n 'documentTarget',\n] as const;\nexport type WritingGoalKind = (typeof WRITING_GOAL_KINDS)[number];\nexport const WRITING_GOALS_MAX = 50;\nexport const WRITING_STATS_GRANULARITIES = [\n 'day',\n 'week',\n 'month',\n 'year',\n] as const;\nexport type WritingStatsGranularity =\n (typeof WRITING_STATS_GRANULARITIES)[number];\n\nconst isoInstant = z.iso.datetime({ offset: true });\n\n/**\n * `POST /me/writing-sessions`. `clientSessionId` is the row id (`wss_...`, made by the client) and makes the upload\n * idempotent: a repeat is accepted and changes nothing, so a device may retry and may upload offline sessions later.\n */\nexport const writingSessionSchema = z\n .object({\n clientSessionId: z\n .string()\n .min(8)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/),\n documentId: z.string().min(1).max(100).nullable().optional(),\n startedAt: isoInstant,\n endedAt: isoInstant,\n activeSeconds: z.number().int().min(0).max(86_400),\n wordsAdded: z.number().int().min(0).max(1_000_000),\n wordsRemoved: z.number().int().min(0).max(1_000_000),\n netPagesEighths: z.number().int().min(-100_000).max(100_000),\n sprint: z\n .object({\n targetWords: z.number().int().min(1).max(1_000_000).optional(),\n targetMinutes: z.number().int().min(1).max(1440).optional(),\n })\n .optional(),\n })\n .refine((s) => Date.parse(s.endedAt) >= Date.parse(s.startedAt), {\n message: 'endedAt is before startedAt',\n path: ['endedAt'],\n });\nexport type WritingSessionRequest = z.input<typeof writingSessionSchema>;\nexport interface WritingSessionResponse {\n accepted: true;\n}\n\nconst localDate = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\n/** `GET /me/writing-stats`: dates are calendar days in the user's time zone (`users.time_zone`). Defaults: the last 30 days by day. */\nexport const writingStatsQuerySchema = z.object({\n from: localDate.optional(),\n to: localDate.optional(),\n granularity: z.enum(WRITING_STATS_GRANULARITIES).default('day'),\n documentId: z.string().min(1).max(100).optional(),\n});\nexport type WritingStatsQuery = z.input<typeof writingStatsQuerySchema>;\n\nexport interface WritingStatsBucket {\n /** `YYYY-MM-DD`: the first day of the day/week (Monday)/month/year, in the user's time zone. */\n start: string;\n wordsAdded: number;\n wordsRemoved: number;\n /** `netPagesEighths / 8`. */\n netPages: number;\n activeSeconds: number;\n}\n/** A day counts when the user added words on it (over all documents, in their time zone). Today does not break a streak until it ends. */\nexport interface StreakSummary {\n current: number;\n longest: number;\n /** `YYYY-MM-DD` of the latest day with words, or null. */\n lastActiveDate: string | null;\n activeToday: boolean;\n}\nexport interface WritingStats {\n buckets: WritingStatsBucket[];\n streak: StreakSummary;\n}\n\nexport const writingGoalInputSchema = z\n .object({\n id: z\n .string()\n .min(4)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n kind: z.enum(WRITING_GOAL_KINDS),\n documentId: z.string().min(1).max(100).nullable().optional(),\n target: z.number().int().min(1).max(10_000_000),\n daysOfWeek: z.array(z.number().int().min(0).max(6)).max(7).optional(),\n idleTimeoutSec: z.number().int().min(5).max(3600).optional(),\n })\n .refine((g) => g.kind !== 'documentTarget' || !!g.documentId, {\n message: 'documentTarget needs documentId',\n path: ['documentId'],\n });\n/** `PUT /me/writing-goals`: the whole list. A goal missing from it is deleted; one without `id` is created. `daysOfWeek`: 0 = Sunday. */\n/** No `.max` here on purpose: more than `WRITING_GOALS_MAX` is 409 `LIMIT_EXCEEDED` from the server, not `VALIDATION`. */\nexport const writingGoalsPutSchema = z.object({\n goals: z.array(writingGoalInputSchema),\n});\nexport type WritingGoalsPutRequest = z.input<typeof writingGoalsPutSchema>;\nexport interface WritingGoal {\n id: string;\n kind: WritingGoalKind;\n documentId: string | null;\n target: number;\n daysOfWeek: number[] | null;\n idleTimeoutSec: number | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─── export, delete, restore ──────────────────────────────────────────────────\n\nexport const ACCOUNT_DELETE_CONFIRM = 'DELETE';\nexport const accountDeleteSchema = z.object({\n confirm: z.literal(ACCOUNT_DELETE_CONFIRM),\n});\nexport type AccountDeleteRequest = z.infer<typeof accountDeleteSchema>;\nexport interface AccountDeleteResponse {\n deletionScheduledFor: string;\n}\nexport interface AccountRestoreResponse {\n restored: true;\n}\n/** `account.export` job input: none. The output is `fadewright-export.zip`. */\nexport const accountExportInputSchema = z.object({}).default({});\nexport const ACCOUNT_EXPORT_FILENAME = 'fadewright-export.zip';\n\n// ─── per-user document state and stars (§6.26) ────────────────────────────────\n\nexport const DOCUMENT_VIEW_STATE_MAX_BYTES = 64 * 1024;\n\nconst deviceViewSchema = z.looseObject({\n view: z.string().max(40).optional(),\n zoom: z.number().optional(),\n invisibles: z.boolean().optional(),\n ruler: z.boolean().optional(),\n});\n\n/**\n * Cross-device view state of one document for one user: Navigator tabs and columns, split layout, view mode and zoom per\n * device class. Caret, selection, undo history and the Beat Board viewport stay device-local. Every key optional: the\n * client merges per top-level key.\n */\nexport const documentViewStateSchema = z.strictObject({\n navigator: z\n .looseObject({\n tabs: z.array(z.looseObject({})).max(50).optional(),\n activeTab: z.string().max(80).nullable().optional(),\n })\n .optional(),\n layout: z\n .looseObject({\n split: z.union([z.string().max(40), z.number(), z.null()]).optional(),\n panes: z.array(z.unknown()).max(20).optional(),\n })\n .optional(),\n views: z\n .strictObject({\n phone: deviceViewSchema.optional(),\n tablet: deviceViewSchema.optional(),\n desktop: deviceViewSchema.optional(),\n })\n .optional(),\n});\nexport type DocumentViewState = z.output<typeof documentViewStateSchema>;\n\n/** `GET /documents/:did/my-state`: `{}` until first saved, then the state plus `updatedAt`. */\nexport type DocumentViewStateResponse = DocumentViewState & {\n updatedAt?: string;\n};\n\n/** `PUT`: the whole state; `baseUpdatedAt` is the `updatedAt` last read (null or absent when the GET returned `{}`). */\nexport const documentViewStatePutSchema = documentViewStateSchema.extend({\n baseUpdatedAt: z.string().min(1).max(40).nullable().optional(),\n});\nexport type DocumentViewStatePutRequest = z.input<\n typeof documentViewStatePutSchema\n>;\nexport interface DocumentViewStatePutResponse {\n updatedAt: string;\n}\n\nexport interface StarResponse {\n starred: boolean;\n}\n","import { z } from 'zod';\nimport type { TemplateCategory, TemplateJSON } from '@sudobility/writing_core';\n\nexport type TemplateScope = 'builtin' | 'user' | 'workspace';\n\n/** `GET /templates` item (spec 05 §6.8). The full body is writing_core's Template. */\nexport interface TemplateSummary {\n id: string;\n scope: TemplateScope;\n builtinKey: string | null;\n /** Set for `workspace` templates. */\n workspaceId: string | null;\n name: string;\n description: string | null;\n category: TemplateCategory;\n latestVersion: number;\n /** A first-page thumbnail was rendered (`template.thumbnail` job). Built-ins use static assets, so this is false for them. */\n hasThumbnail: boolean;\n /**\n * BCP-47 (writing_core's `TemplateJSON.locale`), set only for `scope: 'builtin'` — the catalogue's language\n * variants (screenplay-standard, tv-one-hour, ...) each carry one. `user`/`workspace` templates have no locale\n * concept (they're the caller's own authored content, not language variants of a catalog) and never set this.\n */\n locale?: string;\n}\n\n/** `GET /templates` query: user templates always; `workspaceId` adds that workspace's; `scope` narrows.\n * `locale` filters built-ins to one BCP-47 language (e.g. the app's current UI language); user/workspace templates\n * are never filtered by it, since they have no locale of their own. */\nexport const templateListQuerySchema = z.object({\n category: z.string().optional(),\n workspaceId: z.string().optional(),\n scope: z.enum(['builtin', 'user', 'workspace']).optional(),\n locale: z.string().optional(),\n});\nexport type TemplateListQuery = z.infer<typeof templateListQuerySchema>;\n\n/** `GET /templates/:tid?version=`: an older version of a user/workspace template (immutable). */\nexport const templateGetQuerySchema = z.object({\n version: z.coerce.number().int().min(1).optional(),\n});\n\n// ─── B14: template lifecycle (spec 05 §6.8) ─────────────────────────────────\n\n/** The body is validated server-side with writing_core's `TemplateJSON` schema (`TEMPLATE_INVALID` with the issues). */\nconst templateBody = z.custom<TemplateJSON>(\n (v) => typeof v === 'object' && v !== null && !Array.isArray(v),\n {\n message: 'template must be an object',\n }\n);\n\nexport const templateCreateSchema = z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n template: templateBody,\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n });\nexport type TemplateCreateRequest = z.input<typeof templateCreateSchema>;\n\nexport const templateVersionCreateSchema = z.object({ template: templateBody });\nexport type TemplateVersionCreateRequest = z.input<\n typeof templateVersionCreateSchema\n>;\n\nexport const templateUpdateSchema = z.object({\n name: z.string().trim().min(1).max(120).optional(),\n description: z.string().max(2000).nullable().optional(),\n category: z.string().min(1).max(40).optional(),\n});\nexport type TemplateUpdateRequest = z.infer<typeof templateUpdateSchema>;\n\nexport interface TemplateArchiveResponse {\n archived: true;\n}\n\n/** Template file formats: ViaInk's own JSON and the two foreign ones spec 04 §4.3 names. */\nexport const TEMPLATE_FILE_FORMATS = [\n 'fwtemplate',\n 'fadein-template',\n 'fdxt',\n] as const;\nexport type TemplateFileFormat = (typeof TEMPLATE_FILE_FORMATS)[number];\n/** `{ \"format\": \"fadewright-template\", \"formatVersion\": 1, \"template\": <TemplateJSON> }` (spec 04 §4.3.1). */\nexport const FWTEMPLATE_FORMAT = 'fadewright-template';\nexport const FWTEMPLATE_FORMAT_VERSION = 1;\n\n/**\n * `POST /templates/import`. Spec 05's `importId` flow is `templateImportByIdSchema` (B16); this body form (the file inline, like\n * `documents/import`) keeps working. The result is the created template.\n */\nexport const templateImportSchema = z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n filename: z.string().min(1).max(255),\n contentB64: z.string().min(1),\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n });\nexport type TemplateImportRequest = z.input<typeof templateImportSchema>;\n\n/**\n * The upload flow (B16): `POST /imports {templateTarget, filename, sizeBytes, sha256Hex}`, PUT the file, then\n * `POST /templates/import {importId}`. Scope and workspace come from the upload, never from this request.\n */\nexport const templateImportByIdSchema = z.object({\n importId: z.string().min(1),\n});\nexport type TemplateImportByIdRequest = z.infer<\n typeof templateImportByIdSchema\n>;\n\n/** `GET /templates/:tid/export?format=` (only `fwtemplate` is built). */\nexport const templateExportQuerySchema = z.object({\n format: z\n .enum(['fwtemplate', 'json', 'fadein-template', 'fdxt'])\n .default('fwtemplate'),\n version: z.coerce.number().int().min(1).optional(),\n});\nexport type TemplateExportQuery = z.infer<typeof templateExportQuerySchema>;\n\nexport interface TemplateExportResponse {\n filename: string;\n mimeType: string;\n contentB64: string;\n format: TemplateFileFormat;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/** Spec 03 §10.2 (canonical, kebab-case). */\nexport const SNAPSHOT_AUTO_REASONS = [\n 'pre-ai-polish',\n 'pre-import',\n 'pre-template',\n 'pre-open',\n 'pre-restore',\n 'pre-cherry-pick-bulk',\n 'pre-clear-revisions',\n 'pre-delete-revision-set',\n 'pre-unlock-all-pages',\n 'pre-bulk-change-decision',\n 'pre-account-transfer',\n 'offline-edits',\n 'access-revoked',\n] as const;\nexport type SnapshotAutoReason = (typeof SNAPSHOT_AUTO_REASONS)[number];\n\n/** The only reasons a client may send itself. */\nexport const CLIENT_AUTO_REASONS = ['offline-edits', 'access-revoked'] as const;\n\nexport const SNAPSHOT_KINDS = ['manual', 'auto'] as const;\nexport type SnapshotKind = (typeof SNAPSHOT_KINDS)[number];\n\nexport const VERSION_REASONS = [\n 'interval',\n 'session-end',\n 'pre-epoch',\n 'pre-restore',\n 'daily',\n 'reconnect',\n] as const;\nexport type VersionReason = (typeof VERSION_REASONS)[number];\n\nexport interface DocStats {\n pages: number;\n scenes: number;\n words: number;\n activeRevisionSetId?: string | null;\n}\n\n/** A row of `GET /documents/:did/versions` (spec 05 §6.10). */\nexport interface VersionPoint {\n id: string;\n createdAt: string;\n contributors: string[];\n stats: DocStats;\n epoch: number;\n reason: VersionReason;\n}\n\n/** Snapshot marker interleaved in the version list. */\nexport interface SnapshotMarker {\n marker: 'snapshot';\n snapshotId: string;\n name: string;\n createdAt: string;\n}\n\nexport type VersionListItem = VersionPoint | SnapshotMarker;\n\nexport interface SnapshotSummary {\n id: string;\n documentId: string;\n parentId: string | null;\n name: string;\n note: string | null;\n kind: SnapshotKind;\n autoReason: SnapshotAutoReason | null;\n stats: DocStats;\n createdBy: string | null;\n createdOnDevice: string | null;\n createdAt: string;\n receivedAt: string;\n forkedDocumentIds: string[];\n hiddenForMe: boolean;\n noteCount: number;\n}\n\n/** `GET /documents/:did/snapshots` */\nexport interface SnapshotListResponse {\n liveParentSnapshotId: string | null;\n snapshots: SnapshotSummary[];\n}\n\nexport const snapshotCreateSchema = z.object({\n /** Idempotency key, unique per document. */\n clientSnapshotId: z.string().min(1).max(64).optional(),\n name: z.string().trim().min(1).max(120),\n note: z.string().max(2000).optional(),\n kind: z.enum(SNAPSHOT_KINDS).optional(),\n autoReason: z.enum(SNAPSHOT_AUTO_REASONS).optional(),\n sourceEpoch: z.number().int().min(0).optional(),\n assumedParentId: z.string().nullable().optional(),\n createdAt: z.string().optional(),\n createdOnDevice: z.string().max(200).optional(),\n /**\n * Client-provided state for offline creation (spec 03 §10.2, spec 05 §6.11): exactly what the writer saw, uploaded through\n * `POST /uploads/state`. With it, `sourceEpoch` may be older than the live epoch (an offline-edits snapshot after an epoch bump).\n */\n state: z.object({ uploadKey: z.string().min(1).max(128) }).optional(),\n});\nexport type SnapshotCreateRequest = z.infer<typeof snapshotCreateSchema>;\n\nexport type SnapshotCreateResponse = SnapshotSummary & {\n reparentedLive: boolean;\n};\n\nexport type SnapshotDetail = SnapshotSummary & {\n parentChain: SnapshotSummary[];\n};\n\nexport const snapshotOpenSchema = z.object({\n confirm: z.literal(true),\n dryRun: z.boolean().optional(),\n});\nexport type SnapshotOpenRequest = z.infer<typeof snapshotOpenSchema>;\n\nexport const snapshotForkSchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().optional(),\n});\nexport type SnapshotForkRequest = z.infer<typeof snapshotForkSchema>;\n\n/** Where a read or compare takes its content from (spec 05 §6.7.1). */\nexport type SourceRef =\n | { kind: 'live'; documentId: string }\n | { kind: 'snapshot'; snapshotId: string }\n | { kind: 'version'; documentId: string; versionId: string };\n\nexport const sourceRefSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('live'), documentId: z.string() }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string() }),\n z.object({\n kind: z.literal('version'),\n documentId: z.string(),\n versionId: z.string(),\n }),\n]);\n\n/** `POST /documents/:did/versions/:vid/snapshot` body. */\nexport interface VersionSnapshotRequest {\n name: string;\n note?: string;\n}\n\n/** `POST /documents/:did/versions/:vid/restore` (bumps the epoch). */\nexport interface VersionRestoreResponse {\n document: import('../projects/index.js').DocumentMeta;\n epoch: number;\n preRestoreSnapshot: SnapshotSummary;\n}\n\n/** `POST /snapshots/:sid/open` (bumps the epoch). */\nexport interface SnapshotOpenResponse {\n document: import('../projects/index.js').DocumentMeta;\n epoch: number;\n preOpenSnapshot: SnapshotSummary;\n}\n\n// ─── B15: restore-as-copy, prefs, notes, comments, compare, history, presence ────────────────────────────────────\n\n/** `POST /documents/:did/versions/:vid/restore-as-copy` (spec 05 §6.10). Response: `DocumentMeta`. */\nexport const versionRestoreAsCopySchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().optional(),\n});\nexport type VersionRestoreAsCopyRequest = z.infer<\n typeof versionRestoreAsCopySchema\n>;\n\n/** `PUT /snapshots/:sid/prefs`: per-user hide; the snapshot row never changes. */\nexport const snapshotPrefsSchema = z.object({ hidden: z.boolean() });\nexport type SnapshotPrefsRequest = z.infer<typeof snapshotPrefsSchema>;\nexport interface SnapshotPrefsResponse {\n hidden: boolean;\n}\n\nexport const SNAPSHOT_NOTES_MAX = 200;\nexport const snapshotNoteCreateSchema = z.object({\n body: z.string().trim().min(1).max(2000),\n});\nexport type SnapshotNoteCreateRequest = z.infer<\n typeof snapshotNoteCreateSchema\n>;\n/** Append-only (spec 09 F-SNAP-009): there is no edit or delete route. */\nexport interface SnapshotNote {\n id: string;\n snapshotId: string;\n body: string;\n authorId: string | null;\n createdAt: string;\n}\n\nexport const snapshotCommentAnchorSchema = z.object({\n elementId: z.string().min(1),\n offset: z.number().int().min(0),\n length: z.number().int().min(0),\n});\nexport type SnapshotCommentAnchor = z.infer<typeof snapshotCommentAnchorSchema>;\nexport const snapshotCommentCreateSchema = z.object({\n anchor: snapshotCommentAnchorSchema,\n body: z.string().trim().min(1).max(10_000),\n /** User ids mentioned in the body (notifications are B12). */\n mentions: z.array(z.string().min(1)).max(50).optional(),\n});\nexport type SnapshotCommentCreateRequest = z.infer<\n typeof snapshotCommentCreateSchema\n>;\nexport const snapshotCommentResolveSchema = z.object({ resolved: z.boolean() });\nexport type SnapshotCommentResolveRequest = z.infer<\n typeof snapshotCommentResolveSchema\n>;\n/** A review comment on an immutable snapshot (R6). */\nexport interface SnapshotComment {\n id: string;\n snapshotId: string;\n anchor: SnapshotCommentAnchor;\n body: string;\n mentions: string[];\n authorId: string | null;\n viaLinkId: string | null;\n resolvedAt: string | null;\n resolvedBy: string | null;\n copiedToLiveNoteId: string | null;\n createdAt: string;\n}\nexport const snapshotCommentsQuerySchema = cursorQuerySchema;\nexport interface CopyToLiveResponse {\n noteId: string;\n}\n\n// Compare (spec 03 §11.1)\nexport const COMPARE_GRANULARITIES = ['scene', 'element', 'word'] as const;\nexport const TRACKED_CHANGE_MODES = [\n 'accept-all',\n 'reject-all',\n 'as-marked',\n] as const;\nexport const compareRequestSchema = z.object({\n base: sourceRefSchema,\n target: sourceRefSchema,\n granularity: z.enum(COMPARE_GRANULARITIES).default('element'),\n ignoreFormatting: z.boolean().default(false),\n ignoreRevisionMarks: z.boolean().default(false),\n ignoreTrackedChanges: z.enum(TRACKED_CHANGE_MODES).default('as-marked'),\n});\nexport type CompareRequest = z.input<typeof compareRequestSchema>;\n\n/** Above this many combined pages a compare is refused (spec 05 returns a `doc.compare` job; no runner exists, so 413 `COMPARE_TOO_LARGE`). */\nexport const COMPARE_MAX_PAGES = 400;\n\nexport type WordOp = { op: 'equal' | 'insert' | 'delete'; text: string };\nexport type ElementDiffStatus =\n 'unchanged' | 'modified' | 'added' | 'removed' | 'moved' | 'restyled';\nexport interface ElementDiff {\n status: ElementDiffStatus;\n baseElementId?: string;\n targetElementId?: string;\n alignment: 'id' | 'text';\n styleChange?: { from: string; to: string };\n /** `modified`: only formatting (marks) changed, the words are equal. */\n formattingOnly?: boolean;\n /** Plain text of the side(s), so a client can render a row without loading either document. */\n baseText?: string;\n targetText?: string;\n /** `granularity: \"word\"`, modified elements only. */\n words?: WordOp[];\n}\nexport type SceneDiffStatus =\n 'unchanged' | 'modified' | 'added' | 'removed' | 'moved' | 'moved-modified';\nexport interface SceneDiff {\n status: SceneDiffStatus;\n baseSceneId?: string;\n targetSceneId?: string;\n alignment: 'id' | 'fuzzy';\n similarity?: number;\n heading?: string;\n /** Empty at `granularity: \"scene\"`. */\n elements: ElementDiff[];\n}\nexport interface BeatDiff {\n status: 'unchanged' | 'modified' | 'added' | 'removed';\n id: string;\n baseTitle?: string;\n targetTitle?: string;\n}\nexport interface EntityDiff {\n status: 'unchanged' | 'modified' | 'added' | 'removed';\n id: string;\n kind?: string;\n baseName?: string;\n targetName?: string;\n}\nexport interface DocumentDiff {\n scenes: SceneDiff[];\n titlePage: ElementDiff[];\n beats: BeatDiff[];\n entities: EntityDiff[];\n summary: {\n scenesAdded: number;\n scenesRemoved: number;\n scenesModified: number;\n scenesMoved: number;\n wordsAdded: number;\n wordsRemoved: number;\n pageDelta: number;\n };\n}\n\n/** `GET /documents/:did/elements/:elementId/history`: newest first (spec 03 §14). */\nexport const elementHistoryQuerySchema = cursorQuerySchema;\nexport interface ElementHistoryEntry {\n at: string;\n authors: string[];\n text: string;\n source: 'update' | 'version';\n}\n\n/** `GET /documents/:did/presence`: who has the document open on this API instance right now. */\nexport interface PresenceEntry {\n userId: string;\n displayName: string | null;\n colour: string;\n since: string;\n deviceId: string | null;\n deviceName: string | null;\n mode: 'edit' | 'view';\n role: string;\n}\n","import { z } from 'zod';\n\n/**\n * A writing_core command as plain JSON. The command bodies are typed by\n * writing_core; here they are opaque records until the API validates them.\n */\nexport type WritingCommandJson = Record<string, unknown>;\n\nexport const COMMAND_BATCH_MAX = 500;\n\nexport const commandBatchRequestSchema = z.object({\n commands: z\n .array(z.record(z.string(), z.unknown()))\n .min(1)\n .max(COMMAND_BATCH_MAX),\n baseEpoch: z.number().int().min(0),\n expectedHashes: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type CommandBatchRequest = z.infer<typeof commandBatchRequestSchema>;\n\nexport interface CommandWarning {\n index: number;\n code: string;\n message: string;\n}\n\nexport interface CommandEffects {\n /** Elements the batch created, changed and removed (sorted ids). */\n createdIds: string[];\n changedIds: string[];\n deletedIds: string[];\n /** Fresh content hashes (spec 11 4.2) of every created or changed element. */\n newHashes: Record<string, string>;\n}\n\n/**\n * `POST /documents/:did/commands` response (thin B5 version). A `dryRun` returns the same shape\n * with `applied: 0` and `dryRun: true`: the effects the batch WOULD have, nothing changed.\n * `expectedHashes` keys are element or scene ids; a mismatch is 409 `CONTENT_CHANGED` with\n * `details.ids`.\n */\nexport interface CommandBatchResponse {\n applied: number;\n epoch: number;\n dryRun?: boolean;\n effects: CommandEffects;\n warnings: CommandWarning[];\n}\n\n/** `COMMAND_INVALID` (422) `details`. `reason` is a writing_core ReasonCode (or `exception`). */\nexport interface CommandInvalidDetails {\n index: number;\n reason: string;\n detail?: Record<string, unknown>;\n}\n\n// ---- Scene and element reads (spec 05 6.7.1, live document) ----\n\nexport const SCENE_BATCH_MAX = 20;\nexport const ELEMENT_BATCH_MAX = 500;\n\nexport interface OutlineScene {\n id: string;\n /** Formatted scene number label, or null when unnumbered. */\n number: string | null;\n heading: string;\n omitted: boolean;\n synopsis: string;\n elementCount: number;\n contentHash: string;\n}\n\nexport interface OutlineResponse {\n scenes: OutlineScene[];\n}\n\nexport interface ElementRead {\n id: string;\n styleId: string;\n styleName: string;\n /** The style's role (`sceneHeading`, `action`, `character`, `dialogue`, ...), for callers that must not guess from names. */\n styleRole?: string;\n text: string;\n contentHash: string;\n}\n\nexport interface SceneRead {\n id: string;\n number: string | null;\n heading: string;\n synopsis: string;\n contentHash: string;\n elements: ElementRead[];\n}\n\nexport const elementsBatchRequestSchema = z.object({\n elementIds: z.array(z.string().min(1)).min(1).max(ELEMENT_BATCH_MAX),\n});\nexport type ElementsBatchRequest = z.infer<typeof elementsBatchRequestSchema>;\nexport interface ElementsBatchResponse {\n elements: ElementRead[];\n}\n\nexport const scenesBatchRequestSchema = z.object({\n sceneIds: z.array(z.string().min(1)).min(1).max(SCENE_BATCH_MAX),\n});\nexport type ScenesBatchRequest = z.infer<typeof scenesBatchRequestSchema>;\nexport interface ScenesBatchResponse {\n scenes: SceneRead[];\n}\n","import { z } from 'zod';\nimport { documentKindSchema } from '../projects/index.js';\nimport type { DocumentMeta } from '../projects/index.js';\n\n/** Import and export over HTTP (synchronous; spec 05 §6.18 minus the job framework). */\n\n/** Formats the server can import: ids of `writing_formats`. */\nexport const IMPORT_FORMAT_IDS = ['fountain', 'fdx', 'fadein'] as const;\nexport const EXPORT_FORMAT_IDS = ['fountain', 'fdx', 'json'] as const;\nexport type ExportFormatId = (typeof EXPORT_FORMAT_IDS)[number];\n\n/** Default `IMPORT_MAX_BYTES`: 100 MiB of decoded file bytes. */\nexport const IMPORT_MAX_BYTES_DEFAULT = 100 * 1024 * 1024;\n\n/** Mirror of `writing_formats` `Diagnostic` (this package cannot depend on it). */\nexport interface ConversionDiagnostic {\n code: string;\n severity: 'info' | 'warn' | 'loss' | 'error';\n message: string;\n feature: string;\n count: number;\n locations?: {\n elementIndex?: number;\n sourceLine?: number;\n sourcePath?: string;\n }[];\n}\n\n/** Mirror of `writing_formats` `ConversionReport` (spec 04 §3.1). */\nexport interface ConversionReport {\n direction: 'import' | 'export';\n format: string;\n sourceVersion?: string;\n diagnostics: ConversionDiagnostic[];\n stats: {\n elements: number;\n scenes: number;\n pages?: number;\n durationMs: number;\n };\n confidence?: number;\n summary: { info: number; warn: number; loss: number; error: number };\n}\n\n/** `POST /projects/:pid/documents/import` (idempotent on `id`, like document create). */\nexport const documentImportSchema = z.object({\n /** Client-generated `doc_...`; import is idempotent on it. */\n id: z.string().startsWith('doc_').optional(),\n /** Only a hint: the format is detected from the content. */\n filename: z.string().min(1).max(500),\n /** Base64 of the file bytes. */\n contentB64: z.string(),\n /** Defaults to the file's title page title, then the filename. */\n title: z.string().trim().min(1).max(200).optional(),\n kind: documentKindSchema.optional(),\n templateId: z.string().optional(),\n language: z.string().max(16).optional(),\n});\nexport type DocumentImportRequest = z.infer<typeof documentImportSchema>;\n\nexport interface DocumentImportResult {\n document: DocumentMeta;\n report: ConversionReport;\n /** Detected source format id. */\n format: string;\n}\n\n/** `POST /documents/:did/export` */\nexport const documentExportSchema = z.object({\n format: z.string().min(1).max(32),\n});\nexport type DocumentExportRequest = { format: ExportFormatId };\n\nexport interface DocumentExportResult {\n filename: string;\n mimeType: string;\n contentB64: string;\n report: ConversionReport;\n format: ExportFormatId;\n}\n\n/** `GET /formats` */\nexport interface FormatInfo {\n id: string;\n label: string;\n extensions: string[];\n canImport: boolean;\n canExport: boolean;\n}\n","/**\n * Projection-backed reads (spec 05 §6.7.1, §6.7.2, §6.12, §6.14, §6.15, §6.17), slice B10.\n * The Y.Doc is canonical; these are the shapes the API returns for entities, tags, notes, beats, the Bin,\n * revisions, tracked changes, alternates, title page, statistics, shots, locators and search.\n */\nimport { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n// ─── ?source= ───────────────────────────────────────────────────────────────\n\n/** Query encoding of a `SourceRef` (spec 05 §6.7.1): `live`, `snapshot:<snapshotId>` or `version:<versionId>`. */\nexport const sourceParamSchema = z\n .string()\n .regex(\n /^(live|snapshot:[A-Za-z0-9_-]+|version:[A-Za-z0-9_-]+)$/,\n 'source must be live, snapshot:<id> or version:<id>'\n );\n\n/** JSON-body source on a document route: the document is implied by the route (spec 03 `SourceRef` without `documentId`). */\nexport const docSourceSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('live') }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string().min(1) }),\n z.object({ kind: z.literal('version'), versionId: z.string().min(1) }),\n]);\nexport type DocSource = z.infer<typeof docSourceSchema>;\n\nexport const sourceQuerySchema = z.object({\n source: sourceParamSchema.optional(),\n});\nexport type SourceQuery = z.infer<typeof sourceQuerySchema>;\n\nexport function sourceParamOf(ref: DocSource | undefined): string | undefined {\n if (!ref || ref.kind === 'live') return undefined;\n return ref.kind === 'snapshot'\n ? `snapshot:${ref.snapshotId}`\n : `version:${ref.versionId}`;\n}\n\n// ─── Entities (spec 05 §6.12) ───────────────────────────────────────────────\n\nexport const entityListQuerySchema = cursorQuerySchema.extend({\n kind: z.string().min(1).optional(),\n q: z.string().min(1).max(200).optional(),\n source: sourceParamSchema.optional(),\n});\nexport type EntityListQuery = z.infer<typeof entityListQuerySchema>;\n\nexport interface EntitySummary {\n id: string;\n kind: string;\n name: string;\n aliases: string[];\n color: string | null;\n sceneCount: number;\n firstSceneId: string | null;\n /** Characters only. */\n dialogueCount?: number;\n}\n\n/** A character's age or a location's version (spec 01 §5.8.1), read raw from the Y.Doc. */\nexport interface EntityVariantSummary {\n id: string;\n label: string;\n ageValue: number | null;\n setting: string | null;\n sortKey: string;\n appearances: { id: string; label: string }[];\n}\n\nexport interface EntityDetail extends EntitySummary {\n description: string;\n fields: Record<string, unknown>;\n attributes: Record<string, unknown>;\n categoryId: string | null;\n origin: string;\n retain: boolean;\n scenes: { id: string; number: string | null }[];\n tagsByScene: Record<string, string[]>;\n /** Asset links arrive with slice B11: always empty until then. */\n assetLinks: { assetLinkId: string; role: string }[];\n contentHash: string;\n variants: EntityVariantSummary[];\n worksheetIds: string[];\n}\n\nexport const entityUsageQuerySchema = z.object({\n variantId: z.string().min(1).optional(),\n source: sourceParamSchema.optional(),\n});\nexport type EntityUsageQuery = z.infer<typeof entityUsageQuerySchema>;\n\nexport interface SceneRef {\n id: string;\n number: string | null;\n heading?: string;\n synopsis?: string;\n}\n\n/**\n * What blocks deleting an entity and what the character and location lists show behind *Show usages*\n * (spec 09 F-TAG-017, F-TAG-021). `total` = cues + headings + tags + arcBeats + noteMentions + assetLinks\n * (`sceneLinks` is the informational scene presence and is not counted).\n */\nexport interface EntityUsage {\n total: number;\n cues: {\n elementId: string;\n sceneId: string | null;\n sceneNumber: string | null;\n page: string | null;\n variantId: string | null;\n }[];\n headings: {\n sceneId: string;\n sceneNumber: string | null;\n page: string | null;\n variantId: string | null;\n }[];\n sceneLinks: SceneRef[];\n tags: { tagId: string; categoryId: string; sceneId: string | null }[];\n arcBeats: SceneRef[];\n noteMentions: { noteId: string }[];\n assetLinks: { assetLinkId: string; role: string }[];\n byVariant: Record<string, number>;\n /** Uses (cues for a character, headings for a location) that name no variant. */\n unassigned: number;\n}\n\nexport const entityDialogueQuerySchema = z.object({\n sceneIds: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\n\n/** Dialogue Tuner view (spec 05 §6.7.1). */\nexport interface DialogueSceneView {\n sceneId: string;\n sceneNumber: string | null;\n elements: {\n id: string;\n styleId: string;\n text: string;\n contentHash: string;\n }[];\n}\n\n// ─── Tags, notes, beats, bin, revisions, changes, alternates ────────────────\n\nexport interface TagCategoryRow {\n id: string;\n key: string | null;\n name: string;\n color: string;\n entityKind: string;\n}\n\nexport const tagsQuerySchema = z.object({\n sceneId: z.string().optional(),\n categoryId: z.string().optional(),\n entityId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface TagRow {\n id: string;\n categoryId: string;\n entityId: string;\n elementId: string;\n range: { index: number; length: number } | null;\n text: string;\n sceneId: string | null;\n}\n\nexport const notesQuerySchema = z.object({\n sceneId: z.string().optional(),\n type: z.string().optional(),\n status: z.enum(['open', 'resolved']).optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface NoteSummary {\n id: string;\n anchor: { kind: string; elementId?: string; beatId?: string };\n sceneId: string | null;\n /** The note type's name (falls back to its id). */\n type: string | null;\n typeId: string | null;\n color: string | null;\n title: string;\n body: string;\n author: string | null;\n createdAt: number | null;\n replies: { id: string; author: string; body: string; at: number }[];\n status: 'open' | 'resolved';\n contentHash: string;\n}\n\nexport interface BeatRow {\n id: string;\n title: string;\n body: string;\n color: string | null;\n x: number | null;\n y: number | null;\n links: { id: string; to: string; label: string }[];\n sceneId?: string;\n}\n\nexport interface BinRow {\n id: string;\n title: string;\n preview: string;\n createdAt: number;\n}\n\nexport interface RevisionsView {\n sets: {\n id: string;\n name: string;\n color: string;\n mark: string;\n fullDraft: boolean;\n date: number | null;\n }[];\n activeSetId: string | null;\n revisionMode: boolean;\n trackChanges: boolean;\n}\n\nexport const changesQuerySchema = z.object({\n authorId: z.string().optional(),\n sceneId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface ChangeRow {\n id: string;\n kind: 'insert' | 'delete' | 'style' | 'fmt';\n authorId: string;\n at: number;\n elementId: string;\n before: string;\n after: string;\n}\n\n/** The element's own text is the active alternate (index 0); the inactive ones follow. */\nexport interface AlternatesView {\n activeIndex: number;\n alternates: { id: string; text: string }[];\n}\n\nexport interface TitlePageRead {\n fields: Record<string, string>;\n elements: {\n id: string;\n styleId: string;\n text: string;\n field: string | null;\n }[];\n computed: Record<string, unknown>;\n}\n\nexport interface StatsRead {\n pages: number;\n eighths: number;\n scenes: number;\n words: number;\n elementsByStyle: Record<string, number>;\n estRuntimeMin: number;\n intExt: Record<string, number>;\n dayNight: Record<string, number>;\n dialoguePct: number;\n}\n\nexport interface ShotRow {\n id: string;\n index: number;\n sceneId: string;\n label: string;\n description: string;\n elementRange: { startElementId: string; endElementId: string } | null;\n camera: Record<string, unknown>;\n estDurationSec: number | null;\n attributes: Record<string, unknown>;\n contentHash: string;\n}\n\nexport const fountainQuerySchema = z.object({\n sceneIds: z.string().optional(),\n fromSceneId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\n/** `GET /documents/:did/fountain` truncates at this many bytes and sets `X-Next-From-Scene`. */\nexport const FOUNTAIN_MAX_BYTES = 1_000_000;\n\n// ─── Locators (spec 11 §1.3, spec 05 §6.7.2) ────────────────────────────────\n\nexport const LOCATOR_KINDS = [\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'page',\n] as const;\nexport type LocatorKind = (typeof LOCATOR_KINDS)[number];\n\nexport type ResolveResult =\n | { status: 'resolved'; kind: LocatorKind; id: string; label: string }\n | {\n status: 'ambiguous';\n kind: LocatorKind;\n candidates: { id: string; label: string; score: number }[];\n }\n | {\n status: 'not_found';\n kind: LocatorKind;\n suggestions: { id: string; label: string }[];\n };\n\nexport const RESOLVE_BATCH_MAX = 200;\nexport const resolveBatchSchema = z.object({\n locators: z.array(z.string().min(1).max(500)).min(1).max(RESOLVE_BATCH_MAX),\n snapshotId: z.string().min(1).optional(),\n});\nexport type ResolveBatchRequest = z.infer<typeof resolveBatchSchema>;\n/** `GET /documents/:did/resolve?ref=&snapshotId=`. */\nexport const resolveOneQuerySchema = z.object({\n ref: z.string().min(1).max(500),\n snapshotId: z.string().min(1).optional(),\n});\n\n// ─── Search (spec 05 §6.17) ─────────────────────────────────────────────────\n\nexport const SEARCH_HIT_TYPES = [\n 'document',\n 'scene',\n 'element',\n 'entity',\n 'note',\n 'asset',\n] as const;\nexport type SearchHitType = (typeof SEARCH_HIT_TYPES)[number];\n\nconst csv = (v: unknown) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v;\n\nexport const searchQuerySchema = cursorQuerySchema.extend({\n q: z.string().min(1).max(200),\n workspaceId: z.string().min(1).optional(),\n projectId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n types: z.preprocess(csv, z.array(z.enum(SEARCH_HIT_TYPES)).min(1)).optional(),\n styleIds: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n characterId: z.string().min(1).optional(),\n language: z.string().min(2).max(35).optional(),\n});\nexport type SearchQuery = z.infer<typeof searchQuerySchema>;\n\n/** `GET /documents/:did/search` (in-document find, spec 05 §6.7.1). */\nexport const documentSearchQuerySchema = z.object({\n q: z.string().min(1).max(500),\n mode: z.enum(['text', 'regex']).default('text'),\n styles: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n characters: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n limit: z.coerce.number().int().min(1).max(100).default(50),\n source: sourceParamSchema.optional(),\n});\nexport type DocumentSearchQuery = z.infer<typeof documentSearchQuerySchema>;\n\nexport interface DocumentSearchHit {\n sceneId: string | null;\n sceneNumber: string | null;\n elementId: string;\n styleId: string;\n snippet: string;\n page: string | null;\n}\n\nexport interface SearchHit {\n type: SearchHitType;\n documentId: string | null;\n projectId: string;\n targetId: string;\n title: string;\n /** At most 240 characters; `marks` are `[start, end)` ranges into it (never HTML). */\n snippet: string;\n marks: [number, number][];\n sceneNumber?: string | null;\n pageNumber?: string | null;\n rank: number;\n}\n","import { z } from 'zod';\nimport { documentKindSchema } from '../projects/index.js';\nimport { docSourceSchema } from '../reads/index.js';\nimport type { ConversionReport } from '../formats/index.js';\n\n/**\n * Imports, exports and batch watermark as jobs, plus the upload port they share (slice B16; spec 05 §6.18, §6.1 `uploads`,\n * §13). The synchronous `POST /projects/:pid/documents/import`, `POST /documents/:did/export` and `GET /formats` (see\n * `formats/`) stay until the app migrates.\n *\n * Formats are exactly what `writing_formats` has today: import Fountain, FDX and Fade In; export Fountain, FDX and the plain\n * JSON backup. PDF, DOCX, Celtx, Scrivener and OCR answer `IMPORT_FORMAT_UNSUPPORTED` / `EXPORT_FORMAT_UNSUPPORTED` /\n * `OCR_UNAVAILABLE`; nothing fakes them.\n */\n\n/** Formats `POST /imports` accepts (a job kind `import.<format>` exists for each). */\nexport const JOB_IMPORT_FORMATS = ['fountain', 'fdx', 'fadein'] as const;\nexport type JobImportFormat = (typeof JOB_IMPORT_FORMATS)[number];\n/** Formats an export job produces (`export.<format>`). */\nexport const JOB_EXPORT_FORMATS = ['fountain', 'fdx', 'json'] as const;\nexport type JobExportFormat = (typeof JOB_EXPORT_FORMATS)[number];\n/** `POST /documents/export-combined` takes these (spec 05: pdf, fdx, fountain; pdf is not built). */\nexport const COMBINED_EXPORT_FORMATS = ['fdx', 'fountain'] as const;\n/** At most this many documents in one combined export (the job's `sources` cap). */\nexport const COMBINED_EXPORT_MAX_DOCUMENTS = 20;\n/** At most this many recipients in one batch watermark (spec 05 §6.18). */\nexport const BATCH_WATERMARK_MAX_RECIPIENTS = 500;\n\n// ─── uploads (spec 05 §6.1 `uploads`, §8) ─────────────────────────────────────\n\nexport const UPLOAD_PURPOSES = ['state', 'watermark_lookup', 'import'] as const;\nexport type UploadPurpose = (typeof UPLOAD_PURPOSES)[number];\n\nconst sha256HexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{64}$/, 'sha256Hex must be 64 hex characters');\n\n/**\n * `POST /uploads/state`. `purpose` defaults to `state` (a Yjs state blob); `watermark_lookup` is a leaked file for\n * `POST /workspaces/:wid/watermark-lookup`. `import` uploads are created by `POST /imports`, never here.\n */\nexport const uploadStateRequestSchema = z.object({\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema,\n purpose: z.enum(['state', 'watermark_lookup']).default('state'),\n});\nexport type UploadStateRequest = z.input<typeof uploadStateRequestSchema>;\n\n/** A presigned PUT: send the bytes with `PUT url` (no `Authorization`), then use `uploadKey`. */\nexport interface UploadStateResponse {\n uploadKey: string;\n url: string;\n /** When the PUT url stops working (`SIGNED_URL_TTL_S`). */\n expiresAt: string;\n}\n\n// ─── imports ─────────────────────────────────────────────────────────────────\n\nexport const importOptionsSchema = z.object({\n templateId: z.string().min(1).optional(),\n /** `auto`: OCR a PDF without a text layer; `force`; `off`. No OCR exists yet: `force` is `OCR_UNAVAILABLE`. */\n ocr: z.enum(['auto', 'force', 'off']).default('auto'),\n ocrLanguage: z.string().min(2).max(16).optional(),\n title: z.string().trim().min(1).max(200).optional(),\n kind: documentKindSchema.optional(),\n language: z.string().max(16).optional(),\n});\nexport type ImportOptions = z.input<typeof importOptionsSchema>;\n\nconst importFileFields = {\n filename: z.string().min(1).max(500),\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema,\n /** Auto-detected from the uploaded bytes when omitted. */\n format: z.string().min(1).max(32).optional(),\n options: importOptionsSchema.optional(),\n};\n\n/** `POST /imports`: one of `targetProjectId` (import as a new document) or `templateTarget` (a template file, `POST /templates/import {importId}`). */\nexport const importCreateSchema = z\n .object({\n targetProjectId: z.string().min(1).optional(),\n templateTarget: z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n })\n .optional(),\n ...importFileFields,\n })\n .refine(\n (v) => (v.targetProjectId ? 1 : 0) + (v.templateTarget ? 1 : 0) === 1,\n {\n message: 'Send exactly one of targetProjectId and templateTarget',\n path: ['targetProjectId'],\n }\n );\nexport type ImportCreateRequest = z.input<typeof importCreateSchema>;\n\n/** `POST /documents/:did/import-over`: the document is the route's. */\nexport const importOverSchema = z.object(importFileFields);\nexport type ImportOverRequest = z.input<typeof importOverSchema>;\n\n/** Both answer this: PUT the file to `upload.url`, then `POST /imports/:importId/start`. No job exists yet. */\nexport interface ImportCreateResponse {\n importId: string;\n upload: { url: string; expiresAt: string };\n}\n\n/** Input stored on `import.<format>` jobs (spec 05 §13). `newDocumentId` is minted at start so a retried run cannot make two documents. */\nexport const importJobInputSchema = z.object({\n importId: z.string().min(1),\n targetProjectId: z.string().min(1),\n newDocumentId: z.string().min(1),\n filename: z.string().min(1).max(500),\n options: importOptionsSchema.optional(),\n});\nexport type ImportJobInput = z.infer<typeof importJobInputSchema>;\n\n/** Input stored on `doc.importOver` jobs. */\nexport const importOverJobInputSchema = z.object({\n importId: z.string().min(1),\n documentId: z.string().min(1),\n filename: z.string().min(1).max(500),\n options: importOptionsSchema.optional(),\n});\nexport type ImportOverJobInput = z.infer<typeof importOverJobInputSchema>;\n\n/** One document an import made; the job's outputs carry one `conversion-report.json` per document (`output.documentId`). */\nexport interface ImportedDocumentRef {\n documentId: string;\n title: string;\n format: string;\n}\n/** What a finished `import.*` job stores as `result` (also readable from the outputs). */\nexport interface ImportJobResult {\n documents: ImportedDocumentRef[];\n report: ConversionReport;\n}\n/** What a finished `doc.importOver` job stores as `result`. */\nexport interface ImportOverJobResult {\n documentId: string;\n epoch: number;\n preImportSnapshotId: string;\n format: string;\n report: ConversionReport;\n}\n\n/** Name of the per-document (import) or per-file (export) conversion report output. */\nexport const CONVERSION_REPORT_OUTPUT = 'conversion-report.json';\n\n// ─── exports ─────────────────────────────────────────────────────────────────\n\n/** Visible watermark. `text` tokens: `{recipient}`, `{email}`, `{company}`, `{title}`, `{date}`. */\nexport const watermarkStyleSchema = z.object({\n text: z.string().min(1).max(200).default('{recipient}'),\n opacity: z.number().min(0.05).max(1).optional(),\n position: z\n .enum(['diagonalAscending', 'diagonalDescending', 'horizontal'])\n .optional(),\n});\nexport type WatermarkStyle = z.input<typeof watermarkStyleSchema>;\n\nexport const batchWatermarkSchema = z.object({\n recipients: z\n .array(\n z.object({\n name: z.string().trim().min(1).max(200),\n email: z.string().trim().min(1).max(320).optional(),\n company: z.string().trim().min(1).max(200).optional(),\n })\n )\n .min(1)\n .max(BATCH_WATERMARK_MAX_RECIPIENTS),\n visible: watermarkStyleSchema.optional(),\n /** Forensic mark. Only a PDF writer can embed one; text formats carry the export code as a visible note (see the API notes). */\n invisible: z.boolean().default(false),\n /** `email` needs the notification slice (B12): refused with `VALIDATION` until then. */\n deliver: z.enum(['download', 'email']).default('download'),\n emailMessage: z.string().max(2000).optional(),\n});\nexport type BatchWatermark = z.input<typeof batchWatermarkSchema>;\n\nexport const exportOptionsSchema = z.object({\n /** Download name without extension (default: the document title). */\n filename: z.string().trim().min(1).max(120).optional(),\n batchWatermark: batchWatermarkSchema.optional(),\n});\nexport type ExportOptions = z.input<typeof exportOptionsSchema>;\n\n/** `POST /documents/:did/exports`. `format` is validated by the server (`EXPORT_FORMAT_UNSUPPORTED` for anything but fountain, fdx, json). */\nexport const exportCreateSchema = z.object({\n format: z.string().min(1).max(32),\n source: docSourceSchema.optional(),\n options: exportOptionsSchema.optional(),\n});\nexport type ExportCreateRequest = z.input<typeof exportCreateSchema>;\n\n/** `POST /documents/export-combined`: the first document's title page and template, bodies concatenated in the order given. */\nexport const exportCombinedSchema = z.object({\n documentIds: z\n .array(z.string().min(1))\n .min(1)\n .max(COMBINED_EXPORT_MAX_DOCUMENTS),\n format: z.string().min(1).max(32),\n options: exportOptionsSchema.omit({ batchWatermark: true }).optional(),\n});\nexport type ExportCombinedRequest = z.input<typeof exportCombinedSchema>;\n\n/** Input stored on `export.<format>` and `watermark.batch` jobs. */\nexport const exportJobInputSchema = z.object({\n format: z.enum(JOB_EXPORT_FORMATS),\n documentIds: z\n .array(z.string().min(1))\n .max(COMBINED_EXPORT_MAX_DOCUMENTS)\n .optional(),\n source: docSourceSchema.optional(),\n options: exportOptionsSchema.optional(),\n});\nexport type ExportJobInput = z.infer<typeof exportJobInputSchema>;\n\n/** What a finished `watermark.batch` job stores as `result`. `invisibleApplied` is false for every text format. */\nexport interface WatermarkBatchResult {\n recipients: number;\n format: JobExportFormat;\n visibleApplied: boolean;\n invisibleApplied: boolean;\n /** How the export code travels in the file. */\n codeCarrier: 'fountain-note' | 'fdx-comment' | 'json-field';\n}\n\n// ─── watermark lookup ────────────────────────────────────────────────────────\n\n/** Prefix of an export code as printed in a file: `FWX-` + 26 base32 characters (128 random bits). */\nexport const EXPORT_CODE_PREFIX = 'FWX-';\n\n/** `{exportId}` or `{pdfUploadKey}` (a leaked file uploaded through `/uploads/state` with `purpose: \"watermark_lookup\"`). */\nexport const watermarkLookupSchema = z\n .object({\n exportId: z.string().trim().min(8).max(64).optional(),\n pdfUploadKey: z.string().min(1).max(100).optional(),\n })\n .refine((v) => (v.exportId ? 1 : 0) + (v.pdfUploadKey ? 1 : 0) === 1, {\n message: 'Send exactly one of exportId and pdfUploadKey',\n path: ['exportId'],\n });\nexport type WatermarkLookupRequest = z.input<typeof watermarkLookupSchema>;\n\nexport interface WatermarkMatch {\n exportId: string;\n recipient: { name: string; email: string | null; company: string | null };\n documentId: string | null;\n documentTitle: string | null;\n /** Display name (else email) of who ran the export. */\n exportedBy: string | null;\n exportedAt: string;\n source: {\n documentId: string | null;\n kind: 'live' | 'snapshot' | 'version';\n snapshotId?: string;\n versionId?: string;\n };\n}\nexport interface WatermarkLookupResponse {\n matches: WatermarkMatch[];\n}\n","import { z } from 'zod';\n\n/**\n * AI features (spec 06): script review and polish through ShapeShyft.\n *\n * Only the tasks implemented so far are in `AI_TASKS`; adding one means a registry row in\n * `screenwriter_api/src/services/ai/tasks.ts`, a prompt builder, an output schema here and a fixture.\n * Output schemas are written for structured output: every field is required (nullable, never optional)\n * and objects are closed, so `z.toJSONSchema` gives the exact schema to store on the ShapeShyft endpoint.\n */\n\nexport const AI_TASKS = ['coverage', 'polish.dialogue'] as const;\nexport type AiTask = (typeof AI_TASKS)[number];\nexport const aiTaskSchema = z.enum(AI_TASKS);\n\n/** ShapeShyft endpoint names (spec 06 2.1). `summarize-chunk` is stage 1 of a long coverage run. */\nexport const AI_ENDPOINTS = [\n 'coverage-review',\n 'polish',\n 'summarize-chunk',\n] as const;\nexport type AiEndpoint = (typeof AI_ENDPOINTS)[number];\n\nexport const AI_JOB_STATUSES = [\n 'queued',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport type AiJobStatus = (typeof AI_JOB_STATUSES)[number];\n\n/** Counted limits, declared once: schemas, validators and prompt text all read these. */\nexport const AI_LIMITS = {\n noteTitleMax: 80,\n noteBodyMax: 1200,\n noteAnchorsMax: 8,\n strengthsMax: 8,\n weaknessesMax: 12,\n sceneNotesMax: 20,\n loglineMax: 300,\n summaryMax: 4000,\n genreMax: 3,\n verdictRationaleMax: 800,\n polishSuggestionsMax: 200,\n polishTextMax: 4000,\n rationaleMax: 400,\n chunkSummaryMax: 1200,\n sceneSummaryMax: 280,\n polishMaxScenes: 8,\n instructionsMax: 500,\n} as const;\n\nexport const REVIEW_CATEGORIES = [\n 'premise',\n 'structure',\n 'character',\n 'dialogue',\n 'pacing',\n 'tone',\n 'theme',\n 'worldbuilding',\n 'format',\n 'marketability',\n 'clarity',\n 'continuity',\n] as const;\nexport type ReviewCategory = (typeof REVIEW_CATEGORIES)[number];\nexport const SEVERITIES = ['praise', 'minor', 'moderate', 'major'] as const;\nexport type Severity = (typeof SEVERITIES)[number];\nexport const COVERAGE_VERDICTS = ['recommend', 'consider', 'pass'] as const;\n\n// ---- Model output (untrusted until validated; what the ShapeShyft endpoint returns) ----\n\n/** Where a note points. `elementId: null` means the whole scene. The server adds the content hash. */\nexport const anchorRefSchema = z.object({\n sceneId: z.string(),\n elementId: z.string().nullable(),\n});\nexport type AnchorRef = z.infer<typeof anchorRefSchema>;\n\nexport const noteSchema = z.object({\n category: z.enum(REVIEW_CATEGORIES),\n severity: z.enum(SEVERITIES),\n title: z.string().min(1).max(AI_LIMITS.noteTitleMax),\n body: z.string().min(1).max(AI_LIMITS.noteBodyMax),\n anchors: z.array(anchorRefSchema).max(AI_LIMITS.noteAnchorsMax),\n});\nexport type ModelNote = z.infer<typeof noteSchema>;\n\n/** `coverage-review` output. */\nexport const coverageResponseSchema = z.object({\n logline: z.string().max(AI_LIMITS.loglineMax),\n summary: z.string().max(AI_LIMITS.summaryMax),\n genre: z.array(z.string()).max(AI_LIMITS.genreMax),\n strengths: z.array(noteSchema).max(AI_LIMITS.strengthsMax),\n weaknesses: z.array(noteSchema).max(AI_LIMITS.weaknessesMax),\n /** Notes about specific scenes: each must anchor at least one scene. */\n sceneNotes: z.array(noteSchema).max(AI_LIMITS.sceneNotesMax),\n verdict: z.enum(COVERAGE_VERDICTS),\n verdictRationale: z.string().max(AI_LIMITS.verdictRationaleMax),\n});\nexport type CoverageResponse = z.infer<typeof coverageResponseSchema>;\n\n/** `polish` output: one proposed replacement per element. */\nexport const polishResponseSchema = z.object({\n suggestions: z\n .array(\n z.object({\n elementId: z.string(),\n after: z.string().max(AI_LIMITS.polishTextMax),\n rationale: z.string().max(AI_LIMITS.rationaleMax),\n })\n )\n .max(AI_LIMITS.polishSuggestionsMax),\n});\nexport type PolishResponse = z.infer<typeof polishResponseSchema>;\n\n/** `summarize-chunk` output (stage 1 of a long-script coverage run). */\nexport const chunkSummaryResponseSchema = z.object({\n scenes: z.array(\n z.object({\n sceneId: z.string(),\n summary: z.string().max(AI_LIMITS.sceneSummaryMax),\n intensity: z.number().int().min(1).max(5),\n })\n ),\n chunkSummary: z.string().max(AI_LIMITS.chunkSummaryMax),\n});\nexport type ChunkSummaryResponse = z.infer<typeof chunkSummaryResponseSchema>;\n\n/** The five input fields every endpoint takes (spec 06 2.1). */\nexport const aiEndpointInputSchema = z.object({\n context: z.string(),\n brief: z.string(),\n max_output_tokens: z.number().int().positive(),\n locale: z.string(),\n script_language: z.string(),\n});\nexport type AiEndpointInput = z.infer<typeof aiEndpointInputSchema>;\n\n/** Endpoint -> output schema. `bun run ai:schemas` in screenwriter_api prints these as JSON Schema. */\nexport const AI_ENDPOINT_OUTPUT_SCHEMAS = {\n 'coverage-review': coverageResponseSchema,\n polish: polishResponseSchema,\n 'summarize-chunk': chunkSummaryResponseSchema,\n} as const satisfies Record<AiEndpoint, z.ZodType>;\n\n// ---- Stored / returned shapes ----\n\nexport interface Anchor {\n sceneId: string;\n elementId?: string;\n /** Content hash (spec 11 4.2) of the element, or of the scene when there is no elementId, at generation time. */\n contentHash: string;\n}\n\nexport interface AiNote {\n id: string;\n category: ReviewCategory;\n severity: Severity;\n title: string;\n body: string;\n anchors: Anchor[];\n}\n\nexport interface CoverageReport {\n logline: string;\n summary: string;\n genre: string[];\n verdict: (typeof COVERAGE_VERDICTS)[number];\n verdictRationale: string;\n strengths: AiNote[];\n weaknesses: AiNote[];\n notesByScene: { sceneId: string; heading: string; notes: AiNote[] }[];\n stats: { scenes: number; chunks: number; droppedItems: number };\n}\n\nexport interface AiTokenUsage {\n promptTokens: number;\n completionTokens: number;\n calls: number;\n model: string | null;\n}\n\n// ---- Jobs ----\n\nexport const aiScopeSchema = z.object({\n sceneIds: z.array(z.string().min(1)).max(200).optional(),\n elementIds: z.array(z.string().min(1)).max(2000).optional(),\n});\nexport type AiScope = z.infer<typeof aiScopeSchema>;\n\nexport const aiJobOptionsSchema = z.object({\n /** Writer's own request, fenced separately from the script. Fixture failure markers only work in test mode. */\n instructions: z.string().max(AI_LIMITS.instructionsMax).optional(),\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n locale: z.string().min(2).max(20).optional(),\n});\nexport type AiJobOptions = z.infer<typeof aiJobOptionsSchema>;\n\n/** `POST /documents/:did/ai/jobs` body. `polish.dialogue` needs a scope; `coverage` defaults to the whole script. */\nexport const aiJobCreateSchema = z.object({\n task: aiTaskSchema,\n scope: aiScopeSchema.optional(),\n options: aiJobOptionsSchema.optional(),\n});\nexport type AiJobCreateRequest = z.infer<typeof aiJobCreateSchema>;\n\n/** 202 response. */\nexport interface AiJobCreated {\n jobId: string;\n status: 'queued';\n}\n\nexport interface AiJobProgress {\n stage: string;\n done: number;\n total: number;\n}\n\nexport interface AiJobError {\n code: string;\n message: string;\n}\n\nexport type AiJobResult =\n | { kind: 'report'; report: CoverageReport }\n /** `suggestionSetId` is null when the model found nothing worth changing (count 0). */\n | {\n kind: 'suggestions';\n suggestionSetId: string | null;\n count: number;\n droppedItems: number;\n };\n\n/** `GET /ai/jobs/:jobId` and the items of `GET /documents/:did/ai/jobs`. Poll until `status` is final. */\nexport interface AiJob {\n id: string;\n documentId: string;\n task: AiTask;\n status: AiJobStatus;\n progress?: AiJobProgress;\n result?: AiJobResult;\n error?: AiJobError;\n promptVersion: string;\n usage?: AiTokenUsage;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\n// ---- Suggestion sets (spec 06 7) ----\n\nexport const SUGGESTION_STATUSES = [\n 'pending',\n 'accepted',\n 'rejected',\n 'stale',\n] as const;\nexport type SuggestionStatus = (typeof SUGGESTION_STATUSES)[number];\nexport const SUGGESTION_SET_STATUSES = [\n 'pending',\n 'partiallyAccepted',\n 'accepted',\n 'rejected',\n 'stale',\n 'expired',\n] as const;\nexport type SuggestionSetStatus = (typeof SUGGESTION_SET_STATUSES)[number];\n\nexport interface Suggestion {\n id: string;\n elementId: string;\n kind: 'replaceText';\n before: string;\n after: string;\n rationale: string;\n /** The element's content hash when the suggestion was generated; accepting checks it. */\n contentHash: string;\n status: SuggestionStatus;\n decidedAt: string | null;\n}\n\nexport interface SuggestionSetSummary {\n id: string;\n documentId: string;\n jobId: string;\n task: AiTask;\n promptVersion: string;\n status: SuggestionSetStatus;\n sourceEpoch: number;\n counts: Record<SuggestionStatus, number>;\n createdAt: string;\n}\n\nexport interface SuggestionSet extends SuggestionSetSummary {\n suggestions: Suggestion[];\n}\n\nexport const suggestionAcceptSchema = z.object({\n suggestionIds: z.array(z.string().min(1)).min(1).max(200),\n});\nexport type SuggestionAcceptRequest = z.infer<typeof suggestionAcceptSchema>;\n\n/** `reject` with no ids rejects every pending suggestion in the set. */\nexport const suggestionRejectSchema = z.object({\n suggestionIds: z.array(z.string().min(1)).min(1).max(200).optional(),\n});\nexport type SuggestionRejectRequest = z.infer<typeof suggestionRejectSchema>;\n\nexport interface SuggestionAcceptResponse {\n applied: string[];\n set: SuggestionSet;\n}\n\n// ---- Availability ----\n\n/** `fixture` = canned test-mode answers (AI_TEST_MODE=1); `live` = ShapeShyft configured; `unavailable` = neither. */\nexport type AiStatusMode = 'live' | 'fixture' | 'unavailable';\n\n/** `GET /ai/status`. */\nexport interface AiStatus {\n available: boolean;\n mode: AiStatusMode;\n}\n\n// ---- Consent (spec 06 §9.3: gate 3) ----\n\n/** Bumping this requires every user to re-accept before their next AI job. */\nexport const AI_CONSENT_VERSION = 1;\n\n/** `GET /me/ai-consents`. */\nexport interface AiConsentStatus {\n currentVersion: number;\n acceptedVersion: number | null;\n acceptedAt: string | null;\n}\n\n/** `POST /me/ai-consents`: `version` must equal `AI_CONSENT_VERSION`, else `VALIDATION`. */\nexport const aiConsentAcceptSchema = z.object({ version: z.number().int() });\nexport type AiConsentAcceptRequest = z.infer<typeof aiConsentAcceptSchema>;\n\nexport interface AiConsentAcceptResponse {\n acceptedVersion: number;\n acceptedAt: string;\n}\n\n// ---- Estimate and pricing (spec 06 §10.1, §10.3) ----\n\n/** What a quote was computed from. Pages are approximated from word count until the paginator runs server-side (M2). */\nexport interface AiPriceBasis {\n pages: number;\n scopePages?: number;\n}\n\nexport const aiEstimateRequestSchema = z.object({\n task: aiTaskSchema,\n scope: z\n .object({\n sceneIds: z.array(z.string()).optional(),\n elementIds: z.array(z.string()).optional(),\n })\n .optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AiEstimateRequest = z.infer<typeof aiEstimateRequestSchema>;\n\n/** `POST /documents/:did/ai/estimate`: the same pricing function `startJob` charges at, run without creating a job. */\nexport interface AiEstimateResponse {\n credits: number;\n basis: AiPriceBasis;\n withinLimit: boolean;\n balance: number;\n}\n\n// ---- Activity (spec 05 §6.3) ----\n\n/** `GET /me/ai-activity`, `GET /workspaces/:wid/ai-activity` (the latter adds `userId`). */\nexport interface AiActivityItem {\n jobId: string;\n task: AiTask;\n documentId: string;\n documentTitle: string;\n status: AiJobStatus;\n quotedCredits: number | null;\n chargedCredits: number | null;\n refundedCredits: number | null;\n createdAt: string;\n}\n\n// ---- Reports (spec 06 §11) ----\n\n/** `GET /documents/:did/ai/reports`: a saved coverage/review job, summarised. */\nexport interface AiReportSummary {\n jobId: string;\n task: AiTask;\n status: AiJobStatus;\n createdAt: string;\n finishedAt: string | null;\n}\n\n/** `POST .../reports/:jobId/notes/:noteId/convert`: `noteId` is `\"strengths:<i>\" | \"weaknesses:<i>\" | \"sceneNotes:<i>\"`,\n * the note's position in the immutable stored report (reports have no independently stable note ids). */\nexport interface AiNoteConvertResponse {\n scriptNoteId: string;\n}\n\n// ---- Suggestion decide (spec 06 §7.4): a combined, server-side accept/reject for API/MCP callers ----\n\nexport const suggestionDecideSchema = z.object({\n accept: z.union([z.array(z.string().min(1)), z.literal('allPending')]),\n reject: z.union([z.array(z.string().min(1)), z.literal('allPending')]),\n expectedHashes: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type SuggestionDecideRequest = z.infer<typeof suggestionDecideSchema>;\n\nexport interface SuggestionDecideResponse {\n accepted: string[];\n rejected: string[];\n skippedStale: string[];\n skippedConflicted: string[];\n autoSnapshotId: string | null;\n epoch: number;\n}\n","import { z } from 'zod';\n\n/**\n * Synchronous AI actions: `POST /ai/{action}` in screenwriter_api, which authenticates the caller and turns around\n * to one ShapeShyft endpoint of the same name. Unlike the document jobs in `./index.ts` (coverage, polish) these take\n * their whole input in the request body, read no document, and answer in the same HTTP response.\n *\n * The output schemas follow the same convention as `AI_ENDPOINT_OUTPUT_SCHEMAS`: written for structured output, so\n * every field is required (nullable, never optional) and objects are closed — `z.toJSONSchema` gives the exact schema\n * to store on the ShapeShyft endpoint (`bun run ai:schemas` in screenwriter_api prints them). What the API returns to\n * the client is the normalised `*Result` shape (nulls dropped), not the raw model shape.\n */\n\nexport const AI_ACTIONS = [\n 'generate-character-skeleton',\n 'generate-script',\n 'polish-character-dialogue',\n 'polish-scene',\n] as const;\nexport type AiAction = (typeof AI_ACTIONS)[number];\nexport const aiActionSchema = z.enum(AI_ACTIONS);\n\n/** Counted limits for the action requests, declared once: request schemas, output schemas and prompts read these. */\nexport const AI_ACTION_LIMITS = {\n /** Free-form text a writer pastes in: a character description, or the story to turn into a script. */\n descriptionMax: 8_000,\n storyMax: 30_000,\n skeletonFieldMax: 1_000,\n characterNameMax: 80,\n languageMax: 35,\n /** Dialogue polish: one character's lines. */\n dialoguesMax: 100,\n dialogueTextMax: 2_000,\n /** Scene polish. */\n sceneElementsMax: 300,\n sceneElementTextMax: 2_000,\n sceneCharactersMax: 20,\n /** Script generation output. */\n scenesMax: 40,\n elementsPerSceneMax: 200,\n elementTextMax: 2_000,\n titleMax: 120,\n locationMax: 120,\n timeMax: 40,\n idMax: 64,\n} as const;\n\n// ---- Character skeleton (the shape `screenwriter_app`'s CharacterSkeletonEditor edits) ----\n\n/** Physical, Social, Psychological — the bone structure. Only `age` is required; every other field is optional. */\nexport const CHARACTER_SKELETON_FIELDS = {\n physical: [\n 'age',\n 'race',\n 'height',\n 'weight',\n 'appearance',\n 'sexOrientationExperience',\n 'posture',\n 'unusualCharacteristics',\n 'health',\n ],\n social: [\n 'occupationAndAttitude',\n 'education',\n 'money',\n 'class',\n 'relationships',\n 'homeLife',\n 'religion',\n 'placeInCommunity',\n 'politics',\n 'interests',\n ],\n psychological: [\n 'attitudeTowardLife',\n 'moralStandard',\n 'intelligence',\n 'ambitions',\n 'frustrations',\n 'fearsAndObsessions',\n 'extrovertOrIntrovert',\n 'specialQualities',\n 'proudestAchievement',\n 'greatestSorrow',\n 'greatestShame',\n 'noticedFirst',\n 'secret',\n 'noticedLast',\n 'coreContradictions',\n 'deepestDesire',\n ],\n} as const;\n\nexport const CHARACTER_SKELETON_KEYS = [\n ...CHARACTER_SKELETON_FIELDS.physical,\n ...CHARACTER_SKELETON_FIELDS.social,\n ...CHARACTER_SKELETON_FIELDS.psychological,\n] as const;\nexport type CharacterSkeletonKey = (typeof CHARACTER_SKELETON_KEYS)[number];\n\nconst skeletonText = z.string().max(AI_ACTION_LIMITS.skeletonFieldMax);\n\n/** A skeleton as it is stored and sent between client and API: `age` plus whichever other fields have a value. */\nexport const characterSkeletonSchema = z.object({\n age: skeletonText.min(1),\n ...Object.fromEntries(\n CHARACTER_SKELETON_KEYS.filter((k) => k !== 'age').map((k) => [\n k,\n skeletonText.optional(),\n ])\n ),\n} as { age: z.ZodString } & Record<\n Exclude<CharacterSkeletonKey, 'age'>,\n z.ZodOptional<z.ZodString>\n>);\nexport type CharacterSkeleton = z.infer<typeof characterSkeletonSchema>;\n\n/** The model-facing shape: every field required, `null` = the text does not say. */\nconst characterSkeletonModelSchema = z.strictObject({\n age: skeletonText.min(1),\n ...Object.fromEntries(\n CHARACTER_SKELETON_KEYS.filter((k) => k !== 'age').map((k) => [\n k,\n skeletonText.nullable(),\n ])\n ),\n} as { age: z.ZodString } & Record<\n Exclude<CharacterSkeletonKey, 'age'>,\n z.ZodNullable<z.ZodString>\n>);\n\n// ---- Script elements (the editor's element styles, minus the scene heading which is structured) ----\n\nexport const SCRIPT_ELEMENT_TYPES = [\n 'action',\n 'character',\n 'parenthetical',\n 'dialogue',\n 'transition',\n] as const;\nexport type ScriptElementType = (typeof SCRIPT_ELEMENT_TYPES)[number];\n\nexport const scriptElementSchema = z.strictObject({\n type: z.enum(SCRIPT_ELEMENT_TYPES),\n text: z.string().min(1).max(AI_ACTION_LIMITS.elementTextMax),\n});\nexport type ScriptElement = z.infer<typeof scriptElementSchema>;\n\nexport const SCENE_SETTINGS = ['int', 'ext', 'intExt'] as const;\nexport const sceneHeadingSchema = z.strictObject({\n setting: z.enum(SCENE_SETTINGS),\n location: z.string().min(1).max(AI_ACTION_LIMITS.locationMax),\n /** \"DAY\", \"NIGHT\", \"LATER\" … as it would follow the dash in a heading. */\n time: z.string().min(1).max(AI_ACTION_LIMITS.timeMax),\n});\nexport type SceneHeading = z.infer<typeof sceneHeadingSchema>;\n\nexport const generatedSceneSchema = z.strictObject({\n heading: sceneHeadingSchema,\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.elementsPerSceneMax),\n});\nexport type GeneratedScene = z.infer<typeof generatedSceneSchema>;\n\n// ---- 1. generate-character-skeleton ----\n\nexport const generateCharacterSkeletonRequestSchema = z.strictObject({\n /** A free-form paragraph describing the character. */\n text: z.string().trim().min(1).max(AI_ACTION_LIMITS.descriptionMax),\n /** BCP 47 tag the skeleton values are written in. Default: the language of `text`. */\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type GenerateCharacterSkeletonRequest = z.infer<\n typeof generateCharacterSkeletonRequestSchema\n>;\n\nexport const generateCharacterSkeletonModelSchema = z.strictObject({\n skeleton: characterSkeletonModelSchema,\n});\nexport const generateCharacterSkeletonResultSchema = z.strictObject({\n skeleton: characterSkeletonSchema,\n});\nexport type GenerateCharacterSkeletonResult = z.infer<\n typeof generateCharacterSkeletonResultSchema\n>;\n\n// ---- 2. generate-script ----\n\nexport const generateScriptRequestSchema = z.strictObject({\n /** The story in common language: a premise, a synopsis or a full retelling. */\n story: z.string().trim().min(1).max(AI_ACTION_LIMITS.storyMax),\n title: z.string().trim().max(AI_ACTION_LIMITS.titleMax).optional(),\n /** BCP 47 tag the script is written in. Default: the language of `story`. */\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type GenerateScriptRequest = z.infer<typeof generateScriptRequestSchema>;\n\nexport const generateScriptModelSchema = z.strictObject({\n title: z.string().max(AI_ACTION_LIMITS.titleMax).nullable(),\n scenes: z.array(generatedSceneSchema).min(1).max(AI_ACTION_LIMITS.scenesMax),\n});\nexport const generateScriptResultSchema = generateScriptModelSchema;\nexport type GenerateScriptResult = z.infer<typeof generateScriptResultSchema>;\n\n// ---- 3. polish-character-dialogue ----\n\nexport const dialogueLineSchema = z.strictObject({\n /** The caller's own id for the line, echoed back so the result maps onto it. */\n id: z.string().min(1).max(AI_ACTION_LIMITS.idMax),\n text: z.string().min(1).max(AI_ACTION_LIMITS.dialogueTextMax),\n});\nexport type DialogueLine = z.infer<typeof dialogueLineSchema>;\n\nexport const polishCharacterDialogueRequestSchema = z.strictObject({\n character: z.string().trim().min(1).max(AI_ACTION_LIMITS.characterNameMax),\n skeleton: characterSkeletonSchema,\n /** One character's lines, in script order. */\n dialogues: z\n .array(dialogueLineSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.dialoguesMax),\n /** How much to change; default `medium`. */\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type PolishCharacterDialogueRequest = z.infer<\n typeof polishCharacterDialogueRequestSchema\n>;\n\nexport const polishCharacterDialogueModelSchema = z.strictObject({\n /** The same ids in the same order, each with the polished line. */\n dialogues: z\n .array(dialogueLineSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.dialoguesMax),\n});\nexport const polishCharacterDialogueResultSchema =\n polishCharacterDialogueModelSchema;\nexport type PolishCharacterDialogueResult = z.infer<\n typeof polishCharacterDialogueResultSchema\n>;\n\n// ---- 4. polish-scene ----\n\nexport const sceneCharacterSchema = z.strictObject({\n /** The name as it appears in the script's character cues. */\n name: z.string().trim().min(1).max(AI_ACTION_LIMITS.characterNameMax),\n skeleton: characterSkeletonSchema,\n});\nexport type SceneCharacter = z.infer<typeof sceneCharacterSchema>;\n\nexport const polishSceneRequestSchema = z.strictObject({\n scene: z.strictObject({\n /** The scene heading as text, e.g. \"INT. LAB - DAY\". Context only: it is not rewritten. */\n heading: z\n .string()\n .max(AI_ACTION_LIMITS.locationMax + AI_ACTION_LIMITS.timeMax + 16)\n .optional(),\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneElementsMax),\n }),\n /** A skeleton for every character involved in the scene. */\n characters: z\n .array(sceneCharacterSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneCharactersMax),\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type PolishSceneRequest = z.infer<typeof polishSceneRequestSchema>;\n\n/** The scene may be freely rewritten, so the result is a fresh element list rather than a per-id mapping. */\nexport const polishSceneModelSchema = z.strictObject({\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneElementsMax),\n});\nexport const polishSceneResultSchema = polishSceneModelSchema;\nexport type PolishSceneResult = z.infer<typeof polishSceneResultSchema>;\n\n// ---- Registry ----\n\n/** Action -> schema of what the model returns (stored on the ShapeShyft endpoint). */\nexport const AI_ACTION_MODEL_SCHEMAS = {\n 'generate-character-skeleton': generateCharacterSkeletonModelSchema,\n 'generate-script': generateScriptModelSchema,\n 'polish-character-dialogue': polishCharacterDialogueModelSchema,\n 'polish-scene': polishSceneModelSchema,\n} as const satisfies Record<AiAction, z.ZodType>;\n\n/** Action -> schema of the request body the client sends. */\nexport const AI_ACTION_REQUEST_SCHEMAS = {\n 'generate-character-skeleton': generateCharacterSkeletonRequestSchema,\n 'generate-script': generateScriptRequestSchema,\n 'polish-character-dialogue': polishCharacterDialogueRequestSchema,\n 'polish-scene': polishSceneRequestSchema,\n} as const satisfies Record<AiAction, z.ZodType>;\n\n/** What `POST /ai/{action}` returns in `data`: the normalised result plus what the call cost. */\nexport interface AiActionUsage {\n /** Credits charged (0 for a site admin). */\n credits: number;\n promptTokens: number;\n completionTokens: number;\n}\nexport interface AiActionResponse<R> {\n result: R;\n usage: AiActionUsage;\n}\n","import { z } from 'zod';\nimport type { AiTask } from '../ai/index.js';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/**\n * Generic jobs (spec 05 §6.19, §13; slice B9). A job is one row of `jobs`; `ai_jobs` rows are mirrored as `ai.*`\n * jobs (decision D21a) so `/ai/jobs/:id` and `/jobs/:id` read the same job.\n */\n\nexport const JOB_STATUSES = [\n 'queued',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport type JobStatus = (typeof JOB_STATUSES)[number];\nexport const TERMINAL_JOB_STATUSES = [\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport const isTerminalJobStatus = (s: JobStatus): boolean =>\n (TERMINAL_JOB_STATUSES as readonly string[]).includes(s);\n\nexport const JOB_LANES = [\n 'ai',\n 'interactive',\n 'bulk',\n 'system',\n 'provider',\n] as const;\nexport type JobLane = (typeof JOB_LANES)[number];\n\n/**\n * Closed vocabulary of job kinds, `<family>.<variant>` (R10). Every kind has a `job_kind_config` row; a kind\n * without a registered runner is seeded disabled and `POST /jobs` answers `JOB_KIND_DISABLED`. Extend by adding a\n * member here and a row in `screenwriter_api/src/services/jobs/kinds.ts`. `test.*` kinds exist only to prove the\n * framework and are enabled only under `AI_TEST_MODE=1`.\n */\nexport const JOB_KINDS = [\n 'ai.review',\n 'ai.polish',\n 'ai.describe',\n 'export.pdf',\n 'export.fdx',\n 'export.fountain',\n 'export.fadein',\n 'export.fadewright',\n 'export.json',\n 'export.docx',\n 'watermark.batch',\n 'import.fdx',\n 'import.fountain',\n 'import.fadein',\n 'import.pdf',\n 'import.ocr',\n 'import.celtx',\n 'import.scrivener',\n 'import.fdxt',\n 'report.render',\n 'doc.applyTemplate',\n 'doc.importOver',\n 'doc.snapshotOpen',\n 'doc.versionRestore',\n 'doc.compare',\n 'doc.normalize',\n 'doc.renormalize',\n 'doc.compact',\n 'snapshot.project',\n 'project.duplicate',\n 'asset.derive',\n 'account.export',\n 'system.emailSend',\n 'system.emailDigest',\n 'system.writingReminder',\n 'system.pushSend',\n 'system.purge',\n 'system.retentionSweep',\n 'template.thumbnail',\n // reserved for media adapters (spec 11 §6.2): registered, seeded disabled\n 'image.generate',\n 'image.edit',\n 'image.upscale',\n 'image.turnaround',\n 'video.generate',\n 'video.extend',\n 'video.upscale',\n 'video.lipSync',\n 'voice.tts',\n 'voice.cloneProfile',\n 'voice.change',\n 'music.generate',\n 'sfx.generate',\n 'audio.isolate',\n 'model3d.generate',\n 'model3d.convert',\n 'model3d.rig',\n 'storyboard.generate',\n 'animatic.assemble',\n 'timeline.export',\n // framework tests\n 'test.echo',\n 'test.flaky',\n] as const;\nexport type JobKind = (typeof JOB_KINDS)[number];\nexport const jobKindSchema = z.enum(JOB_KINDS);\n\n/** The `ai.*` kind an `AiTask` mirrors as (its `subkind` is the task itself). */\nexport function aiKindForTask(task: AiTask): JobKind {\n return task.startsWith('polish') ? 'ai.polish' : 'ai.review';\n}\nexport const isAiKind = (kind: string): boolean => kind.startsWith('ai.');\n\nexport interface JobProgress {\n /** 0..1 */\n fraction: number;\n stage: string | null;\n /** An i18n key plus params, never prose (spec 05 §13.6). */\n message: string | null;\n}\n\nexport interface JobUsage {\n promptTokens?: number;\n completionTokens?: number;\n model?: string | null;\n pages?: number;\n}\n\n/** What `GET /jobs/:id` says about an output: no storage key, no URL (fetch those from `/jobs/:id/outputs`). */\nexport interface JobOutputSummary {\n name: string;\n mimeType: string;\n sizeBytes: number;\n recipientId?: string;\n assetId?: string;\n documentId?: string;\n}\n\n/** `GET /jobs/:jobId` never carries `request` or `result` bodies (spec 05 §10 rule 5), only summaries. */\nexport interface Job {\n id: string;\n kind: JobKind;\n subkind: string | null;\n status: JobStatus;\n progress: JobProgress;\n documentId: string | null;\n /** Small scalar digest of the request (long strings dropped, arrays counted). */\n requestSummary: Record<string, unknown>;\n sources: JobSource[];\n estimate?: JobEstimate;\n quotedCredits?: number | null;\n chargedCredits?: number | null;\n refundedCredits?: number | null;\n error?: string | null;\n errorCode?: string | null;\n usage?: JobUsage;\n outputs?: JobOutputSummary[];\n cancelRequested: boolean;\n sourcesChangedDuringRun?: boolean | null;\n attempt: number;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\nexport interface JobEstimate {\n credits: number;\n billable: boolean;\n}\n\nexport const jobSourceSchema = z.object({\n documentId: z.string().min(1),\n snapshotId: z.string().min(1).optional(),\n targetKind: z.string().min(1).max(40),\n targetId: z.string().min(1).max(100),\n});\nexport type JobSource = z.infer<typeof jobSourceSchema> & {\n sourceHash?: string;\n};\n\n/** `POST /jobs`. `idempotencyKey` (or the `Idempotency-Key` header) makes a retried create return the original job. */\nexport const jobCreateSchema = z.object({\n kind: jobKindSchema,\n input: z.record(z.string(), z.unknown()).default({}),\n sources: z.array(jobSourceSchema).max(20).default([]),\n idempotencyKey: z.string().min(1).max(128).optional(),\n maxCredits: z.number().int().min(0).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type JobCreateRequest = z.input<typeof jobCreateSchema>;\n\n/** `dryRun: true` answers this instead of a job. */\nexport interface JobDryRunResponse {\n estimate: JobEstimate;\n}\n\n/** `?kind=` is exact (`export.pdf`) or a family prefix ending in a dot (`ai.`). */\nexport const jobListQuerySchema = cursorQuerySchema.extend({\n documentId: z.string().min(1).optional(),\n kind: z\n .string()\n .regex(/^[A-Za-z0-9]+(\\.[A-Za-z0-9]*)?$/)\n .optional(),\n status: z.enum(JOB_STATUSES).optional(),\n});\nexport type JobListQuery = z.input<typeof jobListQuerySchema>;\n\n/** `GET /jobs/:jobId?wait=N` long-polls up to N seconds (max 120) until status or progress stage changes. */\nexport const JOB_WAIT_MAX_S = 120;\nexport const jobGetQuerySchema = z.object({\n wait: z.coerce.number().int().min(0).max(JOB_WAIT_MAX_S).optional(),\n});\nexport type JobGetQuery = z.input<typeof jobGetQuerySchema>;\n\nexport interface JobOutput extends JobOutputSummary {\n /** Signed download URL (or a `data:` URL for a small inline output). */\n url: string;\n expiresAt: string | null;\n}\nexport interface JobOutputsResponse {\n outputs: JobOutput[];\n}\n\n/** `GET /jobs/:jobId/recipients` item (batch watermark, B16). */\nexport interface JobRecipient {\n id: string;\n name: string;\n email: string | null;\n company: string | null;\n exportId: string;\n emailedAt: string | null;\n firstDownloadedAt: string | null;\n downloadCount: number;\n}\n\n/** `POST /webhooks/jobs/:adapterId`: every verified delivery answers this. */\nexport interface JobWebhookResponse {\n ok: true;\n}\n\n/** Header carrying `sha256=<hex HMAC-SHA256(secret, raw body)>` on a provider webhook. */\nexport const JOB_WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\n/** The generic `Idempotency-Key` header (spec 05 §6.25). Values are 1-128 characters. */\nexport const IDEMPOTENCY_HEADER = 'Idempotency-Key';\nexport const IDEMPOTENT_REPLAY_HEADER = 'Idempotent-Replayed';\nexport const idempotencyKeySchema = z.string().min(1).max(128);\n","/**\n * Reports (spec 09 §10 F-RPT-000..018, spec 05 §6.18), slice B10.\n *\n * `REPORT_KINDS` belongs in `writing_core` (spec 09 R25) but Tasks 29-35 have not landed there; until they do the\n * vocabulary, the options and the columns live here so the API, the client and MCP share one declaration.\n * A report is a list of tables; CSV, HTML and PDF are all rendered from those same tables, which is what\n * F-RPT-000's acceptance (\"CSV and PDF contain the same rows\") rests on.\n */\nimport { z } from 'zod';\nimport { sourceParamSchema, docSourceSchema } from '../reads/index.js';\n\nexport const REPORT_KINDS = [\n 'scene',\n 'location',\n 'character',\n 'cast',\n 'dialogue',\n 'script',\n 'text',\n 'notes',\n 'synopsis',\n 'revisions',\n 'tags',\n 'statistics',\n 'inclusivity',\n 'presentProgressive',\n 'dayOutOfDays',\n 'shotList',\n 'structure',\n 'characterArcs',\n] as const;\nexport type ReportKind = (typeof REPORT_KINDS)[number];\n\nexport const REPORT_FORMATS = ['json', 'csv', 'pdf', 'html'] as const;\nexport type ReportFormat = (typeof REPORT_FORMATS)[number];\n\n/** Documents up to this many pages run a report inline; larger ones answer with a `report.render` job (spec 05 §6.18). */\nexport const REPORT_SYNC_MAX_PAGES = 200;\n\nexport interface ReportOptionDef {\n name: string;\n type: 'boolean' | 'number' | 'string' | 'enum' | 'stringList';\n default?: boolean | number | string | string[];\n values?: readonly string[];\n min?: number;\n max?: number;\n required?: boolean;\n description?: string;\n}\n\nexport interface ReportColumn {\n id: string;\n label: string;\n align?: 'left' | 'right';\n}\n\nexport type ReportCell = string | number | null;\nexport type ReportRow = Record<string, ReportCell>;\n\nexport interface ReportTable {\n id: string;\n title?: string;\n columns: ReportColumn[];\n rows: ReportRow[];\n /** Optional totals row, rendered last (CSV, HTML and PDF all include it). */\n footer?: ReportRow;\n}\n\nexport interface ReportResult {\n kind: ReportKind;\n title: string;\n documentId: string;\n /** `live`, `snapshot:<id>` or `version:<id>`. */\n source: string;\n options: Record<string, unknown>;\n tables: ReportTable[];\n /** Set when the report does not apply (e.g. present-progressive in a language without the construction). */\n notice?: string;\n}\n\nexport interface ReportKindInfo {\n kind: ReportKind;\n featureId: string;\n title: string;\n /** False until the report is built; running it answers 501 `REPORT_KIND_UNAVAILABLE`. */\n available: boolean;\n unavailableReason?: string;\n options: ReportOptionDef[];\n /** Column ids of the main table(s), in order. */\n columns: ReportColumn[];\n formats: readonly ReportFormat[];\n}\n\nconst col = (id: string, label: string, align?: 'right'): ReportColumn => ({\n id,\n label,\n ...(align ? { align } : {}),\n});\nconst bool = (\n name: string,\n def: boolean,\n description?: string\n): ReportOptionDef => ({\n name,\n type: 'boolean',\n default: def,\n ...(description ? { description } : {}),\n});\nconst list = (name: string, description?: string): ReportOptionDef => ({\n name,\n type: 'stringList',\n default: [],\n ...(description ? { description } : {}),\n});\nconst en = (\n name: string,\n values: readonly string[],\n def: string\n): ReportOptionDef => ({ name, type: 'enum', values, default: def });\n\ninterface ReportDef {\n featureId: string;\n title: string;\n options: ReportOptionDef[];\n columns: ReportColumn[];\n unavailable?: string;\n}\n\n/** Column and option declarations. The tables a report returns use exactly these column ids. */\nexport const REPORT_DEFS: Record<ReportKind, ReportDef> = {\n scene: {\n featureId: 'F-RPT-001',\n title: 'Scene report',\n options: [\n en(\n 'sort',\n ['scriptOrder', 'sceneNumber', 'location', 'scriptDay'],\n 'scriptOrder'\n ),\n bool('includeOmitted', false),\n ],\n columns: [\n col('number', 'Scene'),\n col('intro', 'Intro'),\n col('location', 'Location'),\n col('time', 'Time'),\n col('heading', 'Heading'),\n col('page', 'Page'),\n col('length', 'Length'),\n col('estTime', 'Est. time', 'right'),\n col('synopsis', 'Synopsis'),\n col('colour', 'Colour'),\n col('speaking', 'Speaking'),\n col('nonSpeaking', 'Non-speaking'),\n col('scriptDay', 'Script day'),\n ],\n },\n location: {\n featureId: 'F-RPT-002',\n title: 'Location report',\n options: [en('sort', ['name', 'firstAppearance', 'length'], 'name')],\n columns: [\n col('location', 'Location'),\n col('intExt', 'INT/EXT'),\n col('times', 'Times of day'),\n col('scenes', 'Scenes'),\n col('pages', 'Pages'),\n col('eighths', 'Length'),\n col('sceneCount', 'Scene count', 'right'),\n ],\n },\n character: {\n featureId: 'F-RPT-003',\n title: 'Character report',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n bool('includeNonSpeaking', false),\n {\n name: 'monologueWords',\n type: 'number',\n default: 100,\n min: 1,\n max: 10000,\n },\n bool('includeDialogue', false),\n ],\n columns: [\n col('character', 'Character'),\n col('scenes', 'Speaking scenes'),\n col('nonSpeakingScenes', 'Non-speaking scenes'),\n col('extensions', 'Extensions'),\n col('parentheticals', 'Parentheticals', 'right'),\n col('monologues', 'Monologues', 'right'),\n col('dialogue', 'Dialogue'),\n ],\n },\n cast: {\n featureId: 'F-RPT-004',\n title: 'Cast report',\n options: [\n en(\n 'sort',\n ['alphabetical', 'scriptOrder', 'dialogueCount', 'words'],\n 'alphabetical'\n ),\n ],\n columns: [\n col('character', 'Character'),\n col('dialogues', 'Dialogues', 'right'),\n col('words', 'Words', 'right'),\n col('lines', 'Lines', 'right'),\n col('speakingScenes', 'Speaking scenes', 'right'),\n col('totalScenes', 'Total scenes', 'right'),\n col('pagesPresent', 'Pages present'),\n col('firstAppearance', 'First appearance'),\n col('gender', 'Gender'),\n col('role', 'Role'),\n col('age', 'Age'),\n ],\n },\n dialogue: {\n featureId: 'F-RPT-005',\n title: 'Dialogue report',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n bool('includeParentheticals', false),\n ],\n columns: [\n col('number', '#', 'right'),\n col('scene', 'Scene'),\n col('page', 'Page'),\n col('character', 'Character'),\n col('text', 'Dialogue'),\n ],\n },\n script: {\n featureId: 'F-RPT-006',\n title: 'Script report',\n options: [list('styles', 'Style ids or roles; empty means every element')],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('style', 'Style'),\n col('text', 'Text'),\n ],\n },\n text: {\n featureId: 'F-RPT-007',\n title: 'Text report',\n options: [\n {\n name: 'q',\n type: 'string',\n required: true,\n description: 'Text to find',\n },\n en('mode', ['text', 'regex'], 'text'),\n list('styles', 'Restrict to these style ids'),\n ],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('style', 'Style'),\n col('snippet', 'Context'),\n ],\n },\n notes: {\n featureId: 'F-RPT-008',\n title: 'Notes report',\n options: [\n list('types'),\n list('authors'),\n en('status', ['any', 'open', 'resolved'], 'any'),\n list('colours'),\n ],\n columns: [\n col('order', '#', 'right'),\n col('colour', 'Colour'),\n col('type', 'Type'),\n col('title', 'Title'),\n col('body', 'Note'),\n col('author', 'Author'),\n col('created', 'Created'),\n col('modified', 'Modified'),\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('status', 'Status'),\n col('replies', 'Replies', 'right'),\n ],\n },\n synopsis: {\n featureId: 'F-RPT-009',\n title: 'Synopsis report',\n options: [bool('includeEmpty', true)],\n columns: [\n col('number', 'Scene'),\n col('heading', 'Heading'),\n col('synopsis', 'Synopsis'),\n col('colour', 'Colour'),\n ],\n },\n revisions: {\n featureId: 'F-RPT-010',\n title: 'Revisions report',\n options: [list('sets', 'Revision set ids; empty means every set')],\n columns: [\n col('set', 'Revision'),\n col('colour', 'Colour'),\n col('mark', 'Mark'),\n col('date', 'Date'),\n col('pages', 'Pages'),\n col('scenes', 'Scenes'),\n col('revisedElements', 'Revised elements', 'right'),\n ],\n },\n tags: {\n featureId: 'F-RPT-011',\n title: 'Tags report',\n options: [\n en('mode', ['byScene', 'byCategory'], 'byScene'),\n list('categories', 'Tag category ids; empty means all'),\n ],\n columns: [\n col('scene', 'Scene'),\n col('heading', 'Heading'),\n col('page', 'Page'),\n col('length', 'Length'),\n col('scriptDay', 'Script day'),\n col('category', 'Category'),\n col('entities', 'Entities'),\n ],\n },\n statistics: {\n featureId: 'F-RPT-012',\n title: 'Statistics report',\n options: [\n { name: 'topWords', type: 'number', default: 20, min: 0, max: 200 },\n { name: 'longestScenes', type: 'number', default: 5, min: 0, max: 50 },\n ],\n columns: [col('metric', 'Metric'), col('value', 'Value', 'right')],\n },\n inclusivity: {\n featureId: 'F-RPT-013',\n title: 'Inclusivity and gender analysis',\n options: [en('by', ['gender', 'role'], 'gender')],\n columns: [\n col('group', 'Group'),\n col('characters', 'Characters', 'right'),\n col('dialogues', 'Dialogues', 'right'),\n col('words', 'Words', 'right'),\n col('scenesSpeaking', 'Scenes speaking', 'right'),\n col('wordsPct', 'Words %', 'right'),\n ],\n },\n presentProgressive: {\n featureId: 'F-RPT-014',\n title: 'Present progressive check',\n options: [],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('match', 'Match'),\n col('text', 'Action line'),\n ],\n },\n dayOutOfDays: {\n featureId: 'F-RPT-015',\n title: 'Day out of days',\n options: [],\n columns: [\n col('character', 'Character'),\n col('workDays', 'Work days', 'right'),\n col('holds', 'Holds', 'right'),\n ],\n },\n shotList: {\n featureId: 'F-RPT-016',\n title: 'Shot list',\n options: [],\n columns: [\n col('scene', 'Scene'),\n col('shot', 'Shot'),\n col('label', 'Label'),\n col('description', 'Description'),\n col('size', 'Size'),\n col('angle', 'Angle'),\n col('movement', 'Movement'),\n col('lens', 'Lens'),\n col('durationSec', 'Duration (s)', 'right'),\n ],\n },\n structure: {\n featureId: 'F-RPT-017',\n title: 'Structure report',\n options: [],\n columns: [\n col('node', 'Act / sequence / beat'),\n col('goal', 'Goal pages'),\n col('actual', 'Actual pages'),\n col('delta', 'Delta', 'right'),\n ],\n unavailable:\n 'Outline page goals are not modelled in writing_core yet (spec 01 §5.13 goals), so there is nothing to compare actual pages with',\n },\n characterArcs: {\n featureId: 'F-RPT-018',\n title: 'Character arcs',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n ],\n columns: [\n col('character', 'Character'),\n col('scene', 'Scene'),\n col('heading', 'Heading'),\n col('note', 'Arc note'),\n ],\n },\n};\n\nexport function reportKindInfos(): ReportKindInfo[] {\n return REPORT_KINDS.map((kind) => {\n const d = REPORT_DEFS[kind];\n return {\n kind,\n featureId: d.featureId,\n title: d.title,\n available: !d.unavailable,\n ...(d.unavailable ? { unavailableReason: d.unavailable } : {}),\n options: d.options,\n columns: d.columns,\n formats: REPORT_FORMATS,\n };\n });\n}\n\nexport const isReportKind = (v: unknown): v is ReportKind =>\n typeof v === 'string' && (REPORT_KINDS as readonly string[]).includes(v);\n\nexport type ParsedReportOptions =\n | { ok: true; options: Record<string, unknown> }\n | { ok: false; issues: { path: string; message: string }[] };\n\n/** Validates and defaults `raw` against the kind's option declarations (unknown keys are refused). */\nexport function parseReportOptions(\n kind: ReportKind,\n raw: unknown\n): ParsedReportOptions {\n const defs = REPORT_DEFS[kind].options;\n const issues: { path: string; message: string }[] = [];\n if (raw === undefined || raw === null) raw = {};\n if (typeof raw !== 'object' || Array.isArray(raw))\n return {\n ok: false,\n issues: [{ path: '', message: 'options must be an object' }],\n };\n const input = raw as Record<string, unknown>;\n const known = new Set(defs.map((d) => d.name));\n for (const k of Object.keys(input))\n if (!known.has(k)) issues.push({ path: k, message: 'unknown option' });\n const out: Record<string, unknown> = {};\n for (const d of defs) {\n const v = input[d.name];\n if (v === undefined) {\n if (d.required) issues.push({ path: d.name, message: 'required' });\n else if (d.default !== undefined)\n out[d.name] = Array.isArray(d.default) ? [...d.default] : d.default;\n continue;\n }\n switch (d.type) {\n case 'boolean':\n if (typeof v !== 'boolean')\n issues.push({ path: d.name, message: 'must be a boolean' });\n else out[d.name] = v;\n break;\n case 'number':\n if (\n typeof v !== 'number' ||\n !Number.isFinite(v) ||\n (d.min !== undefined && v < d.min) ||\n (d.max !== undefined && v > d.max)\n ) {\n issues.push({\n path: d.name,\n message: `must be a number${d.min !== undefined ? ` from ${d.min}` : ''}${d.max !== undefined ? ` to ${d.max}` : ''}`,\n });\n } else out[d.name] = v;\n break;\n case 'string':\n if (\n typeof v !== 'string' ||\n (d.required && v.length === 0) ||\n v.length > 500\n )\n issues.push({\n path: d.name,\n message: 'must be a non-empty string of at most 500 characters',\n });\n else out[d.name] = v;\n break;\n case 'enum':\n if (typeof v !== 'string' || !d.values!.includes(v))\n issues.push({\n path: d.name,\n message: `must be one of ${d.values!.join(', ')}`,\n });\n else out[d.name] = v;\n break;\n case 'stringList':\n if (\n !Array.isArray(v) ||\n v.length > 500 ||\n v.some((x) => typeof x !== 'string')\n )\n issues.push({ path: d.name, message: 'must be an array of strings' });\n else out[d.name] = v;\n break;\n }\n }\n return issues.length > 0 ? { ok: false, issues } : { ok: true, options: out };\n}\n\n// ─── Requests ───────────────────────────────────────────────────────────────\n\n/** `GET /documents/:did/reports/:kind?source=&options=<json>`. */\nexport const reportGetQuerySchema = z.object({\n source: sourceParamSchema.optional(),\n options: z.string().max(20_000).optional(),\n});\nexport type ReportGetQuery = z.infer<typeof reportGetQuerySchema>;\n\n/** `POST /documents/:did/reports`. `json` answers the result; the other formats a `report.render` job. */\nexport const reportCreateSchema = z.object({\n kind: z.enum(REPORT_KINDS),\n source: docSourceSchema.optional(),\n options: z.record(z.string(), z.unknown()).default({}),\n format: z.enum(REPORT_FORMATS).default('json'),\n});\nexport type ReportCreateRequest = z.infer<typeof reportCreateSchema>;\n\n/** The `input` of a `report.render` job (`sources[0]` is the document). */\nexport const reportRenderInputSchema = z.object({\n kind: z.enum(REPORT_KINDS),\n source: z.string().default('live'),\n options: z.record(z.string(), z.unknown()).default({}),\n format: z.enum(REPORT_FORMATS).default('csv'),\n});\nexport type ReportRenderInput = z.infer<typeof reportRenderInputSchema>;\n\n// ─── Rendering (shared by the API's CSV/HTML/PDF and by any client that wants the same text) ─────────────\n\nexport const cellText = (v: ReportCell): string =>\n v === null || v === undefined ? '' : String(v);\n\nconst csvField = (s: string) =>\n /[\",\\r\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n\n/** CSV of every table (a title line and a blank line between tables when there is more than one). RFC 4180 quoting, CRLF. */\nexport function reportToCsv(result: Pick<ReportResult, 'tables'>): string {\n const blocks = result.tables.map((t) => {\n const lines: string[] = [];\n if (result.tables.length > 1 && t.title) lines.push(csvField(t.title));\n lines.push(t.columns.map((c) => csvField(c.label)).join(','));\n for (const r of t.rows)\n lines.push(\n t.columns.map((c) => csvField(cellText(r[c.id] ?? null))).join(',')\n );\n if (t.footer)\n lines.push(\n t.columns\n .map((c) => csvField(cellText(t.footer![c.id] ?? null)))\n .join(',')\n );\n return lines.join('\\r\\n');\n });\n return blocks.join('\\r\\n\\r\\n') + '\\r\\n';\n}\n","/**\n * Production packets (spec 11 §7, spec 05 §6.22), slice B10. Schemas are the contract MCP and generators consume\n * (`scenePacketSchema` and friends); the API validates its own output against them in tests.\n * Asset lists are always empty until slice B11 (assets) lands.\n */\nimport { z } from 'zod';\n\nexport const PACKET_VERSION = 1;\n\n/**\n * `?snapshotId=&include=` shared by the four packet routes. `include` is a comma list added to the defaults (`assets` and\n * `script` are on by default; `neighbors` and `pages` are opt-in; `-script` and `-assets` switch a default off).\n */\nexport const PACKET_INCLUDE_FLAGS = [\n 'assets',\n 'assetUrls',\n 'script',\n 'neighbors',\n 'pages',\n] as const;\nexport const packetQuerySchema = z.object({\n snapshotId: z.string().min(1).optional(),\n include: z\n .preprocess(\n (v) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v,\n z.array(\n z.enum([\n 'assets',\n 'assetUrls=original',\n 'script',\n 'neighbors',\n 'pages',\n '-assets',\n '-script',\n ])\n )\n )\n .optional(),\n});\nexport type PacketQuery = z.infer<typeof packetQuerySchema>;\n\n/** 2 MB JSON cap (spec 11 §7.1): beyond it script text is truncated per element with `truncated: true`. */\nexport const PACKET_MAX_BYTES = 2 * 1024 * 1024;\n\nconst envelope = <K extends string, B extends z.ZodType>(kind: K, body: B) =>\n z.object({\n packetVersion: z.literal(PACKET_VERSION),\n kind: z.literal(kind),\n documentId: z.string(),\n documentTitle: z.string(),\n snapshotId: z.string().nullable(),\n templateId: z.string(),\n language: z.string(),\n generatedAt: z.string(),\n /** `packetHash` of the packet without `generatedAt`, `hash` and signed-URL fields (spec 11 §4.2). */\n hash: z.string(),\n truncated: z.boolean().optional(),\n body,\n });\n\nconst assetSummary = z\n .object({\n assetId: z.string(),\n role: z.string(),\n kind: z.string(),\n title: z.string(),\n })\n .passthrough();\n\nconst pages = z\n .object({ start: z.string(), end: z.string(), eighths: z.number().int() })\n .nullable();\n\nexport const packetElementSchema = z.union([\n z.object({\n id: z.string(),\n type: z.literal('character'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n extension: z.string().nullable(),\n }),\n z.object({\n id: z.string(),\n type: z.literal('parenthetical'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n }),\n z.object({\n id: z.string(),\n type: z.literal('dialogue'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n dual: z.boolean(),\n lineIndex: z.number().int(),\n }),\n // every other role: sceneHeading, action, transition, shot, normal, ...\n z.object({\n id: z.string(),\n type: z\n .string()\n .refine((t) => !['character', 'parenthetical', 'dialogue'].includes(t)),\n text: z.string(),\n }),\n]);\nexport type PacketElement = z.infer<typeof packetElementSchema>;\n\nconst shotSummary = z.object({\n id: z.string(),\n number: z.string().nullable(),\n label: z.string().nullable(),\n status: z.string(),\n camera: z.record(z.string(), z.unknown()),\n estimatedDurationMs: z.number().nullable(),\n description: z.string().nullable(),\n elementIds: z.array(z.string()),\n contentHash: z.string(),\n assets: z.array(assetSummary),\n});\nexport type ShotSummary = z.infer<typeof shotSummary>;\n\nconst sceneRef = z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n synopsis: z.string(),\n});\n\nconst sceneHeader = z.object({\n id: z.string(),\n number: z.string().nullable(),\n ordinal: z.number().int(),\n omitted: z.boolean(),\n heading: z.object({\n raw: z.string(),\n intro: z.string().nullable(),\n location: z.string().nullable(),\n time: z.string().nullable(),\n }),\n locationEntityId: z.string().nullable(),\n synopsis: z.string(),\n color: z.string().nullable(),\n pages,\n estimatedDurationMs: z.number(),\n folders: z.array(\n z.object({ id: z.string(), kind: z.string(), title: z.string() })\n ),\n contentHash: z.string(),\n scriptDay: z.string().nullable(),\n});\n\nconst locationBlock = z\n .object({\n entityId: z.string(),\n name: z.string(),\n fields: z.record(z.string(), z.unknown()),\n description: z.string(),\n assets: z.array(assetSummary),\n })\n .nullable();\n\nexport const scenePacketBodySchema = z.object({\n scene: sceneHeader,\n script: z.array(packetElementSchema),\n cast: z.array(\n z.object({\n entityId: z.string(),\n name: z.string(),\n speaking: z.boolean(),\n lineCount: z.number().int(),\n wordCount: z.number().int(),\n firstAppearance: z.boolean(),\n summary: z.string(),\n fields: z.record(z.string(), z.unknown()),\n traits: z.record(z.string(), z.union([z.string(), z.number()])),\n assets: z.array(assetSummary),\n })\n ),\n location: locationBlock,\n elements: z.array(\n z.object({\n entityId: z.string(),\n kind: z.string(),\n name: z.string(),\n description: z.string(),\n tagCount: z.number().int(),\n assets: z.array(assetSummary),\n })\n ),\n shots: z.array(shotSummary),\n notes: z.array(\n z.object({\n id: z.string(),\n type: z.string(),\n text: z.string(),\n anchorElementId: z.string().nullable(),\n })\n ),\n sceneAssets: z.array(assetSummary),\n neighbors: z\n .object({ previous: sceneRef.nullable(), next: sceneRef.nullable() })\n .optional(),\n});\nexport const scenePacketSchema = envelope('scene', scenePacketBodySchema);\nexport type ScenePacket = z.infer<typeof scenePacketSchema>;\n\nexport const characterPacketBodySchema = z.object({\n character: z.object({\n id: z.string(),\n name: z.string(),\n aliases: z.array(z.string()),\n description: z.string(),\n fields: z.record(z.string(), z.unknown()),\n traits: z.record(z.string(), z.union([z.string(), z.number()])),\n attributes: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n }),\n ages: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n ageValue: z.number().nullable(),\n description: z.string(),\n skeleton: z.array(\n z.object({\n section: z.string().nullable(),\n label: z.string(),\n answer: z.string(),\n })\n ),\n appearances: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n description: z.string(),\n assetIds: z.array(z.string()),\n })\n ),\n sceneCount: z.number().int(),\n })\n ),\n skeleton: z.array(\n z.object({\n section: z.string().nullable(),\n label: z.string(),\n answer: z.string(),\n })\n ),\n stats: z.object({\n sceneCount: z.number().int(),\n speakingSceneCount: z.number().int(),\n lineCount: z.number().int(),\n wordCount: z.number().int(),\n firstSceneId: z.string().nullable(),\n lastSceneId: z.string().nullable(),\n }),\n scenes: z.array(\n z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n speaking: z.boolean(),\n lineCount: z.number().int(),\n ageId: z.string().nullable(),\n appearanceId: z.string().nullable(),\n })\n ),\n sampleDialogue: z.array(\n z.object({ elementId: z.string(), sceneId: z.string(), text: z.string() })\n ),\n relationships: z.array(\n z.object({\n entityId: z.string(),\n name: z.string(),\n sharedSceneCount: z.number().int(),\n })\n ),\n props: z.array(z.object({ entityId: z.string(), name: z.string() })),\n assets: z.array(assetSummary),\n});\nexport const characterPacketSchema = envelope(\n 'character',\n characterPacketBodySchema\n);\nexport type CharacterPacket = z.infer<typeof characterPacketSchema>;\n\nexport const locationPacketBodySchema = z.object({\n location: z.object({\n id: z.string(),\n name: z.string(),\n aliases: z.array(z.string()),\n description: z.string(),\n fields: z.record(z.string(), z.unknown()),\n parent: z.object({ id: z.string(), name: z.string() }).nullable(),\n children: z.array(z.object({ id: z.string(), name: z.string() })),\n contentHash: z.string(),\n }),\n versions: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n description: z.string(),\n setting: z.string().nullable(),\n sceneCount: z.number().int(),\n })\n ),\n scenes: z.array(\n z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n time: z.string().nullable(),\n pages,\n cast: z.array(z.string()),\n versionId: z.string().nullable(),\n })\n ),\n totals: z.object({\n sceneCount: z.number().int(),\n eighths: z.number().int(),\n timesOfDay: z.record(z.string(), z.number().int()),\n }),\n setElements: z.array(\n z.object({ entityId: z.string(), kind: z.string(), name: z.string() })\n ),\n assets: z.array(assetSummary),\n});\nexport const locationPacketSchema = envelope(\n 'location',\n locationPacketBodySchema\n);\nexport type LocationPacket = z.infer<typeof locationPacketSchema>;\n\nexport const shotPacketBodySchema = z.object({\n shot: shotSummary.extend({\n sceneId: z.string(),\n range: z\n .object({\n startElementId: z.string(),\n endElementId: z.string(),\n text: z.string(),\n })\n .nullable(),\n }),\n scene: z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.object({\n raw: z.string(),\n intro: z.string().nullable(),\n location: z.string().nullable(),\n time: z.string().nullable(),\n }),\n locationEntityId: z.string().nullable(),\n contentHash: z.string(),\n }),\n script: z.array(packetElementSchema),\n subjects: z.array(\n z.object({\n entityId: z.string(),\n kind: z.string(),\n name: z.string(),\n fields: z.record(z.string(), z.unknown()),\n assets: z.array(assetSummary),\n })\n ),\n location: locationBlock,\n previousShot: shotSummary.nullable(),\n nextShot: shotSummary.nullable(),\n});\nexport const shotPacketSchema = envelope('shot', shotPacketBodySchema);\nexport type ShotPacket = z.infer<typeof shotPacketSchema>;\n\nexport type AnyPacket =\n ScenePacket | CharacterPacket | LocationPacket | ShotPacket;\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/**\n * The asset library (slice B11; spec 05 §6.13, §8.6, §14.1, spec 11 §3 and §4.5). Assets are workspace files with metadata;\n * bytes never pass through the API (presigned multipart PUT to R2). This file holds the vocabularies, the DTOs and the\n * role-to-target table the server enforces (`ROLE_NOT_ALLOWED_FOR_TARGET`).\n */\n\n// ─── vocabularies ────────────────────────────────────────────────────────────\n\nexport const ASSET_KINDS = [\n 'image',\n 'video',\n 'audio',\n 'model3d',\n 'document',\n 'archive',\n 'data',\n] as const;\nexport type AssetKind = (typeof ASSET_KINDS)[number];\nexport const assetKindSchema = z.enum(ASSET_KINDS);\n\nexport const ASSET_ROLES = [\n // launch\n 'reference',\n 'headshot',\n 'photo',\n 'logo',\n 'beat_image',\n 'inline_image',\n 'panel_reference',\n 'location_scout',\n 'mood_board',\n 'attachment',\n // future production (valid now, unused by launch UI)\n 'turnaround',\n 'expression_sheet',\n 'costume_design',\n 'set_concept',\n 'set_plan',\n 'storyboard_frame',\n 'animatic',\n 'previz',\n 'rendered_video',\n 'rendered_shot',\n 'dialogue_audio',\n 'voice_sample',\n 'voice_profile',\n 'music_cue',\n 'sound_effect',\n 'lip_sync',\n 'captions',\n 'model3d',\n 'model3d_rig',\n 'texture',\n 'lora',\n 'timeline',\n] as const;\nexport type AssetRole = (typeof ASSET_ROLES)[number];\nexport const assetRoleSchema = z.enum(ASSET_ROLES);\n\nexport const ASSET_ROLE_GROUPS: Record<\n AssetRole,\n 'reference' | 'design' | 'storyboard' | 'video' | 'audio' | '3d' | 'other'\n> = {\n reference: 'reference',\n headshot: 'reference',\n photo: 'reference',\n logo: 'other',\n beat_image: 'other',\n inline_image: 'other',\n panel_reference: 'storyboard',\n location_scout: 'reference',\n mood_board: 'reference',\n attachment: 'other',\n turnaround: 'design',\n expression_sheet: 'design',\n costume_design: 'design',\n set_concept: 'design',\n set_plan: 'design',\n storyboard_frame: 'storyboard',\n animatic: 'video',\n previz: 'video',\n rendered_video: 'video',\n rendered_shot: 'video',\n dialogue_audio: 'audio',\n voice_sample: 'audio',\n voice_profile: 'audio',\n music_cue: 'audio',\n sound_effect: 'audio',\n lip_sync: 'video',\n captions: 'other',\n model3d: '3d',\n model3d_rig: '3d',\n texture: '3d',\n lora: 'other',\n timeline: 'other',\n};\n\nexport const ASSET_TARGET_KINDS = [\n 'document',\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'beat',\n 'title_page',\n 'snapshot',\n] as const;\nexport type AssetTargetKind = (typeof ASSET_TARGET_KINDS)[number];\nexport const assetTargetKindSchema = z.enum(ASSET_TARGET_KINDS);\n\n/**\n * Which target kinds a role may sit on (spec 05 §6.13: \"enforces spec 11's role-to-target table\"; spec 11 §3.7 lists the\n * roles but not the table, so this is the decision made in B11). A role not listed here may go on any target.\n */\nexport const ASSET_ROLE_TARGETS: Partial<\n Record<AssetRole, readonly AssetTargetKind[]>\n> = {\n headshot: ['entity'],\n turnaround: ['entity'],\n expression_sheet: ['entity'],\n costume_design: ['entity'],\n voice_sample: ['entity'],\n voice_profile: ['entity'],\n set_concept: ['entity', 'scene'],\n set_plan: ['entity', 'scene'],\n location_scout: ['entity', 'scene'],\n beat_image: ['beat'],\n inline_image: ['element'],\n panel_reference: ['element', 'scene', 'shot'],\n logo: ['title_page', 'document'],\n storyboard_frame: ['shot', 'scene'],\n animatic: ['shot', 'scene', 'document'],\n previz: ['shot', 'scene', 'document'],\n rendered_video: ['shot', 'scene', 'document'],\n rendered_shot: ['shot'],\n dialogue_audio: ['element', 'shot', 'scene'],\n music_cue: ['scene', 'shot', 'document'],\n sound_effect: ['scene', 'shot', 'element'],\n lip_sync: ['shot', 'element'],\n captions: ['scene', 'shot', 'document'],\n timeline: ['document', 'scene'],\n};\n/** Roles that only fit an entity of one kind (checked against `proj_entities.kind`). */\nexport const ASSET_ROLE_ENTITY_KINDS: Partial<\n Record<AssetRole, readonly string[]>\n> = {\n headshot: ['character'],\n turnaround: ['character'],\n expression_sheet: ['character'],\n costume_design: ['character'],\n voice_sample: ['character'],\n voice_profile: ['character'],\n set_concept: ['location'],\n set_plan: ['location'],\n location_scout: ['location'],\n};\n\nexport const ASSET_ORIGINS = [\n 'upload',\n 'import',\n 'generated',\n 'external_tool',\n] as const;\nexport type AssetOrigin = (typeof ASSET_ORIGINS)[number];\n\nexport const ASSET_VERSION_STATUSES = [\n 'uploading',\n 'processing',\n 'ready',\n 'failed',\n] as const;\nexport type AssetVersionStatus = (typeof ASSET_VERSION_STATUSES)[number];\n\nexport const STALENESS_VALUES = [\n 'fresh',\n 'stale',\n 'target_deleted',\n 'unknown',\n] as const;\nexport type Staleness = (typeof STALENESS_VALUES)[number];\n\n/** Multipart parts are this big (the last one smaller); an upload of at most one part is a single presigned PUT. */\nexport const ASSET_PART_SIZE_BYTES = 8 * 1024 * 1024;\n/** How many part PUTs the client helper runs at once. */\nexport const ASSET_UPLOAD_CONCURRENCY = 3;\n/** Presigned part URLs and the upload itself live this long (seconds); a resume re-signs. */\nexport const ASSET_UPLOAD_TTL_S = 3600;\n/** Presigned GET lifetime for `GET /assets/:aid/versions/:vid/url` (seconds). */\nexport const ASSET_URL_TTL_S = 300;\n\n/** Largest original per kind (spec 11 §3.2). */\nexport const ASSET_MAX_BYTES: Record<AssetKind, number> = {\n image: 100 * 1024 ** 2,\n video: 10 * 1024 ** 3,\n audio: 2 * 1024 ** 3,\n model3d: 5 * 1024 ** 3,\n document: 200 * 1024 ** 2,\n archive: 10 * 1024 ** 3,\n data: 50 * 1024 ** 2,\n};\n\n/** Extension -> kind and the MIME types accepted for it (spec 11 §3.2). The extension must be listed and the magic bytes must agree. */\nexport const ASSET_EXTENSIONS: Record<\n string,\n { kind: AssetKind; mimes: readonly string[] }\n> = {\n '.png': { kind: 'image', mimes: ['image/png'] },\n '.jpg': { kind: 'image', mimes: ['image/jpeg'] },\n '.jpeg': { kind: 'image', mimes: ['image/jpeg'] },\n '.webp': { kind: 'image', mimes: ['image/webp'] },\n '.avif': { kind: 'image', mimes: ['image/avif'] },\n '.gif': { kind: 'image', mimes: ['image/gif'] },\n '.heic': { kind: 'image', mimes: ['image/heic'] },\n '.heif': { kind: 'image', mimes: ['image/heif'] },\n '.svg': { kind: 'image', mimes: ['image/svg+xml'] },\n '.tif': { kind: 'image', mimes: ['image/tiff'] },\n '.tiff': { kind: 'image', mimes: ['image/tiff'] },\n '.exr': { kind: 'image', mimes: ['image/x-exr'] },\n '.psd': { kind: 'image', mimes: ['image/vnd.adobe.photoshop'] },\n '.mp4': { kind: 'video', mimes: ['video/mp4'] },\n '.mov': { kind: 'video', mimes: ['video/quicktime'] },\n '.webm': { kind: 'video', mimes: ['video/webm'] },\n '.mkv': { kind: 'video', mimes: ['video/x-matroska'] },\n '.wav': { kind: 'audio', mimes: ['audio/wav', 'audio/x-wav', 'audio/wave'] },\n '.aif': { kind: 'audio', mimes: ['audio/x-aiff', 'audio/aiff'] },\n '.aiff': { kind: 'audio', mimes: ['audio/x-aiff', 'audio/aiff'] },\n '.flac': { kind: 'audio', mimes: ['audio/flac'] },\n '.mp3': { kind: 'audio', mimes: ['audio/mpeg'] },\n '.aac': { kind: 'audio', mimes: ['audio/aac'] },\n '.m4a': { kind: 'audio', mimes: ['audio/mp4', 'audio/x-m4a'] },\n '.ogg': { kind: 'audio', mimes: ['audio/ogg'] },\n '.opus': { kind: 'audio', mimes: ['audio/ogg', 'audio/opus'] },\n '.glb': { kind: 'model3d', mimes: ['model/gltf-binary'] },\n '.gltf': { kind: 'model3d', mimes: ['model/gltf+json'] },\n '.usdz': { kind: 'model3d', mimes: ['model/vnd.usdz+zip'] },\n '.blend': {\n kind: 'model3d',\n mimes: ['application/x-blender', 'application/octet-stream'],\n },\n '.fbx': {\n kind: 'model3d',\n mimes: ['model/vnd.fbx', 'application/octet-stream'],\n },\n '.obj': { kind: 'model3d', mimes: ['model/obj', 'text/plain'] },\n '.stl': {\n kind: 'model3d',\n mimes: ['model/stl', 'application/sla', 'application/octet-stream'],\n },\n '.usda': { kind: 'model3d', mimes: ['model/vnd.usda', 'text/plain'] },\n '.usdc': {\n kind: 'model3d',\n mimes: ['model/vnd.usda', 'application/octet-stream'],\n },\n '.pdf': { kind: 'document', mimes: ['application/pdf'] },\n '.txt': { kind: 'document', mimes: ['text/plain'] },\n '.md': { kind: 'document', mimes: ['text/markdown'] },\n '.docx': {\n kind: 'document',\n mimes: [\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n ],\n },\n '.zip': {\n kind: 'archive',\n mimes: ['application/zip', 'application/x-zip-compressed'],\n },\n '.json': { kind: 'data', mimes: ['application/json'] },\n '.csv': { kind: 'data', mimes: ['text/csv'] },\n '.srt': { kind: 'data', mimes: ['application/x-subrip', 'text/plain'] },\n '.vtt': { kind: 'data', mimes: ['text/vtt'] },\n '.otio': {\n kind: 'data',\n mimes: ['application/otio+json', 'application/json'],\n },\n '.fcpxml': {\n kind: 'data',\n mimes: ['application/x-fcpxml', 'application/xml', 'text/xml'],\n },\n '.edl': { kind: 'data', mimes: ['application/edl', 'text/plain'] },\n};\n\n/** `.ext` of a file name, lower-cased ('' when it has none). */\nexport const assetExtension = (filename: string): string => {\n const m = /(\\.[A-Za-z0-9]{1,10})$/.exec(filename);\n return m ? m[1]!.toLowerCase() : '';\n};\n\n/** Client-side pre-check that mirrors the server's: null when the file could be accepted, else why not. */\nexport function checkAssetFile(\n filename: string,\n mimeType: string,\n sizeBytes: number,\n kind: AssetKind\n): 'type' | 'mime' | 'kind' | 'size' | null {\n const spec = ASSET_EXTENSIONS[assetExtension(filename)];\n if (!spec) return 'type';\n if (spec.kind !== kind) return 'kind';\n if (!spec.mimes.includes(mimeType.toLowerCase().split(';')[0]!.trim()))\n return 'mime';\n if (sizeBytes > ASSET_MAX_BYTES[kind]) return 'size';\n return null;\n}\n\n// ─── rights and provenance (spec 11 §3.6, §3.8) ──────────────────────────────\n\nexport const assetRightsSchema = z.object({\n ownership: z\n .enum(['owned', 'licensed', 'public_domain', 'generated', 'unknown'])\n .default('unknown'),\n license: z.string().max(500).optional(),\n attribution: z.string().max(500).optional(),\n sourceUrl: z.string().max(2000).optional(),\n restrictions: z.string().max(1000).optional(),\n expiresAt: z.string().optional(),\n containsLikenessOf: z.array(z.string().max(200)).max(50).optional(),\n consentAssetId: z.string().optional(),\n aiTrainingAllowed: z.boolean().default(false),\n});\nexport type AssetRights = z.output<typeof assetRightsSchema>;\n\nexport const assetSourceRefSchema = z.object({\n documentId: z.string(),\n snapshotId: z.string().optional(),\n targetKind: z.enum([\n 'document',\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'beat',\n 'title_page',\n ]),\n targetId: z.string(),\n sourceHash: z.string(),\n});\nexport type AssetSourceRef = z.infer<typeof assetSourceRefSchema>;\n\n/** What a caller may send as `provenance` (the server fills `upload` and `import` itself). */\nexport const assetProvenanceInputSchema = z.discriminatedUnion('origin', [\n z.object({\n origin: z.literal('external_tool'),\n tool: z.string().min(1).max(100),\n toolVersion: z.string().max(100).optional(),\n description: z.string().max(2000).optional(),\n sourceRefs: z.array(assetSourceRefSchema).max(100).default([]),\n createdVia: z.enum(['mcp', 'api', 'app']).default('api'),\n }),\n z.object({\n origin: z.literal('generated'),\n jobId: z.string().optional(),\n adapter: z.string().min(1).max(100),\n provider: z.string().min(1).max(100),\n model: z.string().max(200).optional(),\n prompt: z.string().max(20000).optional(),\n negativePrompt: z.string().max(20000).optional(),\n parameters: z.record(z.string(), z.unknown()).default({}),\n inputs: z\n .array(\n z.object({\n assetVersionId: z.string().optional(),\n packetHash: z.string().optional(),\n role: z.string(),\n })\n )\n .max(100)\n .default([]),\n sourceRefs: z.array(assetSourceRefSchema).max(100).default([]),\n costCredits: z.number().optional(),\n providerJobId: z.string().optional(),\n createdVia: z.enum(['mcp', 'api', 'app']).default('api'),\n }),\n]);\nexport type AssetProvenanceInput = z.input<typeof assetProvenanceInputSchema>;\n\n/** The stored, immutable provenance of a version (spec 11 §3.6). */\nexport type AssetProvenance =\n | {\n origin: 'upload';\n uploadedBy: string;\n originalFilename: string;\n client?: Record<string, unknown>;\n }\n | {\n origin: 'import';\n importJobId: string;\n sourceFormat: string;\n originalPath?: string;\n }\n | ({\n origin: 'generated';\n agent?: { client: string; apiKeyId: string };\n } & Record<string, unknown>)\n | ({\n origin: 'external_tool';\n agent?: { client: string; apiKeyId: string };\n } & Record<string, unknown>);\n\n// ─── resources ───────────────────────────────────────────────────────────────\n\nexport interface AssetDerivative {\n mime: string;\n sizeBytes: number;\n}\n\nexport interface AssetVersion {\n id: string;\n assetId: string;\n parentVersionId: string | null;\n versionNumber: number;\n mime: string;\n ext: string;\n sizeBytes: number;\n sha256: string | null;\n status: AssetVersionStatus;\n errorCode: string | null;\n media: Record<string, unknown>;\n /** Derivative name (`thumb_256`, `preview_1600`, `poster`, `proxy_720p`, ...) -> its type and size. Empty until `asset.derive` has run. */\n derivatives: Record<string, AssetDerivative>;\n provenance: AssetProvenance;\n origin: AssetOrigin;\n rights: AssetRights;\n createdBy: string | null;\n createdAt: string;\n}\n\nexport interface AssetSummary {\n id: string;\n workspaceId: string;\n kind: AssetKind;\n title: string;\n description: string;\n /** Null until the first version is ready (or processing finished without a derive worker: see `status`). */\n currentVersionId: string | null;\n versionCount: number;\n /** Fields of the current version (the latest one when none is current yet). */\n mime: string | null;\n sizeBytes: number | null;\n status: AssetVersionStatus | null;\n origin: AssetOrigin | null;\n rights: AssetRights | null;\n hasThumbnail: boolean;\n createdBy: string | null;\n createdAt: string;\n updatedAt: string;\n deletedAt: string | null;\n}\n\nexport interface AssetLink {\n id: string;\n workspaceId: string;\n assetId: string;\n /** Null = follow the asset's current version. */\n pinnedVersionId: string | null;\n /** Null = a workspace-level link (its target is `{kind: 'document', id: <workspaceId>}`). */\n documentId: string | null;\n targetKind: AssetTargetKind;\n targetId: string;\n role: AssetRole;\n sortOrder: number;\n sourceHash: string | null;\n sourceSnapshotId: string | null;\n originalTargetId: string | null;\n note: string;\n createdBy: string | null;\n createdAt: string;\n deletedAt: string | null;\n}\n\nexport type AssetListItem = AssetSummary & {\n role?: AssetRole;\n sortOrder?: number;\n};\nexport type AssetDetail = AssetSummary & {\n versions: AssetVersion[];\n links: AssetLink[];\n};\n\n// ─── upload flow (spec 05 §6.13) ─────────────────────────────────────────────\n\nconst sha256HexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{64}$/, 'sha256Hex must be 64 hex characters');\n\nexport const assetUploadRequestSchema = z.object({\n /** Client-minted `asset_...` id for offline staging; accepted when unused (`ID_CONFLICT` otherwise). */\n assetId: z\n .string()\n .regex(/^asset_[0-9A-Za-z]{10,40}$/)\n .optional(),\n filename: z.string().min(1).max(500),\n mimeType: z.string().min(1).max(200),\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema.optional(),\n kind: assetKindSchema,\n title: z.string().trim().min(1).max(200).optional(),\n /** A new version of an existing asset: the version it derives from. */\n parentVersionId: z.string().min(1).optional(),\n provenance: assetProvenanceInputSchema.optional(),\n rights: assetRightsSchema.partial().optional(),\n});\nexport type AssetUploadRequest = z.input<typeof assetUploadRequestSchema>;\n\nexport interface AssetPartUrl {\n partNumber: number;\n url: string;\n expiresAt: string;\n}\n\nexport interface AssetUploadInit {\n uploadId: string;\n assetId: string;\n versionId: string;\n partSizeBytes: number;\n partCount: number;\n parts: AssetPartUrl[];\n expiresAt: string;\n /** The workspace already holds these exact bytes: nothing to PUT (`parts` is empty); call complete. */\n deduplicated: boolean;\n}\n\nexport interface AssetCompletedPart {\n partNumber: number;\n etag: string;\n sizeBytes?: number;\n}\n\nexport interface AssetUploadStatus {\n uploadId: string;\n assetId: string;\n versionId: string;\n partSizeBytes: number;\n partCount: number;\n completedParts: AssetCompletedPart[];\n expiresAt: string;\n completedAt: string | null;\n}\n\nexport const assetPartsRequestSchema = z.object({\n partNumbers: z.array(z.number().int().min(1).max(10000)).min(1).max(100),\n});\nexport type AssetPartsRequest = z.infer<typeof assetPartsRequestSchema>;\nexport interface AssetPartsResponse {\n parts: AssetPartUrl[];\n}\n\nexport const assetCompleteSchema = z.object({\n parts: z\n .array(\n z.object({\n partNumber: z.number().int().min(1),\n etag: z.string().min(1).max(200),\n })\n )\n .max(10000),\n sha256Hex: sha256HexSchema.optional(),\n});\nexport type AssetCompleteRequest = z.infer<typeof assetCompleteSchema>;\n\nexport interface AssetAbortResponse {\n aborted: true;\n}\n\n// ─── library routes ──────────────────────────────────────────────────────────\n\nconst linkedToSchema = z\n .string()\n .regex(\n /^(entity|scene|shot|element):[A-Za-z0-9_-]+$/,\n 'linkedTo is <entity|scene|shot|element>:<id>'\n );\n\nexport const assetListQuerySchema = cursorQuerySchema.extend({\n workspaceId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n linkedTo: linkedToSchema.optional(),\n role: assetRoleSchema.optional(),\n kind: assetKindSchema.optional(),\n q: z.string().trim().min(1).max(200).optional(),\n origin: z.enum(ASSET_ORIGINS).optional(),\n});\nexport type AssetListQuery = z.output<typeof assetListQuerySchema>;\n\nexport const assetUpdateSchema = z\n .object({\n title: z.string().trim().min(1).max(200).optional(),\n description: z.string().max(5000).optional(),\n rights: assetRightsSchema.partial().optional(),\n })\n .refine((v) => Object.keys(v).length > 0, 'Nothing to update');\nexport type AssetUpdateRequest = z.input<typeof assetUpdateSchema>;\n\nexport const ASSET_URL_VARIANTS = [\n 'original',\n 'thumb_256',\n 'thumb_512',\n 'preview_1600',\n 'poster',\n 'proxy_720p',\n 'proxy_1080p',\n 'preview',\n 'waveform',\n 'sprite',\n] as const;\nexport const assetUrlQuerySchema = z.object({\n variant: z\n .string()\n .regex(/^[a-z0-9_]{1,40}$/)\n .default('original'),\n});\nexport type AssetUrlQuery = z.output<typeof assetUrlQuerySchema>;\nexport interface AssetUrlResponse {\n url: string;\n expiresAt: string;\n}\n\nexport interface AssetDeleteResponse {\n deletedAt: string;\n}\n\n// ─── links ───────────────────────────────────────────────────────────────────\n\nexport const assetLinkCreateSchema = z.object({\n assetId: z.string().min(1),\n pinnedVersionId: z.string().min(1).optional(),\n /** Null/omitted = a workspace-level link: the target must then be `{kind: 'document', id: <the workspace id>}`. */\n documentId: z.string().min(1).nullable().optional(),\n target: z.object({\n kind: assetTargetKindSchema,\n id: z.string().min(1).max(200),\n }),\n role: assetRoleSchema,\n sortOrder: z.number().int().min(0).max(1_000_000).optional(),\n /** Version-prefixed content hash of the target when the asset was derived from it (spec 11 §4.2). */\n sourceHash: z.string().min(1).max(200).optional(),\n sourceSnapshotId: z.string().min(1).optional(),\n note: z.string().max(2000).optional(),\n});\nexport type AssetLinkCreateRequest = z.input<typeof assetLinkCreateSchema>;\n\nexport const assetLinkUpdateSchema = z\n .object({\n role: assetRoleSchema.optional(),\n sortOrder: z.number().int().min(0).max(1_000_000).optional(),\n /** `null` unpins (follow the current version). */\n pinnedVersionId: z.string().min(1).nullable().optional(),\n note: z.string().max(2000).optional(),\n })\n .refine((v) => Object.keys(v).length > 0, 'Nothing to update');\nexport type AssetLinkUpdateRequest = z.input<typeof assetLinkUpdateSchema>;\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\nexport const documentAssetLinksQuerySchema = z.object({\n targetKind: assetTargetKindSchema.optional(),\n targetId: z.string().min(1).optional(),\n role: assetRoleSchema.optional(),\n withStaleness: boolQuery.optional(),\n});\nexport type DocumentAssetLinksQuery = z.output<\n typeof documentAssetLinksQuerySchema\n>;\nexport type AssetLinkWithStaleness = AssetLink & { staleness?: Staleness };\n\nexport interface AssetLinkDeleteResponse {\n deletedAt: string;\n}\n\n// ─── staleness (spec 11 §4.5) ────────────────────────────────────────────────\n\nexport const STALENESS_TARGET_KINDS = [\n 'scene',\n 'element',\n 'shot',\n 'entity',\n] as const;\nexport const documentStalenessQuerySchema = z.object({\n targetKind: z.enum(STALENESS_TARGET_KINDS).optional(),\n});\nexport type DocumentStalenessQuery = z.output<\n typeof documentStalenessQuerySchema\n>;\n\n/** `GET /documents/:did/staleness`: per target with derived links, for badges. */\nexport interface TargetStaleness {\n targetKind: (typeof STALENESS_TARGET_KINDS)[number];\n targetId: string;\n fresh: number;\n stale: number;\n deleted: number;\n}\n\nexport interface LinkStaleness {\n staleness: Staleness;\n /** When the target's hash last changed (the normalizer's record); only for `stale`. */\n changedAt?: string;\n /** Snapshot-target links: how the live document compares (always `fresh` against the snapshot itself). */\n liveStaleness?: Staleness;\n /** Not built (needs the target's old element hashes, spec 11 §4.5's LCS diff); never sent. */\n diffSummary?: { added: number; removed: number; changed: number };\n}\n\n// ─── the `asset.derive` job (a documented stub: see the API's CLAUDE.md) ─────\n\nexport const assetDeriveInputSchema = z.object({\n assetVersionId: z.string().min(1),\n});\nexport type AssetDeriveInput = z.infer<typeof assetDeriveInputSchema>;\n","/**\n * Collaboration DTOs (spec 05 §6.15 notes/mentions/chat/activity, §6.16 notifications, §6.24 devices/push,\n * §6.26 `writingReminder` prefs; slice B12). Tables: `note_mentions`, `document_chat_messages`, `activity_events`,\n * `notifications`, `devices`.\n */\nimport { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n// ─── Notification kinds and prefs (§6.16, §6.26) ────────────────────────────\n\nexport const NOTIFICATION_KINDS = [\n 'mention',\n 'note_reply',\n 'note_on_my_document',\n 'snapshot_comment',\n 'chat_mention',\n 'invitation',\n 'share_granted',\n 'snapshot_opened_by_collaborator',\n 'job_finished',\n 'job_failed',\n 'ai_suggestions_ready',\n 'ai_refunded',\n 'export_ready',\n 'watermark_batch_sent',\n 'writing_reminder',\n 'credits_low',\n 'purchase_completed',\n 'account_deletion_scheduled',\n] as const;\nexport type NotificationKind = (typeof NOTIFICATION_KINDS)[number];\n\nexport const NOTIFICATION_EMAIL_MODES = ['immediate', 'digest', 'off'] as const;\nexport type NotificationEmailMode = (typeof NOTIFICATION_EMAIL_MODES)[number];\n\nexport interface NotificationKindPrefs {\n inApp: boolean;\n push: boolean;\n email: NotificationEmailMode;\n}\n\n/** Kinds that default to an immediate email (the rest default to `digest` or `off`; see `defaultNotificationKindPrefs`). */\nconst DEFAULT_IMMEDIATE_EMAIL: ReadonlySet<NotificationKind> = new Set([\n 'mention',\n 'note_reply',\n 'chat_mention',\n 'invitation',\n 'share_granted',\n 'job_failed',\n 'export_ready',\n 'watermark_batch_sent',\n 'credits_low',\n 'purchase_completed',\n 'account_deletion_scheduled',\n]);\nconst DEFAULT_DIGEST_EMAIL: ReadonlySet<NotificationKind> = new Set([\n 'snapshot_comment',\n 'note_on_my_document',\n 'ai_suggestions_ready',\n 'ai_refunded',\n 'snapshot_opened_by_collaborator',\n]);\n/** Kinds a person is not plausibly interrupted for, off by default: no email, no push. */\nconst DEFAULT_QUIET: ReadonlySet<NotificationKind> = new Set([\n 'job_finished',\n 'writing_reminder',\n]);\n\n/** Every kind gets a sane default; a person may override any of `inApp`/`push`/`email` per kind. */\nexport function defaultNotificationKindPrefs(\n kind: NotificationKind\n): NotificationKindPrefs {\n const email: NotificationEmailMode = DEFAULT_IMMEDIATE_EMAIL.has(kind)\n ? 'immediate'\n : DEFAULT_DIGEST_EMAIL.has(kind)\n ? 'digest'\n : 'off';\n return { inApp: true, push: !DEFAULT_QUIET.has(kind), email };\n}\n\nexport interface NotificationPrefs {\n kinds: Record<NotificationKind, NotificationKindPrefs>;\n /** `HH:MM` local time (§6.26 `system.writingReminder`); `null` = the reminder job never fires for this user. */\n writingReminderTime: string | null;\n}\n\nexport function defaultNotificationPrefs(): NotificationPrefs {\n return {\n kinds: Object.fromEntries(\n NOTIFICATION_KINDS.map((k) => [k, defaultNotificationKindPrefs(k)])\n ) as Record<NotificationKind, NotificationKindPrefs>,\n writingReminderTime: null,\n };\n}\n\nconst notificationKindPrefsPatchSchema = z.object({\n inApp: z.boolean().optional(),\n push: z.boolean().optional(),\n email: z.enum(NOTIFICATION_EMAIL_MODES).optional(),\n});\n\nconst HHMM_RE = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\n/** `PUT /me/notification-prefs`: a sparse per-kind patch (only the kinds/fields given change) plus the reminder time. */\nexport const notificationPrefsSchema = z.object({\n kinds: z\n .record(z.string(), notificationKindPrefsPatchSchema)\n .refine(\n (obj) =>\n Object.keys(obj).every((k) =>\n (NOTIFICATION_KINDS as readonly string[]).includes(k)\n ),\n {\n message: 'unknown notification kind',\n }\n )\n .optional(),\n writingReminderTime: z\n .string()\n .regex(HHMM_RE, 'writingReminderTime must be HH:MM (24h, local)')\n .nullable()\n .optional(),\n});\nexport type NotificationPrefsUpdate = z.infer<typeof notificationPrefsSchema>;\n\n/** `{...current, ...update}` per kind (a patch's fields win); `writingReminderTime` replaces whole. */\nexport function mergeNotificationPrefs(\n current: NotificationPrefs,\n update: NotificationPrefsUpdate\n): NotificationPrefs {\n const kinds = { ...current.kinds };\n for (const [k, patch] of Object.entries(update.kinds ?? {})) {\n const kind = k as NotificationKind;\n kinds[kind] = {\n ...(kinds[kind] ?? defaultNotificationKindPrefs(kind)),\n ...patch,\n };\n }\n return {\n kinds,\n writingReminderTime:\n update.writingReminderTime === undefined\n ? current.writingReminderTime\n : update.writingReminderTime,\n };\n}\n\n// ─── Notifications (§6.16) ───────────────────────────────────────────────────\n\nexport interface Notification {\n id: string;\n kind: NotificationKind;\n /** Ids and display strings only; never document/script content (spec 05 §8.7). */\n payload: Record<string, unknown>;\n workspaceId: string | null;\n documentId: string | null;\n readAt: string | null;\n createdAt: string;\n}\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\n\nexport const notificationsQuerySchema = cursorQuerySchema.extend({\n unread: boolQuery.optional(),\n});\nexport type NotificationsQuery = z.infer<typeof notificationsQuerySchema>;\n\nexport const notificationsReadSchema = z\n .object({\n ids: z.array(z.string().min(1)).max(200).optional(),\n all: z.literal(true).optional(),\n before: z.iso.datetime({ offset: true }).optional(),\n })\n .refine(\n (v) => v.ids !== undefined || v.all !== undefined || v.before !== undefined,\n {\n message: 'one of ids, all or before is required',\n }\n );\nexport type NotificationsReadRequest = z.infer<typeof notificationsReadSchema>;\nexport interface NotificationsReadResponse {\n updated: number;\n}\nexport interface NotificationDeleteResponse {\n deleted: true;\n}\n\n// ─── Notes mentions, mentions-without-access (§6.15) ────────────────────────\n\nexport interface MentionWithoutAccess {\n noteId: string;\n replyId?: string;\n userId: string;\n email: string | null;\n createdAt: string;\n}\n\n// ─── Chat (§6.15, §8.7 `document_chat_messages`) ────────────────────────────\n\nexport const CHAT_BODY_MAX = 4000;\nexport const CHAT_EDIT_WINDOW_MINUTES = 15;\n\n/** Y.Doc notes use plain `mentions: string[]` (user ids, no offset/length: writing_core's simplification); chat mirrors it in the DTO for consistency with the spec's shape, offset/length optional. */\nexport const mentionRefSchema = z.object({\n userId: z.string().min(1),\n offset: z.number().int().min(0).optional(),\n length: z.number().int().min(1).optional(),\n});\nexport type MentionRef = z.infer<typeof mentionRefSchema>;\n\nexport interface ChatMessage {\n id: string;\n documentId: string;\n authorId: string | null;\n body: string;\n mentions: MentionRef[];\n createdAt: string;\n editedAt: string | null;\n deletedAt: string | null;\n}\n\nexport const chatMessageCreateSchema = z.object({\n clientMessageId: z\n .string()\n .min(8)\n .max(64)\n .regex(/^msg_[0-9A-Za-z]+$/, 'clientMessageId must be a msg_ prefixed id'),\n body: z.string().trim().min(1).max(CHAT_BODY_MAX),\n mentions: z.array(mentionRefSchema).max(50).optional(),\n});\nexport type ChatMessageCreateRequest = z.infer<typeof chatMessageCreateSchema>;\n\nexport const chatMessageUpdateSchema = z.object({\n body: z.string().trim().min(1).max(CHAT_BODY_MAX),\n});\nexport type ChatMessageUpdateRequest = z.infer<typeof chatMessageUpdateSchema>;\n\nexport const chatQuerySchema = cursorQuerySchema.extend({\n before: z.iso.datetime({ offset: true }).optional(),\n});\nexport type ChatQuery = z.infer<typeof chatQuerySchema>;\n\nexport interface ChatMessageDeleteResponse {\n deletedAt: string;\n}\n\n// ─── Activity (§6.15, §8.7 `activity_events`) ───────────────────────────────\n\nexport const ACTIVITY_KINDS = [\n 'document.created',\n 'document.renamed',\n 'document.moved',\n 'document.trashed',\n 'document.restored',\n 'session.edited',\n 'snapshot.created',\n 'snapshot.opened',\n 'snapshot.forked',\n 'version.restored',\n 'template.applied',\n 'import.over',\n 'revision.setCreated',\n 'locks.changed',\n 'changes.decided',\n 'ai.jobCompleted',\n 'ai.suggestionsDecided',\n 'share.granted',\n 'share.linkCreated',\n 'member.joined',\n 'member.left',\n 'mcp.commandsApplied',\n] as const;\nexport type ActivityKind = (typeof ACTIVITY_KINDS)[number];\n\nexport const ACTOR_KINDS = ['user', 'mcp', 'api', 'ai', 'system'] as const;\nexport type ActorKind = (typeof ACTOR_KINDS)[number];\n\nexport interface ActivitySummary {\n i18nKey: string;\n params?: Record<string, unknown>;\n}\n\nexport interface ActivityEvent {\n id: string;\n kind: ActivityKind;\n actorId: string | null;\n actorKind: ActorKind;\n summary: ActivitySummary;\n targetIds: string[];\n createdAt: string;\n}\n/** `GET /workspaces/:wid/activity` items also carry the document they happened on. */\nexport interface WorkspaceActivityEvent extends ActivityEvent {\n documentId: string | null;\n}\n\nconst csvList = (v: unknown) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v;\n\nexport const activityQuerySchema = cursorQuerySchema.extend({\n kinds: z.preprocess(csvList, z.array(z.string())).optional(),\n});\nexport type ActivityQuery = z.infer<typeof activityQuerySchema>;\n\nexport const workspaceActivityQuerySchema = cursorQuerySchema.extend({\n projectId: z.string().min(1).optional(),\n});\nexport type WorkspaceActivityQuery = z.infer<\n typeof workspaceActivityQuerySchema\n>;\n\n// ─── Devices, push tokens (§6.24) ────────────────────────────────────────────\n\nexport const DEVICE_PLATFORMS = [\n 'web',\n 'ios',\n 'ipados',\n 'android',\n 'macos',\n 'windows',\n] as const;\nexport type DevicePlatform = (typeof DEVICE_PLATFORMS)[number];\n\nexport const PUSH_PLATFORMS = ['apns', 'fcm', 'wns', 'webpush'] as const;\nexport type PushPlatform = (typeof PUSH_PLATFORMS)[number];\n\nexport interface Device {\n id: string;\n displayName: string;\n platform: DevicePlatform;\n appVersion: string;\n lastSeenAt: string;\n revokedAt: string | null;\n /** True for the device making the current request (matched by id). */\n current: boolean;\n /** Per-device: offline availability (F-SAFE-004), local-backup status; never per-user data. */\n settings: Record<string, unknown>;\n}\n\nexport const deviceCreateSchema = z.object({\n id: z\n .string()\n .min(8)\n .max(64)\n .regex(/^dev_[0-9A-Za-z]+$/, 'id must be a dev_ prefixed id'),\n installId: z.string().min(1).max(128),\n displayName: z.string().trim().min(1).max(80),\n platform: z.enum(DEVICE_PLATFORMS),\n appVersion: z.string().min(1).max(40),\n});\nexport type DeviceCreateRequest = z.infer<typeof deviceCreateSchema>;\nexport interface DeviceCreateResponse extends Device {\n /** A second live install presenting the same `id` gets a fresh one (spec 03 §12.8); this is that fresh id. */\n reassignedId?: string;\n}\n\nexport const deviceUpdateSchema = z.object({\n displayName: z.string().trim().min(1).max(80),\n});\nexport type DeviceUpdateRequest = z.infer<typeof deviceUpdateSchema>;\n\nexport interface DeviceRevokeResponse {\n revokedAt: string;\n}\n\nexport const pushTokenSetSchema = z.object({\n platform: z.enum(PUSH_PLATFORMS),\n token: z.string().min(1).max(4096),\n environment: z.enum(['production', 'sandbox']).optional(),\n});\nexport type PushTokenSetRequest = z.infer<typeof pushTokenSetSchema>;\nexport interface PushTokenSetResponse {\n registeredAt: string;\n}\nexport interface PushTokenDeleteResponse {\n deleted: true;\n}\n","import { z } from 'zod';\n\n/**\n * Credits (spec 05 §6.20, spec 06 §10): a thin re-export of `@sudobility/types`' generic consumables\n * shapes, plus the two things specific to ViaInk — the priced product catalog and the purchase\n * handoff for platforms that cannot buy in-app (spec 05 §6.21).\n *\n * The ledger itself (`consumable_balances/_purchases/_usages`) is `@sudobility/consumables_service`'s,\n * called in-process from `screenwriter_api` exactly as `music_api` does; this module never redefines it.\n */\nexport type {\n ConsumableBalanceResponse,\n ConsumablePurchaseRecord,\n ConsumablePurchaseRequest,\n ConsumableSource,\n ConsumableUsageRecord,\n ConsumableUseRequest,\n ConsumableUseResponse,\n} from '@sudobility/types';\n\nexport const CONSUMABLE_SOURCES = ['web', 'apple', 'google', 'free'] as const;\n\n/** `GET /consumables/products`: the priced catalog (`CREDIT_PRODUCTS`, spec 06 §10.1). */\nexport interface CreditProduct {\n productId: string;\n credits: number;\n}\n\n/** `POST /purchases/handoff` (spec 05 §6.21): lets a platform with no in-app purchase (Windows) send the user to the web to buy. */\nexport const purchaseHandoffRequestSchema = z.object({\n productId: z.string().optional(),\n returnTo: z.string().min(1).max(2000),\n});\nexport type PurchaseHandoffRequest = z.infer<\n typeof purchaseHandoffRequestSchema\n>;\n\nexport interface PurchaseHandoffResponse {\n handoffUrl: string;\n expiresAt: string;\n}\n","import { z } from 'zod';\n\n/**\n * Public routes (spec 05 §6.21, B18): no session needed. `/public/templates[/:key]` reuse `TemplateSummary`\n * (templates/index.ts) and writing_core's `TemplateJSON` for the full body.\n */\n\n/** `GET /public/config` (R31): the single client-policy route. Clients below `minClientVersion` show the update\n * prompt; a call from one is answered `CLIENT_TOO_OLD` (426), read from the `X-Client-Version` request header. */\nexport interface PublicConfig {\n uiLanguages: string[];\n scriptLanguages: string[];\n assetLimits: Record<string, unknown>;\n maxImportBytes: number;\n importFormats: string[];\n exportFormats: string[];\n aiTasks: { task: string; pricingBasis: string }[];\n aiConsentVersion: number;\n syncProtocolVersion: number;\n docSchemaVersion: number;\n minClientVersion: {\n web: string;\n ios: string;\n android: string;\n macos: string;\n windows: string;\n };\n namesDbVersion: number;\n features: { ocr: boolean; grammar: boolean; push: boolean };\n}\n\n/** `GET /public/names-db/:version` (spec 09): served gzipped with a far-future immutable Cache-Control. */\nexport interface NamesDbEntry {\n name: string;\n gender?: 'f' | 'm' | 'u';\n origins: string[];\n}\nexport interface NamesDbResponse {\n version: number;\n names: NamesDbEntry[];\n}\n\n/** `GET /public/health/deep`: readiness, no secrets. */\nexport interface DeepHealthResponse {\n db: 'ok' | 'error';\n storage: 'ok' | 'unconfigured' | 'error';\n ai: 'ok' | 'unconfigured';\n email: 'ok' | 'unconfigured';\n}\n\n/** `GET /public/watermarked/:exportId/:token`: the recipient's download page payload (never the file itself). */\nexport interface WatermarkedDownloadInfo {\n documentTitle: string;\n senderName: string;\n url: string;\n expiresAt: string;\n}\n\n/** `POST /public/purchases/handoff/redeem`: exchanges a handoff token for a Firebase custom token (same uid), so the web page signs in without a password. */\nexport const purchaseHandoffRedeemSchema = z.object({\n token: z.string().min(1),\n});\nexport type PurchaseHandoffRedeemRequest = z.infer<\n typeof purchaseHandoffRedeemSchema\n>;\nexport interface PurchaseHandoffRedeemResponse {\n customToken: string;\n}\n\n// ---- Telemetry (spec 05 §6.24) ----\n\nexport const telemetryEventSchema = z.object({\n name: z.string().min(1).max(120),\n ts: z.string(),\n /** Allow-listed, flat properties only: no script text, no free-form nesting. */\n properties: z\n .record(\n z.string(),\n z.union([z.string().max(500), z.number(), z.boolean(), z.null()])\n )\n .optional(),\n});\nexport type TelemetryEvent = z.infer<typeof telemetryEventSchema>;\n\nexport const clientErrorReportSchema = z.object({\n message: z.string().min(1).max(2000),\n stack: z.string().max(8000).optional(),\n context: z\n .record(\n z.string(),\n z.union([z.string().max(500), z.number(), z.boolean(), z.null()])\n )\n .optional(),\n});\nexport type ClientErrorReport = z.infer<typeof clientErrorReportSchema>;\n\nexport const telemetryRequestSchema = z.object({\n events: z.array(telemetryEventSchema).max(100),\n errors: z.array(clientErrorReportSchema).max(20).optional(),\n});\nexport type TelemetryRequest = z.infer<typeof telemetryRequestSchema>;\nexport interface TelemetryResponse {\n accepted: boolean;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\nimport { JOB_STATUSES } from '../jobs/index.js';\n\n/**\n * Admin routes (spec 05 §6.23): `/api/v1/admin/*` requires `siteAdmin` on a user principal (never an API key).\n * Every call writes `audit_log`.\n */\n\nexport interface AdminUserLookup {\n id: string;\n email: string | null;\n emailVerified: boolean;\n displayName: string | null;\n siteAdmin: boolean;\n createdAt: string;\n lastSeenAt: string | null;\n deletionScheduledFor: string | null;\n deletedAt: string | null;\n}\n\nexport const adminJobListQuerySchema = cursorQuerySchema.extend({\n status: z.enum(JOB_STATUSES).optional(),\n kind: z.string().optional(),\n});\nexport interface AdminJobListQuery {\n limit?: number;\n cursor?: string;\n status?: (typeof JOB_STATUSES)[number];\n kind?: string;\n}\n\n/** `PATCH /admin/job-kinds/:kind`: a sparse patch onto `job_kind_config`. */\nexport const adminJobKindPatchSchema = z.object({\n enabled: z.boolean().optional(),\n maxAttempts: z.number().int().min(1).max(10).optional(),\n maxRetries: z.number().int().min(0).max(10).optional(),\n maxConcurrentPerUser: z.number().int().min(1).nullable().optional(),\n maxConcurrentGlobal: z.number().int().min(1).nullable().optional(),\n timeoutMs: z.number().int().min(1000).optional(),\n});\nexport type AdminJobKindPatchRequest = z.infer<typeof adminJobKindPatchSchema>;\n\nexport interface AdminJobKind {\n kind: string;\n enabled: boolean;\n adapter: string;\n lane: string;\n billable: boolean;\n maxAttempts: number;\n maxRetries: number;\n maxConcurrentPerUser: number | null;\n maxConcurrentGlobal: number | null;\n timeoutMs: number;\n updatedAt: string;\n}\n\n/** `POST /admin/jobs/:id/refund`: an optional partial amount; defaults to the job's full `chargedCredits`. */\nexport const adminJobRefundSchema = z.object({\n credits: z.number().int().positive().optional(),\n});\nexport type AdminJobRefundRequest = z.infer<typeof adminJobRefundSchema>;\nexport interface AdminJobRefundResponse {\n refundedCredits: number;\n balance: number;\n}\n\n/** `POST /admin/users/:uid/restore`. */\nexport interface AdminUserRestoreResponse {\n restored: true;\n}\n\n/**\n * `DELETE /admin/users/:uid`: schedules an IMMEDIATE deletion (no grace period) and revokes the user's API keys and\n * share links — the same bounded action `DELETE /me` takes, admin-triggered. **Not** a destructive data purge: no\n * `system.purge` job exists anywhere in this codebase yet to actually delete a user's workspaces/documents/content,\n * and `workspaces.created_by` is `ON DELETE RESTRICT`, so a raw row delete cannot work without first reassigning\n * or deleting every workspace the person created — real work for that job, not this route.\n */\nexport interface AdminUserPurgeResponse {\n deletionScheduledFor: string;\n}\n\n/** `GET /admin/documents/:did/meta`: metadata only, never content. */\nexport interface AdminDocumentMeta {\n id: string;\n title: string;\n kind: string;\n projectId: string;\n workspaceId: string;\n ownerEmail: string | null;\n epoch: number;\n schemaVersion: number;\n excludeFromAi: boolean;\n createdAt: string;\n trashedAt: string | null;\n}\n","/**\n * Spec 03 §3.2 write matrix as data, projected from spec 05's role matrix onto Y.Doc keys.\n * The server checks inbound updates against it; `markPermissionsFor` is what `subscribed` and\n * `roleChanged` send so a client can disable UI instead of being rejected.\n */\nimport type { Role } from '../tenancy/index.js';\n\n/** Top-level Y.Doc keys a commenter may change (notes and replies, R6). */\nexport const COMMENTER_WRITABLE_KEYS: readonly string[] = ['notes'];\n\n/** Inline marks a commenter may add or remove inside element text: note anchors `n:<NoteId>` and the highlighter. */\nexport const isCommenterMark = (name: string): boolean =>\n name === 'hl' || name.startsWith('n:');\n\n/** What a role may produce (courtesy for the UI; the server check is the authority). */\nexport interface MarkPermissions {\n /** Text, attributes, structure, tags, revisions, settings: everything an owner/admin/writer writes. */\n edit: boolean;\n /** Notes and replies (`notes` + `n:` marks). */\n comment: boolean;\n /** Highlighter (`hl` marks). */\n highlight: boolean;\n}\n\nexport function markPermissionsFor(role: Role | 'none'): MarkPermissions {\n const edit = role === 'owner' || role === 'admin' || role === 'writer';\n const comment = edit || role === 'commenter';\n return { edit, comment, highlight: comment };\n}\n\n/** Roles that may send `update` frames at all (a commenter's are filtered by the matrix). */\nexport const canSendUpdates = (role: Role): boolean => role !== 'viewer';\n","import { z } from 'zod';\n\n/** Spec 03 §2. Subprotocol string is `fadewright-sync.v1`. */\nexport const SYNC_PROTOCOL_VERSION = 1;\nexport const SYNC_SUBPROTOCOL = 'fadewright-sync.v1';\nexport const SYNC_PATH = '/api/v1/sync';\nexport const SYNC_HEARTBEAT_MS = 25_000;\nexport const SYNC_MAX_FRAME_BYTES = 1_048_576;\nexport const SYNC_AUTH_TIMEOUT_MS = 5_000;\n\n/** Numeric message-type codes (spec 03 §2.3). Frame = channelId, messageType, payload. */\nexport const SYNC_MESSAGE_TYPES = {\n auth: 0,\n authOk: 1,\n authError: 2,\n reauth: 3,\n ping: 4,\n pong: 4,\n subscribe: 10,\n subscribed: 11,\n subscribeError: 12,\n unsubscribe: 13,\n syncStep1: 20,\n syncStep2: 21,\n update: 22,\n ack: 23,\n reject: 24,\n awareness: 30,\n epochChanged: 40,\n roleChanged: 41,\n documentDeleted: 42,\n normalized: 43,\n serverShutdown: 50,\n} as const;\nexport type SyncMessageName = keyof typeof SYNC_MESSAGE_TYPES;\n\n/** Close codes (spec 03 §2.6). */\nexport const SYNC_CLOSE_CODES = {\n NORMAL: 1000,\n GOING_AWAY: 1001,\n MALFORMED_FRAME: 4400,\n AUTH_TIMEOUT_OR_INVALID: 4401,\n ACCOUNT_DISABLED_OR_DEVICE_REVOKED: 4403,\n PROTOCOL_UNSUPPORTED: 4406,\n HEARTBEAT_TIMEOUT: 4408,\n /** Document epoch changed (snapshot open / version restore): resubscribe at the new epoch. */\n EPOCH_CHANGED: 4409,\n FRAME_TOO_LARGE: 4413,\n RATE_LIMITED: 4429,\n} as const;\nexport type SyncCloseCode =\n (typeof SYNC_CLOSE_CODES)[keyof typeof SYNC_CLOSE_CODES];\n\n// ─── Vocabularies ───────────────────────────────────────────────────────────\n\nexport const SYNC_AUTH_SCHEMES = ['firebase', 'apikey', 'link'] as const;\nexport const SYNC_AUTH_ERROR_CODES = [\n 'UNAUTHENTICATED',\n 'ACCOUNT_DISABLED',\n 'DEVICE_REVOKED',\n 'LINK_EXPIRED',\n 'CLIENT_TOO_OLD',\n 'SERVER_TOO_OLD',\n] as const;\nexport const SYNC_SUBSCRIBE_ERROR_CODES = [\n 'NOT_FOUND',\n 'FORBIDDEN',\n 'DOCUMENT_DELETED',\n 'EPOCH_MISMATCH',\n 'DOCUMENT_LOCKED',\n 'CLIENT_TOO_OLD',\n] as const;\nexport const SYNC_REJECT_CODES = [\n 'FORBIDDEN',\n 'EPOCH_MISMATCH',\n 'UPDATE_INVALID',\n 'PAYLOAD_TOO_LARGE',\n 'SCHEMA_VIOLATION',\n] as const;\nexport const SYNC_SUBSCRIBE_MODES = ['edit', 'view'] as const;\nexport const SYNC_EPOCH_REASONS = [\n 'snapshot-open',\n 'import-over',\n 'version-restore',\n 'schema-migration',\n] as const;\n\nconst roleOrNone = z.enum([\n 'owner',\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n 'none',\n]);\nconst bytes = z.instanceof(Uint8Array);\nconst uint = z.number().int().min(0);\n\n// ─── Payload schemas (JSON UTF-8 payloads) ──────────────────────────────────\n\nexport const authPayloadSchema = z.object({\n scheme: z.enum(SYNC_AUTH_SCHEMES),\n token: z.string(),\n deviceId: z.string(),\n installId: z.string(),\n clientVersion: z.string(),\n schemaVersion: uint,\n /** Unlock-session token (`POST /documents/:did/unlock-session`) for opening locked documents. */\n unlockToken: z.string().optional(),\n});\nexport const authOkPayloadSchema = z.object({\n userId: z.string(),\n sessionId: z.string(),\n serverSchemaVersion: uint,\n heartbeatMs: uint,\n maxFrameBytes: uint,\n});\nexport const authErrorPayloadSchema = z.object({\n code: z.enum(SYNC_AUTH_ERROR_CODES),\n message: z.string(),\n});\nexport const reauthPayloadSchema = z.object({ token: z.string() });\nexport const pingPayloadSchema = z.object({ t: z.number() });\nexport const subscribePayloadSchema = z.object({\n channelId: uint.min(1),\n documentId: z.string(),\n epoch: uint,\n /** base64 state vector */\n stateVector: z.string().optional(),\n mode: z.enum(SYNC_SUBSCRIBE_MODES),\n snapshotId: z.string().optional(),\n});\nexport const subscribedPayloadSchema = z.object({\n documentId: z.string(),\n role: roleOrNone,\n epoch: uint,\n markPermissions: z.unknown(),\n schemaVersion: uint,\n});\nexport const subscribeErrorPayloadSchema = z.object({\n code: z.enum(SYNC_SUBSCRIBE_ERROR_CODES),\n detail: z.unknown().optional(),\n});\nexport const unsubscribePayloadSchema = z.object({ channelId: uint.min(1) });\nexport const ackPayloadSchema = z.object({\n clientSeq: uint,\n serverSeq: uint,\n});\nexport const rejectPayloadSchema = z.object({\n clientSeq: uint,\n code: z.enum(SYNC_REJECT_CODES),\n detail: z.unknown().optional(),\n});\nexport const epochChangedPayloadSchema = z.object({\n newEpoch: uint,\n reason: z.enum(SYNC_EPOCH_REASONS),\n byUserId: z.string(),\n snapshotId: z.string().optional(),\n});\nexport const roleChangedPayloadSchema = z.object({\n role: roleOrNone,\n markPermissions: z.unknown(),\n});\nexport const documentDeletedPayloadSchema = z.object({\n byUserId: z.string(),\n recoverableUntil: z.string(),\n});\nexport const normalizedPayloadSchema = z.object({\n serverSeq: uint,\n contentHashes: z.record(z.string(), z.string()),\n});\nexport const serverShutdownPayloadSchema = z.object({\n reconnectAfterMs: uint,\n});\n\n// ─── Frame schemas: decoded `{channelId, type, payload}` ────────────────────\n\nconst ctl = z.literal(0);\nconst chan = uint.min(1);\n\nexport const syncFrameSchema = z.discriminatedUnion('type', [\n z.object({\n channelId: ctl,\n type: z.literal('auth'),\n payload: authPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('authOk'),\n payload: authOkPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('authError'),\n payload: authErrorPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('reauth'),\n payload: reauthPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('ping'),\n payload: pingPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('pong'),\n payload: pingPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('subscribe'),\n payload: subscribePayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('subscribed'),\n payload: subscribedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('subscribeError'),\n payload: subscribeErrorPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('unsubscribe'),\n payload: unsubscribePayloadSchema,\n }),\n z.object({ channelId: chan, type: z.literal('syncStep1'), payload: bytes }),\n z.object({ channelId: chan, type: z.literal('syncStep2'), payload: bytes }),\n z.object({\n channelId: chan,\n type: z.literal('update'),\n payload: z.object({ epoch: uint, clientSeq: uint, update: bytes }),\n }),\n z.object({\n channelId: chan,\n type: z.literal('ack'),\n payload: ackPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('reject'),\n payload: rejectPayloadSchema,\n }),\n z.object({ channelId: chan, type: z.literal('awareness'), payload: bytes }),\n z.object({\n channelId: chan,\n type: z.literal('epochChanged'),\n payload: epochChangedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('roleChanged'),\n payload: roleChangedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('documentDeleted'),\n payload: documentDeletedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('normalized'),\n payload: normalizedPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('serverShutdown'),\n payload: serverShutdownPayloadSchema,\n }),\n]);\nexport type SyncFrame = z.infer<typeof syncFrameSchema>;\nexport type SyncFrameOf<T extends SyncFrame['type']> = Extract<\n SyncFrame,\n { type: T }\n>;\n\nexport * from './permissions.js';\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &amp;,&lt;,&gt;,&#39;,&quot;\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, r => /** @type {string} */ ({\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&#39;': \"'\",\n '&quot;': '\"'\n }[r]))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Binary wire codec for sync frames (spec 03 §2.2). Shared by the API and the frontend client.\n * Platform-free: only `lib0` (pure JS), no Node built-ins, no DOM.\n *\n * frame := channelId:varuint messageType:varuint payload\n *\n * Payload by type:\n * - JSON UTF-8 (the JSON text fills the rest of the frame): auth, authOk, authError, reauth, ping/pong, subscribe, subscribed, subscribeError,\n * unsubscribe, ack, reject, epochChanged, roleChanged, documentDeleted, normalized,\n * serverShutdown.\n * - syncStep1 / syncStep2 / awareness: `varuint8array` (the y-protocols payload, which is\n * exactly what follows the message-type tag in y-protocols/sync and /awareness).\n * - update: `epoch:varuint clientSeq:varuint update:varuint8array`.\n *\n * ping and pong share code 4. `decodeFrame` returns type `ping` for it; a heartbeat frame is a\n * liveness signal only and must never be answered (otherwise the two sides would echo forever).\n */\nimport * as decoding from 'lib0/decoding';\nimport * as encoding from 'lib0/encoding';\nimport * as string from 'lib0/string';\nimport {\n SYNC_MESSAGE_TYPES,\n syncFrameSchema,\n type SyncFrame,\n} from './index.js';\n\nexport class SyncCodecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SyncCodecError';\n }\n}\n\nconst BINARY_TYPES = new Set(['syncStep1', 'syncStep2', 'awareness']);\n\nconst NAME_BY_CODE = new Map<number, SyncFrame['type']>();\nfor (const [name, code] of Object.entries(SYNC_MESSAGE_TYPES)) {\n // ping and pong share a code: the first registration (ping) wins on decode.\n if (!NAME_BY_CODE.has(code))\n NAME_BY_CODE.set(code, name as SyncFrame['type']);\n}\n\nexport function encodeFrame(frame: SyncFrame): Uint8Array {\n const enc = encoding.createEncoder();\n encoding.writeVarUint(enc, frame.channelId);\n encoding.writeVarUint(enc, SYNC_MESSAGE_TYPES[frame.type]);\n if (BINARY_TYPES.has(frame.type)) {\n encoding.writeVarUint8Array(enc, frame.payload as Uint8Array);\n } else if (frame.type === 'update') {\n encoding.writeVarUint(enc, frame.payload.epoch);\n encoding.writeVarUint(enc, frame.payload.clientSeq);\n encoding.writeVarUint8Array(enc, frame.payload.update);\n } else {\n encoding.writeUint8Array(\n enc,\n string.encodeUtf8(JSON.stringify(frame.payload))\n );\n }\n return encoding.toUint8Array(enc);\n}\n\n/** Throws `SyncCodecError` on any malformed or schema-invalid frame. */\nexport function decodeFrame(bytes: Uint8Array): SyncFrame {\n let candidate: unknown;\n try {\n const dec = decoding.createDecoder(bytes);\n const channelId = decoding.readVarUint(dec);\n const code = decoding.readVarUint(dec);\n const type = NAME_BY_CODE.get(code);\n if (!type) throw new SyncCodecError(`unknown message type ${code}`);\n let payload: unknown;\n if (BINARY_TYPES.has(type)) {\n payload = decoding.readVarUint8Array(dec);\n if (decoding.hasContent(dec)) throw new SyncCodecError('trailing bytes');\n } else if (type === 'update') {\n const epoch = decoding.readVarUint(dec);\n const clientSeq = decoding.readVarUint(dec);\n const update = decoding.readVarUint8Array(dec);\n if (decoding.hasContent(dec)) throw new SyncCodecError('trailing bytes');\n payload = { epoch, clientSeq, update };\n } else {\n const rest = decoding.readTailAsUint8Array(dec);\n payload = JSON.parse(string.decodeUtf8(rest));\n }\n candidate = { channelId, type, payload };\n } catch (e) {\n if (e instanceof SyncCodecError) throw e;\n throw new SyncCodecError(\n `malformed frame: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n const parsed = syncFrameSchema.safeParse(candidate);\n if (!parsed.success)\n throw new SyncCodecError(`invalid frame: ${parsed.error.message}`);\n return parsed.data;\n}\n"],"names":["r","boolQuery","max","sha256HexSchema","bytes","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarUint8Array","encoding.writeUint8Array","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarUint8Array","decoding.hasContent","decoding.readTailAsUint8Array","string.decodeUtf8"],"mappings":";;;;AAMA,MAAM,cAAc;AAAA,EAClB,CAAC,gBAAgB,GAAG;AAAA,EACpB,CAAC,mBAAmB,GAAG;AAAA,EACvB,CAAC,qBAAqB,GAAG;AAAA,EACzB,CAAC,aAAa,GAAG;AAAA,EACjB,CAAC,mBAAmB,GAAG;AAAA,EACvB,CAAC,aAAa,GAAG;AAAA,EACjB,CAAC,qBAAqB,GAAG;AAAA,EACzB,CAAC,sBAAsB,GAAG;AAAA,EAC1B,CAAC,sBAAsB,GAAG;AAAA,EAC1B,CAAC,sBAAsB,GAAG;AAAA,EAC1B,CAAC,kBAAkB,GAAG;AAAA,EACtB,CAAC,oBAAoB,GAAG;AAAA,EACxB,CAAC,oBAAoB,GAAG;AAAA,EACxB,CAAC,cAAc,GAAG;AAAA,EAClB,CAAC,mBAAmB,GAAG;AAAA,EACvB,CAAC,oBAAoB,GAAG;AAAA,EACxB,CAAC,yBAAyB,GAAG;AAAA,EAC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AAO,OAAO;AAChB;","x_google_ignoreList":[27,28,29,30,31,32,33]}
1
+ {"version":3,"file":"index.js","sources":["../src/api/envelope.ts","../src/api/pagination.ts","../src/api/routes.ts","../src/tenancy/index.ts","../src/sharing/index.ts","../src/projects/index.ts","../src/lifecycle/index.ts","../src/me/index.ts","../src/account/index.ts","../src/templates/index.ts","../src/versions/index.ts","../src/commands/index.ts","../src/formats/index.ts","../src/reads/index.ts","../src/io/index.ts","../src/ai/index.ts","../src/ai/actions.ts","../src/jobs/index.ts","../src/reports/index.ts","../src/packets/index.ts","../src/assets/index.ts","../src/collab/index.ts","../src/credits/index.ts","../src/public/index.ts","../src/admin/index.ts","../src/sync/permissions.ts","../src/sync/index.ts","../node_modules/lib0/binary.js","../node_modules/lib0/math.js","../node_modules/lib0/number.js","../node_modules/lib0/string.js","../node_modules/lib0/error.js","../node_modules/lib0/encoding.js","../node_modules/lib0/decoding.js","../src/sync/codec.ts"],"sourcesContent":["/**\n * Response envelope, error vocabulary (spec 05 §12) and pagination shape.\n * Platform-free: no clock is read here, so the envelope carries no timestamp.\n */\n\n/** Every REST error code and its fixed HTTP status (spec 05 §12). */\nconst ERROR_TABLE = [\n ['UNAUTHORIZED', 401],\n ['REAUTH_REQUIRED', 401],\n ['API_KEY_FORBIDDEN', 403],\n ['FORBIDDEN', 403],\n ['ROLE_ESCALATION', 403],\n ['NOT_FOUND', 404],\n ['PROJECT_NOT_FOUND', 404],\n ['DOCUMENT_NOT_FOUND', 404],\n ['SNAPSHOT_NOT_FOUND', 404],\n ['TEMPLATE_NOT_FOUND', 404],\n ['ITEM_NOT_FOUND', 404],\n ['ANCHOR_NOT_FOUND', 404],\n ['TARGET_NOT_FOUND', 404],\n ['VALIDATION', 400],\n ['COMMAND_INVALID', 422],\n ['TEMPLATE_INVALID', 422],\n ['CONFIRMATION_MISMATCH', 400],\n ['EPOCH_MISMATCH', 409],\n ['DOCUMENT_LOCKED', 423],\n ['DOCUMENT_BUSY', 409],\n ['JOB_ALREADY_RUNNING', 409],\n ['JOB_FINISHED', 409],\n ['JOB_NOT_FINISHED', 409],\n ['LAST_OWNER', 409],\n ['ALREADY_MEMBER', 409],\n ['NOT_A_MEMBER', 409],\n ['PERSONAL_WORKSPACE_IMMUTABLE', 409],\n ['OWNS_TEAM_WORKSPACE', 409],\n ['NOT_IN_TRASH', 409],\n ['PARENT_IN_TRASH', 409],\n ['FOLDER_DEPTH', 409],\n ['FOLDER_CYCLE', 409],\n ['MOVE_FORBIDDEN', 403],\n ['BUILTIN_IMMUTABLE', 409],\n ['LOCATOR_AMBIGUOUS', 409],\n ['INVITATION_INVALID', 410],\n ['INVITATION_EXPIRED', 410],\n ['INVITATION_CLOSED', 410],\n ['EMAIL_MISMATCH', 403],\n ['SHARE_LINK_INVALID', 404],\n ['SHARE_LINK_PASSWORD_REQUIRED', 401],\n ['WATERMARK_REQUIRED', 403],\n ['EDIT_WINDOW_CLOSED', 409],\n ['ASSET_TOO_LARGE', 413],\n ['IMPORT_TOO_LARGE', 413],\n ['UNSUPPORTED_FORMAT', 400],\n ['IMPORT_FAILED', 400],\n ['IMPORT_INVALID', 422],\n ['ASSET_TYPE_REJECTED', 415],\n ['ASSET_CHECKSUM_MISMATCH', 422],\n ['ASSET_NOT_READY', 409],\n ['ASSET_IN_USE', 409],\n ['UPLOAD_INCOMPLETE', 409],\n ['UPLOAD_EXPIRED', 410],\n ['STORAGE_QUOTA_EXCEEDED', 507],\n ['STORAGE_UNAVAILABLE', 503],\n ['IMPORT_FORMAT_UNSUPPORTED', 415],\n ['EXPORT_FORMAT_UNSUPPORTED', 415],\n ['COMPARE_TOO_LARGE', 413],\n ['LIMIT_EXCEEDED', 409],\n ['RATE_LIMITED', 429],\n ['QUOTA_EXCEEDED', 429],\n ['INSUFFICIENT_CREDITS', 402],\n ['COUPON_NOT_FOUND', 404],\n ['COUPON_EMAIL_MISMATCH', 403],\n ['COUPON_ALREADY_REDEEMED', 409],\n ['COUPON_EXPIRED', 410],\n ['AI_UNAVAILABLE', 503],\n ['AI_INPUT_TOO_LARGE', 413],\n ['AI_GENERATION_FAILED', 502],\n ['AI_OUTPUT_INVALID', 502],\n ['CONFIG_MISSING', 503],\n ['CLIENT_TOO_OLD', 426],\n ['CONTENT_CHANGED', 409],\n ['STYLE_NOT_IN_TEMPLATE', 422],\n ['NOT_CONTIGUOUS', 422],\n ['LOCKED_CONTENT', 409],\n ['NAME_COLLISION', 409],\n ['KIND_MISMATCH', 422],\n ['OVERLAPPING_SHOTS', 422],\n ['OVERLAPPING_NODE', 422],\n ['SCENES_LOCKED', 409],\n ['NOT_LOCKED', 409],\n ['RANGE_OUT_OF_BOUNDS', 422],\n ['INVALID_TARGET', 422],\n ['INVALID_DUAL_DIALOGUE', 422],\n ['FOUNTAIN_PARSE_ERROR', 422],\n ['UNMAPPED_STYLES', 422],\n ['RANGE_TOO_LARGE', 413],\n ['PAYLOAD_TOO_LARGE', 413],\n ['INVALID_REGEX', 400],\n ['REPORT_OPTIONS_INVALID', 400],\n ['REPORT_KIND_UNAVAILABLE', 501],\n ['ENTITY_IN_USE', 409],\n ['VARIANT_IN_USE', 409],\n ['SNAPSHOT_NOT_IN_DOCUMENT', 404],\n ['ITEM_NOT_IN_SNAPSHOT', 404],\n ['INVALID_LOCATOR', 400],\n ['LOCATOR_NOT_FOUND', 404],\n ['ROLE_NOT_ALLOWED_FOR_TARGET', 422],\n ['ID_CONFLICT', 409],\n ['IDEMPOTENCY_KEY_REUSED', 409],\n ['IDEMPOTENCY_IN_PROGRESS', 409],\n ['DEVICE_REVOKED', 403],\n ['MACRO_TRIGGER_TAKEN', 409],\n ['STALE_WRITE', 409],\n ['HANDOFF_INVALID', 410],\n ['WATERMARK_NOT_FOUND', 404],\n ['OCR_UNAVAILABLE', 503],\n ['GRAMMAR_UNAVAILABLE', 503],\n ['AI_CONSENT_REQUIRED', 403],\n ['AI_DISABLED_FOR_WORKSPACE', 403],\n ['AI_EXCLUDED_DOCUMENT', 403],\n ['AI_KEY_NOT_PERMITTED', 403],\n ['QUOTE_EXCEEDS_MAX', 402],\n ['AI_CONTENT_REFUSED', 422],\n ['SCOPE_TOO_LARGE', 413],\n ['SUGGESTION_UNAVAILABLE', 409],\n ['JOB_KIND_DISABLED', 501],\n ['JOB_KIND_NOT_GENERIC', 400],\n ['JOB_FAILED', 409],\n ['JOB_TIMEOUT', 504],\n ['LIKENESS_CONSENT_REQUIRED', 422],\n ['CONTENT_REJECTED', 422],\n ['INTERNAL', 500],\n] as const;\n\ntype ErrorTable = typeof ERROR_TABLE;\nexport type ApiErrorCode = ErrorTable[number][0];\n\nexport const API_ERROR_CODES = Object.fromEntries(\n ERROR_TABLE.map(([code]) => [code, code])\n) as { readonly [C in ApiErrorCode]: C };\n\n/** HTTP status per error code. */\nexport const ERROR_STATUS = Object.fromEntries(ERROR_TABLE) as Record<\n ApiErrorCode,\n number\n>;\n\nexport interface ApiSuccess<T> {\n success: true;\n data: T;\n}\n\nexport interface ApiFailure {\n success: false;\n /** Human-readable message. */\n error: string;\n code: ApiErrorCode;\n /** Code-specific details (e.g. `issues`, `index`, `ids`). */\n details?: Record<string, unknown>;\n}\n\nexport type ApiResponse<T> = ApiSuccess<T> | ApiFailure;\n\nexport function successResponse<T>(data: T): ApiSuccess<T> {\n return { success: true, data };\n}\n\n/** The only constructor for failure envelopes. */\nexport function errorResponse(\n message: string,\n code: ApiErrorCode,\n details?: Record<string, unknown>\n): ApiFailure {\n return details === undefined\n ? { success: false, error: message, code }\n : { success: false, error: message, code, details };\n}\n\n/** Cursor page: `nextCursor` is null on the last page. */\nexport interface Paginated<T> {\n items: T[];\n nextCursor: string | null;\n}\n","import { z } from 'zod';\n\n/** `limit` 1-200 (default 50); `cursor` is an opaque base64url string. */\nexport const cursorQuerySchema = z.object({\n limit: z.coerce.number().int().min(1).max(200).default(50),\n cursor: z\n .string()\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n});\nexport type CursorQuery = z.infer<typeof cursorQuerySchema>;\n","/**\n * Route table for slices B1-B5 (spec 05 §6). Paths are relative to API_BASE_PATH.\n * `auth` uses the spec legend: U user, K key (r/rw scope), L link, P public.\n * `permission` is the spec 05 §5.2 permission checked on the resolved object.\n */\nexport const API_BASE_PATH = '/api/v1';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\nexport interface RouteSpec {\n method: HttpMethod;\n path: string;\n auth: string;\n permission: string | null;\n}\n\nconst r = (\n method: HttpMethod,\n path: string,\n auth: string,\n permission: string | null = null\n): RouteSpec => ({ method, path, auth, permission });\n\nexport const API_ROUTES = {\n // B1\n health: r('GET', '/health', 'P'),\n meGet: r('GET', '/me', 'U,Kr'),\n mePatch: r('PATCH', '/me', 'U'),\n // B2 workspaces\n workspacesList: r('GET', '/workspaces', 'U,Kr'),\n workspaceGet: r('GET', '/workspaces/:wid', 'U,Kr', 'workspace.read'),\n // B2 projects\n projectsList: r('GET', '/workspaces/:wid/projects', 'U,Kr', 'project.read'),\n projectCreate: r(\n 'POST',\n '/workspaces/:wid/projects',\n 'U,Krw',\n 'project.create'\n ),\n projectGet: r('GET', '/projects/:pid', 'U,Kr,L', 'project.read'),\n projectUpdate: r('PATCH', '/projects/:pid', 'U,Krw', 'project.update'),\n projectTrash: r('POST', '/projects/:pid/trash', 'U,Krw', 'project.trash'),\n projectRestore: r(\n 'POST',\n '/projects/:pid/restore',\n 'U,Krw',\n 'project.restore'\n ),\n // B2 documents\n documentsList: r(\n 'GET',\n '/projects/:pid/documents',\n 'U,Kr,L',\n 'document.read'\n ),\n documentCreate: r(\n 'POST',\n '/projects/:pid/documents',\n 'U,Krw',\n 'document.create'\n ),\n documentGet: r('GET', '/documents/:did', 'U,Kr,L', 'document.read'),\n documentUpdate: r('PATCH', '/documents/:did', 'U,Krw', 'document.edit'),\n documentTrash: r('POST', '/documents/:did/trash', 'U,Krw', 'document.trash'),\n documentRestore: r(\n 'POST',\n '/documents/:did/restore',\n 'U,Krw',\n 'document.restore'\n ),\n documentState: r('GET', '/documents/:did/state', 'U,Kr,L', 'document.read'),\n documentContent: r(\n 'GET',\n '/documents/:did/content',\n 'U,Kr,L',\n 'document.read'\n ),\n // B2 templates\n templatesList: r('GET', '/templates', 'U,Kr'),\n templateGet: r('GET', '/templates/:tid', 'U,Kr'),\n // B3 sync (WebSocket upgrade, credentials travel in the first `auth` frame)\n sync: r('GET', '/sync', 'P'),\n // B4 versions and snapshots\n versionsList: r('GET', '/documents/:did/versions', 'U,Kr,L', 'document.read'),\n versionState: r(\n 'GET',\n '/documents/:did/versions/:vid/state',\n 'U,Kr,L',\n 'document.read'\n ),\n versionRestore: r(\n 'POST',\n '/documents/:did/versions/:vid/restore',\n 'U,Krw',\n 'document.restore'\n ),\n versionSnapshot: r(\n 'POST',\n '/documents/:did/versions/:vid/snapshot',\n 'U,Krw',\n 'snapshot.create'\n ),\n snapshotsList: r(\n 'GET',\n '/documents/:did/snapshots',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotCreate: r(\n 'POST',\n '/documents/:did/snapshots',\n 'U,Krw',\n 'snapshot.create'\n ),\n snapshotGet: r('GET', '/snapshots/:sid', 'U,Kr,L', 'snapshot.read'),\n snapshotState: r('GET', '/snapshots/:sid/state', 'U,Kr,L', 'snapshot.read'),\n snapshotContent: r(\n 'GET',\n '/snapshots/:sid/content',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotOpen: r('POST', '/snapshots/:sid/open', 'U,Krw', 'snapshot.open'),\n snapshotFork: r('POST', '/snapshots/:sid/fork', 'U,Krw', 'snapshot.read'),\n // B15 versions, snapshots and sync completion (spec 05 §6.7.1, §6.9-6.11)\n elementHistory: r(\n 'GET',\n '/documents/:did/elements/:elementId/history',\n 'U,Kr',\n 'document.read'\n ),\n documentPresence: r(\n 'GET',\n '/documents/:did/presence',\n 'U,Kr',\n 'document.read'\n ),\n versionRestoreAsCopy: r(\n 'POST',\n '/documents/:did/versions/:vid/restore-as-copy',\n 'U,Krw',\n 'version.restoreAsCopy'\n ),\n snapshotPrefs: r('PUT', '/snapshots/:sid/prefs', 'U', 'snapshot.hideForSelf'),\n snapshotNotesList: r(\n 'GET',\n '/snapshots/:sid/notes',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotNoteCreate: r(\n 'POST',\n '/snapshots/:sid/notes',\n 'U,Krw',\n 'snapshot.appendNote'\n ),\n snapshotCommentsList: r(\n 'GET',\n '/snapshots/:sid/comments',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n snapshotCommentCreate: r(\n 'POST',\n '/snapshots/:sid/comments',\n 'U,L',\n 'document.comment'\n ),\n snapshotCommentCopyToLive: r(\n 'POST',\n '/snapshot-comments/:cid/copy-to-live',\n 'U',\n 'document.edit'\n ),\n snapshotCommentResolve: r(\n 'POST',\n '/snapshot-comments/:cid/resolve',\n 'U',\n 'document.comment'\n ),\n documentCompare: r(\n 'POST',\n '/documents/:did/compare',\n 'U,Kr,L',\n 'snapshot.read'\n ),\n // Import and export (synchronous, no jobs)\n documentImport: r(\n 'POST',\n '/projects/:pid/documents/import',\n 'U,Krw',\n 'document.create'\n ),\n documentExport: r('POST', '/documents/:did/export', 'U,Kr', 'document.read'),\n formatsList: r('GET', '/formats', 'U,Kr'),\n // B5 commands and reads\n commands: r('POST', '/documents/:did/commands', 'U,Krw', 'document.edit'),\n outline: r('GET', '/documents/:did/outline', 'U,Kr,L', 'document.read'),\n scene: r('GET', '/documents/:did/scenes/:sceneId', 'U,Kr,L', 'document.read'),\n scenesBatch: r(\n 'POST',\n '/documents/:did/scenes/batch',\n 'U,Kr,L',\n 'document.read'\n ),\n elementsBatch: r(\n 'POST',\n '/documents/:did/elements/batch',\n 'U,Kr,L',\n 'document.read'\n ),\n // B6 personal API keys (user principals only; a key gets 403 API_KEY_FORBIDDEN)\n apiKeysList: r('GET', '/api-keys', 'U'),\n apiKeyCreate: r('POST', '/api-keys', 'U', 'apiKeys.use'),\n apiKeyUpdate: r('PATCH', '/api-keys/:kid', 'U'),\n apiKeyRevoke: r('DELETE', '/api-keys/:kid', 'U'),\n // B7 AI: script review and polish. Keys need the `ai` flag (403 AI_KEY_NOT_PERMITTED) and, to start\n // jobs or decide suggestions, read_write scope.\n aiStatus: r('GET', '/ai/status', 'U,Kr'),\n // Synchronous AI actions (`ai/actions.ts`): user principals only, gated by AI consent, a daily limit and credits.\n aiGenerateCharacterSkeleton: r(\n 'POST',\n '/ai/generate-character-skeleton',\n 'U'\n ),\n aiGenerateScript: r('POST', '/ai/generate-script', 'U'),\n aiPolishCharacterDialogue: r('POST', '/ai/polish-character-dialogue', 'U'),\n aiPolishScene: r('POST', '/ai/polish-scene', 'U'),\n aiJobCreate: r('POST', '/documents/:did/ai/jobs', 'U,Krw', 'ai.run'),\n aiJobsList: r('GET', '/documents/:did/ai/jobs', 'U,Kr', 'document.read'),\n aiJobGet: r('GET', '/ai/jobs/:jobId', 'U,Kr', 'document.read'),\n aiJobCancel: r('POST', '/ai/jobs/:jobId/cancel', 'U,Krw', 'ai.review'),\n aiSuggestionSetsList: r(\n 'GET',\n '/documents/:did/ai/suggestion-sets',\n 'U,Kr',\n 'document.read'\n ),\n aiSuggestionSetGet: r(\n 'GET',\n '/ai/suggestion-sets/:ssid',\n 'U,Kr',\n 'document.read'\n ),\n aiSuggestionSetAccept: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/accept',\n 'U,Krw',\n 'document.edit'\n ),\n aiSuggestionSetReject: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/reject',\n 'U,Krw',\n 'document.edit'\n ),\n // B8 tenancy, roles, sharing. Keys (K) only read members and /me/shared; everything else is user-only (403 API_KEY_FORBIDDEN).\n workspaceCreate: r('POST', '/workspaces', 'U'),\n workspaceUpdate: r('PATCH', '/workspaces/:wid', 'U', 'workspace.update'),\n workspaceDelete: r('DELETE', '/workspaces/:wid', 'U', 'workspace.delete'),\n workspaceTransfer: r(\n 'POST',\n '/workspaces/:wid/transfer',\n 'U',\n 'workspace.transfer'\n ),\n workspaceLeave: r('POST', '/workspaces/:wid/leave', 'U', 'workspace.leave'),\n workspaceUsage: r('GET', '/workspaces/:wid/usage', 'U', 'workspace.read'),\n workspaceAudit: r(\n 'GET',\n '/workspaces/:wid/audit.csv',\n 'U',\n 'workspace.audit'\n ),\n membersList: r('GET', '/workspaces/:wid/members', 'U,Kr', 'members.read'),\n memberUpdate: r(\n 'PATCH',\n '/workspaces/:wid/members/:uid',\n 'U',\n 'members.updateRole'\n ),\n memberRemove: r(\n 'DELETE',\n '/workspaces/:wid/members/:uid',\n 'U',\n 'members.remove'\n ),\n invitationCreateWorkspace: r(\n 'POST',\n '/workspaces/:wid/invitations',\n 'U',\n 'members.invite'\n ),\n invitationCreateProject: r(\n 'POST',\n '/projects/:pid/invitations',\n 'U',\n 'share.manage'\n ),\n invitationCreateDocument: r(\n 'POST',\n '/documents/:did/invitations',\n 'U',\n 'share.manage'\n ),\n workspaceInvitationsList: r(\n 'GET',\n '/workspaces/:wid/invitations',\n 'U',\n 'members.invite'\n ),\n myInvitations: r('GET', '/me/invitations', 'U'),\n invitationRenew: r('POST', '/invitations/:iid/renew', 'U'),\n invitationCancel: r('DELETE', '/invitations/:iid', 'U'),\n invitationAccept: r('POST', '/invitations/accept', 'U'),\n invitationAcceptById: r('POST', '/invitations/:iid/accept', 'U'),\n invitationDecline: r('POST', '/invitations/:iid/decline', 'U'),\n sharedWithMe: r('GET', '/me/shared', 'U,Kr'),\n documentLock: r('POST', '/documents/:did/lock', 'U', 'document.lock'),\n documentUnlock: r('DELETE', '/documents/:did/lock', 'U', 'document.lock'),\n documentUnlockSession: r(\n 'POST',\n '/documents/:did/unlock-session',\n 'U',\n 'document.read'\n ),\n shareLinkCreateDocument: r(\n 'POST',\n '/documents/:did/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkCreateProject: r(\n 'POST',\n '/projects/:pid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkCreateSnapshot: r(\n 'POST',\n '/snapshots/:sid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinksListDocument: r(\n 'GET',\n '/documents/:did/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinksListProject: r(\n 'GET',\n '/projects/:pid/share-links',\n 'U',\n 'share.manage'\n ),\n shareLinkUpdate: r('PATCH', '/share-links/:lid', 'U', 'share.manage'),\n shareLinkRevoke: r('DELETE', '/share-links/:lid', 'U', 'share.manage'),\n grantsListDocument: r('GET', '/documents/:did/grants', 'U', 'share.manage'),\n grantsListProject: r('GET', '/projects/:pid/grants', 'U', 'share.manage'),\n grantUpdate: r('PATCH', '/grants/:gid', 'U', 'share.manage'),\n grantRemove: r('DELETE', '/grants/:gid', 'U', 'share.manage'),\n // B8 public link routes: the token in the path is the credential; an optional Bearer is a user or a link session (`fls_`).\n publicShareResolve: r('GET', '/public/share/:token', 'P'),\n shareUnlock: r('POST', '/share/:token/unlock', 'P'),\n shareState: r('GET', '/share/:token/state', 'P,L', 'document.read'),\n // B9 generic jobs (spec 05 §6.19). Jobs are visible to their owner, or to anyone who can read the job's document;\n // cancel, outputs and recipients are owner-only. `/ai/jobs*` stays as the AI facade over the same rows.\n jobsList: r('GET', '/jobs', 'U,Kr', 'document.read'),\n jobGet: r('GET', '/jobs/:jobId', 'U,Kr,L', 'document.read'),\n jobCreate: r('POST', '/jobs', 'U,Krw', 'document.read'),\n jobCancel: r('POST', '/jobs/:jobId/cancel', 'U,Krw', 'document.read'),\n jobOutputs: r('GET', '/jobs/:jobId/outputs', 'U,K,L', 'document.export'),\n jobRecipients: r('GET', '/jobs/:jobId/recipients', 'U', 'document.export'),\n // Provider webhook: unauthenticated, HMAC-signed with JOB_WEBHOOK_SECRET_<ADAPTER> (fails closed: 401 when unset).\n jobWebhook: r('POST', '/webhooks/jobs/:adapterId', 'W'),\n // B10 projection-backed reads, search, reports, packets (spec 05 §6.7.1, §6.7.2, §6.12, §6.14, §6.15, §6.17, §6.18, §6.22).\n // `?source=live|snapshot:<id>|version:<id>` selects the state a read answers from. Keys (K) read all of these; the report\n // and resolve POSTs are reads, so a read-only key may send them.\n entitiesList: r('GET', '/documents/:did/entities', 'U,Kr,L', 'document.read'),\n entityGet: r(\n 'GET',\n '/documents/:did/entities/:eid',\n 'U,Kr,L',\n 'document.read'\n ),\n entityUsage: r(\n 'GET',\n '/documents/:did/entities/:eid/usage',\n 'U,Kr,L',\n 'document.read'\n ),\n entityDialogue: r(\n 'GET',\n '/documents/:did/entities/:eid/dialogue',\n 'U,Kr,L',\n 'document.read'\n ),\n tagCategoriesList: r(\n 'GET',\n '/documents/:did/tag-categories',\n 'U,Kr,L',\n 'document.read'\n ),\n tagsList: r('GET', '/documents/:did/tags', 'U,Kr,L', 'document.read'),\n notesList: r('GET', '/documents/:did/notes', 'U,Kr,L', 'document.read'),\n beatsList: r('GET', '/documents/:did/beats', 'U,Kr,L', 'document.read'),\n binList: r('GET', '/documents/:did/bin', 'U,Kr,L', 'document.read'),\n revisionsGet: r(\n 'GET',\n '/documents/:did/revisions',\n 'U,Kr,L',\n 'document.read'\n ),\n changesList: r('GET', '/documents/:did/changes', 'U,Kr,L', 'document.read'),\n alternatesGet: r(\n 'GET',\n '/documents/:did/alternates/:elementId',\n 'U,Kr,L',\n 'document.read'\n ),\n titlePageGet: r(\n 'GET',\n '/documents/:did/title-page',\n 'U,Kr,L',\n 'document.read'\n ),\n statsGet: r('GET', '/documents/:did/stats', 'U,Kr,L', 'document.read'),\n fountainGet: r('GET', '/documents/:did/fountain', 'U,Kr,L', 'document.read'),\n sceneShotsList: r(\n 'GET',\n '/documents/:did/scenes/:sceneId/shots',\n 'U,Kr,L',\n 'document.read'\n ),\n resolveBatch: r('POST', '/documents/:did/resolve', 'U,Kr,L', 'document.read'),\n resolveOne: r('GET', '/documents/:did/resolve', 'U,Kr,L', 'document.read'),\n documentSearch: r('GET', '/documents/:did/search', 'U,Kr,L', 'document.read'),\n workspaceSearch: r(\n 'GET',\n '/workspaces/:wid/search',\n 'U,Kr',\n 'workspace.read'\n ),\n search: r('GET', '/search', 'U,Kr'),\n reportKinds: r('GET', '/reports/kinds', 'U,Kr'),\n reportGet: r('GET', '/documents/:did/reports/:kind', 'U,Kr,L', 'reports.run'),\n reportCreate: r('POST', '/documents/:did/reports', 'U,Kr,L', 'reports.run'),\n packetScene: r(\n 'GET',\n '/documents/:did/packets/scene/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetCharacter: r(\n 'GET',\n '/documents/:did/packets/character/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetLocation: r(\n 'GET',\n '/documents/:did/packets/location/:locator',\n 'U,Kr',\n 'document.read'\n ),\n packetShot: r(\n 'GET',\n '/documents/:did/packets/shot/:locator',\n 'U,Kr',\n 'document.read'\n ),\n // B13 account and per-user data (spec 05 §6.1, §6.1.1, §6.26). User-only (a key gets 403 API_KEY_FORBIDDEN) except the macro list (Kr).\n meDictionaryGet: r('GET', '/me/dictionary', 'U'),\n meDictionaryUpdate: r('PUT', '/me/dictionary', 'U'),\n mePreferencesGet: r('GET', '/me/preferences', 'U'),\n mePreferencesSet: r('PUT', '/me/preferences', 'U'),\n meMacrosList: r('GET', '/me/macros', 'U,Kr'),\n meMacroCreate: r('POST', '/me/macros', 'U'),\n meMacroUpdate: r('PATCH', '/me/macros/:mid', 'U'),\n meMacroDelete: r('DELETE', '/me/macros/:mid', 'U'),\n meWritingStats: r('GET', '/me/writing-stats', 'U'),\n meWritingSessionCreate: r('POST', '/me/writing-sessions', 'U'),\n meWritingGoalsGet: r('GET', '/me/writing-goals', 'U'),\n meWritingGoalsSet: r('PUT', '/me/writing-goals', 'U'),\n meExport: r('POST', '/me/export', 'U'),\n meDelete: r('DELETE', '/me', 'U'),\n meRestore: r('POST', '/me/restore', 'U'),\n documentMyStateGet: r(\n 'GET',\n '/documents/:did/my-state',\n 'U',\n 'document.read'\n ),\n documentMyStateSet: r(\n 'PUT',\n '/documents/:did/my-state',\n 'U',\n 'document.read'\n ),\n documentStar: r('PUT', '/documents/:did/star', 'U', 'document.read'),\n documentUnstar: r('DELETE', '/documents/:did/star', 'U', 'document.read'),\n // B14 project, document and template lifecycle, workspace settings (spec 05 §6.2, §6.6-§6.8, §6.26). Writes are `Krw`; purge,\n // trash-empty, workspace defaults and contacts are user-only (a key gets 403 API_KEY_FORBIDDEN).\n workspaceDocuments: r(\n 'GET',\n '/workspaces/:wid/documents',\n 'U,Kr',\n 'project.read'\n ),\n workspaceTrash: r('GET', '/workspaces/:wid/trash', 'U,Kr', 'project.read'),\n workspaceTrashEmpty: r(\n 'POST',\n '/workspaces/:wid/trash/empty',\n 'U',\n 'project.purge'\n ),\n projectPurge: r('DELETE', '/projects/:pid', 'U', 'project.purge'),\n projectDuplicate: r(\n 'POST',\n '/projects/:pid/duplicate',\n 'U,Krw',\n 'project.create'\n ),\n projectFolderCreate: r(\n 'POST',\n '/projects/:pid/folders',\n 'U,Krw',\n 'project.update'\n ),\n projectFolderUpdate: r(\n 'PATCH',\n '/project-folders/:fid',\n 'U,Krw',\n 'project.update'\n ),\n projectFolderDelete: r(\n 'DELETE',\n '/project-folders/:fid',\n 'U,Krw',\n 'project.update'\n ),\n documentMove: r('POST', '/documents/:did/move', 'U,Krw', 'document.move'),\n documentPurge: r('DELETE', '/documents/:did', 'U', 'project.purge'),\n documentDuplicate: r(\n 'POST',\n '/documents/:did/duplicate',\n 'U,Krw',\n 'document.create'\n ),\n documentApplyTemplate: r(\n 'POST',\n '/documents/:did/template',\n 'U,Krw',\n 'document.lock'\n ),\n templateCreate: r('POST', '/templates', 'U,Krw', 'templates.manage'),\n templateVersionCreate: r(\n 'POST',\n '/templates/:tid/versions',\n 'U,Krw',\n 'templates.manage'\n ),\n templateUpdate: r('PATCH', '/templates/:tid', 'U,Krw', 'templates.manage'),\n templateDelete: r('DELETE', '/templates/:tid', 'U,Krw', 'templates.manage'),\n templateImport: r('POST', '/templates/import', 'U,Krw', 'templates.manage'),\n templateExport: r('GET', '/templates/:tid/export', 'U,Kr'),\n projectBinList: r('GET', '/projects/:pid/bin', 'U,Kr', 'project.read'),\n projectBinCreate: r('POST', '/projects/:pid/bin', 'U,Krw', 'document.edit'),\n projectBinDelete: r(\n 'DELETE',\n '/project-bin-items/:id',\n 'U,Krw',\n 'document.edit'\n ),\n workspaceDefaultsGet: r(\n 'GET',\n '/workspaces/:wid/defaults',\n 'U,Kr',\n 'workspace.read'\n ),\n workspaceDefaultsSet: r(\n 'PUT',\n '/workspaces/:wid/defaults',\n 'U',\n 'workspace.update'\n ),\n workspaceContactsList: r(\n 'GET',\n '/workspaces/:wid/contacts',\n 'U',\n 'workspace.read'\n ),\n workspaceContactsCreate: r(\n 'POST',\n '/workspaces/:wid/contacts',\n 'U',\n 'workspace.update'\n ),\n workspaceContactUpdate: r(\n 'PATCH',\n '/workspace-contacts/:cid',\n 'U',\n 'workspace.update'\n ),\n workspaceContactDelete: r(\n 'DELETE',\n '/workspace-contacts/:cid',\n 'U',\n 'workspace.update'\n ),\n // B16 imports, exports and watermark as jobs (spec 05 §6.18). `POST /imports*` and `/uploads/state` are `Krw`; exports are `Kr` (a read key may\n // export what it can read); the watermark lookup is user-only (403 API_KEY_FORBIDDEN for a key). The synchronous\n // `documentImport`/`documentExport`/`formatsList` stay until the app moves to these (see the plan's B16 \"Deferred\" list).\n uploadState: r('POST', '/uploads/state', 'U,Krw'),\n importCreate: r('POST', '/imports', 'U,Krw', 'document.create'),\n importStart: r('POST', '/imports/:importId/start', 'U,Krw'),\n documentImportOver: r(\n 'POST',\n '/documents/:did/import-over',\n 'U,Krw',\n 'document.edit'\n ),\n documentExportCreate: r(\n 'POST',\n '/documents/:did/exports',\n 'U,Kr',\n 'document.export'\n ),\n documentExportCombined: r(\n 'POST',\n '/documents/export-combined',\n 'U,Kr',\n 'document.export'\n ),\n watermarkLookup: r(\n 'POST',\n '/workspaces/:wid/watermark-lookup',\n 'U',\n 'workspace.audit'\n ),\n // B11 assets and R2 (spec 05 §6.13). Bytes go to object storage through presigned URLs, never through the API. Writes are `Krw`, reads `Kr`;\n // share-link readers (`L`) are not built (no `/share/:token/assets` route yet). The uploader routes check the caller is the uploader.\n assetUploadCreate: r(\n 'POST',\n '/workspaces/:wid/assets/uploads',\n 'U,Krw',\n 'assets.upload'\n ),\n assetUploadGet: r('GET', '/assets/uploads/:uploadId', 'U,Krw'),\n assetUploadParts: r('POST', '/assets/uploads/:uploadId/parts', 'U,Krw'),\n assetUploadComplete: r('POST', '/assets/uploads/:uploadId/complete', 'U,Krw'),\n assetUploadAbort: r('DELETE', '/assets/uploads/:uploadId', 'U,Krw'),\n assetsList: r('GET', '/assets', 'U,Kr', 'assets.read'),\n assetGet: r('GET', '/assets/:aid', 'U,Kr', 'assets.read'),\n assetUrl: r('GET', '/assets/:aid/versions/:vid/url', 'U,Kr', 'assets.read'),\n assetUpdate: r('PATCH', '/assets/:aid', 'U,Krw', 'assets.upload'),\n assetDelete: r('DELETE', '/assets/:aid', 'U,Krw', 'assets.upload'),\n assetRestore: r('POST', '/assets/:aid/restore', 'U,Krw', 'assets.upload'),\n assetLinkCreate: r('POST', '/asset-links', 'U,Krw', 'assets.link'),\n documentAssetLinks: r(\n 'GET',\n '/documents/:did/asset-links',\n 'U,Kr',\n 'assets.read'\n ),\n assetLinkUpdate: r('PATCH', '/asset-links/:lid', 'U,Krw', 'assets.link'),\n assetLinkDelete: r('DELETE', '/asset-links/:lid', 'U,Krw', 'assets.link'),\n documentStaleness: r(\n 'GET',\n '/documents/:did/staleness',\n 'U,Kr',\n 'document.read'\n ),\n assetLinkStaleness: r(\n 'GET',\n '/asset-links/:lid/staleness',\n 'U,Kr',\n 'assets.read'\n ),\n // B12 collaboration, notifications, devices, email (spec 05 §6.15, §6.16, §6.24, §6.26). Most of this slice is\n // user-only (a key gets 403 API_KEY_FORBIDDEN): personal notifications and devices, and chat/activity writes are\n // never for a key. `documentChatList` and `documentActivity` are the two exceptions (`Kr`, a read key may read them).\n meNotificationPrefsGet: r('GET', '/me/notification-prefs', 'U'),\n meNotificationPrefsSet: r('PUT', '/me/notification-prefs', 'U'),\n documentMentionsWithoutAccess: r(\n 'GET',\n '/documents/:did/mentions-without-access',\n 'U',\n 'share.manage'\n ),\n documentChatList: r('GET', '/documents/:did/chat', 'U,Kr,L', 'document.chat'),\n documentChatCreate: r('POST', '/documents/:did/chat', 'U,L', 'document.chat'),\n chatMessageUpdate: r('PATCH', '/chat-messages/:mid', 'U', 'document.chat'),\n chatMessageDelete: r('DELETE', '/chat-messages/:mid', 'U', 'document.chat'),\n documentActivity: r(\n 'GET',\n '/documents/:did/activity',\n 'U,Kr',\n 'document.activity'\n ),\n workspaceActivity: r(\n 'GET',\n '/workspaces/:wid/activity',\n 'U',\n 'workspace.read'\n ),\n notificationsList: r('GET', '/notifications', 'U'),\n notificationsRead: r('POST', '/notifications/read', 'U'),\n notificationDelete: r('DELETE', '/notifications/:nid', 'U'),\n notificationsStream: r('GET', '/notifications/stream', 'U'),\n devicesList: r('GET', '/devices', 'U'),\n deviceCreate: r('POST', '/devices', 'U'),\n deviceUpdate: r('PATCH', '/devices/:devid', 'U'),\n deviceRevoke: r('POST', '/devices/:devid/revoke', 'U'),\n devicePushTokenSet: r('PUT', '/devices/:devid/push-token', 'U'),\n devicePushTokenDelete: r('DELETE', '/devices/:devid/push-token', 'U'),\n // B17 AI completion and credits (spec 05 §6.3, §6.19, §6.20, §6.21; spec 06 §9-10). AI routes need the key's `ai`\n // flag (403 AI_KEY_NOT_PERMITTED); `decide` needs read_write. Consent, activity and credits are user-only except\n // the balance/products reads (Kr; a key spends its own workspace's credits so it may read them) — `consumables/products`\n // is also public (unauthenticated pricing display). `GET .../suggestion-sets` and `GET /suggestion-sets/:ssid` are\n // already built (B7, under `/ai/` — kept as-is rather than duplicated at the bare path spec 05 Appendix A also lists).\n meAiConsentGet: r('GET', '/me/ai-consents', 'U'),\n meAiConsentAccept: r('POST', '/me/ai-consents', 'U'),\n meAiActivity: r('GET', '/me/ai-activity', 'U'),\n workspaceAiActivity: r(\n 'GET',\n '/workspaces/:wid/ai-activity',\n 'U',\n 'workspace.audit'\n ),\n aiEstimate: r('POST', '/documents/:did/ai/estimate', 'U,Kr', 'document.read'),\n aiReportsList: r(\n 'GET',\n '/documents/:did/ai/reports',\n 'U,Kr',\n 'document.read'\n ),\n aiReportGet: r(\n 'GET',\n '/documents/:did/ai/reports/:jobId',\n 'U,Kr',\n 'document.read'\n ),\n aiReportNoteConvert: r(\n 'POST',\n '/documents/:did/ai/reports/:jobId/notes/:noteId/convert',\n 'U,Krw',\n 'document.comment'\n ),\n aiSuggestionSetDecide: r(\n 'POST',\n '/ai/suggestion-sets/:ssid/decide',\n 'U,Krw',\n 'document.edit'\n ),\n consumablesBalance: r('GET', '/consumables/balance', 'U,Kr'),\n consumablesPurchaseTarget: r('POST', '/consumables/purchase-target', 'U'),\n consumablesRedeemCoupon: r('POST', '/consumables/redeem-coupon', 'U'),\n consumablesCouponsList: r('GET', '/consumables/coupons/history', 'U'),\n consumablesCouponsCreate: r('POST', '/consumables/coupons', 'U'),\n consumablesPurchases: r('GET', '/consumables/purchases', 'U'),\n consumablesUsages: r('GET', '/consumables/usages', 'U'),\n consumablesProducts: r('GET', '/consumables/products', 'U,Kr,P'),\n consumablesWebhook: r('POST', '/consumables/webhook', 'W'),\n purchaseHandoffCreate: r('POST', '/purchases/handoff', 'U'),\n // B18 public, admin, telemetry (spec 05 §6.21, §6.23, §6.24; `/language/*` skipped by decision, see the plan's\n // B18 note). Public routes need no session at all. Admin needs `siteAdmin` on a USER principal specifically —\n // never an API key, whatever its scope — enforced in the handler (there is no per-object permission to check).\n publicTemplatesList: r('GET', '/public/templates', 'P'),\n publicTemplateGet: r('GET', '/public/templates/:builtinKey', 'P'),\n publicConfig: r('GET', '/public/config', 'P'),\n publicNamesDb: r('GET', '/public/names-db/:version', 'P'),\n publicHealthDeep: r('GET', '/public/health/deep', 'P'),\n publicWatermarkedGet: r('GET', '/public/watermarked/:exportId/:token', 'P'),\n purchaseHandoffRedeem: r('POST', '/public/purchases/handoff/redeem', 'P'),\n telemetryCreate: r('POST', '/telemetry', 'U,P'),\n adminUsersLookup: r('GET', '/admin/users', 'U'),\n adminUserRestore: r('POST', '/admin/users/:uid/restore', 'U'),\n adminUserPurge: r('DELETE', '/admin/users/:uid', 'U'),\n adminJobsList: r('GET', '/admin/jobs', 'U'),\n adminJobRetry: r('POST', '/admin/jobs/:id/retry', 'U'),\n adminJobRefund: r('POST', '/admin/jobs/:id/refund', 'U'),\n adminJobKindUpdate: r('PATCH', '/admin/job-kinds/:kind', 'U'),\n adminDocumentMeta: r('GET', '/admin/documents/:did/meta', 'U'),\n} as const satisfies Record<string, RouteSpec>;\n\nexport type ApiRouteName = keyof typeof API_ROUTES;\n","import { z } from 'zod';\n\nexport const WORKSPACE_KINDS = ['personal', 'team'] as const;\nexport type WorkspaceKind = (typeof WORKSPACE_KINDS)[number];\n\n/** Ordered by authority (spec 05 §5.2). */\nexport const ROLES = [\n 'owner',\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const workspaceKindSchema = z.enum(WORKSPACE_KINDS);\nexport const roleSchema = z.enum(ROLES);\n\nexport interface WorkspaceSummary {\n id: string;\n kind: WorkspaceKind;\n name: string;\n avatarAssetId: string | null;\n}\n\nexport interface Workspace extends WorkspaceSummary {\n defaultTemplateId: string | null;\n defaultLanguage: string;\n aiEnabled: boolean;\n /** F-SET-009: false disables every existing `anyone with the link` share link of the workspace and refuses new ones. */\n allowPublicLinks: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/** `GET /workspaces` item: summary plus the caller's role. */\nexport type WorkspaceListItem = WorkspaceSummary & { role: Role };\n\n/** `GET /workspaces/:wid` */\nexport type WorkspaceDetail = Workspace & {\n role: Role;\n memberCount: number;\n storageBytes: number;\n};\n\n// ─── Permissions (spec 05 §5.2) ─────────────────────────────────────────────\n\n/**\n * Every permission with the LOWEST role that holds it. The matrix is monotonic (a higher role has\n * everything a lower one has), so `ROLE_PERMISSIONS` is derived from this table.\n * Notes on the two permissions with a condition beyond the role:\n * - `share.manage` for a writer only applies to documents/projects they created (checked by the API).\n * - `project.trash` / `project.restore` for a writer only applies to projects they created.\n */\nexport const PERMISSION_MIN_ROLE = {\n 'workspace.read': 'viewer',\n 'workspace.update': 'admin',\n 'workspace.aiToggle': 'owner',\n 'workspace.audit': 'admin',\n 'workspace.delete': 'owner',\n 'workspace.transfer': 'owner',\n 'workspace.leave': 'viewer',\n 'members.read': 'viewer',\n 'members.invite': 'admin',\n 'members.updateRole': 'admin',\n 'members.remove': 'admin',\n 'project.create': 'writer',\n 'project.read': 'viewer',\n 'project.update': 'writer',\n 'project.trash': 'writer',\n 'project.restore': 'writer',\n 'project.purge': 'admin',\n 'document.create': 'writer',\n 'document.read': 'viewer',\n 'document.export': 'viewer',\n 'document.edit': 'writer',\n 'document.comment': 'commenter',\n 'document.chat': 'commenter',\n 'document.activity': 'viewer',\n 'document.trash': 'writer',\n 'document.restore': 'writer',\n 'document.move': 'writer',\n 'document.lock': 'writer',\n 'document.aiExclude': 'writer',\n 'snapshot.create': 'writer',\n 'snapshot.open': 'writer',\n 'snapshot.fork': 'writer',\n 'snapshot.cherryPick': 'writer',\n 'snapshot.appendNote': 'writer',\n 'snapshot.read': 'viewer',\n 'snapshot.compare': 'viewer',\n 'snapshot.hideForSelf': 'viewer',\n 'version.restore': 'writer',\n 'version.restoreAsCopy': 'writer',\n 'share.manage': 'writer',\n 'assets.upload': 'writer',\n 'assets.link': 'writer',\n 'assets.read': 'viewer',\n 'ai.run': 'writer',\n 'ai.review': 'commenter',\n 'jobs.media': 'writer',\n 'templates.manage': 'writer',\n 'reports.run': 'viewer',\n 'apiKeys.use': 'viewer',\n} as const satisfies Record<string, Role>;\n\nexport type Permission = keyof typeof PERMISSION_MIN_ROLE;\nexport const PERMISSIONS = Object.keys(PERMISSION_MIN_ROLE) as Permission[];\n\n/** 0 = owner ... 4 = viewer; a smaller number is more authority. */\nconst RANK: Record<Role, number> = {\n owner: 0,\n admin: 1,\n writer: 2,\n commenter: 3,\n viewer: 4,\n};\n\n/** True when `a` has at least the authority of `b`. */\nexport const roleAtLeast = (a: Role, b: Role): boolean => RANK[a] <= RANK[b];\n\n/** The higher-authority of the given roles (nulls ignored); null when there are none. */\nexport function maxRole(...roles: (Role | null | undefined)[]): Role | null {\n let best: Role | null = null;\n for (const r of roles)\n if (r && (best === null || RANK[r] < RANK[best])) best = r;\n return best;\n}\n\n/** The lower-authority of two roles (used to cap an API key by its scope). */\nexport const minRole = (a: Role, b: Role): Role => (RANK[a] >= RANK[b] ? a : b);\n\nexport const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> =\n Object.fromEntries(\n ROLES.map((role) => [\n role,\n PERMISSIONS.filter((p) => roleAtLeast(role, PERMISSION_MIN_ROLE[p])),\n ])\n ) as unknown as Record<Role, readonly Permission[]>;\n\n/** The only check routes call. */\nexport const hasPermission = (role: Role, permission: Permission): boolean =>\n roleAtLeast(role, PERMISSION_MIN_ROLE[permission]);\n\n/** Lowest role that holds `permission` (goes in a 403's `details.requiredRole`). */\nexport const requiredRoleFor = (permission: Permission): Role =>\n PERMISSION_MIN_ROLE[permission];\n\n/** Roles a share grant or a project/document invitation may carry: `owner` is never granted by share. */\nexport const SHARE_ROLES = ['admin', 'writer', 'commenter', 'viewer'] as const;\nexport type ShareRole = (typeof SHARE_ROLES)[number];\n","/**\n * Tenancy management and sharing DTOs (spec 05 §5.3, §5.4, §6.2-6.4, §6.7, §6.21, §8.3), slice B8.\n */\nimport { z } from 'zod';\nimport { roleSchema, type Role } from '../tenancy/index.js';\n\n// ─── Workspaces ─────────────────────────────────────────────────────────────\n\nexport const TEAM_WORKSPACE_LIMIT = 50;\n\nexport const workspaceCreateSchema = z.object({\n name: z.string().trim().min(1).max(80),\n avatarAssetId: z.string().min(1).nullable().optional(),\n});\nexport type WorkspaceCreateRequest = z.infer<typeof workspaceCreateSchema>;\n\nexport const workspaceUpdateSchema = z.object({\n name: z.string().trim().min(1).max(80).optional(),\n avatarAssetId: z.string().min(1).nullable().optional(),\n defaultTemplateId: z.string().min(1).nullable().optional(),\n defaultLanguage: z.string().min(2).max(35).optional(),\n aiEnabled: z.boolean().optional(),\n allowPublicLinks: z.boolean().optional(),\n});\nexport type WorkspaceUpdateRequest = z.infer<typeof workspaceUpdateSchema>;\n\nexport const workspaceDeleteSchema = z.object({ confirmName: z.string() });\nexport type WorkspaceDeleteRequest = z.infer<typeof workspaceDeleteSchema>;\n/** `DELETE /workspaces/:wid` response (soft delete). */\nexport interface WorkspaceDeleteResponse {\n deletedAt: string;\n}\n\nexport const workspaceTransferSchema = z.object({\n toUserId: z.string().min(1),\n});\nexport type WorkspaceTransferRequest = z.infer<typeof workspaceTransferSchema>;\n\n/** `GET /workspaces/:wid/audit.csv` query: an ISO-8601 range of at most one year. */\nexport const workspaceAuditQuerySchema = z.object({\n from: z.iso.datetime({ offset: true }).optional(),\n to: z.iso.datetime({ offset: true }).optional(),\n});\nexport type WorkspaceAuditQuery = z.infer<typeof workspaceAuditQuerySchema>;\nexport const AUDIT_CSV_COLUMNS = [\n 'created_at',\n 'actor',\n 'action',\n 'target_type',\n 'target_id',\n 'ip',\n] as const;\nexport const AUDIT_MAX_RANGE_DAYS = 366;\n\nexport interface WorkspaceUsage {\n storageBytes: number;\n quotaBytes: number;\n documentCount: number;\n assetCount: number;\n}\n\n// ─── Members ────────────────────────────────────────────────────────────────\n\nexport interface Member {\n userId: string;\n email: string | null;\n displayName: string | null;\n role: Role;\n invitedBy: string | null;\n joinedAt: string;\n}\n\nexport const memberUpdateSchema = z.object({ role: roleSchema });\nexport type MemberUpdateRequest = z.infer<typeof memberUpdateSchema>;\n\n// ─── Invitations ────────────────────────────────────────────────────────────\n\nexport const INVITATION_TARGETS = ['workspace', 'project', 'document'] as const;\nexport type InvitationTarget = (typeof INVITATION_TARGETS)[number];\nexport const INVITATION_TTL_DAYS = 14;\nexport const INVITATION_STATUSES = [\n 'pending',\n 'accepted',\n 'declined',\n 'cancelled',\n 'expired',\n] as const;\nexport type InvitationStatus = (typeof INVITATION_STATUSES)[number];\n\n/** `role` for a workspace invitation is `admin|writer|commenter|viewer` (never `owner`); for a project or document it is a grant role. */\nexport const invitationCreateSchema = z.object({\n email: z.email().max(254),\n role: roleSchema,\n});\nexport type InvitationCreateRequest = z.infer<typeof invitationCreateSchema>;\n\n/** The token is never in this shape: it travels only in the invitation email (`notifyInvitation`, slice B12). */\nexport interface Invitation {\n id: string;\n targetType: InvitationTarget;\n workspaceId: string;\n projectId: string | null;\n documentId: string | null;\n email: string;\n role: Role;\n invitedBy: string;\n /** Inviter's display name or email, and the target's name, so an invitee can recognise it. */\n invitedByName: string | null;\n targetName: string | null;\n status: InvitationStatus;\n expiresAt: string;\n createdAt: string;\n}\n\nexport const invitationAcceptSchema = z.object({ token: z.string().min(1) });\nexport type InvitationAcceptRequest = z.infer<typeof invitationAcceptSchema>;\nexport interface InvitationAcceptResult {\n workspaceId?: string;\n projectId?: string;\n documentId?: string;\n}\n\n/** Where an invitation, grant list or link list points. */\nexport type ShareTarget =\n | { type: 'workspace'; id: string }\n | { type: 'project'; id: string }\n | { type: 'document'; id: string };\n\n// ─── Grants ─────────────────────────────────────────────────────────────────\n\nexport interface ShareGrant {\n id: string;\n targetType: 'project' | 'document';\n projectId: string | null;\n documentId: string | null;\n userId: string;\n email: string | null;\n displayName: string | null;\n role: Role;\n grantedBy: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport const grantUpdateSchema = z.object({ role: roleSchema });\nexport type GrantUpdateRequest = z.infer<typeof grantUpdateSchema>;\n\n/** `GET /me/shared` item: a project or document reached through a grant, not through a workspace membership. */\nexport interface SharedItem {\n type: 'project' | 'document';\n id: string;\n title: string;\n role: Role;\n workspaceId: string;\n /** For a document: its project. */\n projectId: string | null;\n projectName: string | null;\n sharedBy: string | null;\n grantedAt: string;\n}\n\n// ─── Share links ────────────────────────────────────────────────────────────\n\nexport const SHARE_LINK_ACCESS = ['view', 'comment'] as const;\nexport type ShareLinkAccess = (typeof SHARE_LINK_ACCESS)[number];\n/** `anyone`: the URL alone opens it at `access`. `restricted`: only people on the access list (grants/membership). */\nexport const SHARE_LINK_GENERAL_ACCESS = ['anyone', 'restricted'] as const;\nexport type ShareLinkGeneralAccess = (typeof SHARE_LINK_GENERAL_ACCESS)[number];\nexport const SHARE_LINK_TARGETS = ['project', 'document', 'snapshot'] as const;\nexport type ShareLinkTarget = (typeof SHARE_LINK_TARGETS)[number];\nexport const SHARE_LINK_TOKEN_PREFIX = 'fws_';\n/** Link session (`fls_...`) lifetime, seconds (spec 05 §5.4). */\nexport const LINK_SESSION_TTL_S = 900;\nexport const LINK_SESSION_PREFIX = 'fls_';\n\nexport const shareLinkCreateSchema = z.object({\n access: z.enum(SHARE_LINK_ACCESS),\n generalAccess: z.enum(SHARE_LINK_GENERAL_ACCESS).default('anyone'),\n expiresAt: z.iso.datetime({ offset: true }).nullable().optional(),\n password: z.string().min(1).max(200).optional(),\n allowDownload: z.boolean().default(true),\n watermarkText: z.string().max(200).nullable().optional(),\n});\nexport type ShareLinkCreateRequest = z.input<typeof shareLinkCreateSchema>;\n\nexport const shareLinkUpdateSchema = z\n .object({\n access: z.enum(SHARE_LINK_ACCESS).optional(),\n generalAccess: z.enum(SHARE_LINK_GENERAL_ACCESS).optional(),\n expiresAt: z.iso.datetime({ offset: true }).nullable().optional(),\n password: z.string().min(1).max(200).optional(),\n clearPassword: z.boolean().optional(),\n allowDownload: z.boolean().optional(),\n watermarkText: z.string().max(200).nullable().optional(),\n })\n .refine((v) => !(v.password !== undefined && v.clearPassword), {\n message: 'password and clearPassword are exclusive',\n });\nexport type ShareLinkUpdateRequest = z.infer<typeof shareLinkUpdateSchema>;\n\nexport interface ShareLink {\n id: string;\n targetType: ShareLinkTarget;\n projectId: string | null;\n documentId: string | null;\n snapshotId: string | null;\n access: ShareLinkAccess;\n generalAccess: ShareLinkGeneralAccess;\n /** Last 4 characters of the token, for the UI list. */\n tokenHint: string;\n hasPassword: boolean;\n allowDownload: boolean;\n watermarkText: string | null;\n expiresAt: string | null;\n revokedAt: string | null;\n accessCount: number;\n lastAccessedAt: string | null;\n createdBy: string | null;\n createdAt: string;\n}\n/** The full token (and so the URL) is returned once, at creation. */\nexport type ShareLinkCreated = ShareLink & { url: string; token: string };\nexport interface ShareLinkRevokeResponse {\n revokedAt: string;\n}\n\n/** `GET /public/share/:token` (no content, no auth). A restricted link hides the title. */\nexport interface PublicShareInfo {\n targetType: ShareLinkTarget;\n title: string | null;\n access: ShareLinkAccess;\n generalAccess: ShareLinkGeneralAccess;\n requiresPassword: boolean;\n /** True for a `comment` link: adding a note needs a signed-in user. */\n requiresSignInToComment: boolean;\n expiresAt: string | null;\n allowDownload: boolean;\n}\n\nexport const shareUnlockSchema = z.object({\n password: z.string().max(200).optional(),\n});\nexport type ShareUnlockRequest = z.infer<typeof shareUnlockSchema>;\n/** Also the way to obtain (and renew) a session for a password-less link. Send `linkSession` as `Authorization: Bearer` on `/share/:token/*` and as the sync `link` auth token. */\nexport interface ShareUnlockResponse {\n linkSession: string;\n expiresAt: string;\n /** What the session allows: `comment` only for a comment link opened by a signed-in user. */\n access: ShareLinkAccess;\n}\n\n// ─── Document lock ──────────────────────────────────────────────────────────\n\nexport const UNLOCK_SESSION_TTL_S = 1800;\nexport const REAUTH_MAX_AGE_S = 300;\nexport interface DocumentLockResponse {\n locked: boolean;\n}\nexport interface UnlockSession {\n sessionToken: string;\n expiresAt: string;\n}\n","import { z } from 'zod';\nimport { DOCUMENT_KINDS } from '@sudobility/writing_core';\nimport type { DocumentKind } from '@sudobility/writing_core';\nimport type { Role } from '../tenancy/index.js';\n\nexport { DOCUMENT_KINDS };\nexport type { DocumentKind };\n\nexport const documentKindSchema = z.enum(DOCUMENT_KINDS);\n\nexport const SORT_OPTIONS = ['updated', 'name', 'created'] as const;\n\n/** Spec 05 §6.26: a `series` project orders its episodes by `(season, episode)` (F-COL-006). */\nexport const PROJECT_KINDS = ['feature', 'series', 'play', 'other'] as const;\nexport type ProjectKind = (typeof PROJECT_KINDS)[number];\nexport const projectKindSchema = z.enum(PROJECT_KINDS);\n\n/** Document labels (F-COL-006): at most 20 per document, each 1-40 characters. */\nexport const DOCUMENT_LABELS_MAX = 20;\nexport const DOCUMENT_LABEL_MAX_CHARS = 40;\nexport const documentLabelsSchema = z\n .array(z.string().trim().min(1).max(DOCUMENT_LABEL_MAX_CHARS))\n .max(DOCUMENT_LABELS_MAX);\n\n// ─── Projects (spec 05 §6.6) ────────────────────────────────────────────────\n\nexport interface ProjectSummary {\n id: string;\n workspaceId: string;\n name: string;\n description: string | null;\n color: string | null;\n coverAssetId: string | null;\n kind: ProjectKind;\n logline: string | null;\n documentCount: number;\n createdAt: string;\n updatedAt: string;\n trashedAt: string | null;\n}\n\nexport interface DocumentMeta {\n id: string;\n projectId: string;\n workspaceId: string;\n folderId: string | null;\n kind: DocumentKind;\n title: string;\n logline: string | null;\n color: string | null;\n labels: string[];\n /** Series projects: episodes order by `(season, episode)`. */\n season: number | null;\n episode: number | null;\n position: number;\n language: string;\n templateId: string | null;\n templateVersion: number | null;\n epoch: number;\n excludeFromAi: boolean;\n locked: boolean;\n pageCount: number;\n sceneCount: number;\n wordCount: number;\n parentSnapshotId: string | null;\n createdBy: string | null;\n createdAt: string;\n updatedAt: string;\n lastEditedAt: string | null;\n trashedAt: string | null;\n}\n\nexport interface ProjectFolder {\n id: string;\n projectId: string;\n parentFolderId: string | null;\n name: string;\n position: number;\n}\n\n/** `GET /projects/:pid` */\nexport interface Project extends ProjectSummary {\n role: Role;\n folders: ProjectFolder[];\n documents: DocumentMeta[];\n}\n\nexport const projectCreateSchema = z.object({\n name: z.string().trim().min(1).max(200),\n description: z.string().max(2000).optional(),\n coverAssetId: z.string().optional(),\n color: z.string().max(32).optional(),\n kind: projectKindSchema.optional(),\n logline: z.string().max(2000).optional(),\n});\nexport type ProjectCreateRequest = z.infer<typeof projectCreateSchema>;\n\nexport const projectUpdateSchema = z.object({\n name: z.string().trim().min(1).max(200).optional(),\n description: z.string().max(2000).nullable().optional(),\n coverAssetId: z.string().nullable().optional(),\n color: z.string().max(32).nullable().optional(),\n kind: projectKindSchema.optional(),\n logline: z.string().max(2000).nullable().optional(),\n workspaceId: z.string().optional(),\n});\nexport type ProjectUpdateRequest = z.infer<typeof projectUpdateSchema>;\n\nexport const projectListQuerySchema = z.object({\n trashed: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n q: z.string().optional(),\n sort: z.enum(SORT_OPTIONS).optional(),\n});\nexport type ProjectListQuery = z.infer<typeof projectListQuerySchema>;\n\n// ─── Documents (spec 05 §6.7) ───────────────────────────────────────────────\n\nexport const documentCreateSchema = z.object({\n /** Client-generated `doc_...`; creation is idempotent on it. */\n id: z.string().startsWith('doc_').optional(),\n title: z.string().trim().min(1).max(200),\n kind: documentKindSchema,\n folderId: z.string().optional(),\n templateId: z.string().optional(),\n templateVersion: z.number().int().positive().optional(),\n language: z.string().max(16).optional(),\n labels: documentLabelsSchema.optional(),\n season: z.number().int().min(0).max(9999).optional(),\n episode: z.number().int().min(0).max(99999).optional(),\n});\nexport type DocumentCreateRequest = z.infer<typeof documentCreateSchema>;\n\nexport const documentUpdateSchema = z.object({\n title: z.string().trim().min(1).max(200).optional(),\n folderId: z.string().nullable().optional(),\n position: z.number().optional(),\n color: z.string().max(32).nullable().optional(),\n language: z.string().max(16).optional(),\n logline: z.string().max(2000).nullable().optional(),\n excludeFromAi: z.boolean().optional(),\n labels: documentLabelsSchema.optional(),\n season: z.number().int().min(0).max(9999).nullable().optional(),\n episode: z.number().int().min(0).max(99999).nullable().optional(),\n});\nexport type DocumentUpdateRequest = z.infer<typeof documentUpdateSchema>;\n\nexport const documentListQuerySchema = z.object({\n trashed: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n folderId: z.string().optional(),\n kind: documentKindSchema.optional(),\n /** `episode` = `(season, episode)` with unnumbered documents last; the default for a `series` project. */\n order: z.enum(['position', 'episode']).optional(),\n});\nexport type DocumentListQuery = z.infer<typeof documentListQuerySchema>;\n\n/** Style row in `DocumentDetail.template` (`code` = shortcut digit, `enter`/`tab` = next style ids). */\nexport interface DocumentTemplateStyle {\n id: string;\n name: string;\n code: number | null;\n enter: string | null;\n tab: string | null;\n}\n\nexport interface DocumentTemplateInfo {\n id: string;\n version: number;\n name: string;\n layoutMode: 'flow' | 'panels';\n styles: DocumentTemplateStyle[];\n}\n\n/** `GET /documents/:did` (metadata plus live-state facts, no content). */\nexport interface DocumentDetail extends DocumentMeta {\n role: Role;\n schemaVersion: number;\n template: DocumentTemplateInfo | null;\n}\n\n// ─── Trash ──────────────────────────────────────────────────────────────────\n\nexport interface TrashResult {\n trashedAt: string;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\nimport { documentKindSchema } from '../projects/index.js';\nimport type { Job } from '../jobs/index.js';\n\n/**\n * Project, document and template lifecycle, workspace settings (slice B14; spec 05 §6.2, §6.6, §6.7, §6.26).\n * Folders, move / duplicate / purge / apply template, the workspace documents list and trash, the Shared Bin, the workspace\n * defaults and the batch-watermark contacts. Template CRUD types live in `templates/`.\n */\n\n/** Trashed items are purged (`system.purge`) this many days after they were trashed (spec 05 §17). */\nexport const TRASH_RETENTION_DAYS = 30;\n\nexport interface PurgeScheduledResponse {\n purgeScheduled: true;\n}\n\n// ─── project folders (`pfd_`, §6.6) ───────────────────────────────────────────\n\n/** A folder may sit at most this deep (`FOLDER_DEPTH`): the root's children are depth 1. */\nexport const FOLDER_MAX_DEPTH = 8;\n\nexport const projectFolderCreateSchema = z.object({\n name: z.string().trim().min(1).max(120),\n parentFolderId: z.string().min(1).optional(),\n});\nexport type ProjectFolderCreateRequest = z.infer<\n typeof projectFolderCreateSchema\n>;\n\nexport const projectFolderUpdateSchema = z.object({\n name: z.string().trim().min(1).max(120).optional(),\n /** `null` moves the folder to the project root. */\n parentFolderId: z.string().min(1).nullable().optional(),\n position: z.number().finite().optional(),\n});\nexport type ProjectFolderUpdateRequest = z.infer<\n typeof projectFolderUpdateSchema\n>;\n\n/** `DELETE /project-folders/:fid?moveContentsTo=<fid>|root`; without it the contents move up to the folder's own parent. */\nexport const projectFolderDeleteQuerySchema = z.object({\n moveContentsTo: z.string().min(1).optional(),\n});\nexport type ProjectFolderDeleteQuery = z.infer<\n typeof projectFolderDeleteQuerySchema\n>;\n\nexport interface ProjectFolderDeleteResponse {\n deleted: true;\n}\n\n// ─── projects: purge and duplicate ────────────────────────────────────────────\n\nexport const projectPurgeSchema = z.object({ confirmName: z.string() });\nexport type ProjectPurgeRequest = z.infer<typeof projectPurgeSchema>;\n\nexport const projectDuplicateSchema = z.object({\n name: z.string().trim().min(1).max(200),\n targetWorkspaceId: z.string().min(1).optional(),\n includeSnapshots: z.boolean().default(false),\n /** Re-links the source's asset links onto the copy (B11); a no-op when the target is a different workspace. */\n includeAssets: z.boolean().default(false),\n});\nexport type ProjectDuplicateRequest = z.input<typeof projectDuplicateSchema>;\n\n/** `job.result` of a finished `project.duplicate` job. */\nexport interface ProjectDuplicateResult {\n projectId: string;\n documents: number;\n snapshots: number;\n /** Documents that were not copied: a locked document needs a re-authentication a job cannot give. */\n skipped: { documentId: string; reason: 'locked' }[];\n}\n\n// ─── documents: move, duplicate, apply template ───────────────────────────────\n\nexport const documentMoveSchema = z.object({\n targetProjectId: z.string().min(1),\n folderId: z.string().min(1).nullable().optional(),\n});\nexport type DocumentMoveRequest = z.infer<typeof documentMoveSchema>;\n\nexport const documentDuplicateSchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().min(1).optional(),\n includeSnapshots: z.boolean().default(false),\n includeAssets: z.boolean().default(false),\n});\nexport type DocumentDuplicateRequest = z.input<typeof documentDuplicateSchema>;\n\n/** `POST /documents/:did/template`. `templateVersion` defaults to the template's latest. */\nexport const documentApplyTemplateSchema = z.object({\n templateId: z.string().min(1),\n templateVersion: z.number().int().min(1).optional(),\n /** Old style id -> style id of the new template, for styles the new template has no counterpart of. */\n mapping: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type DocumentApplyTemplateRequest = z.infer<\n typeof documentApplyTemplateSchema\n>;\n\nexport interface ApplyTemplateDryRunResponse {\n /** Style ids used by elements that have no counterpart (same id, same role or explicit `mapping`) in the new template. */\n unmappedStyles: string[];\n /** Pages of the document after minus before. */\n pageDelta: number;\n}\nexport type ApplyTemplateResponse = Job | ApplyTemplateDryRunResponse;\n\n/** `job.result` of a finished `doc.applyTemplate` job. */\nexport interface ApplyTemplateResult {\n templateId: string;\n templateVersion: number;\n remapped: number;\n preTemplateSnapshotId: string;\n}\n\n// ─── workspace documents and trash ────────────────────────────────────────────\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\n\n/** `GET /workspaces/:wid/documents`: across every project; `starred` is the caller's own stars (`document_stars`). */\nexport const workspaceDocumentsQuerySchema = cursorQuerySchema.extend({\n q: z.string().max(200).optional(),\n kind: documentKindSchema.optional(),\n trashed: boolQuery.optional(),\n starred: boolQuery.optional(),\n label: z.string().max(40).optional(),\n});\nexport type WorkspaceDocumentsQuery = z.output<\n typeof workspaceDocumentsQuerySchema\n>;\n\nexport const TRASH_ITEM_TYPES = ['project', 'document', 'asset'] as const;\nexport type TrashItemType = (typeof TRASH_ITEM_TYPES)[number];\n\n/** `GET /workspaces/:wid/trash`. A document trashed together with its project is not listed on its own (restore the project). */\nexport interface TrashItem {\n type: TrashItemType;\n id: string;\n title: string;\n /** A document's project, for the \"in <project>\" line. */\n projectId: string | null;\n trashedAt: string;\n trashedBy: string | null;\n /** `trashedAt` + `TRASH_RETENTION_DAYS`. */\n purgeAt: string;\n}\n\n/** `confirm` must be `EMPTY`: anything else is the server's `CONFIRMATION_MISMATCH`, not a schema error. */\nexport const trashEmptySchema = z.object({ confirm: z.string() });\nexport type TrashEmptyRequest = z.infer<typeof trashEmptySchema>;\n\n/** The `system.purge` job's input (also what a purge job row shows in its `requestSummary`). */\nexport const purgeInputSchema = z.object({\n workspaceId: z.string().optional(),\n projectId: z.string().optional(),\n documentId: z.string().optional(),\n});\nexport type PurgeInput = z.infer<typeof purgeInputSchema>;\nexport interface PurgeResult {\n projects: number;\n documents: number;\n}\n\n// ─── Shared Bin (`bin_`, §6.26) ───────────────────────────────────────────────\n\n/** Serialised size cap of one snippet (`LIMIT_EXCEEDED`). */\nexport const PROJECT_BIN_ITEM_MAX_BYTES = 2 * 1024 * 1024;\n\nexport interface ProjectBinItem {\n id: string;\n projectId: string;\n title: string;\n /** Frozen `ElementJSON[]`: notes and tags are stripped. */\n elements: Record<string, unknown>[];\n sourceDocumentId: string | null;\n createdBy: string | null;\n createdAt: string;\n}\n\nexport const projectBinCreateSchema = z.object({\n id: z.string().startsWith('bin_').optional(),\n title: z.string().trim().min(1).max(200).optional(),\n elements: z.array(z.record(z.string(), z.unknown())).min(1),\n sourceDocumentId: z.string().min(1).optional(),\n});\nexport type ProjectBinCreateRequest = z.input<typeof projectBinCreateSchema>;\n\nexport interface ProjectBinDeleteResponse {\n deleted: true;\n}\n\n// ─── workspace defaults (§6.26) ───────────────────────────────────────────────\n\nexport const DEFAULT_PROJECT_ROLES = [\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n] as const;\nexport type DefaultProjectRole = (typeof DEFAULT_PROJECT_ROLES)[number];\n\nconst looseItems = (max: number) => z.array(z.looseObject({})).max(max);\n\n/**\n * What *New document* copies into a document of the workspace (then the two diverge, spec 01 §5.4) and *Save as workspace\n * worksheet* writes to. The lists are open objects owned by spec 09 features.\n */\nexport const workspaceDefaultsSchema = z.object({\n tagCategories: looseItems(200).default([]),\n revisionColourSets: looseItems(100).default([]),\n noteTypes: looseItems(100).default([]),\n worksheets: looseItems(200).default([]),\n /** The role newly created projects grant workspace members who have none (F-SET-009). */\n defaultProjectRole: z.enum(DEFAULT_PROJECT_ROLES).nullable().default(null),\n});\nexport type WorkspaceDefaultsInput = z.input<typeof workspaceDefaultsSchema>;\nexport type WorkspaceDefaultsDoc = z.output<typeof workspaceDefaultsSchema>;\nexport interface WorkspaceDefaults extends WorkspaceDefaultsDoc {\n updatedAt: string;\n}\n/** Serialised size cap of the defaults document (`LIMIT_EXCEEDED`). */\nexport const WORKSPACE_DEFAULTS_MAX_BYTES = 256 * 1024;\n\nexport const workspaceDefaultsPutSchema = workspaceDefaultsSchema.extend({\n baseUpdatedAt: z.string().min(1),\n});\nexport type WorkspaceDefaultsPutRequest = z.input<\n typeof workspaceDefaultsPutSchema\n>;\nexport interface WorkspaceDefaultsPutResponse {\n updatedAt: string;\n}\n\n// ─── contacts (`ctc_`, §6.26) ─────────────────────────────────────────────────\n\nexport const WORKSPACE_CONTACTS_BATCH_MAX = 500;\n\nexport interface WorkspaceContact {\n id: string;\n name: string;\n company: string | null;\n email: string | null;\n}\n\nconst contactFields = {\n name: z.string().trim().min(1).max(200),\n company: z.string().trim().max(200).nullable().optional(),\n email: z.string().trim().max(320).nullable().optional(),\n};\nexport const workspaceContactInputSchema = z.object({\n id: z.string().startsWith('ctc_').optional(),\n ...contactFields,\n});\n/** More than `WORKSPACE_CONTACTS_BATCH_MAX` entries is the server's `LIMIT_EXCEEDED`, not a schema error. */\nexport const workspaceContactsCreateSchema = z.object({\n contacts: z.array(workspaceContactInputSchema).min(1),\n});\nexport type WorkspaceContactsCreateRequest = z.input<\n typeof workspaceContactsCreateSchema\n>;\nexport const workspaceContactPatchSchema = z.object({\n name: contactFields.name.optional(),\n company: contactFields.company,\n email: contactFields.email,\n});\nexport type WorkspaceContactPatchRequest = z.infer<\n typeof workspaceContactPatchSchema\n>;\nexport const workspaceContactsQuerySchema = cursorQuerySchema.extend({\n q: z.string().max(200).optional(),\n});\nexport type WorkspaceContactsQuery = z.output<\n typeof workspaceContactsQuerySchema\n>;\nexport interface WorkspaceContactDeleteResponse {\n deleted: true;\n}\n\n// ─── job inputs (`project.duplicate`, `doc.applyTemplate`, `template.thumbnail`; `system.purge` is `purgeInputSchema`) ───\n\nexport const projectDuplicateJobInputSchema = z.object({\n projectId: z.string().min(1),\n name: z.string().min(1),\n targetWorkspaceId: z.string().min(1),\n includeSnapshots: z.boolean(),\n includeAssets: z.boolean(),\n});\nexport type ProjectDuplicateJobInput = z.infer<\n typeof projectDuplicateJobInputSchema\n>;\n\nexport const applyTemplateJobInputSchema = z.object({\n templateId: z.string().min(1),\n templateVersion: z.number().int().min(1),\n mapping: z.record(z.string(), z.string()).optional(),\n});\nexport type ApplyTemplateJobInput = z.infer<typeof applyTemplateJobInputSchema>;\n\nexport const templateThumbnailInputSchema = z.object({\n templateId: z.string().min(1),\n version: z.number().int().min(1),\n});\nexport type TemplateThumbnailInput = z.infer<\n typeof templateThumbnailInputSchema\n>;\n","import { z } from 'zod';\n\nexport const UI_LANGUAGES = [\n 'en',\n 'es',\n 'fr',\n 'de',\n 'pt',\n 'it',\n 'ja',\n 'zh',\n] as const;\nexport type UiLanguage = (typeof UI_LANGUAGES)[number];\n\n/** `GET /me` (spec 05 §6.1). */\nexport interface Me {\n userId: string;\n email: string | null;\n displayName: string | null;\n avatarUrl: string | null;\n locale: string;\n uiLanguage: string;\n timeZone: string;\n siteAdmin: boolean;\n personalWorkspaceId: string;\n createdAt: string;\n /** Set while an account deletion is scheduled (`DELETE /me`); `POST /me/restore` clears it. */\n deletionScheduledFor?: string | null;\n}\n\nexport const meUpdateSchema = z.object({\n displayName: z.string().trim().min(1).max(120).optional(),\n avatarAssetId: z.string().nullable().optional(),\n locale: z.string().min(2).max(35).optional(),\n uiLanguage: z.enum(UI_LANGUAGES).optional(),\n timeZone: z.string().min(1).max(64).optional(),\n});\nexport type MeUpdateRequest = z.infer<typeof meUpdateSchema>;\n","import { z } from 'zod';\n\n/**\n * Account and per-user data (slice B13; spec 05 §6.1, §6.1.1, §6.26, §8.1, §17).\n * Everything here belongs to one user: preferences, spelling dictionary, macros, writing sessions, stats, goals, the\n * per-document view state (`my-state`) and stars. All are user-only routes (an API key gets 403 `API_KEY_FORBIDDEN`),\n * except the macro list, which a key may read.\n */\n\n// ─── user preferences (§6.1.1) ────────────────────────────────────────────────\n\nexport const USER_PREFERENCES_VERSION = 1;\n/** Serialised size cap of `PUT /me/preferences` (`LIMIT_EXCEEDED`). */\nexport const USER_PREFERENCES_MAX_BYTES = 256 * 1024;\nexport const AUTOCORRECT_MAX_PAIRS = 5000;\nexport const RECENT_SEARCHES_MAX = 20;\n\nexport const DEVICE_CLASSES = ['phone', 'tablet', 'desktop'] as const;\nexport type DeviceClass = (typeof DEVICE_CLASSES)[number];\n\n/** A section is an open object: its keys are owned by spec 09/10 features and grow without a types release. */\nconst section = z.looseObject({});\n\nconst appearanceSchema = z.looseObject({\n theme: z.enum(['system', 'light', 'dark']).optional(),\n pageTheme: z\n .enum(['paper', 'night', 'midnight', 'sepia', 'custom'])\n .optional(),\n custom: section.optional(),\n density: z.string().max(40).optional(),\n largeIcons: z.boolean().optional(),\n reducedMotion: z.boolean().optional(),\n});\n\nconst keymapSchema = z.looseObject({\n preset: z.enum(['fadewright', 'finalDraft', 'fadeIn']).optional(),\n overrides: z.record(z.string(), z.string().nullable()).optional(),\n byPlatform: section.optional(),\n});\n\nconst autocorrectSchema = z.looseObject({\n options: section.optional(),\n pairs: z\n .array(\n z.object({ from: z.string().min(1).max(200), to: z.string().max(200) })\n )\n .max(AUTOCORRECT_MAX_PAIRS)\n .optional(),\n});\n\nconst languageSchema = z.looseObject({\n scriptDefault: z.string().max(35).optional(),\n installedDictionaries: z.array(z.string().max(35)).max(50).optional(),\n ignoreLists: section.optional(),\n lookups: z\n .array(z.object({ label: z.string().max(80), url: z.string().max(500) }))\n .max(50)\n .optional(),\n});\n\nconst tableReadSchema = z.looseObject({\n narratorVoiceByLanguage: z.record(z.string(), section).optional(),\n rate: z.number().optional(),\n actors: z\n .array(z.looseObject({ id: z.string(), name: z.string() }))\n .max(200)\n .optional(),\n});\n\n/**\n * `UserPreferences`: one JSON document per user, closed at the top level (an unknown top-level key is `VALIDATION`),\n * open inside each section. `version` is `USER_PREFERENCES_VERSION`; a higher version from a newer client is stored as is.\n */\nexport const userPreferencesSchema = z.strictObject({\n version: z.number().int().min(1).max(1000).default(USER_PREFERENCES_VERSION),\n appearance: appearanceSchema.optional(),\n editor: section.optional(),\n deviceClasses: z\n .strictObject({\n phone: section.optional(),\n tablet: section.optional(),\n desktop: section.optional(),\n })\n .optional(),\n keymap: keymapSchema.optional(),\n autocorrect: autocorrectSchema.optional(),\n language: languageSchema.optional(),\n tableRead: tableReadSchema.optional(),\n toolbar: section.optional(),\n recentSearches: z\n .array(z.string().max(500))\n .max(RECENT_SEARCHES_MAX)\n .optional(),\n revisionColourSets: z.array(section).max(100).optional(),\n offline: section.optional(),\n});\nexport type UserPreferences = z.output<typeof userPreferencesSchema>;\nexport type UserPreferencesInput = z.input<typeof userPreferencesSchema>;\nexport const USER_PREFERENCES_KEYS = [\n 'version',\n 'appearance',\n 'editor',\n 'deviceClasses',\n 'keymap',\n 'autocorrect',\n 'language',\n 'tableRead',\n 'toolbar',\n 'recentSearches',\n 'revisionColourSets',\n 'offline',\n] as const;\n\n/** `GET /me/preferences` (and `details.current` of a `STALE_WRITE`): the document plus its optimistic-concurrency token. */\nexport type UserPreferencesResponse = UserPreferences & { updatedAt: string };\n\n/** `PUT /me/preferences`: a whole-document replace; `baseUpdatedAt` is the `updatedAt` of the last GET/PUT. */\nexport const userPreferencesPutSchema = userPreferencesSchema.extend({\n baseUpdatedAt: z.string().min(1).max(40),\n});\nexport type UserPreferencesPutRequest = z.input<\n typeof userPreferencesPutSchema\n>;\nexport interface UserPreferencesPutResponse {\n updatedAt: string;\n}\n\n// ─── dictionary ───────────────────────────────────────────────────────────────\n\nexport const DICTIONARY_MAX_WORDS = 50_000;\nconst dictionaryWord = z.string().trim().min(1).max(100);\nexport const dictionaryUpdateSchema = z.object({\n add: z.array(dictionaryWord).max(5000).optional(),\n remove: z.array(dictionaryWord).max(5000).optional(),\n});\nexport type DictionaryUpdateRequest = z.infer<typeof dictionaryUpdateSchema>;\nexport interface DictionaryResponse {\n words: string[];\n}\nexport interface DictionaryUpdateResponse {\n count: number;\n}\n\n// ─── macros ───────────────────────────────────────────────────────────────────\n\nexport const USER_MACRO_MAX = 500;\nexport const MACRO_TRIGGER_KINDS = ['shortcut', 'alias'] as const;\n\nconst macroOptionFields = {\n smartReplace: z.boolean(),\n confirm: z.boolean(),\n wordOnly: z.boolean(),\n matchCase: z.boolean(),\n activeInStyles: z.array(z.string().max(80)).max(100),\n};\n/** Create: every option defaulted. */\nconst macroOptionsSchema = z.object({\n smartReplace: macroOptionFields.smartReplace.default(false),\n confirm: macroOptionFields.confirm.default(false),\n wordOnly: macroOptionFields.wordOnly.default(true),\n matchCase: macroOptionFields.matchCase.default(false),\n activeInStyles: macroOptionFields.activeInStyles.default([]),\n});\n/** Patch: no defaults (a default would overwrite the stored value of an option the request did not mention). */\nconst macroOptionsPatchSchema = z.object(macroOptionFields).partial();\n\nexport const userMacroSchema = z.object({\n name: z.string().trim().min(1).max(120),\n trigger: z.object({\n kind: z.enum(MACRO_TRIGGER_KINDS),\n value: z.string().trim().min(1).max(80),\n }),\n insertText: z.string().max(10_000),\n setElementStyle: z.string().max(80).nullable().optional(),\n nextElementStyle: z.string().max(80).nullable().optional(),\n options: macroOptionsSchema.prefault({}),\n});\nexport type UserMacroCreateRequest = z.input<typeof userMacroSchema>;\n\n/** `PATCH /me/macros/:mid`: any subset; `options` and `trigger` merge into the stored ones. */\nexport const userMacroPatchSchema = z.object({\n name: userMacroSchema.shape.name.optional(),\n trigger: z\n .object({\n kind: z.enum(MACRO_TRIGGER_KINDS).optional(),\n value: userMacroSchema.shape.trigger.shape.value.optional(),\n })\n .optional(),\n insertText: userMacroSchema.shape.insertText.optional(),\n setElementStyle: userMacroSchema.shape.setElementStyle,\n nextElementStyle: userMacroSchema.shape.nextElementStyle,\n options: macroOptionsPatchSchema.optional(),\n});\nexport type UserMacroPatchRequest = z.input<typeof userMacroPatchSchema>;\n\nexport interface UserMacro {\n id: string;\n name: string;\n trigger: { kind: (typeof MACRO_TRIGGER_KINDS)[number]; value: string };\n insertText: string;\n setElementStyle: string | null;\n nextElementStyle: string | null;\n options: z.output<typeof macroOptionsSchema>;\n createdAt: string;\n updatedAt: string;\n}\nexport interface DeleteResponse {\n deleted: true;\n}\n\n// ─── writing sessions, stats, goals ───────────────────────────────────────────\n\nexport const WRITING_GOAL_KINDS = [\n 'wordsPerDay',\n 'pagesPerDay',\n 'minutesPerDay',\n 'wordsPerWeek',\n 'documentTarget',\n] as const;\nexport type WritingGoalKind = (typeof WRITING_GOAL_KINDS)[number];\nexport const WRITING_GOALS_MAX = 50;\nexport const WRITING_STATS_GRANULARITIES = [\n 'day',\n 'week',\n 'month',\n 'year',\n] as const;\nexport type WritingStatsGranularity =\n (typeof WRITING_STATS_GRANULARITIES)[number];\n\nconst isoInstant = z.iso.datetime({ offset: true });\n\n/**\n * `POST /me/writing-sessions`. `clientSessionId` is the row id (`wss_...`, made by the client) and makes the upload\n * idempotent: a repeat is accepted and changes nothing, so a device may retry and may upload offline sessions later.\n */\nexport const writingSessionSchema = z\n .object({\n clientSessionId: z\n .string()\n .min(8)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/),\n documentId: z.string().min(1).max(100).nullable().optional(),\n startedAt: isoInstant,\n endedAt: isoInstant,\n activeSeconds: z.number().int().min(0).max(86_400),\n wordsAdded: z.number().int().min(0).max(1_000_000),\n wordsRemoved: z.number().int().min(0).max(1_000_000),\n netPagesEighths: z.number().int().min(-100_000).max(100_000),\n sprint: z\n .object({\n targetWords: z.number().int().min(1).max(1_000_000).optional(),\n targetMinutes: z.number().int().min(1).max(1440).optional(),\n })\n .optional(),\n })\n .refine((s) => Date.parse(s.endedAt) >= Date.parse(s.startedAt), {\n message: 'endedAt is before startedAt',\n path: ['endedAt'],\n });\nexport type WritingSessionRequest = z.input<typeof writingSessionSchema>;\nexport interface WritingSessionResponse {\n accepted: true;\n}\n\nconst localDate = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\n/** `GET /me/writing-stats`: dates are calendar days in the user's time zone (`users.time_zone`). Defaults: the last 30 days by day. */\nexport const writingStatsQuerySchema = z.object({\n from: localDate.optional(),\n to: localDate.optional(),\n granularity: z.enum(WRITING_STATS_GRANULARITIES).default('day'),\n documentId: z.string().min(1).max(100).optional(),\n});\nexport type WritingStatsQuery = z.input<typeof writingStatsQuerySchema>;\n\nexport interface WritingStatsBucket {\n /** `YYYY-MM-DD`: the first day of the day/week (Monday)/month/year, in the user's time zone. */\n start: string;\n wordsAdded: number;\n wordsRemoved: number;\n /** `netPagesEighths / 8`. */\n netPages: number;\n activeSeconds: number;\n}\n/** A day counts when the user added words on it (over all documents, in their time zone). Today does not break a streak until it ends. */\nexport interface StreakSummary {\n current: number;\n longest: number;\n /** `YYYY-MM-DD` of the latest day with words, or null. */\n lastActiveDate: string | null;\n activeToday: boolean;\n}\nexport interface WritingStats {\n buckets: WritingStatsBucket[];\n streak: StreakSummary;\n}\n\nexport const writingGoalInputSchema = z\n .object({\n id: z\n .string()\n .min(4)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n kind: z.enum(WRITING_GOAL_KINDS),\n documentId: z.string().min(1).max(100).nullable().optional(),\n target: z.number().int().min(1).max(10_000_000),\n daysOfWeek: z.array(z.number().int().min(0).max(6)).max(7).optional(),\n idleTimeoutSec: z.number().int().min(5).max(3600).optional(),\n })\n .refine((g) => g.kind !== 'documentTarget' || !!g.documentId, {\n message: 'documentTarget needs documentId',\n path: ['documentId'],\n });\n/** `PUT /me/writing-goals`: the whole list. A goal missing from it is deleted; one without `id` is created. `daysOfWeek`: 0 = Sunday. */\n/** No `.max` here on purpose: more than `WRITING_GOALS_MAX` is 409 `LIMIT_EXCEEDED` from the server, not `VALIDATION`. */\nexport const writingGoalsPutSchema = z.object({\n goals: z.array(writingGoalInputSchema),\n});\nexport type WritingGoalsPutRequest = z.input<typeof writingGoalsPutSchema>;\nexport interface WritingGoal {\n id: string;\n kind: WritingGoalKind;\n documentId: string | null;\n target: number;\n daysOfWeek: number[] | null;\n idleTimeoutSec: number | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─── export, delete, restore ──────────────────────────────────────────────────\n\nexport const ACCOUNT_DELETE_CONFIRM = 'DELETE';\nexport const accountDeleteSchema = z.object({\n confirm: z.literal(ACCOUNT_DELETE_CONFIRM),\n});\nexport type AccountDeleteRequest = z.infer<typeof accountDeleteSchema>;\nexport interface AccountDeleteResponse {\n deletionScheduledFor: string;\n}\nexport interface AccountRestoreResponse {\n restored: true;\n}\n/** `account.export` job input: none. The output is `fadewright-export.zip`. */\nexport const accountExportInputSchema = z.object({}).default({});\nexport const ACCOUNT_EXPORT_FILENAME = 'fadewright-export.zip';\n\n// ─── per-user document state and stars (§6.26) ────────────────────────────────\n\nexport const DOCUMENT_VIEW_STATE_MAX_BYTES = 64 * 1024;\n\nconst deviceViewSchema = z.looseObject({\n view: z.string().max(40).optional(),\n zoom: z.number().optional(),\n invisibles: z.boolean().optional(),\n ruler: z.boolean().optional(),\n});\n\n/**\n * Cross-device view state of one document for one user: Navigator tabs and columns, split layout, view mode and zoom per\n * device class. Caret, selection, undo history and the Beat Board viewport stay device-local. Every key optional: the\n * client merges per top-level key.\n */\nexport const documentViewStateSchema = z.strictObject({\n navigator: z\n .looseObject({\n tabs: z.array(z.looseObject({})).max(50).optional(),\n activeTab: z.string().max(80).nullable().optional(),\n })\n .optional(),\n layout: z\n .looseObject({\n split: z.union([z.string().max(40), z.number(), z.null()]).optional(),\n panes: z.array(z.unknown()).max(20).optional(),\n })\n .optional(),\n views: z\n .strictObject({\n phone: deviceViewSchema.optional(),\n tablet: deviceViewSchema.optional(),\n desktop: deviceViewSchema.optional(),\n })\n .optional(),\n});\nexport type DocumentViewState = z.output<typeof documentViewStateSchema>;\n\n/** `GET /documents/:did/my-state`: `{}` until first saved, then the state plus `updatedAt`. */\nexport type DocumentViewStateResponse = DocumentViewState & {\n updatedAt?: string;\n};\n\n/** `PUT`: the whole state; `baseUpdatedAt` is the `updatedAt` last read (null or absent when the GET returned `{}`). */\nexport const documentViewStatePutSchema = documentViewStateSchema.extend({\n baseUpdatedAt: z.string().min(1).max(40).nullable().optional(),\n});\nexport type DocumentViewStatePutRequest = z.input<\n typeof documentViewStatePutSchema\n>;\nexport interface DocumentViewStatePutResponse {\n updatedAt: string;\n}\n\nexport interface StarResponse {\n starred: boolean;\n}\n","import { z } from 'zod';\nimport type { TemplateCategory, TemplateJSON } from '@sudobility/writing_core';\n\nexport type TemplateScope = 'builtin' | 'user' | 'workspace';\n\n/** `GET /templates` item (spec 05 §6.8). The full body is writing_core's Template. */\nexport interface TemplateSummary {\n id: string;\n scope: TemplateScope;\n builtinKey: string | null;\n /** Set for `workspace` templates. */\n workspaceId: string | null;\n name: string;\n description: string | null;\n category: TemplateCategory;\n latestVersion: number;\n /** A first-page thumbnail was rendered (`template.thumbnail` job). Built-ins use static assets, so this is false for them. */\n hasThumbnail: boolean;\n /**\n * BCP-47 (writing_core's `TemplateJSON.locale`), set only for `scope: 'builtin'` — the catalogue's language\n * variants (screenplay-standard, tv-one-hour, ...) each carry one. `user`/`workspace` templates have no locale\n * concept (they're the caller's own authored content, not language variants of a catalog) and never set this.\n */\n locale?: string;\n}\n\n/** `GET /templates` query: user templates always; `workspaceId` adds that workspace's; `scope` narrows.\n * `locale` filters built-ins to one BCP-47 language (e.g. the app's current UI language); user/workspace templates\n * are never filtered by it, since they have no locale of their own. */\nexport const templateListQuerySchema = z.object({\n category: z.string().optional(),\n workspaceId: z.string().optional(),\n scope: z.enum(['builtin', 'user', 'workspace']).optional(),\n locale: z.string().optional(),\n});\nexport type TemplateListQuery = z.infer<typeof templateListQuerySchema>;\n\n/** `GET /templates/:tid?version=`: an older version of a user/workspace template (immutable). */\nexport const templateGetQuerySchema = z.object({\n version: z.coerce.number().int().min(1).optional(),\n});\n\n// ─── B14: template lifecycle (spec 05 §6.8) ─────────────────────────────────\n\n/** The body is validated server-side with writing_core's `TemplateJSON` schema (`TEMPLATE_INVALID` with the issues). */\nconst templateBody = z.custom<TemplateJSON>(\n (v) => typeof v === 'object' && v !== null && !Array.isArray(v),\n {\n message: 'template must be an object',\n }\n);\n\nexport const templateCreateSchema = z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n template: templateBody,\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n });\nexport type TemplateCreateRequest = z.input<typeof templateCreateSchema>;\n\nexport const templateVersionCreateSchema = z.object({ template: templateBody });\nexport type TemplateVersionCreateRequest = z.input<\n typeof templateVersionCreateSchema\n>;\n\nexport const templateUpdateSchema = z.object({\n name: z.string().trim().min(1).max(120).optional(),\n description: z.string().max(2000).nullable().optional(),\n category: z.string().min(1).max(40).optional(),\n});\nexport type TemplateUpdateRequest = z.infer<typeof templateUpdateSchema>;\n\nexport interface TemplateArchiveResponse {\n archived: true;\n}\n\n/** Template file formats: ViaInk's own JSON and the two foreign ones spec 04 §4.3 names. */\nexport const TEMPLATE_FILE_FORMATS = [\n 'fwtemplate',\n 'fadein-template',\n 'fdxt',\n] as const;\nexport type TemplateFileFormat = (typeof TEMPLATE_FILE_FORMATS)[number];\n/** `{ \"format\": \"fadewright-template\", \"formatVersion\": 1, \"template\": <TemplateJSON> }` (spec 04 §4.3.1). */\nexport const FWTEMPLATE_FORMAT = 'fadewright-template';\nexport const FWTEMPLATE_FORMAT_VERSION = 1;\n\n/**\n * `POST /templates/import`. Spec 05's `importId` flow is `templateImportByIdSchema` (B16); this body form (the file inline, like\n * `documents/import`) keeps working. The result is the created template.\n */\nexport const templateImportSchema = z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n filename: z.string().min(1).max(255),\n contentB64: z.string().min(1),\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n });\nexport type TemplateImportRequest = z.input<typeof templateImportSchema>;\n\n/**\n * The upload flow (B16): `POST /imports {templateTarget, filename, sizeBytes, sha256Hex}`, PUT the file, then\n * `POST /templates/import {importId}`. Scope and workspace come from the upload, never from this request.\n */\nexport const templateImportByIdSchema = z.object({\n importId: z.string().min(1),\n});\nexport type TemplateImportByIdRequest = z.infer<\n typeof templateImportByIdSchema\n>;\n\n/** `GET /templates/:tid/export?format=` (only `fwtemplate` is built). */\nexport const templateExportQuerySchema = z.object({\n format: z\n .enum(['fwtemplate', 'json', 'fadein-template', 'fdxt'])\n .default('fwtemplate'),\n version: z.coerce.number().int().min(1).optional(),\n});\nexport type TemplateExportQuery = z.infer<typeof templateExportQuerySchema>;\n\nexport interface TemplateExportResponse {\n filename: string;\n mimeType: string;\n contentB64: string;\n format: TemplateFileFormat;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/** Spec 03 §10.2 (canonical, kebab-case). */\nexport const SNAPSHOT_AUTO_REASONS = [\n 'pre-ai-polish',\n 'pre-import',\n 'pre-template',\n 'pre-open',\n 'pre-restore',\n 'pre-cherry-pick-bulk',\n 'pre-clear-revisions',\n 'pre-delete-revision-set',\n 'pre-unlock-all-pages',\n 'pre-bulk-change-decision',\n 'pre-account-transfer',\n 'offline-edits',\n 'access-revoked',\n] as const;\nexport type SnapshotAutoReason = (typeof SNAPSHOT_AUTO_REASONS)[number];\n\n/** The only reasons a client may send itself. */\nexport const CLIENT_AUTO_REASONS = ['offline-edits', 'access-revoked'] as const;\n\nexport const SNAPSHOT_KINDS = ['manual', 'auto'] as const;\nexport type SnapshotKind = (typeof SNAPSHOT_KINDS)[number];\n\nexport const VERSION_REASONS = [\n 'interval',\n 'session-end',\n 'pre-epoch',\n 'pre-restore',\n 'daily',\n 'reconnect',\n] as const;\nexport type VersionReason = (typeof VERSION_REASONS)[number];\n\nexport interface DocStats {\n pages: number;\n scenes: number;\n words: number;\n activeRevisionSetId?: string | null;\n}\n\n/** A row of `GET /documents/:did/versions` (spec 05 §6.10). */\nexport interface VersionPoint {\n id: string;\n createdAt: string;\n contributors: string[];\n stats: DocStats;\n epoch: number;\n reason: VersionReason;\n}\n\n/** Snapshot marker interleaved in the version list. */\nexport interface SnapshotMarker {\n marker: 'snapshot';\n snapshotId: string;\n name: string;\n createdAt: string;\n}\n\nexport type VersionListItem = VersionPoint | SnapshotMarker;\n\nexport interface SnapshotSummary {\n id: string;\n documentId: string;\n parentId: string | null;\n name: string;\n note: string | null;\n kind: SnapshotKind;\n autoReason: SnapshotAutoReason | null;\n stats: DocStats;\n createdBy: string | null;\n createdOnDevice: string | null;\n createdAt: string;\n receivedAt: string;\n forkedDocumentIds: string[];\n hiddenForMe: boolean;\n noteCount: number;\n}\n\n/** `GET /documents/:did/snapshots` */\nexport interface SnapshotListResponse {\n liveParentSnapshotId: string | null;\n snapshots: SnapshotSummary[];\n}\n\nexport const snapshotCreateSchema = z.object({\n /** Idempotency key, unique per document. */\n clientSnapshotId: z.string().min(1).max(64).optional(),\n name: z.string().trim().min(1).max(120),\n note: z.string().max(2000).optional(),\n kind: z.enum(SNAPSHOT_KINDS).optional(),\n autoReason: z.enum(SNAPSHOT_AUTO_REASONS).optional(),\n sourceEpoch: z.number().int().min(0).optional(),\n assumedParentId: z.string().nullable().optional(),\n createdAt: z.string().optional(),\n createdOnDevice: z.string().max(200).optional(),\n /**\n * Client-provided state for offline creation (spec 03 §10.2, spec 05 §6.11): exactly what the writer saw, uploaded through\n * `POST /uploads/state`. With it, `sourceEpoch` may be older than the live epoch (an offline-edits snapshot after an epoch bump).\n */\n state: z.object({ uploadKey: z.string().min(1).max(128) }).optional(),\n});\nexport type SnapshotCreateRequest = z.infer<typeof snapshotCreateSchema>;\n\nexport type SnapshotCreateResponse = SnapshotSummary & {\n reparentedLive: boolean;\n};\n\nexport type SnapshotDetail = SnapshotSummary & {\n parentChain: SnapshotSummary[];\n};\n\nexport const snapshotOpenSchema = z.object({\n confirm: z.literal(true),\n dryRun: z.boolean().optional(),\n});\nexport type SnapshotOpenRequest = z.infer<typeof snapshotOpenSchema>;\n\nexport const snapshotForkSchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().optional(),\n});\nexport type SnapshotForkRequest = z.infer<typeof snapshotForkSchema>;\n\n/** Where a read or compare takes its content from (spec 05 §6.7.1). */\nexport type SourceRef =\n | { kind: 'live'; documentId: string }\n | { kind: 'snapshot'; snapshotId: string }\n | { kind: 'version'; documentId: string; versionId: string };\n\nexport const sourceRefSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('live'), documentId: z.string() }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string() }),\n z.object({\n kind: z.literal('version'),\n documentId: z.string(),\n versionId: z.string(),\n }),\n]);\n\n/** `POST /documents/:did/versions/:vid/snapshot` body. */\nexport interface VersionSnapshotRequest {\n name: string;\n note?: string;\n}\n\n/** `POST /documents/:did/versions/:vid/restore` (bumps the epoch). */\nexport interface VersionRestoreResponse {\n document: import('../projects/index.js').DocumentMeta;\n epoch: number;\n preRestoreSnapshot: SnapshotSummary;\n}\n\n/** `POST /snapshots/:sid/open` (bumps the epoch). */\nexport interface SnapshotOpenResponse {\n document: import('../projects/index.js').DocumentMeta;\n epoch: number;\n preOpenSnapshot: SnapshotSummary;\n}\n\n// ─── B15: restore-as-copy, prefs, notes, comments, compare, history, presence ────────────────────────────────────\n\n/** `POST /documents/:did/versions/:vid/restore-as-copy` (spec 05 §6.10). Response: `DocumentMeta`. */\nexport const versionRestoreAsCopySchema = z.object({\n title: z.string().trim().min(1).max(200),\n targetProjectId: z.string().optional(),\n});\nexport type VersionRestoreAsCopyRequest = z.infer<\n typeof versionRestoreAsCopySchema\n>;\n\n/** `PUT /snapshots/:sid/prefs`: per-user hide; the snapshot row never changes. */\nexport const snapshotPrefsSchema = z.object({ hidden: z.boolean() });\nexport type SnapshotPrefsRequest = z.infer<typeof snapshotPrefsSchema>;\nexport interface SnapshotPrefsResponse {\n hidden: boolean;\n}\n\nexport const SNAPSHOT_NOTES_MAX = 200;\nexport const snapshotNoteCreateSchema = z.object({\n body: z.string().trim().min(1).max(2000),\n});\nexport type SnapshotNoteCreateRequest = z.infer<\n typeof snapshotNoteCreateSchema\n>;\n/** Append-only (spec 09 F-SNAP-009): there is no edit or delete route. */\nexport interface SnapshotNote {\n id: string;\n snapshotId: string;\n body: string;\n authorId: string | null;\n createdAt: string;\n}\n\nexport const snapshotCommentAnchorSchema = z.object({\n elementId: z.string().min(1),\n offset: z.number().int().min(0),\n length: z.number().int().min(0),\n});\nexport type SnapshotCommentAnchor = z.infer<typeof snapshotCommentAnchorSchema>;\nexport const snapshotCommentCreateSchema = z.object({\n anchor: snapshotCommentAnchorSchema,\n body: z.string().trim().min(1).max(10_000),\n /** User ids mentioned in the body (notifications are B12). */\n mentions: z.array(z.string().min(1)).max(50).optional(),\n});\nexport type SnapshotCommentCreateRequest = z.infer<\n typeof snapshotCommentCreateSchema\n>;\nexport const snapshotCommentResolveSchema = z.object({ resolved: z.boolean() });\nexport type SnapshotCommentResolveRequest = z.infer<\n typeof snapshotCommentResolveSchema\n>;\n/** A review comment on an immutable snapshot (R6). */\nexport interface SnapshotComment {\n id: string;\n snapshotId: string;\n anchor: SnapshotCommentAnchor;\n body: string;\n mentions: string[];\n authorId: string | null;\n viaLinkId: string | null;\n resolvedAt: string | null;\n resolvedBy: string | null;\n copiedToLiveNoteId: string | null;\n createdAt: string;\n}\nexport const snapshotCommentsQuerySchema = cursorQuerySchema;\nexport interface CopyToLiveResponse {\n noteId: string;\n}\n\n// Compare (spec 03 §11.1)\nexport const COMPARE_GRANULARITIES = ['scene', 'element', 'word'] as const;\nexport const TRACKED_CHANGE_MODES = [\n 'accept-all',\n 'reject-all',\n 'as-marked',\n] as const;\nexport const compareRequestSchema = z.object({\n base: sourceRefSchema,\n target: sourceRefSchema,\n granularity: z.enum(COMPARE_GRANULARITIES).default('element'),\n ignoreFormatting: z.boolean().default(false),\n ignoreRevisionMarks: z.boolean().default(false),\n ignoreTrackedChanges: z.enum(TRACKED_CHANGE_MODES).default('as-marked'),\n});\nexport type CompareRequest = z.input<typeof compareRequestSchema>;\n\n/** Above this many combined pages a compare is refused (spec 05 returns a `doc.compare` job; no runner exists, so 413 `COMPARE_TOO_LARGE`). */\nexport const COMPARE_MAX_PAGES = 400;\n\nexport type WordOp = { op: 'equal' | 'insert' | 'delete'; text: string };\nexport type ElementDiffStatus =\n 'unchanged' | 'modified' | 'added' | 'removed' | 'moved' | 'restyled';\nexport interface ElementDiff {\n status: ElementDiffStatus;\n baseElementId?: string;\n targetElementId?: string;\n alignment: 'id' | 'text';\n styleChange?: { from: string; to: string };\n /** `modified`: only formatting (marks) changed, the words are equal. */\n formattingOnly?: boolean;\n /** Plain text of the side(s), so a client can render a row without loading either document. */\n baseText?: string;\n targetText?: string;\n /** `granularity: \"word\"`, modified elements only. */\n words?: WordOp[];\n}\nexport type SceneDiffStatus =\n 'unchanged' | 'modified' | 'added' | 'removed' | 'moved' | 'moved-modified';\nexport interface SceneDiff {\n status: SceneDiffStatus;\n baseSceneId?: string;\n targetSceneId?: string;\n alignment: 'id' | 'fuzzy';\n similarity?: number;\n heading?: string;\n /** Empty at `granularity: \"scene\"`. */\n elements: ElementDiff[];\n}\nexport interface BeatDiff {\n status: 'unchanged' | 'modified' | 'added' | 'removed';\n id: string;\n baseTitle?: string;\n targetTitle?: string;\n}\nexport interface EntityDiff {\n status: 'unchanged' | 'modified' | 'added' | 'removed';\n id: string;\n kind?: string;\n baseName?: string;\n targetName?: string;\n}\nexport interface DocumentDiff {\n scenes: SceneDiff[];\n titlePage: ElementDiff[];\n beats: BeatDiff[];\n entities: EntityDiff[];\n summary: {\n scenesAdded: number;\n scenesRemoved: number;\n scenesModified: number;\n scenesMoved: number;\n wordsAdded: number;\n wordsRemoved: number;\n pageDelta: number;\n };\n}\n\n/** `GET /documents/:did/elements/:elementId/history`: newest first (spec 03 §14). */\nexport const elementHistoryQuerySchema = cursorQuerySchema;\nexport interface ElementHistoryEntry {\n at: string;\n authors: string[];\n text: string;\n source: 'update' | 'version';\n}\n\n/** `GET /documents/:did/presence`: who has the document open on this API instance right now. */\nexport interface PresenceEntry {\n userId: string;\n displayName: string | null;\n colour: string;\n since: string;\n deviceId: string | null;\n deviceName: string | null;\n mode: 'edit' | 'view';\n role: string;\n}\n","import { z } from 'zod';\n\n/**\n * A writing_core command as plain JSON. The command bodies are typed by\n * writing_core; here they are opaque records until the API validates them.\n */\nexport type WritingCommandJson = Record<string, unknown>;\n\nexport const COMMAND_BATCH_MAX = 500;\n\nexport const commandBatchRequestSchema = z.object({\n commands: z\n .array(z.record(z.string(), z.unknown()))\n .min(1)\n .max(COMMAND_BATCH_MAX),\n baseEpoch: z.number().int().min(0),\n expectedHashes: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type CommandBatchRequest = z.infer<typeof commandBatchRequestSchema>;\n\nexport interface CommandWarning {\n index: number;\n code: string;\n message: string;\n}\n\nexport interface CommandEffects {\n /** Elements the batch created, changed and removed (sorted ids). */\n createdIds: string[];\n changedIds: string[];\n deletedIds: string[];\n /** Fresh content hashes (spec 11 4.2) of every created or changed element. */\n newHashes: Record<string, string>;\n}\n\n/**\n * `POST /documents/:did/commands` response (thin B5 version). A `dryRun` returns the same shape\n * with `applied: 0` and `dryRun: true`: the effects the batch WOULD have, nothing changed.\n * `expectedHashes` keys are element or scene ids; a mismatch is 409 `CONTENT_CHANGED` with\n * `details.ids`.\n */\nexport interface CommandBatchResponse {\n applied: number;\n epoch: number;\n dryRun?: boolean;\n effects: CommandEffects;\n warnings: CommandWarning[];\n}\n\n/** `COMMAND_INVALID` (422) `details`. `reason` is a writing_core ReasonCode (or `exception`). */\nexport interface CommandInvalidDetails {\n index: number;\n reason: string;\n detail?: Record<string, unknown>;\n}\n\n// ---- Scene and element reads (spec 05 6.7.1, live document) ----\n\nexport const SCENE_BATCH_MAX = 20;\nexport const ELEMENT_BATCH_MAX = 500;\n\nexport interface OutlineScene {\n id: string;\n /** Formatted scene number label, or null when unnumbered. */\n number: string | null;\n heading: string;\n omitted: boolean;\n synopsis: string;\n elementCount: number;\n contentHash: string;\n}\n\nexport interface OutlineResponse {\n scenes: OutlineScene[];\n}\n\nexport interface ElementRead {\n id: string;\n styleId: string;\n styleName: string;\n /** The style's role (`sceneHeading`, `action`, `character`, `dialogue`, ...), for callers that must not guess from names. */\n styleRole?: string;\n text: string;\n contentHash: string;\n}\n\nexport interface SceneRead {\n id: string;\n number: string | null;\n heading: string;\n synopsis: string;\n contentHash: string;\n elements: ElementRead[];\n}\n\nexport const elementsBatchRequestSchema = z.object({\n elementIds: z.array(z.string().min(1)).min(1).max(ELEMENT_BATCH_MAX),\n});\nexport type ElementsBatchRequest = z.infer<typeof elementsBatchRequestSchema>;\nexport interface ElementsBatchResponse {\n elements: ElementRead[];\n}\n\nexport const scenesBatchRequestSchema = z.object({\n sceneIds: z.array(z.string().min(1)).min(1).max(SCENE_BATCH_MAX),\n});\nexport type ScenesBatchRequest = z.infer<typeof scenesBatchRequestSchema>;\nexport interface ScenesBatchResponse {\n scenes: SceneRead[];\n}\n","import { z } from 'zod';\nimport { documentKindSchema } from '../projects/index.js';\nimport type { DocumentMeta } from '../projects/index.js';\n\n/** Import and export over HTTP (synchronous; spec 05 §6.18 minus the job framework). */\n\n/** Formats the server can import: ids of `writing_formats`. */\nexport const IMPORT_FORMAT_IDS = ['fountain', 'fdx', 'fadein'] as const;\nexport const EXPORT_FORMAT_IDS = ['fountain', 'fdx', 'json'] as const;\nexport type ExportFormatId = (typeof EXPORT_FORMAT_IDS)[number];\n\n/** Default `IMPORT_MAX_BYTES`: 100 MiB of decoded file bytes. */\nexport const IMPORT_MAX_BYTES_DEFAULT = 100 * 1024 * 1024;\n\n/** Mirror of `writing_formats` `Diagnostic` (this package cannot depend on it). */\nexport interface ConversionDiagnostic {\n code: string;\n severity: 'info' | 'warn' | 'loss' | 'error';\n message: string;\n feature: string;\n count: number;\n locations?: {\n elementIndex?: number;\n sourceLine?: number;\n sourcePath?: string;\n }[];\n}\n\n/** Mirror of `writing_formats` `ConversionReport` (spec 04 §3.1). */\nexport interface ConversionReport {\n direction: 'import' | 'export';\n format: string;\n sourceVersion?: string;\n diagnostics: ConversionDiagnostic[];\n stats: {\n elements: number;\n scenes: number;\n pages?: number;\n durationMs: number;\n };\n confidence?: number;\n summary: { info: number; warn: number; loss: number; error: number };\n}\n\n/** `POST /projects/:pid/documents/import` (idempotent on `id`, like document create). */\nexport const documentImportSchema = z.object({\n /** Client-generated `doc_...`; import is idempotent on it. */\n id: z.string().startsWith('doc_').optional(),\n /** Only a hint: the format is detected from the content. */\n filename: z.string().min(1).max(500),\n /** Base64 of the file bytes. */\n contentB64: z.string(),\n /** Defaults to the file's title page title, then the filename. */\n title: z.string().trim().min(1).max(200).optional(),\n kind: documentKindSchema.optional(),\n templateId: z.string().optional(),\n language: z.string().max(16).optional(),\n});\nexport type DocumentImportRequest = z.infer<typeof documentImportSchema>;\n\nexport interface DocumentImportResult {\n document: DocumentMeta;\n report: ConversionReport;\n /** Detected source format id. */\n format: string;\n}\n\n/** `POST /documents/:did/export` */\nexport const documentExportSchema = z.object({\n format: z.string().min(1).max(32),\n});\nexport type DocumentExportRequest = { format: ExportFormatId };\n\nexport interface DocumentExportResult {\n filename: string;\n mimeType: string;\n contentB64: string;\n report: ConversionReport;\n format: ExportFormatId;\n}\n\n/** `GET /formats` */\nexport interface FormatInfo {\n id: string;\n label: string;\n extensions: string[];\n canImport: boolean;\n canExport: boolean;\n}\n","/**\n * Projection-backed reads (spec 05 §6.7.1, §6.7.2, §6.12, §6.14, §6.15, §6.17), slice B10.\n * The Y.Doc is canonical; these are the shapes the API returns for entities, tags, notes, beats, the Bin,\n * revisions, tracked changes, alternates, title page, statistics, shots, locators and search.\n */\nimport { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n// ─── ?source= ───────────────────────────────────────────────────────────────\n\n/** Query encoding of a `SourceRef` (spec 05 §6.7.1): `live`, `snapshot:<snapshotId>` or `version:<versionId>`. */\nexport const sourceParamSchema = z\n .string()\n .regex(\n /^(live|snapshot:[A-Za-z0-9_-]+|version:[A-Za-z0-9_-]+)$/,\n 'source must be live, snapshot:<id> or version:<id>'\n );\n\n/** JSON-body source on a document route: the document is implied by the route (spec 03 `SourceRef` without `documentId`). */\nexport const docSourceSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('live') }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string().min(1) }),\n z.object({ kind: z.literal('version'), versionId: z.string().min(1) }),\n]);\nexport type DocSource = z.infer<typeof docSourceSchema>;\n\nexport const sourceQuerySchema = z.object({\n source: sourceParamSchema.optional(),\n});\nexport type SourceQuery = z.infer<typeof sourceQuerySchema>;\n\nexport function sourceParamOf(ref: DocSource | undefined): string | undefined {\n if (!ref || ref.kind === 'live') return undefined;\n return ref.kind === 'snapshot'\n ? `snapshot:${ref.snapshotId}`\n : `version:${ref.versionId}`;\n}\n\n// ─── Entities (spec 05 §6.12) ───────────────────────────────────────────────\n\nexport const entityListQuerySchema = cursorQuerySchema.extend({\n kind: z.string().min(1).optional(),\n q: z.string().min(1).max(200).optional(),\n source: sourceParamSchema.optional(),\n});\nexport type EntityListQuery = z.infer<typeof entityListQuerySchema>;\n\nexport interface EntitySummary {\n id: string;\n kind: string;\n name: string;\n aliases: string[];\n color: string | null;\n sceneCount: number;\n firstSceneId: string | null;\n /** Characters only. */\n dialogueCount?: number;\n}\n\n/** A character's age or a location's version (spec 01 §5.8.1), read raw from the Y.Doc. */\nexport interface EntityVariantSummary {\n id: string;\n label: string;\n ageValue: number | null;\n setting: string | null;\n sortKey: string;\n appearances: { id: string; label: string }[];\n}\n\nexport interface EntityDetail extends EntitySummary {\n description: string;\n fields: Record<string, unknown>;\n attributes: Record<string, unknown>;\n categoryId: string | null;\n origin: string;\n retain: boolean;\n scenes: { id: string; number: string | null }[];\n tagsByScene: Record<string, string[]>;\n /** Asset links arrive with slice B11: always empty until then. */\n assetLinks: { assetLinkId: string; role: string }[];\n contentHash: string;\n variants: EntityVariantSummary[];\n worksheetIds: string[];\n}\n\nexport const entityUsageQuerySchema = z.object({\n variantId: z.string().min(1).optional(),\n source: sourceParamSchema.optional(),\n});\nexport type EntityUsageQuery = z.infer<typeof entityUsageQuerySchema>;\n\nexport interface SceneRef {\n id: string;\n number: string | null;\n heading?: string;\n synopsis?: string;\n}\n\n/**\n * What blocks deleting an entity and what the character and location lists show behind *Show usages*\n * (spec 09 F-TAG-017, F-TAG-021). `total` = cues + headings + tags + arcBeats + noteMentions + assetLinks\n * (`sceneLinks` is the informational scene presence and is not counted).\n */\nexport interface EntityUsage {\n total: number;\n cues: {\n elementId: string;\n sceneId: string | null;\n sceneNumber: string | null;\n page: string | null;\n variantId: string | null;\n }[];\n headings: {\n sceneId: string;\n sceneNumber: string | null;\n page: string | null;\n variantId: string | null;\n }[];\n sceneLinks: SceneRef[];\n tags: { tagId: string; categoryId: string; sceneId: string | null }[];\n arcBeats: SceneRef[];\n noteMentions: { noteId: string }[];\n assetLinks: { assetLinkId: string; role: string }[];\n byVariant: Record<string, number>;\n /** Uses (cues for a character, headings for a location) that name no variant. */\n unassigned: number;\n}\n\nexport const entityDialogueQuerySchema = z.object({\n sceneIds: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\n\n/** Dialogue Tuner view (spec 05 §6.7.1). */\nexport interface DialogueSceneView {\n sceneId: string;\n sceneNumber: string | null;\n elements: {\n id: string;\n styleId: string;\n text: string;\n contentHash: string;\n }[];\n}\n\n// ─── Tags, notes, beats, bin, revisions, changes, alternates ────────────────\n\nexport interface TagCategoryRow {\n id: string;\n key: string | null;\n name: string;\n color: string;\n entityKind: string;\n}\n\nexport const tagsQuerySchema = z.object({\n sceneId: z.string().optional(),\n categoryId: z.string().optional(),\n entityId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface TagRow {\n id: string;\n categoryId: string;\n entityId: string;\n elementId: string;\n range: { index: number; length: number } | null;\n text: string;\n sceneId: string | null;\n}\n\nexport const notesQuerySchema = z.object({\n sceneId: z.string().optional(),\n type: z.string().optional(),\n status: z.enum(['open', 'resolved']).optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface NoteSummary {\n id: string;\n anchor: { kind: string; elementId?: string; beatId?: string };\n sceneId: string | null;\n /** The note type's name (falls back to its id). */\n type: string | null;\n typeId: string | null;\n color: string | null;\n title: string;\n body: string;\n author: string | null;\n createdAt: number | null;\n replies: { id: string; author: string; body: string; at: number }[];\n status: 'open' | 'resolved';\n contentHash: string;\n}\n\nexport interface BeatRow {\n id: string;\n title: string;\n body: string;\n color: string | null;\n x: number | null;\n y: number | null;\n links: { id: string; to: string; label: string }[];\n sceneId?: string;\n}\n\nexport interface BinRow {\n id: string;\n title: string;\n preview: string;\n createdAt: number;\n}\n\nexport interface RevisionsView {\n sets: {\n id: string;\n name: string;\n color: string;\n mark: string;\n fullDraft: boolean;\n date: number | null;\n }[];\n activeSetId: string | null;\n revisionMode: boolean;\n trackChanges: boolean;\n}\n\nexport const changesQuerySchema = z.object({\n authorId: z.string().optional(),\n sceneId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\nexport interface ChangeRow {\n id: string;\n kind: 'insert' | 'delete' | 'style' | 'fmt';\n authorId: string;\n at: number;\n elementId: string;\n before: string;\n after: string;\n}\n\n/** The element's own text is the active alternate (index 0); the inactive ones follow. */\nexport interface AlternatesView {\n activeIndex: number;\n alternates: { id: string; text: string }[];\n}\n\nexport interface TitlePageRead {\n fields: Record<string, string>;\n elements: {\n id: string;\n styleId: string;\n text: string;\n field: string | null;\n }[];\n computed: Record<string, unknown>;\n}\n\nexport interface StatsRead {\n pages: number;\n eighths: number;\n scenes: number;\n words: number;\n elementsByStyle: Record<string, number>;\n estRuntimeMin: number;\n intExt: Record<string, number>;\n dayNight: Record<string, number>;\n dialoguePct: number;\n}\n\nexport interface ShotRow {\n id: string;\n index: number;\n sceneId: string;\n label: string;\n description: string;\n elementRange: { startElementId: string; endElementId: string } | null;\n camera: Record<string, unknown>;\n estDurationSec: number | null;\n attributes: Record<string, unknown>;\n contentHash: string;\n}\n\nexport const fountainQuerySchema = z.object({\n sceneIds: z.string().optional(),\n fromSceneId: z.string().optional(),\n source: sourceParamSchema.optional(),\n});\n/** `GET /documents/:did/fountain` truncates at this many bytes and sets `X-Next-From-Scene`. */\nexport const FOUNTAIN_MAX_BYTES = 1_000_000;\n\n// ─── Locators (spec 11 §1.3, spec 05 §6.7.2) ────────────────────────────────\n\nexport const LOCATOR_KINDS = [\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'page',\n] as const;\nexport type LocatorKind = (typeof LOCATOR_KINDS)[number];\n\nexport type ResolveResult =\n | { status: 'resolved'; kind: LocatorKind; id: string; label: string }\n | {\n status: 'ambiguous';\n kind: LocatorKind;\n candidates: { id: string; label: string; score: number }[];\n }\n | {\n status: 'not_found';\n kind: LocatorKind;\n suggestions: { id: string; label: string }[];\n };\n\nexport const RESOLVE_BATCH_MAX = 200;\nexport const resolveBatchSchema = z.object({\n locators: z.array(z.string().min(1).max(500)).min(1).max(RESOLVE_BATCH_MAX),\n snapshotId: z.string().min(1).optional(),\n});\nexport type ResolveBatchRequest = z.infer<typeof resolveBatchSchema>;\n/** `GET /documents/:did/resolve?ref=&snapshotId=`. */\nexport const resolveOneQuerySchema = z.object({\n ref: z.string().min(1).max(500),\n snapshotId: z.string().min(1).optional(),\n});\n\n// ─── Search (spec 05 §6.17) ─────────────────────────────────────────────────\n\nexport const SEARCH_HIT_TYPES = [\n 'document',\n 'scene',\n 'element',\n 'entity',\n 'note',\n 'asset',\n] as const;\nexport type SearchHitType = (typeof SEARCH_HIT_TYPES)[number];\n\nconst csv = (v: unknown) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v;\n\nexport const searchQuerySchema = cursorQuerySchema.extend({\n q: z.string().min(1).max(200),\n workspaceId: z.string().min(1).optional(),\n projectId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n types: z.preprocess(csv, z.array(z.enum(SEARCH_HIT_TYPES)).min(1)).optional(),\n styleIds: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n characterId: z.string().min(1).optional(),\n language: z.string().min(2).max(35).optional(),\n});\nexport type SearchQuery = z.infer<typeof searchQuerySchema>;\n\n/** `GET /documents/:did/search` (in-document find, spec 05 §6.7.1). */\nexport const documentSearchQuerySchema = z.object({\n q: z.string().min(1).max(500),\n mode: z.enum(['text', 'regex']).default('text'),\n styles: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n characters: z.preprocess(csv, z.array(z.string()).min(1)).optional(),\n limit: z.coerce.number().int().min(1).max(100).default(50),\n source: sourceParamSchema.optional(),\n});\nexport type DocumentSearchQuery = z.infer<typeof documentSearchQuerySchema>;\n\nexport interface DocumentSearchHit {\n sceneId: string | null;\n sceneNumber: string | null;\n elementId: string;\n styleId: string;\n snippet: string;\n page: string | null;\n}\n\nexport interface SearchHit {\n type: SearchHitType;\n documentId: string | null;\n projectId: string;\n targetId: string;\n title: string;\n /** At most 240 characters; `marks` are `[start, end)` ranges into it (never HTML). */\n snippet: string;\n marks: [number, number][];\n sceneNumber?: string | null;\n pageNumber?: string | null;\n rank: number;\n}\n","import { z } from 'zod';\nimport { documentKindSchema } from '../projects/index.js';\nimport { docSourceSchema } from '../reads/index.js';\nimport type { ConversionReport } from '../formats/index.js';\n\n/**\n * Imports, exports and batch watermark as jobs, plus the upload port they share (slice B16; spec 05 §6.18, §6.1 `uploads`,\n * §13). The synchronous `POST /projects/:pid/documents/import`, `POST /documents/:did/export` and `GET /formats` (see\n * `formats/`) stay until the app migrates.\n *\n * Formats are exactly what `writing_formats` has today: import Fountain, FDX and Fade In; export Fountain, FDX and the plain\n * JSON backup. PDF, DOCX, Celtx, Scrivener and OCR answer `IMPORT_FORMAT_UNSUPPORTED` / `EXPORT_FORMAT_UNSUPPORTED` /\n * `OCR_UNAVAILABLE`; nothing fakes them.\n */\n\n/** Formats `POST /imports` accepts (a job kind `import.<format>` exists for each). */\nexport const JOB_IMPORT_FORMATS = ['fountain', 'fdx', 'fadein'] as const;\nexport type JobImportFormat = (typeof JOB_IMPORT_FORMATS)[number];\n/** Formats an export job produces (`export.<format>`). */\nexport const JOB_EXPORT_FORMATS = ['fountain', 'fdx', 'json'] as const;\nexport type JobExportFormat = (typeof JOB_EXPORT_FORMATS)[number];\n/** `POST /documents/export-combined` takes these (spec 05: pdf, fdx, fountain; pdf is not built). */\nexport const COMBINED_EXPORT_FORMATS = ['fdx', 'fountain'] as const;\n/** At most this many documents in one combined export (the job's `sources` cap). */\nexport const COMBINED_EXPORT_MAX_DOCUMENTS = 20;\n/** At most this many recipients in one batch watermark (spec 05 §6.18). */\nexport const BATCH_WATERMARK_MAX_RECIPIENTS = 500;\n\n// ─── uploads (spec 05 §6.1 `uploads`, §8) ─────────────────────────────────────\n\nexport const UPLOAD_PURPOSES = ['state', 'watermark_lookup', 'import'] as const;\nexport type UploadPurpose = (typeof UPLOAD_PURPOSES)[number];\n\nconst sha256HexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{64}$/, 'sha256Hex must be 64 hex characters');\n\n/**\n * `POST /uploads/state`. `purpose` defaults to `state` (a Yjs state blob); `watermark_lookup` is a leaked file for\n * `POST /workspaces/:wid/watermark-lookup`. `import` uploads are created by `POST /imports`, never here.\n */\nexport const uploadStateRequestSchema = z.object({\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema,\n purpose: z.enum(['state', 'watermark_lookup']).default('state'),\n});\nexport type UploadStateRequest = z.input<typeof uploadStateRequestSchema>;\n\n/** A presigned PUT: send the bytes with `PUT url` (no `Authorization`), then use `uploadKey`. */\nexport interface UploadStateResponse {\n uploadKey: string;\n url: string;\n /** When the PUT url stops working (`SIGNED_URL_TTL_S`). */\n expiresAt: string;\n}\n\n// ─── imports ─────────────────────────────────────────────────────────────────\n\nexport const importOptionsSchema = z.object({\n templateId: z.string().min(1).optional(),\n /** `auto`: OCR a PDF without a text layer; `force`; `off`. No OCR exists yet: `force` is `OCR_UNAVAILABLE`. */\n ocr: z.enum(['auto', 'force', 'off']).default('auto'),\n ocrLanguage: z.string().min(2).max(16).optional(),\n title: z.string().trim().min(1).max(200).optional(),\n kind: documentKindSchema.optional(),\n language: z.string().max(16).optional(),\n});\nexport type ImportOptions = z.input<typeof importOptionsSchema>;\n\nconst importFileFields = {\n filename: z.string().min(1).max(500),\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema,\n /** Auto-detected from the uploaded bytes when omitted. */\n format: z.string().min(1).max(32).optional(),\n options: importOptionsSchema.optional(),\n};\n\n/** `POST /imports`: one of `targetProjectId` (import as a new document) or `templateTarget` (a template file, `POST /templates/import {importId}`). */\nexport const importCreateSchema = z\n .object({\n targetProjectId: z.string().min(1).optional(),\n templateTarget: z\n .object({\n scope: z.enum(['user', 'workspace']),\n workspaceId: z.string().min(1).optional(),\n })\n .refine((v) => v.scope !== 'workspace' || !!v.workspaceId, {\n message: 'workspaceId is required for a workspace template',\n path: ['workspaceId'],\n })\n .optional(),\n ...importFileFields,\n })\n .refine(\n (v) => (v.targetProjectId ? 1 : 0) + (v.templateTarget ? 1 : 0) === 1,\n {\n message: 'Send exactly one of targetProjectId and templateTarget',\n path: ['targetProjectId'],\n }\n );\nexport type ImportCreateRequest = z.input<typeof importCreateSchema>;\n\n/** `POST /documents/:did/import-over`: the document is the route's. */\nexport const importOverSchema = z.object(importFileFields);\nexport type ImportOverRequest = z.input<typeof importOverSchema>;\n\n/** Both answer this: PUT the file to `upload.url`, then `POST /imports/:importId/start`. No job exists yet. */\nexport interface ImportCreateResponse {\n importId: string;\n upload: { url: string; expiresAt: string };\n}\n\n/** Input stored on `import.<format>` jobs (spec 05 §13). `newDocumentId` is minted at start so a retried run cannot make two documents. */\nexport const importJobInputSchema = z.object({\n importId: z.string().min(1),\n targetProjectId: z.string().min(1),\n newDocumentId: z.string().min(1),\n filename: z.string().min(1).max(500),\n options: importOptionsSchema.optional(),\n});\nexport type ImportJobInput = z.infer<typeof importJobInputSchema>;\n\n/** Input stored on `doc.importOver` jobs. */\nexport const importOverJobInputSchema = z.object({\n importId: z.string().min(1),\n documentId: z.string().min(1),\n filename: z.string().min(1).max(500),\n options: importOptionsSchema.optional(),\n});\nexport type ImportOverJobInput = z.infer<typeof importOverJobInputSchema>;\n\n/** One document an import made; the job's outputs carry one `conversion-report.json` per document (`output.documentId`). */\nexport interface ImportedDocumentRef {\n documentId: string;\n title: string;\n format: string;\n}\n/** What a finished `import.*` job stores as `result` (also readable from the outputs). */\nexport interface ImportJobResult {\n documents: ImportedDocumentRef[];\n report: ConversionReport;\n}\n/** What a finished `doc.importOver` job stores as `result`. */\nexport interface ImportOverJobResult {\n documentId: string;\n epoch: number;\n preImportSnapshotId: string;\n format: string;\n report: ConversionReport;\n}\n\n/** Name of the per-document (import) or per-file (export) conversion report output. */\nexport const CONVERSION_REPORT_OUTPUT = 'conversion-report.json';\n\n// ─── exports ─────────────────────────────────────────────────────────────────\n\n/** Visible watermark. `text` tokens: `{recipient}`, `{email}`, `{company}`, `{title}`, `{date}`. */\nexport const watermarkStyleSchema = z.object({\n text: z.string().min(1).max(200).default('{recipient}'),\n opacity: z.number().min(0.05).max(1).optional(),\n position: z\n .enum(['diagonalAscending', 'diagonalDescending', 'horizontal'])\n .optional(),\n});\nexport type WatermarkStyle = z.input<typeof watermarkStyleSchema>;\n\nexport const batchWatermarkSchema = z.object({\n recipients: z\n .array(\n z.object({\n name: z.string().trim().min(1).max(200),\n email: z.string().trim().min(1).max(320).optional(),\n company: z.string().trim().min(1).max(200).optional(),\n })\n )\n .min(1)\n .max(BATCH_WATERMARK_MAX_RECIPIENTS),\n visible: watermarkStyleSchema.optional(),\n /** Forensic mark. Only a PDF writer can embed one; text formats carry the export code as a visible note (see the API notes). */\n invisible: z.boolean().default(false),\n /** `email` needs the notification slice (B12): refused with `VALIDATION` until then. */\n deliver: z.enum(['download', 'email']).default('download'),\n emailMessage: z.string().max(2000).optional(),\n});\nexport type BatchWatermark = z.input<typeof batchWatermarkSchema>;\n\nexport const exportOptionsSchema = z.object({\n /** Download name without extension (default: the document title). */\n filename: z.string().trim().min(1).max(120).optional(),\n batchWatermark: batchWatermarkSchema.optional(),\n});\nexport type ExportOptions = z.input<typeof exportOptionsSchema>;\n\n/** `POST /documents/:did/exports`. `format` is validated by the server (`EXPORT_FORMAT_UNSUPPORTED` for anything but fountain, fdx, json). */\nexport const exportCreateSchema = z.object({\n format: z.string().min(1).max(32),\n source: docSourceSchema.optional(),\n options: exportOptionsSchema.optional(),\n});\nexport type ExportCreateRequest = z.input<typeof exportCreateSchema>;\n\n/** `POST /documents/export-combined`: the first document's title page and template, bodies concatenated in the order given. */\nexport const exportCombinedSchema = z.object({\n documentIds: z\n .array(z.string().min(1))\n .min(1)\n .max(COMBINED_EXPORT_MAX_DOCUMENTS),\n format: z.string().min(1).max(32),\n options: exportOptionsSchema.omit({ batchWatermark: true }).optional(),\n});\nexport type ExportCombinedRequest = z.input<typeof exportCombinedSchema>;\n\n/** Input stored on `export.<format>` and `watermark.batch` jobs. */\nexport const exportJobInputSchema = z.object({\n format: z.enum(JOB_EXPORT_FORMATS),\n documentIds: z\n .array(z.string().min(1))\n .max(COMBINED_EXPORT_MAX_DOCUMENTS)\n .optional(),\n source: docSourceSchema.optional(),\n options: exportOptionsSchema.optional(),\n});\nexport type ExportJobInput = z.infer<typeof exportJobInputSchema>;\n\n/** What a finished `watermark.batch` job stores as `result`. `invisibleApplied` is false for every text format. */\nexport interface WatermarkBatchResult {\n recipients: number;\n format: JobExportFormat;\n visibleApplied: boolean;\n invisibleApplied: boolean;\n /** How the export code travels in the file. */\n codeCarrier: 'fountain-note' | 'fdx-comment' | 'json-field';\n}\n\n// ─── watermark lookup ────────────────────────────────────────────────────────\n\n/** Prefix of an export code as printed in a file: `FWX-` + 26 base32 characters (128 random bits). */\nexport const EXPORT_CODE_PREFIX = 'FWX-';\n\n/** `{exportId}` or `{pdfUploadKey}` (a leaked file uploaded through `/uploads/state` with `purpose: \"watermark_lookup\"`). */\nexport const watermarkLookupSchema = z\n .object({\n exportId: z.string().trim().min(8).max(64).optional(),\n pdfUploadKey: z.string().min(1).max(100).optional(),\n })\n .refine((v) => (v.exportId ? 1 : 0) + (v.pdfUploadKey ? 1 : 0) === 1, {\n message: 'Send exactly one of exportId and pdfUploadKey',\n path: ['exportId'],\n });\nexport type WatermarkLookupRequest = z.input<typeof watermarkLookupSchema>;\n\nexport interface WatermarkMatch {\n exportId: string;\n recipient: { name: string; email: string | null; company: string | null };\n documentId: string | null;\n documentTitle: string | null;\n /** Display name (else email) of who ran the export. */\n exportedBy: string | null;\n exportedAt: string;\n source: {\n documentId: string | null;\n kind: 'live' | 'snapshot' | 'version';\n snapshotId?: string;\n versionId?: string;\n };\n}\nexport interface WatermarkLookupResponse {\n matches: WatermarkMatch[];\n}\n","import { z } from 'zod';\n\n/**\n * AI features (spec 06): script review and polish through ShapeShyft.\n *\n * Only the tasks implemented so far are in `AI_TASKS`; adding one means a registry row in\n * `screenwriter_api/src/services/ai/tasks.ts`, a prompt builder, an output schema here and a fixture.\n * Output schemas are written for structured output: every field is required (nullable, never optional)\n * and objects are closed, so `z.toJSONSchema` gives the exact schema to store on the ShapeShyft endpoint.\n */\n\nexport const AI_TASKS = ['coverage', 'polish.dialogue'] as const;\nexport type AiTask = (typeof AI_TASKS)[number];\nexport const aiTaskSchema = z.enum(AI_TASKS);\n\n/** ShapeShyft endpoint names (spec 06 2.1). `summarize-chunk` is stage 1 of a long coverage run. */\nexport const AI_ENDPOINTS = [\n 'coverage-review',\n 'polish',\n 'summarize-chunk',\n] as const;\nexport type AiEndpoint = (typeof AI_ENDPOINTS)[number];\n\nexport const AI_JOB_STATUSES = [\n 'queued',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport type AiJobStatus = (typeof AI_JOB_STATUSES)[number];\n\n/** Counted limits, declared once: schemas, validators and prompt text all read these. */\nexport const AI_LIMITS = {\n noteTitleMax: 80,\n noteBodyMax: 1200,\n noteAnchorsMax: 8,\n strengthsMax: 8,\n weaknessesMax: 12,\n sceneNotesMax: 20,\n loglineMax: 300,\n summaryMax: 4000,\n genreMax: 3,\n verdictRationaleMax: 800,\n polishSuggestionsMax: 200,\n polishTextMax: 4000,\n rationaleMax: 400,\n chunkSummaryMax: 1200,\n sceneSummaryMax: 280,\n polishMaxScenes: 8,\n instructionsMax: 500,\n} as const;\n\nexport const REVIEW_CATEGORIES = [\n 'premise',\n 'structure',\n 'character',\n 'dialogue',\n 'pacing',\n 'tone',\n 'theme',\n 'worldbuilding',\n 'format',\n 'marketability',\n 'clarity',\n 'continuity',\n] as const;\nexport type ReviewCategory = (typeof REVIEW_CATEGORIES)[number];\nexport const SEVERITIES = ['praise', 'minor', 'moderate', 'major'] as const;\nexport type Severity = (typeof SEVERITIES)[number];\nexport const COVERAGE_VERDICTS = ['recommend', 'consider', 'pass'] as const;\n\n// ---- Model output (untrusted until validated; what the ShapeShyft endpoint returns) ----\n\n/** Where a note points. `elementId: null` means the whole scene. The server adds the content hash. */\nexport const anchorRefSchema = z.object({\n sceneId: z.string(),\n elementId: z.string().nullable(),\n});\nexport type AnchorRef = z.infer<typeof anchorRefSchema>;\n\nexport const noteSchema = z.object({\n category: z.enum(REVIEW_CATEGORIES),\n severity: z.enum(SEVERITIES),\n title: z.string().min(1).max(AI_LIMITS.noteTitleMax),\n body: z.string().min(1).max(AI_LIMITS.noteBodyMax),\n anchors: z.array(anchorRefSchema).max(AI_LIMITS.noteAnchorsMax),\n});\nexport type ModelNote = z.infer<typeof noteSchema>;\n\n/** `coverage-review` output. */\nexport const coverageResponseSchema = z.object({\n logline: z.string().max(AI_LIMITS.loglineMax),\n summary: z.string().max(AI_LIMITS.summaryMax),\n genre: z.array(z.string()).max(AI_LIMITS.genreMax),\n strengths: z.array(noteSchema).max(AI_LIMITS.strengthsMax),\n weaknesses: z.array(noteSchema).max(AI_LIMITS.weaknessesMax),\n /** Notes about specific scenes: each must anchor at least one scene. */\n sceneNotes: z.array(noteSchema).max(AI_LIMITS.sceneNotesMax),\n verdict: z.enum(COVERAGE_VERDICTS),\n verdictRationale: z.string().max(AI_LIMITS.verdictRationaleMax),\n});\nexport type CoverageResponse = z.infer<typeof coverageResponseSchema>;\n\n/** `polish` output: one proposed replacement per element. */\nexport const polishResponseSchema = z.object({\n suggestions: z\n .array(\n z.object({\n elementId: z.string(),\n after: z.string().max(AI_LIMITS.polishTextMax),\n rationale: z.string().max(AI_LIMITS.rationaleMax),\n })\n )\n .max(AI_LIMITS.polishSuggestionsMax),\n});\nexport type PolishResponse = z.infer<typeof polishResponseSchema>;\n\n/** `summarize-chunk` output (stage 1 of a long-script coverage run). */\nexport const chunkSummaryResponseSchema = z.object({\n scenes: z.array(\n z.object({\n sceneId: z.string(),\n summary: z.string().max(AI_LIMITS.sceneSummaryMax),\n intensity: z.number().int().min(1).max(5),\n })\n ),\n chunkSummary: z.string().max(AI_LIMITS.chunkSummaryMax),\n});\nexport type ChunkSummaryResponse = z.infer<typeof chunkSummaryResponseSchema>;\n\n/** The five input fields every endpoint takes (spec 06 2.1). */\nexport const aiEndpointInputSchema = z.object({\n context: z.string(),\n brief: z.string(),\n max_output_tokens: z.number().int().positive(),\n locale: z.string(),\n script_language: z.string(),\n});\nexport type AiEndpointInput = z.infer<typeof aiEndpointInputSchema>;\n\n/** Endpoint -> output schema. `bun run ai:schemas` in screenwriter_api prints these as JSON Schema. */\nexport const AI_ENDPOINT_OUTPUT_SCHEMAS = {\n 'coverage-review': coverageResponseSchema,\n polish: polishResponseSchema,\n 'summarize-chunk': chunkSummaryResponseSchema,\n} as const satisfies Record<AiEndpoint, z.ZodType>;\n\n// ---- Stored / returned shapes ----\n\nexport interface Anchor {\n sceneId: string;\n elementId?: string;\n /** Content hash (spec 11 4.2) of the element, or of the scene when there is no elementId, at generation time. */\n contentHash: string;\n}\n\nexport interface AiNote {\n id: string;\n category: ReviewCategory;\n severity: Severity;\n title: string;\n body: string;\n anchors: Anchor[];\n}\n\nexport interface CoverageReport {\n logline: string;\n summary: string;\n genre: string[];\n verdict: (typeof COVERAGE_VERDICTS)[number];\n verdictRationale: string;\n strengths: AiNote[];\n weaknesses: AiNote[];\n notesByScene: { sceneId: string; heading: string; notes: AiNote[] }[];\n stats: { scenes: number; chunks: number; droppedItems: number };\n}\n\nexport interface AiTokenUsage {\n promptTokens: number;\n completionTokens: number;\n calls: number;\n model: string | null;\n}\n\n// ---- Jobs ----\n\nexport const aiScopeSchema = z.object({\n sceneIds: z.array(z.string().min(1)).max(200).optional(),\n elementIds: z.array(z.string().min(1)).max(2000).optional(),\n});\nexport type AiScope = z.infer<typeof aiScopeSchema>;\n\nexport const aiJobOptionsSchema = z.object({\n /** Writer's own request, fenced separately from the script. Fixture failure markers only work in test mode. */\n instructions: z.string().max(AI_LIMITS.instructionsMax).optional(),\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n locale: z.string().min(2).max(20).optional(),\n});\nexport type AiJobOptions = z.infer<typeof aiJobOptionsSchema>;\n\n/** `POST /documents/:did/ai/jobs` body. `polish.dialogue` needs a scope; `coverage` defaults to the whole script. */\nexport const aiJobCreateSchema = z.object({\n task: aiTaskSchema,\n scope: aiScopeSchema.optional(),\n options: aiJobOptionsSchema.optional(),\n});\nexport type AiJobCreateRequest = z.infer<typeof aiJobCreateSchema>;\n\n/** 202 response. */\nexport interface AiJobCreated {\n jobId: string;\n status: 'queued';\n}\n\nexport interface AiJobProgress {\n stage: string;\n done: number;\n total: number;\n}\n\nexport interface AiJobError {\n code: string;\n message: string;\n}\n\nexport type AiJobResult =\n | { kind: 'report'; report: CoverageReport }\n /** `suggestionSetId` is null when the model found nothing worth changing (count 0). */\n | {\n kind: 'suggestions';\n suggestionSetId: string | null;\n count: number;\n droppedItems: number;\n };\n\n/** `GET /ai/jobs/:jobId` and the items of `GET /documents/:did/ai/jobs`. Poll until `status` is final. */\nexport interface AiJob {\n id: string;\n documentId: string;\n task: AiTask;\n status: AiJobStatus;\n progress?: AiJobProgress;\n result?: AiJobResult;\n error?: AiJobError;\n promptVersion: string;\n usage?: AiTokenUsage;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\n// ---- Suggestion sets (spec 06 7) ----\n\nexport const SUGGESTION_STATUSES = [\n 'pending',\n 'accepted',\n 'rejected',\n 'stale',\n] as const;\nexport type SuggestionStatus = (typeof SUGGESTION_STATUSES)[number];\nexport const SUGGESTION_SET_STATUSES = [\n 'pending',\n 'partiallyAccepted',\n 'accepted',\n 'rejected',\n 'stale',\n 'expired',\n] as const;\nexport type SuggestionSetStatus = (typeof SUGGESTION_SET_STATUSES)[number];\n\nexport interface Suggestion {\n id: string;\n elementId: string;\n kind: 'replaceText';\n before: string;\n after: string;\n rationale: string;\n /** The element's content hash when the suggestion was generated; accepting checks it. */\n contentHash: string;\n status: SuggestionStatus;\n decidedAt: string | null;\n}\n\nexport interface SuggestionSetSummary {\n id: string;\n documentId: string;\n jobId: string;\n task: AiTask;\n promptVersion: string;\n status: SuggestionSetStatus;\n sourceEpoch: number;\n counts: Record<SuggestionStatus, number>;\n createdAt: string;\n}\n\nexport interface SuggestionSet extends SuggestionSetSummary {\n suggestions: Suggestion[];\n}\n\nexport const suggestionAcceptSchema = z.object({\n suggestionIds: z.array(z.string().min(1)).min(1).max(200),\n});\nexport type SuggestionAcceptRequest = z.infer<typeof suggestionAcceptSchema>;\n\n/** `reject` with no ids rejects every pending suggestion in the set. */\nexport const suggestionRejectSchema = z.object({\n suggestionIds: z.array(z.string().min(1)).min(1).max(200).optional(),\n});\nexport type SuggestionRejectRequest = z.infer<typeof suggestionRejectSchema>;\n\nexport interface SuggestionAcceptResponse {\n applied: string[];\n set: SuggestionSet;\n}\n\n// ---- Availability ----\n\n/** `fixture` = canned test-mode answers (AI_TEST_MODE=1); `live` = ShapeShyft configured; `unavailable` = neither. */\nexport type AiStatusMode = 'live' | 'fixture' | 'unavailable';\n\n/** `GET /ai/status`. */\nexport interface AiStatus {\n available: boolean;\n mode: AiStatusMode;\n}\n\n// ---- Consent (spec 06 §9.3: gate 3) ----\n\n/** Bumping this requires every user to re-accept before their next AI job. */\nexport const AI_CONSENT_VERSION = 1;\n\n/** `GET /me/ai-consents`. */\nexport interface AiConsentStatus {\n currentVersion: number;\n acceptedVersion: number | null;\n acceptedAt: string | null;\n}\n\n/** `POST /me/ai-consents`: `version` must equal `AI_CONSENT_VERSION`, else `VALIDATION`. */\nexport const aiConsentAcceptSchema = z.object({ version: z.number().int() });\nexport type AiConsentAcceptRequest = z.infer<typeof aiConsentAcceptSchema>;\n\nexport interface AiConsentAcceptResponse {\n acceptedVersion: number;\n acceptedAt: string;\n}\n\n// ---- Estimate and pricing (spec 06 §10.1, §10.3) ----\n\n/** What a quote was computed from. Pages are approximated from word count until the paginator runs server-side (M2). */\nexport interface AiPriceBasis {\n pages: number;\n scopePages?: number;\n}\n\nexport const aiEstimateRequestSchema = z.object({\n task: aiTaskSchema,\n scope: z\n .object({\n sceneIds: z.array(z.string()).optional(),\n elementIds: z.array(z.string()).optional(),\n })\n .optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AiEstimateRequest = z.infer<typeof aiEstimateRequestSchema>;\n\n/** `POST /documents/:did/ai/estimate`: the same pricing function `startJob` charges at, run without creating a job. */\nexport interface AiEstimateResponse {\n credits: number;\n basis: AiPriceBasis;\n withinLimit: boolean;\n balance: number;\n}\n\n// ---- Activity (spec 05 §6.3) ----\n\n/** `GET /me/ai-activity`, `GET /workspaces/:wid/ai-activity` (the latter adds `userId`). */\nexport interface AiActivityItem {\n jobId: string;\n task: AiTask;\n documentId: string;\n documentTitle: string;\n status: AiJobStatus;\n quotedCredits: number | null;\n chargedCredits: number | null;\n refundedCredits: number | null;\n createdAt: string;\n}\n\n// ---- Reports (spec 06 §11) ----\n\n/** `GET /documents/:did/ai/reports`: a saved coverage/review job, summarised. */\nexport interface AiReportSummary {\n jobId: string;\n task: AiTask;\n status: AiJobStatus;\n createdAt: string;\n finishedAt: string | null;\n}\n\n/** `POST .../reports/:jobId/notes/:noteId/convert`: `noteId` is `\"strengths:<i>\" | \"weaknesses:<i>\" | \"sceneNotes:<i>\"`,\n * the note's position in the immutable stored report (reports have no independently stable note ids). */\nexport interface AiNoteConvertResponse {\n scriptNoteId: string;\n}\n\n// ---- Suggestion decide (spec 06 §7.4): a combined, server-side accept/reject for API/MCP callers ----\n\nexport const suggestionDecideSchema = z.object({\n accept: z.union([z.array(z.string().min(1)), z.literal('allPending')]),\n reject: z.union([z.array(z.string().min(1)), z.literal('allPending')]),\n expectedHashes: z.record(z.string(), z.string()).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type SuggestionDecideRequest = z.infer<typeof suggestionDecideSchema>;\n\nexport interface SuggestionDecideResponse {\n accepted: string[];\n rejected: string[];\n skippedStale: string[];\n skippedConflicted: string[];\n autoSnapshotId: string | null;\n epoch: number;\n}\n","import { z } from 'zod';\n\n/**\n * Synchronous AI actions: `POST /ai/{action}` in screenwriter_api, which authenticates the caller and turns around\n * to one ShapeShyft endpoint of the same name. Unlike the document jobs in `./index.ts` (coverage, polish) these take\n * their whole input in the request body, read no document, and answer in the same HTTP response.\n *\n * The output schemas follow the same convention as `AI_ENDPOINT_OUTPUT_SCHEMAS`: written for structured output, so\n * every field is required (nullable, never optional) and objects are closed — `z.toJSONSchema` gives the exact schema\n * to store on the ShapeShyft endpoint (`bun run ai:schemas` in screenwriter_api prints them). What the API returns to\n * the client is the normalised `*Result` shape (nulls dropped), not the raw model shape.\n */\n\nexport const AI_ACTIONS = [\n 'generate-character-skeleton',\n 'generate-script',\n 'polish-character-dialogue',\n 'polish-scene',\n] as const;\nexport type AiAction = (typeof AI_ACTIONS)[number];\nexport const aiActionSchema = z.enum(AI_ACTIONS);\n\n/** Counted limits for the action requests, declared once: request schemas, output schemas and prompts read these. */\nexport const AI_ACTION_LIMITS = {\n /** Free-form text a writer pastes in: a character description, or the story to turn into a script. */\n descriptionMax: 8_000,\n storyMax: 30_000,\n skeletonFieldMax: 1_000,\n characterNameMax: 80,\n languageMax: 35,\n /** Dialogue polish: one character's lines. */\n dialoguesMax: 100,\n dialogueTextMax: 2_000,\n /** Scene polish. */\n sceneElementsMax: 300,\n sceneElementTextMax: 2_000,\n sceneCharactersMax: 20,\n /** Script generation output. */\n scenesMax: 40,\n elementsPerSceneMax: 200,\n elementTextMax: 2_000,\n titleMax: 120,\n locationMax: 120,\n timeMax: 40,\n idMax: 64,\n} as const;\n\n// ---- Character skeleton (the shape `screenwriter_app`'s CharacterSkeletonEditor edits) ----\n\n/** Physical, Social, Psychological — the bone structure. Only `age` is required; every other field is optional. */\nexport const CHARACTER_SKELETON_FIELDS = {\n physical: [\n 'age',\n 'race',\n 'height',\n 'weight',\n 'appearance',\n 'sexOrientationExperience',\n 'posture',\n 'unusualCharacteristics',\n 'health',\n ],\n social: [\n 'occupationAndAttitude',\n 'education',\n 'money',\n 'class',\n 'relationships',\n 'homeLife',\n 'religion',\n 'placeInCommunity',\n 'politics',\n 'interests',\n ],\n psychological: [\n 'attitudeTowardLife',\n 'moralStandard',\n 'intelligence',\n 'ambitions',\n 'frustrations',\n 'fearsAndObsessions',\n 'extrovertOrIntrovert',\n 'specialQualities',\n 'proudestAchievement',\n 'greatestSorrow',\n 'greatestShame',\n 'noticedFirst',\n 'secret',\n 'noticedLast',\n 'coreContradictions',\n 'deepestDesire',\n ],\n} as const;\n\nexport const CHARACTER_SKELETON_KEYS = [\n ...CHARACTER_SKELETON_FIELDS.physical,\n ...CHARACTER_SKELETON_FIELDS.social,\n ...CHARACTER_SKELETON_FIELDS.psychological,\n] as const;\nexport type CharacterSkeletonKey = (typeof CHARACTER_SKELETON_KEYS)[number];\n\nconst skeletonText = z.string().max(AI_ACTION_LIMITS.skeletonFieldMax);\n\n/** A skeleton as it is stored and sent between client and API: `age` plus whichever other fields have a value. */\nexport const characterSkeletonSchema = z.object({\n age: skeletonText.min(1),\n ...Object.fromEntries(\n CHARACTER_SKELETON_KEYS.filter((k) => k !== 'age').map((k) => [\n k,\n skeletonText.optional(),\n ])\n ),\n} as { age: z.ZodString } & Record<\n Exclude<CharacterSkeletonKey, 'age'>,\n z.ZodOptional<z.ZodString>\n>);\nexport type CharacterSkeleton = z.infer<typeof characterSkeletonSchema>;\n\n/** The model-facing shape: every field required, `null` = the text does not say. */\nconst characterSkeletonModelSchema = z.strictObject({\n age: skeletonText.min(1),\n ...Object.fromEntries(\n CHARACTER_SKELETON_KEYS.filter((k) => k !== 'age').map((k) => [\n k,\n skeletonText.nullable(),\n ])\n ),\n} as { age: z.ZodString } & Record<\n Exclude<CharacterSkeletonKey, 'age'>,\n z.ZodNullable<z.ZodString>\n>);\n\n// ---- Script elements (the editor's element styles, minus the scene heading which is structured) ----\n\nexport const SCRIPT_ELEMENT_TYPES = [\n 'action',\n 'character',\n 'parenthetical',\n 'dialogue',\n 'transition',\n] as const;\nexport type ScriptElementType = (typeof SCRIPT_ELEMENT_TYPES)[number];\n\nexport const scriptElementSchema = z.strictObject({\n type: z.enum(SCRIPT_ELEMENT_TYPES),\n text: z.string().min(1).max(AI_ACTION_LIMITS.elementTextMax),\n});\nexport type ScriptElement = z.infer<typeof scriptElementSchema>;\n\nexport const SCENE_SETTINGS = ['int', 'ext', 'intExt'] as const;\nexport const sceneHeadingSchema = z.strictObject({\n setting: z.enum(SCENE_SETTINGS),\n location: z.string().min(1).max(AI_ACTION_LIMITS.locationMax),\n /** \"DAY\", \"NIGHT\", \"LATER\" … as it would follow the dash in a heading. */\n time: z.string().min(1).max(AI_ACTION_LIMITS.timeMax),\n});\nexport type SceneHeading = z.infer<typeof sceneHeadingSchema>;\n\nexport const generatedSceneSchema = z.strictObject({\n heading: sceneHeadingSchema,\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.elementsPerSceneMax),\n});\nexport type GeneratedScene = z.infer<typeof generatedSceneSchema>;\n\n// ---- 1. generate-character-skeleton ----\n\nexport const generateCharacterSkeletonRequestSchema = z.strictObject({\n /** A free-form paragraph describing the character. */\n text: z.string().trim().min(1).max(AI_ACTION_LIMITS.descriptionMax),\n /** BCP 47 tag the skeleton values are written in. Default: the language of `text`. */\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type GenerateCharacterSkeletonRequest = z.infer<\n typeof generateCharacterSkeletonRequestSchema\n>;\n\nexport const generateCharacterSkeletonModelSchema = z.strictObject({\n skeleton: characterSkeletonModelSchema,\n});\nexport const generateCharacterSkeletonResultSchema = z.strictObject({\n skeleton: characterSkeletonSchema,\n});\nexport type GenerateCharacterSkeletonResult = z.infer<\n typeof generateCharacterSkeletonResultSchema\n>;\n\n// ---- 2. generate-script ----\n\nexport const generateScriptRequestSchema = z.strictObject({\n /** The story in common language: a premise, a synopsis or a full retelling. */\n story: z.string().trim().min(1).max(AI_ACTION_LIMITS.storyMax),\n title: z.string().trim().max(AI_ACTION_LIMITS.titleMax).optional(),\n /** BCP 47 tag the script is written in. Default: the language of `story`. */\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type GenerateScriptRequest = z.infer<typeof generateScriptRequestSchema>;\n\nexport const generateScriptModelSchema = z.strictObject({\n title: z.string().max(AI_ACTION_LIMITS.titleMax).nullable(),\n scenes: z.array(generatedSceneSchema).min(1).max(AI_ACTION_LIMITS.scenesMax),\n});\nexport const generateScriptResultSchema = generateScriptModelSchema;\nexport type GenerateScriptResult = z.infer<typeof generateScriptResultSchema>;\n\n// ---- 3. polish-character-dialogue ----\n\nexport const dialogueLineSchema = z.strictObject({\n /** The caller's own id for the line, echoed back so the result maps onto it. */\n id: z.string().min(1).max(AI_ACTION_LIMITS.idMax),\n text: z.string().min(1).max(AI_ACTION_LIMITS.dialogueTextMax),\n});\nexport type DialogueLine = z.infer<typeof dialogueLineSchema>;\n\nexport const polishCharacterDialogueRequestSchema = z.strictObject({\n character: z.string().trim().min(1).max(AI_ACTION_LIMITS.characterNameMax),\n skeleton: characterSkeletonSchema,\n /** One character's lines, in script order. */\n dialogues: z\n .array(dialogueLineSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.dialoguesMax),\n /** How much to change; default `medium`. */\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type PolishCharacterDialogueRequest = z.infer<\n typeof polishCharacterDialogueRequestSchema\n>;\n\nexport const polishCharacterDialogueModelSchema = z.strictObject({\n /** The same ids in the same order, each with the polished line. */\n dialogues: z\n .array(dialogueLineSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.dialoguesMax),\n});\nexport const polishCharacterDialogueResultSchema =\n polishCharacterDialogueModelSchema;\nexport type PolishCharacterDialogueResult = z.infer<\n typeof polishCharacterDialogueResultSchema\n>;\n\n// ---- 4. polish-scene ----\n\nexport const sceneCharacterSchema = z.strictObject({\n /** The name as it appears in the script's character cues. */\n name: z.string().trim().min(1).max(AI_ACTION_LIMITS.characterNameMax),\n skeleton: characterSkeletonSchema,\n});\nexport type SceneCharacter = z.infer<typeof sceneCharacterSchema>;\n\nexport const polishSceneRequestSchema = z.strictObject({\n scene: z.strictObject({\n /** The scene heading as text, e.g. \"INT. LAB - DAY\". Context only: it is not rewritten. */\n heading: z\n .string()\n .max(AI_ACTION_LIMITS.locationMax + AI_ACTION_LIMITS.timeMax + 16)\n .optional(),\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneElementsMax),\n }),\n /** A skeleton for every character involved in the scene. */\n characters: z\n .array(sceneCharacterSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneCharactersMax),\n intensity: z.enum(['light', 'medium', 'bold']).optional(),\n language: z.string().max(AI_ACTION_LIMITS.languageMax).optional(),\n});\nexport type PolishSceneRequest = z.infer<typeof polishSceneRequestSchema>;\n\n/** The scene may be freely rewritten, so the result is a fresh element list rather than a per-id mapping. */\nexport const polishSceneModelSchema = z.strictObject({\n elements: z\n .array(scriptElementSchema)\n .min(1)\n .max(AI_ACTION_LIMITS.sceneElementsMax),\n});\nexport const polishSceneResultSchema = polishSceneModelSchema;\nexport type PolishSceneResult = z.infer<typeof polishSceneResultSchema>;\n\n// ---- Registry ----\n\n/** Action -> schema of what the model returns (stored on the ShapeShyft endpoint). */\nexport const AI_ACTION_MODEL_SCHEMAS = {\n 'generate-character-skeleton': generateCharacterSkeletonModelSchema,\n 'generate-script': generateScriptModelSchema,\n 'polish-character-dialogue': polishCharacterDialogueModelSchema,\n 'polish-scene': polishSceneModelSchema,\n} as const satisfies Record<AiAction, z.ZodType>;\n\n/** Action -> schema of the request body the client sends. */\nexport const AI_ACTION_REQUEST_SCHEMAS = {\n 'generate-character-skeleton': generateCharacterSkeletonRequestSchema,\n 'generate-script': generateScriptRequestSchema,\n 'polish-character-dialogue': polishCharacterDialogueRequestSchema,\n 'polish-scene': polishSceneRequestSchema,\n} as const satisfies Record<AiAction, z.ZodType>;\n\n/** What `POST /ai/{action}` returns in `data`: the normalised result plus what the call cost. */\nexport interface AiActionUsage {\n /** Credits charged (0 for a site admin). */\n credits: number;\n promptTokens: number;\n completionTokens: number;\n}\nexport interface AiActionResponse<R> {\n result: R;\n usage: AiActionUsage;\n}\n","import { z } from 'zod';\nimport type { AiTask } from '../ai/index.js';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/**\n * Generic jobs (spec 05 §6.19, §13; slice B9). A job is one row of `jobs`; `ai_jobs` rows are mirrored as `ai.*`\n * jobs (decision D21a) so `/ai/jobs/:id` and `/jobs/:id` read the same job.\n */\n\nexport const JOB_STATUSES = [\n 'queued',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport type JobStatus = (typeof JOB_STATUSES)[number];\nexport const TERMINAL_JOB_STATUSES = [\n 'succeeded',\n 'failed',\n 'cancelled',\n] as const;\nexport const isTerminalJobStatus = (s: JobStatus): boolean =>\n (TERMINAL_JOB_STATUSES as readonly string[]).includes(s);\n\nexport const JOB_LANES = [\n 'ai',\n 'interactive',\n 'bulk',\n 'system',\n 'provider',\n] as const;\nexport type JobLane = (typeof JOB_LANES)[number];\n\n/**\n * Closed vocabulary of job kinds, `<family>.<variant>` (R10). Every kind has a `job_kind_config` row; a kind\n * without a registered runner is seeded disabled and `POST /jobs` answers `JOB_KIND_DISABLED`. Extend by adding a\n * member here and a row in `screenwriter_api/src/services/jobs/kinds.ts`. `test.*` kinds exist only to prove the\n * framework and are enabled only under `AI_TEST_MODE=1`.\n */\nexport const JOB_KINDS = [\n 'ai.review',\n 'ai.polish',\n 'ai.describe',\n 'export.pdf',\n 'export.fdx',\n 'export.fountain',\n 'export.fadein',\n 'export.fadewright',\n 'export.json',\n 'export.docx',\n 'watermark.batch',\n 'import.fdx',\n 'import.fountain',\n 'import.fadein',\n 'import.pdf',\n 'import.ocr',\n 'import.celtx',\n 'import.scrivener',\n 'import.fdxt',\n 'report.render',\n 'doc.applyTemplate',\n 'doc.importOver',\n 'doc.snapshotOpen',\n 'doc.versionRestore',\n 'doc.compare',\n 'doc.normalize',\n 'doc.renormalize',\n 'doc.compact',\n 'snapshot.project',\n 'project.duplicate',\n 'asset.derive',\n 'account.export',\n 'system.emailSend',\n 'system.emailDigest',\n 'system.writingReminder',\n 'system.pushSend',\n 'system.purge',\n 'system.retentionSweep',\n 'template.thumbnail',\n // reserved for media adapters (spec 11 §6.2): registered, seeded disabled\n 'image.generate',\n 'image.edit',\n 'image.upscale',\n 'image.turnaround',\n 'video.generate',\n 'video.extend',\n 'video.upscale',\n 'video.lipSync',\n 'voice.tts',\n 'voice.cloneProfile',\n 'voice.change',\n 'music.generate',\n 'sfx.generate',\n 'audio.isolate',\n 'model3d.generate',\n 'model3d.convert',\n 'model3d.rig',\n 'storyboard.generate',\n 'animatic.assemble',\n 'timeline.export',\n // framework tests\n 'test.echo',\n 'test.flaky',\n] as const;\nexport type JobKind = (typeof JOB_KINDS)[number];\nexport const jobKindSchema = z.enum(JOB_KINDS);\n\n/** The `ai.*` kind an `AiTask` mirrors as (its `subkind` is the task itself). */\nexport function aiKindForTask(task: AiTask): JobKind {\n return task.startsWith('polish') ? 'ai.polish' : 'ai.review';\n}\nexport const isAiKind = (kind: string): boolean => kind.startsWith('ai.');\n\nexport interface JobProgress {\n /** 0..1 */\n fraction: number;\n stage: string | null;\n /** An i18n key plus params, never prose (spec 05 §13.6). */\n message: string | null;\n}\n\nexport interface JobUsage {\n promptTokens?: number;\n completionTokens?: number;\n model?: string | null;\n pages?: number;\n}\n\n/** What `GET /jobs/:id` says about an output: no storage key, no URL (fetch those from `/jobs/:id/outputs`). */\nexport interface JobOutputSummary {\n name: string;\n mimeType: string;\n sizeBytes: number;\n recipientId?: string;\n assetId?: string;\n documentId?: string;\n}\n\n/** `GET /jobs/:jobId` never carries `request` or `result` bodies (spec 05 §10 rule 5), only summaries. */\nexport interface Job {\n id: string;\n kind: JobKind;\n subkind: string | null;\n status: JobStatus;\n progress: JobProgress;\n documentId: string | null;\n /** Small scalar digest of the request (long strings dropped, arrays counted). */\n requestSummary: Record<string, unknown>;\n sources: JobSource[];\n estimate?: JobEstimate;\n quotedCredits?: number | null;\n chargedCredits?: number | null;\n refundedCredits?: number | null;\n error?: string | null;\n errorCode?: string | null;\n usage?: JobUsage;\n outputs?: JobOutputSummary[];\n cancelRequested: boolean;\n sourcesChangedDuringRun?: boolean | null;\n attempt: number;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\nexport interface JobEstimate {\n credits: number;\n billable: boolean;\n}\n\nexport const jobSourceSchema = z.object({\n documentId: z.string().min(1),\n snapshotId: z.string().min(1).optional(),\n targetKind: z.string().min(1).max(40),\n targetId: z.string().min(1).max(100),\n});\nexport type JobSource = z.infer<typeof jobSourceSchema> & {\n sourceHash?: string;\n};\n\n/** `POST /jobs`. `idempotencyKey` (or the `Idempotency-Key` header) makes a retried create return the original job. */\nexport const jobCreateSchema = z.object({\n kind: jobKindSchema,\n input: z.record(z.string(), z.unknown()).default({}),\n sources: z.array(jobSourceSchema).max(20).default([]),\n idempotencyKey: z.string().min(1).max(128).optional(),\n maxCredits: z.number().int().min(0).optional(),\n dryRun: z.boolean().optional(),\n});\nexport type JobCreateRequest = z.input<typeof jobCreateSchema>;\n\n/** `dryRun: true` answers this instead of a job. */\nexport interface JobDryRunResponse {\n estimate: JobEstimate;\n}\n\n/** `?kind=` is exact (`export.pdf`) or a family prefix ending in a dot (`ai.`). */\nexport const jobListQuerySchema = cursorQuerySchema.extend({\n documentId: z.string().min(1).optional(),\n kind: z\n .string()\n .regex(/^[A-Za-z0-9]+(\\.[A-Za-z0-9]*)?$/)\n .optional(),\n status: z.enum(JOB_STATUSES).optional(),\n});\nexport type JobListQuery = z.input<typeof jobListQuerySchema>;\n\n/** `GET /jobs/:jobId?wait=N` long-polls up to N seconds (max 120) until status or progress stage changes. */\nexport const JOB_WAIT_MAX_S = 120;\nexport const jobGetQuerySchema = z.object({\n wait: z.coerce.number().int().min(0).max(JOB_WAIT_MAX_S).optional(),\n});\nexport type JobGetQuery = z.input<typeof jobGetQuerySchema>;\n\nexport interface JobOutput extends JobOutputSummary {\n /** Signed download URL (or a `data:` URL for a small inline output). */\n url: string;\n expiresAt: string | null;\n}\nexport interface JobOutputsResponse {\n outputs: JobOutput[];\n}\n\n/** `GET /jobs/:jobId/recipients` item (batch watermark, B16). */\nexport interface JobRecipient {\n id: string;\n name: string;\n email: string | null;\n company: string | null;\n exportId: string;\n emailedAt: string | null;\n firstDownloadedAt: string | null;\n downloadCount: number;\n}\n\n/** `POST /webhooks/jobs/:adapterId`: every verified delivery answers this. */\nexport interface JobWebhookResponse {\n ok: true;\n}\n\n/** Header carrying `sha256=<hex HMAC-SHA256(secret, raw body)>` on a provider webhook. */\nexport const JOB_WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\n/** The generic `Idempotency-Key` header (spec 05 §6.25). Values are 1-128 characters. */\nexport const IDEMPOTENCY_HEADER = 'Idempotency-Key';\nexport const IDEMPOTENT_REPLAY_HEADER = 'Idempotent-Replayed';\nexport const idempotencyKeySchema = z.string().min(1).max(128);\n","/**\n * Reports (spec 09 §10 F-RPT-000..018, spec 05 §6.18), slice B10.\n *\n * `REPORT_KINDS` belongs in `writing_core` (spec 09 R25) but Tasks 29-35 have not landed there; until they do the\n * vocabulary, the options and the columns live here so the API, the client and MCP share one declaration.\n * A report is a list of tables; CSV, HTML and PDF are all rendered from those same tables, which is what\n * F-RPT-000's acceptance (\"CSV and PDF contain the same rows\") rests on.\n */\nimport { z } from 'zod';\nimport { sourceParamSchema, docSourceSchema } from '../reads/index.js';\n\nexport const REPORT_KINDS = [\n 'scene',\n 'location',\n 'character',\n 'cast',\n 'dialogue',\n 'script',\n 'text',\n 'notes',\n 'synopsis',\n 'revisions',\n 'tags',\n 'statistics',\n 'inclusivity',\n 'presentProgressive',\n 'dayOutOfDays',\n 'shotList',\n 'structure',\n 'characterArcs',\n] as const;\nexport type ReportKind = (typeof REPORT_KINDS)[number];\n\nexport const REPORT_FORMATS = ['json', 'csv', 'pdf', 'html'] as const;\nexport type ReportFormat = (typeof REPORT_FORMATS)[number];\n\n/** Documents up to this many pages run a report inline; larger ones answer with a `report.render` job (spec 05 §6.18). */\nexport const REPORT_SYNC_MAX_PAGES = 200;\n\nexport interface ReportOptionDef {\n name: string;\n type: 'boolean' | 'number' | 'string' | 'enum' | 'stringList';\n default?: boolean | number | string | string[];\n values?: readonly string[];\n min?: number;\n max?: number;\n required?: boolean;\n description?: string;\n}\n\nexport interface ReportColumn {\n id: string;\n label: string;\n align?: 'left' | 'right';\n}\n\nexport type ReportCell = string | number | null;\nexport type ReportRow = Record<string, ReportCell>;\n\nexport interface ReportTable {\n id: string;\n title?: string;\n columns: ReportColumn[];\n rows: ReportRow[];\n /** Optional totals row, rendered last (CSV, HTML and PDF all include it). */\n footer?: ReportRow;\n}\n\nexport interface ReportResult {\n kind: ReportKind;\n title: string;\n documentId: string;\n /** `live`, `snapshot:<id>` or `version:<id>`. */\n source: string;\n options: Record<string, unknown>;\n tables: ReportTable[];\n /** Set when the report does not apply (e.g. present-progressive in a language without the construction). */\n notice?: string;\n}\n\nexport interface ReportKindInfo {\n kind: ReportKind;\n featureId: string;\n title: string;\n /** False until the report is built; running it answers 501 `REPORT_KIND_UNAVAILABLE`. */\n available: boolean;\n unavailableReason?: string;\n options: ReportOptionDef[];\n /** Column ids of the main table(s), in order. */\n columns: ReportColumn[];\n formats: readonly ReportFormat[];\n}\n\nconst col = (id: string, label: string, align?: 'right'): ReportColumn => ({\n id,\n label,\n ...(align ? { align } : {}),\n});\nconst bool = (\n name: string,\n def: boolean,\n description?: string\n): ReportOptionDef => ({\n name,\n type: 'boolean',\n default: def,\n ...(description ? { description } : {}),\n});\nconst list = (name: string, description?: string): ReportOptionDef => ({\n name,\n type: 'stringList',\n default: [],\n ...(description ? { description } : {}),\n});\nconst en = (\n name: string,\n values: readonly string[],\n def: string\n): ReportOptionDef => ({ name, type: 'enum', values, default: def });\n\ninterface ReportDef {\n featureId: string;\n title: string;\n options: ReportOptionDef[];\n columns: ReportColumn[];\n unavailable?: string;\n}\n\n/** Column and option declarations. The tables a report returns use exactly these column ids. */\nexport const REPORT_DEFS: Record<ReportKind, ReportDef> = {\n scene: {\n featureId: 'F-RPT-001',\n title: 'Scene report',\n options: [\n en(\n 'sort',\n ['scriptOrder', 'sceneNumber', 'location', 'scriptDay'],\n 'scriptOrder'\n ),\n bool('includeOmitted', false),\n ],\n columns: [\n col('number', 'Scene'),\n col('intro', 'Intro'),\n col('location', 'Location'),\n col('time', 'Time'),\n col('heading', 'Heading'),\n col('page', 'Page'),\n col('length', 'Length'),\n col('estTime', 'Est. time', 'right'),\n col('synopsis', 'Synopsis'),\n col('colour', 'Colour'),\n col('speaking', 'Speaking'),\n col('nonSpeaking', 'Non-speaking'),\n col('scriptDay', 'Script day'),\n ],\n },\n location: {\n featureId: 'F-RPT-002',\n title: 'Location report',\n options: [en('sort', ['name', 'firstAppearance', 'length'], 'name')],\n columns: [\n col('location', 'Location'),\n col('intExt', 'INT/EXT'),\n col('times', 'Times of day'),\n col('scenes', 'Scenes'),\n col('pages', 'Pages'),\n col('eighths', 'Length'),\n col('sceneCount', 'Scene count', 'right'),\n ],\n },\n character: {\n featureId: 'F-RPT-003',\n title: 'Character report',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n bool('includeNonSpeaking', false),\n {\n name: 'monologueWords',\n type: 'number',\n default: 100,\n min: 1,\n max: 10000,\n },\n bool('includeDialogue', false),\n ],\n columns: [\n col('character', 'Character'),\n col('scenes', 'Speaking scenes'),\n col('nonSpeakingScenes', 'Non-speaking scenes'),\n col('extensions', 'Extensions'),\n col('parentheticals', 'Parentheticals', 'right'),\n col('monologues', 'Monologues', 'right'),\n col('dialogue', 'Dialogue'),\n ],\n },\n cast: {\n featureId: 'F-RPT-004',\n title: 'Cast report',\n options: [\n en(\n 'sort',\n ['alphabetical', 'scriptOrder', 'dialogueCount', 'words'],\n 'alphabetical'\n ),\n ],\n columns: [\n col('character', 'Character'),\n col('dialogues', 'Dialogues', 'right'),\n col('words', 'Words', 'right'),\n col('lines', 'Lines', 'right'),\n col('speakingScenes', 'Speaking scenes', 'right'),\n col('totalScenes', 'Total scenes', 'right'),\n col('pagesPresent', 'Pages present'),\n col('firstAppearance', 'First appearance'),\n col('gender', 'Gender'),\n col('role', 'Role'),\n col('age', 'Age'),\n ],\n },\n dialogue: {\n featureId: 'F-RPT-005',\n title: 'Dialogue report',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n bool('includeParentheticals', false),\n ],\n columns: [\n col('number', '#', 'right'),\n col('scene', 'Scene'),\n col('page', 'Page'),\n col('character', 'Character'),\n col('text', 'Dialogue'),\n ],\n },\n script: {\n featureId: 'F-RPT-006',\n title: 'Script report',\n options: [list('styles', 'Style ids or roles; empty means every element')],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('style', 'Style'),\n col('text', 'Text'),\n ],\n },\n text: {\n featureId: 'F-RPT-007',\n title: 'Text report',\n options: [\n {\n name: 'q',\n type: 'string',\n required: true,\n description: 'Text to find',\n },\n en('mode', ['text', 'regex'], 'text'),\n list('styles', 'Restrict to these style ids'),\n ],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('style', 'Style'),\n col('snippet', 'Context'),\n ],\n },\n notes: {\n featureId: 'F-RPT-008',\n title: 'Notes report',\n options: [\n list('types'),\n list('authors'),\n en('status', ['any', 'open', 'resolved'], 'any'),\n list('colours'),\n ],\n columns: [\n col('order', '#', 'right'),\n col('colour', 'Colour'),\n col('type', 'Type'),\n col('title', 'Title'),\n col('body', 'Note'),\n col('author', 'Author'),\n col('created', 'Created'),\n col('modified', 'Modified'),\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('status', 'Status'),\n col('replies', 'Replies', 'right'),\n ],\n },\n synopsis: {\n featureId: 'F-RPT-009',\n title: 'Synopsis report',\n options: [bool('includeEmpty', true)],\n columns: [\n col('number', 'Scene'),\n col('heading', 'Heading'),\n col('synopsis', 'Synopsis'),\n col('colour', 'Colour'),\n ],\n },\n revisions: {\n featureId: 'F-RPT-010',\n title: 'Revisions report',\n options: [list('sets', 'Revision set ids; empty means every set')],\n columns: [\n col('set', 'Revision'),\n col('colour', 'Colour'),\n col('mark', 'Mark'),\n col('date', 'Date'),\n col('pages', 'Pages'),\n col('scenes', 'Scenes'),\n col('revisedElements', 'Revised elements', 'right'),\n ],\n },\n tags: {\n featureId: 'F-RPT-011',\n title: 'Tags report',\n options: [\n en('mode', ['byScene', 'byCategory'], 'byScene'),\n list('categories', 'Tag category ids; empty means all'),\n ],\n columns: [\n col('scene', 'Scene'),\n col('heading', 'Heading'),\n col('page', 'Page'),\n col('length', 'Length'),\n col('scriptDay', 'Script day'),\n col('category', 'Category'),\n col('entities', 'Entities'),\n ],\n },\n statistics: {\n featureId: 'F-RPT-012',\n title: 'Statistics report',\n options: [\n { name: 'topWords', type: 'number', default: 20, min: 0, max: 200 },\n { name: 'longestScenes', type: 'number', default: 5, min: 0, max: 50 },\n ],\n columns: [col('metric', 'Metric'), col('value', 'Value', 'right')],\n },\n inclusivity: {\n featureId: 'F-RPT-013',\n title: 'Inclusivity and gender analysis',\n options: [en('by', ['gender', 'role'], 'gender')],\n columns: [\n col('group', 'Group'),\n col('characters', 'Characters', 'right'),\n col('dialogues', 'Dialogues', 'right'),\n col('words', 'Words', 'right'),\n col('scenesSpeaking', 'Scenes speaking', 'right'),\n col('wordsPct', 'Words %', 'right'),\n ],\n },\n presentProgressive: {\n featureId: 'F-RPT-014',\n title: 'Present progressive check',\n options: [],\n columns: [\n col('page', 'Page'),\n col('scene', 'Scene'),\n col('match', 'Match'),\n col('text', 'Action line'),\n ],\n },\n dayOutOfDays: {\n featureId: 'F-RPT-015',\n title: 'Day out of days',\n options: [],\n columns: [\n col('character', 'Character'),\n col('workDays', 'Work days', 'right'),\n col('holds', 'Holds', 'right'),\n ],\n },\n shotList: {\n featureId: 'F-RPT-016',\n title: 'Shot list',\n options: [],\n columns: [\n col('scene', 'Scene'),\n col('shot', 'Shot'),\n col('label', 'Label'),\n col('description', 'Description'),\n col('size', 'Size'),\n col('angle', 'Angle'),\n col('movement', 'Movement'),\n col('lens', 'Lens'),\n col('durationSec', 'Duration (s)', 'right'),\n ],\n },\n structure: {\n featureId: 'F-RPT-017',\n title: 'Structure report',\n options: [],\n columns: [\n col('node', 'Act / sequence / beat'),\n col('goal', 'Goal pages'),\n col('actual', 'Actual pages'),\n col('delta', 'Delta', 'right'),\n ],\n unavailable:\n 'Outline page goals are not modelled in writing_core yet (spec 01 §5.13 goals), so there is nothing to compare actual pages with',\n },\n characterArcs: {\n featureId: 'F-RPT-018',\n title: 'Character arcs',\n options: [\n list('characters', 'Entity ids or names; empty means every character'),\n ],\n columns: [\n col('character', 'Character'),\n col('scene', 'Scene'),\n col('heading', 'Heading'),\n col('note', 'Arc note'),\n ],\n },\n};\n\nexport function reportKindInfos(): ReportKindInfo[] {\n return REPORT_KINDS.map((kind) => {\n const d = REPORT_DEFS[kind];\n return {\n kind,\n featureId: d.featureId,\n title: d.title,\n available: !d.unavailable,\n ...(d.unavailable ? { unavailableReason: d.unavailable } : {}),\n options: d.options,\n columns: d.columns,\n formats: REPORT_FORMATS,\n };\n });\n}\n\nexport const isReportKind = (v: unknown): v is ReportKind =>\n typeof v === 'string' && (REPORT_KINDS as readonly string[]).includes(v);\n\nexport type ParsedReportOptions =\n | { ok: true; options: Record<string, unknown> }\n | { ok: false; issues: { path: string; message: string }[] };\n\n/** Validates and defaults `raw` against the kind's option declarations (unknown keys are refused). */\nexport function parseReportOptions(\n kind: ReportKind,\n raw: unknown\n): ParsedReportOptions {\n const defs = REPORT_DEFS[kind].options;\n const issues: { path: string; message: string }[] = [];\n if (raw === undefined || raw === null) raw = {};\n if (typeof raw !== 'object' || Array.isArray(raw))\n return {\n ok: false,\n issues: [{ path: '', message: 'options must be an object' }],\n };\n const input = raw as Record<string, unknown>;\n const known = new Set(defs.map((d) => d.name));\n for (const k of Object.keys(input))\n if (!known.has(k)) issues.push({ path: k, message: 'unknown option' });\n const out: Record<string, unknown> = {};\n for (const d of defs) {\n const v = input[d.name];\n if (v === undefined) {\n if (d.required) issues.push({ path: d.name, message: 'required' });\n else if (d.default !== undefined)\n out[d.name] = Array.isArray(d.default) ? [...d.default] : d.default;\n continue;\n }\n switch (d.type) {\n case 'boolean':\n if (typeof v !== 'boolean')\n issues.push({ path: d.name, message: 'must be a boolean' });\n else out[d.name] = v;\n break;\n case 'number':\n if (\n typeof v !== 'number' ||\n !Number.isFinite(v) ||\n (d.min !== undefined && v < d.min) ||\n (d.max !== undefined && v > d.max)\n ) {\n issues.push({\n path: d.name,\n message: `must be a number${d.min !== undefined ? ` from ${d.min}` : ''}${d.max !== undefined ? ` to ${d.max}` : ''}`,\n });\n } else out[d.name] = v;\n break;\n case 'string':\n if (\n typeof v !== 'string' ||\n (d.required && v.length === 0) ||\n v.length > 500\n )\n issues.push({\n path: d.name,\n message: 'must be a non-empty string of at most 500 characters',\n });\n else out[d.name] = v;\n break;\n case 'enum':\n if (typeof v !== 'string' || !d.values!.includes(v))\n issues.push({\n path: d.name,\n message: `must be one of ${d.values!.join(', ')}`,\n });\n else out[d.name] = v;\n break;\n case 'stringList':\n if (\n !Array.isArray(v) ||\n v.length > 500 ||\n v.some((x) => typeof x !== 'string')\n )\n issues.push({ path: d.name, message: 'must be an array of strings' });\n else out[d.name] = v;\n break;\n }\n }\n return issues.length > 0 ? { ok: false, issues } : { ok: true, options: out };\n}\n\n// ─── Requests ───────────────────────────────────────────────────────────────\n\n/** `GET /documents/:did/reports/:kind?source=&options=<json>`. */\nexport const reportGetQuerySchema = z.object({\n source: sourceParamSchema.optional(),\n options: z.string().max(20_000).optional(),\n});\nexport type ReportGetQuery = z.infer<typeof reportGetQuerySchema>;\n\n/** `POST /documents/:did/reports`. `json` answers the result; the other formats a `report.render` job. */\nexport const reportCreateSchema = z.object({\n kind: z.enum(REPORT_KINDS),\n source: docSourceSchema.optional(),\n options: z.record(z.string(), z.unknown()).default({}),\n format: z.enum(REPORT_FORMATS).default('json'),\n});\nexport type ReportCreateRequest = z.infer<typeof reportCreateSchema>;\n\n/** The `input` of a `report.render` job (`sources[0]` is the document). */\nexport const reportRenderInputSchema = z.object({\n kind: z.enum(REPORT_KINDS),\n source: z.string().default('live'),\n options: z.record(z.string(), z.unknown()).default({}),\n format: z.enum(REPORT_FORMATS).default('csv'),\n});\nexport type ReportRenderInput = z.infer<typeof reportRenderInputSchema>;\n\n// ─── Rendering (shared by the API's CSV/HTML/PDF and by any client that wants the same text) ─────────────\n\nexport const cellText = (v: ReportCell): string =>\n v === null || v === undefined ? '' : String(v);\n\nconst csvField = (s: string) =>\n /[\",\\r\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n\n/** CSV of every table (a title line and a blank line between tables when there is more than one). RFC 4180 quoting, CRLF. */\nexport function reportToCsv(result: Pick<ReportResult, 'tables'>): string {\n const blocks = result.tables.map((t) => {\n const lines: string[] = [];\n if (result.tables.length > 1 && t.title) lines.push(csvField(t.title));\n lines.push(t.columns.map((c) => csvField(c.label)).join(','));\n for (const r of t.rows)\n lines.push(\n t.columns.map((c) => csvField(cellText(r[c.id] ?? null))).join(',')\n );\n if (t.footer)\n lines.push(\n t.columns\n .map((c) => csvField(cellText(t.footer![c.id] ?? null)))\n .join(',')\n );\n return lines.join('\\r\\n');\n });\n return blocks.join('\\r\\n\\r\\n') + '\\r\\n';\n}\n","/**\n * Production packets (spec 11 §7, spec 05 §6.22), slice B10. Schemas are the contract MCP and generators consume\n * (`scenePacketSchema` and friends); the API validates its own output against them in tests.\n * Asset lists are always empty until slice B11 (assets) lands.\n */\nimport { z } from 'zod';\n\nexport const PACKET_VERSION = 1;\n\n/**\n * `?snapshotId=&include=` shared by the four packet routes. `include` is a comma list added to the defaults (`assets` and\n * `script` are on by default; `neighbors` and `pages` are opt-in; `-script` and `-assets` switch a default off).\n */\nexport const PACKET_INCLUDE_FLAGS = [\n 'assets',\n 'assetUrls',\n 'script',\n 'neighbors',\n 'pages',\n] as const;\nexport const packetQuerySchema = z.object({\n snapshotId: z.string().min(1).optional(),\n include: z\n .preprocess(\n (v) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v,\n z.array(\n z.enum([\n 'assets',\n 'assetUrls=original',\n 'script',\n 'neighbors',\n 'pages',\n '-assets',\n '-script',\n ])\n )\n )\n .optional(),\n});\nexport type PacketQuery = z.infer<typeof packetQuerySchema>;\n\n/** 2 MB JSON cap (spec 11 §7.1): beyond it script text is truncated per element with `truncated: true`. */\nexport const PACKET_MAX_BYTES = 2 * 1024 * 1024;\n\nconst envelope = <K extends string, B extends z.ZodType>(kind: K, body: B) =>\n z.object({\n packetVersion: z.literal(PACKET_VERSION),\n kind: z.literal(kind),\n documentId: z.string(),\n documentTitle: z.string(),\n snapshotId: z.string().nullable(),\n templateId: z.string(),\n language: z.string(),\n generatedAt: z.string(),\n /** `packetHash` of the packet without `generatedAt`, `hash` and signed-URL fields (spec 11 §4.2). */\n hash: z.string(),\n truncated: z.boolean().optional(),\n body,\n });\n\nconst assetSummary = z\n .object({\n assetId: z.string(),\n role: z.string(),\n kind: z.string(),\n title: z.string(),\n })\n .passthrough();\n\nconst pages = z\n .object({ start: z.string(), end: z.string(), eighths: z.number().int() })\n .nullable();\n\nexport const packetElementSchema = z.union([\n z.object({\n id: z.string(),\n type: z.literal('character'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n extension: z.string().nullable(),\n }),\n z.object({\n id: z.string(),\n type: z.literal('parenthetical'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n }),\n z.object({\n id: z.string(),\n type: z.literal('dialogue'),\n text: z.string(),\n speakerEntityId: z.string().nullable(),\n dual: z.boolean(),\n lineIndex: z.number().int(),\n }),\n // every other role: sceneHeading, action, transition, shot, normal, ...\n z.object({\n id: z.string(),\n type: z\n .string()\n .refine((t) => !['character', 'parenthetical', 'dialogue'].includes(t)),\n text: z.string(),\n }),\n]);\nexport type PacketElement = z.infer<typeof packetElementSchema>;\n\nconst shotSummary = z.object({\n id: z.string(),\n number: z.string().nullable(),\n label: z.string().nullable(),\n status: z.string(),\n camera: z.record(z.string(), z.unknown()),\n estimatedDurationMs: z.number().nullable(),\n description: z.string().nullable(),\n elementIds: z.array(z.string()),\n contentHash: z.string(),\n assets: z.array(assetSummary),\n});\nexport type ShotSummary = z.infer<typeof shotSummary>;\n\nconst sceneRef = z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n synopsis: z.string(),\n});\n\nconst sceneHeader = z.object({\n id: z.string(),\n number: z.string().nullable(),\n ordinal: z.number().int(),\n omitted: z.boolean(),\n heading: z.object({\n raw: z.string(),\n intro: z.string().nullable(),\n location: z.string().nullable(),\n time: z.string().nullable(),\n }),\n locationEntityId: z.string().nullable(),\n synopsis: z.string(),\n color: z.string().nullable(),\n pages,\n estimatedDurationMs: z.number(),\n folders: z.array(\n z.object({ id: z.string(), kind: z.string(), title: z.string() })\n ),\n contentHash: z.string(),\n scriptDay: z.string().nullable(),\n});\n\nconst locationBlock = z\n .object({\n entityId: z.string(),\n name: z.string(),\n fields: z.record(z.string(), z.unknown()),\n description: z.string(),\n assets: z.array(assetSummary),\n })\n .nullable();\n\nexport const scenePacketBodySchema = z.object({\n scene: sceneHeader,\n script: z.array(packetElementSchema),\n cast: z.array(\n z.object({\n entityId: z.string(),\n name: z.string(),\n speaking: z.boolean(),\n lineCount: z.number().int(),\n wordCount: z.number().int(),\n firstAppearance: z.boolean(),\n summary: z.string(),\n fields: z.record(z.string(), z.unknown()),\n traits: z.record(z.string(), z.union([z.string(), z.number()])),\n assets: z.array(assetSummary),\n })\n ),\n location: locationBlock,\n elements: z.array(\n z.object({\n entityId: z.string(),\n kind: z.string(),\n name: z.string(),\n description: z.string(),\n tagCount: z.number().int(),\n assets: z.array(assetSummary),\n })\n ),\n shots: z.array(shotSummary),\n notes: z.array(\n z.object({\n id: z.string(),\n type: z.string(),\n text: z.string(),\n anchorElementId: z.string().nullable(),\n })\n ),\n sceneAssets: z.array(assetSummary),\n neighbors: z\n .object({ previous: sceneRef.nullable(), next: sceneRef.nullable() })\n .optional(),\n});\nexport const scenePacketSchema = envelope('scene', scenePacketBodySchema);\nexport type ScenePacket = z.infer<typeof scenePacketSchema>;\n\nexport const characterPacketBodySchema = z.object({\n character: z.object({\n id: z.string(),\n name: z.string(),\n aliases: z.array(z.string()),\n description: z.string(),\n fields: z.record(z.string(), z.unknown()),\n traits: z.record(z.string(), z.union([z.string(), z.number()])),\n attributes: z.record(z.string(), z.unknown()),\n contentHash: z.string(),\n }),\n ages: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n ageValue: z.number().nullable(),\n description: z.string(),\n skeleton: z.array(\n z.object({\n section: z.string().nullable(),\n label: z.string(),\n answer: z.string(),\n })\n ),\n appearances: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n description: z.string(),\n assetIds: z.array(z.string()),\n })\n ),\n sceneCount: z.number().int(),\n })\n ),\n skeleton: z.array(\n z.object({\n section: z.string().nullable(),\n label: z.string(),\n answer: z.string(),\n })\n ),\n stats: z.object({\n sceneCount: z.number().int(),\n speakingSceneCount: z.number().int(),\n lineCount: z.number().int(),\n wordCount: z.number().int(),\n firstSceneId: z.string().nullable(),\n lastSceneId: z.string().nullable(),\n }),\n scenes: z.array(\n z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n speaking: z.boolean(),\n lineCount: z.number().int(),\n ageId: z.string().nullable(),\n appearanceId: z.string().nullable(),\n })\n ),\n sampleDialogue: z.array(\n z.object({ elementId: z.string(), sceneId: z.string(), text: z.string() })\n ),\n relationships: z.array(\n z.object({\n entityId: z.string(),\n name: z.string(),\n sharedSceneCount: z.number().int(),\n })\n ),\n props: z.array(z.object({ entityId: z.string(), name: z.string() })),\n assets: z.array(assetSummary),\n});\nexport const characterPacketSchema = envelope(\n 'character',\n characterPacketBodySchema\n);\nexport type CharacterPacket = z.infer<typeof characterPacketSchema>;\n\nexport const locationPacketBodySchema = z.object({\n location: z.object({\n id: z.string(),\n name: z.string(),\n aliases: z.array(z.string()),\n description: z.string(),\n fields: z.record(z.string(), z.unknown()),\n parent: z.object({ id: z.string(), name: z.string() }).nullable(),\n children: z.array(z.object({ id: z.string(), name: z.string() })),\n contentHash: z.string(),\n }),\n versions: z.array(\n z.object({\n id: z.string(),\n label: z.string(),\n description: z.string(),\n setting: z.string().nullable(),\n sceneCount: z.number().int(),\n })\n ),\n scenes: z.array(\n z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.string(),\n time: z.string().nullable(),\n pages,\n cast: z.array(z.string()),\n versionId: z.string().nullable(),\n })\n ),\n totals: z.object({\n sceneCount: z.number().int(),\n eighths: z.number().int(),\n timesOfDay: z.record(z.string(), z.number().int()),\n }),\n setElements: z.array(\n z.object({ entityId: z.string(), kind: z.string(), name: z.string() })\n ),\n assets: z.array(assetSummary),\n});\nexport const locationPacketSchema = envelope(\n 'location',\n locationPacketBodySchema\n);\nexport type LocationPacket = z.infer<typeof locationPacketSchema>;\n\nexport const shotPacketBodySchema = z.object({\n shot: shotSummary.extend({\n sceneId: z.string(),\n range: z\n .object({\n startElementId: z.string(),\n endElementId: z.string(),\n text: z.string(),\n })\n .nullable(),\n }),\n scene: z.object({\n id: z.string(),\n number: z.string().nullable(),\n heading: z.object({\n raw: z.string(),\n intro: z.string().nullable(),\n location: z.string().nullable(),\n time: z.string().nullable(),\n }),\n locationEntityId: z.string().nullable(),\n contentHash: z.string(),\n }),\n script: z.array(packetElementSchema),\n subjects: z.array(\n z.object({\n entityId: z.string(),\n kind: z.string(),\n name: z.string(),\n fields: z.record(z.string(), z.unknown()),\n assets: z.array(assetSummary),\n })\n ),\n location: locationBlock,\n previousShot: shotSummary.nullable(),\n nextShot: shotSummary.nullable(),\n});\nexport const shotPacketSchema = envelope('shot', shotPacketBodySchema);\nexport type ShotPacket = z.infer<typeof shotPacketSchema>;\n\nexport type AnyPacket =\n ScenePacket | CharacterPacket | LocationPacket | ShotPacket;\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n/**\n * The asset library (slice B11; spec 05 §6.13, §8.6, §14.1, spec 11 §3 and §4.5). Assets are workspace files with metadata;\n * bytes never pass through the API (presigned multipart PUT to R2). This file holds the vocabularies, the DTOs and the\n * role-to-target table the server enforces (`ROLE_NOT_ALLOWED_FOR_TARGET`).\n */\n\n// ─── vocabularies ────────────────────────────────────────────────────────────\n\nexport const ASSET_KINDS = [\n 'image',\n 'video',\n 'audio',\n 'model3d',\n 'document',\n 'archive',\n 'data',\n] as const;\nexport type AssetKind = (typeof ASSET_KINDS)[number];\nexport const assetKindSchema = z.enum(ASSET_KINDS);\n\nexport const ASSET_ROLES = [\n // launch\n 'reference',\n 'headshot',\n 'photo',\n 'logo',\n 'beat_image',\n 'inline_image',\n 'panel_reference',\n 'location_scout',\n 'mood_board',\n 'attachment',\n // future production (valid now, unused by launch UI)\n 'turnaround',\n 'expression_sheet',\n 'costume_design',\n 'set_concept',\n 'set_plan',\n 'storyboard_frame',\n 'animatic',\n 'previz',\n 'rendered_video',\n 'rendered_shot',\n 'dialogue_audio',\n 'voice_sample',\n 'voice_profile',\n 'music_cue',\n 'sound_effect',\n 'lip_sync',\n 'captions',\n 'model3d',\n 'model3d_rig',\n 'texture',\n 'lora',\n 'timeline',\n] as const;\nexport type AssetRole = (typeof ASSET_ROLES)[number];\nexport const assetRoleSchema = z.enum(ASSET_ROLES);\n\nexport const ASSET_ROLE_GROUPS: Record<\n AssetRole,\n 'reference' | 'design' | 'storyboard' | 'video' | 'audio' | '3d' | 'other'\n> = {\n reference: 'reference',\n headshot: 'reference',\n photo: 'reference',\n logo: 'other',\n beat_image: 'other',\n inline_image: 'other',\n panel_reference: 'storyboard',\n location_scout: 'reference',\n mood_board: 'reference',\n attachment: 'other',\n turnaround: 'design',\n expression_sheet: 'design',\n costume_design: 'design',\n set_concept: 'design',\n set_plan: 'design',\n storyboard_frame: 'storyboard',\n animatic: 'video',\n previz: 'video',\n rendered_video: 'video',\n rendered_shot: 'video',\n dialogue_audio: 'audio',\n voice_sample: 'audio',\n voice_profile: 'audio',\n music_cue: 'audio',\n sound_effect: 'audio',\n lip_sync: 'video',\n captions: 'other',\n model3d: '3d',\n model3d_rig: '3d',\n texture: '3d',\n lora: 'other',\n timeline: 'other',\n};\n\nexport const ASSET_TARGET_KINDS = [\n 'document',\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'beat',\n 'title_page',\n 'snapshot',\n] as const;\nexport type AssetTargetKind = (typeof ASSET_TARGET_KINDS)[number];\nexport const assetTargetKindSchema = z.enum(ASSET_TARGET_KINDS);\n\n/**\n * Which target kinds a role may sit on (spec 05 §6.13: \"enforces spec 11's role-to-target table\"; spec 11 §3.7 lists the\n * roles but not the table, so this is the decision made in B11). A role not listed here may go on any target.\n */\nexport const ASSET_ROLE_TARGETS: Partial<\n Record<AssetRole, readonly AssetTargetKind[]>\n> = {\n headshot: ['entity'],\n turnaround: ['entity'],\n expression_sheet: ['entity'],\n costume_design: ['entity'],\n voice_sample: ['entity'],\n voice_profile: ['entity'],\n set_concept: ['entity', 'scene'],\n set_plan: ['entity', 'scene'],\n location_scout: ['entity', 'scene'],\n beat_image: ['beat'],\n inline_image: ['element'],\n panel_reference: ['element', 'scene', 'shot'],\n logo: ['title_page', 'document'],\n storyboard_frame: ['shot', 'scene'],\n animatic: ['shot', 'scene', 'document'],\n previz: ['shot', 'scene', 'document'],\n rendered_video: ['shot', 'scene', 'document'],\n rendered_shot: ['shot'],\n dialogue_audio: ['element', 'shot', 'scene'],\n music_cue: ['scene', 'shot', 'document'],\n sound_effect: ['scene', 'shot', 'element'],\n lip_sync: ['shot', 'element'],\n captions: ['scene', 'shot', 'document'],\n timeline: ['document', 'scene'],\n};\n/** Roles that only fit an entity of one kind (checked against `proj_entities.kind`). */\nexport const ASSET_ROLE_ENTITY_KINDS: Partial<\n Record<AssetRole, readonly string[]>\n> = {\n headshot: ['character'],\n turnaround: ['character'],\n expression_sheet: ['character'],\n costume_design: ['character'],\n voice_sample: ['character'],\n voice_profile: ['character'],\n set_concept: ['location'],\n set_plan: ['location'],\n location_scout: ['location'],\n};\n\nexport const ASSET_ORIGINS = [\n 'upload',\n 'import',\n 'generated',\n 'external_tool',\n] as const;\nexport type AssetOrigin = (typeof ASSET_ORIGINS)[number];\n\nexport const ASSET_VERSION_STATUSES = [\n 'uploading',\n 'processing',\n 'ready',\n 'failed',\n] as const;\nexport type AssetVersionStatus = (typeof ASSET_VERSION_STATUSES)[number];\n\nexport const STALENESS_VALUES = [\n 'fresh',\n 'stale',\n 'target_deleted',\n 'unknown',\n] as const;\nexport type Staleness = (typeof STALENESS_VALUES)[number];\n\n/** Multipart parts are this big (the last one smaller); an upload of at most one part is a single presigned PUT. */\nexport const ASSET_PART_SIZE_BYTES = 8 * 1024 * 1024;\n/** How many part PUTs the client helper runs at once. */\nexport const ASSET_UPLOAD_CONCURRENCY = 3;\n/** Presigned part URLs and the upload itself live this long (seconds); a resume re-signs. */\nexport const ASSET_UPLOAD_TTL_S = 3600;\n/** Presigned GET lifetime for `GET /assets/:aid/versions/:vid/url` (seconds). */\nexport const ASSET_URL_TTL_S = 300;\n\n/** Largest original per kind (spec 11 §3.2). */\nexport const ASSET_MAX_BYTES: Record<AssetKind, number> = {\n image: 100 * 1024 ** 2,\n video: 10 * 1024 ** 3,\n audio: 2 * 1024 ** 3,\n model3d: 5 * 1024 ** 3,\n document: 200 * 1024 ** 2,\n archive: 10 * 1024 ** 3,\n data: 50 * 1024 ** 2,\n};\n\n/** Extension -> kind and the MIME types accepted for it (spec 11 §3.2). The extension must be listed and the magic bytes must agree. */\nexport const ASSET_EXTENSIONS: Record<\n string,\n { kind: AssetKind; mimes: readonly string[] }\n> = {\n '.png': { kind: 'image', mimes: ['image/png'] },\n '.jpg': { kind: 'image', mimes: ['image/jpeg'] },\n '.jpeg': { kind: 'image', mimes: ['image/jpeg'] },\n '.webp': { kind: 'image', mimes: ['image/webp'] },\n '.avif': { kind: 'image', mimes: ['image/avif'] },\n '.gif': { kind: 'image', mimes: ['image/gif'] },\n '.heic': { kind: 'image', mimes: ['image/heic'] },\n '.heif': { kind: 'image', mimes: ['image/heif'] },\n '.svg': { kind: 'image', mimes: ['image/svg+xml'] },\n '.tif': { kind: 'image', mimes: ['image/tiff'] },\n '.tiff': { kind: 'image', mimes: ['image/tiff'] },\n '.exr': { kind: 'image', mimes: ['image/x-exr'] },\n '.psd': { kind: 'image', mimes: ['image/vnd.adobe.photoshop'] },\n '.mp4': { kind: 'video', mimes: ['video/mp4'] },\n '.mov': { kind: 'video', mimes: ['video/quicktime'] },\n '.webm': { kind: 'video', mimes: ['video/webm'] },\n '.mkv': { kind: 'video', mimes: ['video/x-matroska'] },\n '.wav': { kind: 'audio', mimes: ['audio/wav', 'audio/x-wav', 'audio/wave'] },\n '.aif': { kind: 'audio', mimes: ['audio/x-aiff', 'audio/aiff'] },\n '.aiff': { kind: 'audio', mimes: ['audio/x-aiff', 'audio/aiff'] },\n '.flac': { kind: 'audio', mimes: ['audio/flac'] },\n '.mp3': { kind: 'audio', mimes: ['audio/mpeg'] },\n '.aac': { kind: 'audio', mimes: ['audio/aac'] },\n '.m4a': { kind: 'audio', mimes: ['audio/mp4', 'audio/x-m4a'] },\n '.ogg': { kind: 'audio', mimes: ['audio/ogg'] },\n '.opus': { kind: 'audio', mimes: ['audio/ogg', 'audio/opus'] },\n '.glb': { kind: 'model3d', mimes: ['model/gltf-binary'] },\n '.gltf': { kind: 'model3d', mimes: ['model/gltf+json'] },\n '.usdz': { kind: 'model3d', mimes: ['model/vnd.usdz+zip'] },\n '.blend': {\n kind: 'model3d',\n mimes: ['application/x-blender', 'application/octet-stream'],\n },\n '.fbx': {\n kind: 'model3d',\n mimes: ['model/vnd.fbx', 'application/octet-stream'],\n },\n '.obj': { kind: 'model3d', mimes: ['model/obj', 'text/plain'] },\n '.stl': {\n kind: 'model3d',\n mimes: ['model/stl', 'application/sla', 'application/octet-stream'],\n },\n '.usda': { kind: 'model3d', mimes: ['model/vnd.usda', 'text/plain'] },\n '.usdc': {\n kind: 'model3d',\n mimes: ['model/vnd.usda', 'application/octet-stream'],\n },\n '.pdf': { kind: 'document', mimes: ['application/pdf'] },\n '.txt': { kind: 'document', mimes: ['text/plain'] },\n '.md': { kind: 'document', mimes: ['text/markdown'] },\n '.docx': {\n kind: 'document',\n mimes: [\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n ],\n },\n '.zip': {\n kind: 'archive',\n mimes: ['application/zip', 'application/x-zip-compressed'],\n },\n '.json': { kind: 'data', mimes: ['application/json'] },\n '.csv': { kind: 'data', mimes: ['text/csv'] },\n '.srt': { kind: 'data', mimes: ['application/x-subrip', 'text/plain'] },\n '.vtt': { kind: 'data', mimes: ['text/vtt'] },\n '.otio': {\n kind: 'data',\n mimes: ['application/otio+json', 'application/json'],\n },\n '.fcpxml': {\n kind: 'data',\n mimes: ['application/x-fcpxml', 'application/xml', 'text/xml'],\n },\n '.edl': { kind: 'data', mimes: ['application/edl', 'text/plain'] },\n};\n\n/** `.ext` of a file name, lower-cased ('' when it has none). */\nexport const assetExtension = (filename: string): string => {\n const m = /(\\.[A-Za-z0-9]{1,10})$/.exec(filename);\n return m ? m[1]!.toLowerCase() : '';\n};\n\n/** Client-side pre-check that mirrors the server's: null when the file could be accepted, else why not. */\nexport function checkAssetFile(\n filename: string,\n mimeType: string,\n sizeBytes: number,\n kind: AssetKind\n): 'type' | 'mime' | 'kind' | 'size' | null {\n const spec = ASSET_EXTENSIONS[assetExtension(filename)];\n if (!spec) return 'type';\n if (spec.kind !== kind) return 'kind';\n if (!spec.mimes.includes(mimeType.toLowerCase().split(';')[0]!.trim()))\n return 'mime';\n if (sizeBytes > ASSET_MAX_BYTES[kind]) return 'size';\n return null;\n}\n\n// ─── rights and provenance (spec 11 §3.6, §3.8) ──────────────────────────────\n\nexport const assetRightsSchema = z.object({\n ownership: z\n .enum(['owned', 'licensed', 'public_domain', 'generated', 'unknown'])\n .default('unknown'),\n license: z.string().max(500).optional(),\n attribution: z.string().max(500).optional(),\n sourceUrl: z.string().max(2000).optional(),\n restrictions: z.string().max(1000).optional(),\n expiresAt: z.string().optional(),\n containsLikenessOf: z.array(z.string().max(200)).max(50).optional(),\n consentAssetId: z.string().optional(),\n aiTrainingAllowed: z.boolean().default(false),\n});\nexport type AssetRights = z.output<typeof assetRightsSchema>;\n\nexport const assetSourceRefSchema = z.object({\n documentId: z.string(),\n snapshotId: z.string().optional(),\n targetKind: z.enum([\n 'document',\n 'scene',\n 'element',\n 'shot',\n 'entity',\n 'beat',\n 'title_page',\n ]),\n targetId: z.string(),\n sourceHash: z.string(),\n});\nexport type AssetSourceRef = z.infer<typeof assetSourceRefSchema>;\n\n/** What a caller may send as `provenance` (the server fills `upload` and `import` itself). */\nexport const assetProvenanceInputSchema = z.discriminatedUnion('origin', [\n z.object({\n origin: z.literal('external_tool'),\n tool: z.string().min(1).max(100),\n toolVersion: z.string().max(100).optional(),\n description: z.string().max(2000).optional(),\n sourceRefs: z.array(assetSourceRefSchema).max(100).default([]),\n createdVia: z.enum(['mcp', 'api', 'app']).default('api'),\n }),\n z.object({\n origin: z.literal('generated'),\n jobId: z.string().optional(),\n adapter: z.string().min(1).max(100),\n provider: z.string().min(1).max(100),\n model: z.string().max(200).optional(),\n prompt: z.string().max(20000).optional(),\n negativePrompt: z.string().max(20000).optional(),\n parameters: z.record(z.string(), z.unknown()).default({}),\n inputs: z\n .array(\n z.object({\n assetVersionId: z.string().optional(),\n packetHash: z.string().optional(),\n role: z.string(),\n })\n )\n .max(100)\n .default([]),\n sourceRefs: z.array(assetSourceRefSchema).max(100).default([]),\n costCredits: z.number().optional(),\n providerJobId: z.string().optional(),\n createdVia: z.enum(['mcp', 'api', 'app']).default('api'),\n }),\n]);\nexport type AssetProvenanceInput = z.input<typeof assetProvenanceInputSchema>;\n\n/** The stored, immutable provenance of a version (spec 11 §3.6). */\nexport type AssetProvenance =\n | {\n origin: 'upload';\n uploadedBy: string;\n originalFilename: string;\n client?: Record<string, unknown>;\n }\n | {\n origin: 'import';\n importJobId: string;\n sourceFormat: string;\n originalPath?: string;\n }\n | ({\n origin: 'generated';\n agent?: { client: string; apiKeyId: string };\n } & Record<string, unknown>)\n | ({\n origin: 'external_tool';\n agent?: { client: string; apiKeyId: string };\n } & Record<string, unknown>);\n\n// ─── resources ───────────────────────────────────────────────────────────────\n\nexport interface AssetDerivative {\n mime: string;\n sizeBytes: number;\n}\n\nexport interface AssetVersion {\n id: string;\n assetId: string;\n parentVersionId: string | null;\n versionNumber: number;\n mime: string;\n ext: string;\n sizeBytes: number;\n sha256: string | null;\n status: AssetVersionStatus;\n errorCode: string | null;\n media: Record<string, unknown>;\n /** Derivative name (`thumb_256`, `preview_1600`, `poster`, `proxy_720p`, ...) -> its type and size. Empty until `asset.derive` has run. */\n derivatives: Record<string, AssetDerivative>;\n provenance: AssetProvenance;\n origin: AssetOrigin;\n rights: AssetRights;\n createdBy: string | null;\n createdAt: string;\n}\n\nexport interface AssetSummary {\n id: string;\n workspaceId: string;\n kind: AssetKind;\n title: string;\n description: string;\n /** Null until the first version is ready (or processing finished without a derive worker: see `status`). */\n currentVersionId: string | null;\n versionCount: number;\n /** Fields of the current version (the latest one when none is current yet). */\n mime: string | null;\n sizeBytes: number | null;\n status: AssetVersionStatus | null;\n origin: AssetOrigin | null;\n rights: AssetRights | null;\n hasThumbnail: boolean;\n createdBy: string | null;\n createdAt: string;\n updatedAt: string;\n deletedAt: string | null;\n}\n\nexport interface AssetLink {\n id: string;\n workspaceId: string;\n assetId: string;\n /** Null = follow the asset's current version. */\n pinnedVersionId: string | null;\n /** Null = a workspace-level link (its target is `{kind: 'document', id: <workspaceId>}`). */\n documentId: string | null;\n targetKind: AssetTargetKind;\n targetId: string;\n role: AssetRole;\n sortOrder: number;\n sourceHash: string | null;\n sourceSnapshotId: string | null;\n originalTargetId: string | null;\n note: string;\n createdBy: string | null;\n createdAt: string;\n deletedAt: string | null;\n}\n\nexport type AssetListItem = AssetSummary & {\n role?: AssetRole;\n sortOrder?: number;\n};\nexport type AssetDetail = AssetSummary & {\n versions: AssetVersion[];\n links: AssetLink[];\n};\n\n// ─── upload flow (spec 05 §6.13) ─────────────────────────────────────────────\n\nconst sha256HexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{64}$/, 'sha256Hex must be 64 hex characters');\n\nexport const assetUploadRequestSchema = z.object({\n /** Client-minted `asset_...` id for offline staging; accepted when unused (`ID_CONFLICT` otherwise). */\n assetId: z\n .string()\n .regex(/^asset_[0-9A-Za-z]{10,40}$/)\n .optional(),\n filename: z.string().min(1).max(500),\n mimeType: z.string().min(1).max(200),\n sizeBytes: z.number().int().min(1),\n sha256Hex: sha256HexSchema.optional(),\n kind: assetKindSchema,\n title: z.string().trim().min(1).max(200).optional(),\n /** A new version of an existing asset: the version it derives from. */\n parentVersionId: z.string().min(1).optional(),\n provenance: assetProvenanceInputSchema.optional(),\n rights: assetRightsSchema.partial().optional(),\n});\nexport type AssetUploadRequest = z.input<typeof assetUploadRequestSchema>;\n\nexport interface AssetPartUrl {\n partNumber: number;\n url: string;\n expiresAt: string;\n}\n\nexport interface AssetUploadInit {\n uploadId: string;\n assetId: string;\n versionId: string;\n partSizeBytes: number;\n partCount: number;\n parts: AssetPartUrl[];\n expiresAt: string;\n /** The workspace already holds these exact bytes: nothing to PUT (`parts` is empty); call complete. */\n deduplicated: boolean;\n}\n\nexport interface AssetCompletedPart {\n partNumber: number;\n etag: string;\n sizeBytes?: number;\n}\n\nexport interface AssetUploadStatus {\n uploadId: string;\n assetId: string;\n versionId: string;\n partSizeBytes: number;\n partCount: number;\n completedParts: AssetCompletedPart[];\n expiresAt: string;\n completedAt: string | null;\n}\n\nexport const assetPartsRequestSchema = z.object({\n partNumbers: z.array(z.number().int().min(1).max(10000)).min(1).max(100),\n});\nexport type AssetPartsRequest = z.infer<typeof assetPartsRequestSchema>;\nexport interface AssetPartsResponse {\n parts: AssetPartUrl[];\n}\n\nexport const assetCompleteSchema = z.object({\n parts: z\n .array(\n z.object({\n partNumber: z.number().int().min(1),\n etag: z.string().min(1).max(200),\n })\n )\n .max(10000),\n sha256Hex: sha256HexSchema.optional(),\n});\nexport type AssetCompleteRequest = z.infer<typeof assetCompleteSchema>;\n\nexport interface AssetAbortResponse {\n aborted: true;\n}\n\n// ─── library routes ──────────────────────────────────────────────────────────\n\nconst linkedToSchema = z\n .string()\n .regex(\n /^(entity|scene|shot|element):[A-Za-z0-9_-]+$/,\n 'linkedTo is <entity|scene|shot|element>:<id>'\n );\n\nexport const assetListQuerySchema = cursorQuerySchema.extend({\n workspaceId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n linkedTo: linkedToSchema.optional(),\n role: assetRoleSchema.optional(),\n kind: assetKindSchema.optional(),\n q: z.string().trim().min(1).max(200).optional(),\n origin: z.enum(ASSET_ORIGINS).optional(),\n});\nexport type AssetListQuery = z.output<typeof assetListQuerySchema>;\n\nexport const assetUpdateSchema = z\n .object({\n title: z.string().trim().min(1).max(200).optional(),\n description: z.string().max(5000).optional(),\n rights: assetRightsSchema.partial().optional(),\n })\n .refine((v) => Object.keys(v).length > 0, 'Nothing to update');\nexport type AssetUpdateRequest = z.input<typeof assetUpdateSchema>;\n\nexport const ASSET_URL_VARIANTS = [\n 'original',\n 'thumb_256',\n 'thumb_512',\n 'preview_1600',\n 'poster',\n 'proxy_720p',\n 'proxy_1080p',\n 'preview',\n 'waveform',\n 'sprite',\n] as const;\nexport const assetUrlQuerySchema = z.object({\n variant: z\n .string()\n .regex(/^[a-z0-9_]{1,40}$/)\n .default('original'),\n});\nexport type AssetUrlQuery = z.output<typeof assetUrlQuerySchema>;\nexport interface AssetUrlResponse {\n url: string;\n expiresAt: string;\n}\n\nexport interface AssetDeleteResponse {\n deletedAt: string;\n}\n\n// ─── links ───────────────────────────────────────────────────────────────────\n\nexport const assetLinkCreateSchema = z.object({\n assetId: z.string().min(1),\n pinnedVersionId: z.string().min(1).optional(),\n /** Null/omitted = a workspace-level link: the target must then be `{kind: 'document', id: <the workspace id>}`. */\n documentId: z.string().min(1).nullable().optional(),\n target: z.object({\n kind: assetTargetKindSchema,\n id: z.string().min(1).max(200),\n }),\n role: assetRoleSchema,\n sortOrder: z.number().int().min(0).max(1_000_000).optional(),\n /** Version-prefixed content hash of the target when the asset was derived from it (spec 11 §4.2). */\n sourceHash: z.string().min(1).max(200).optional(),\n sourceSnapshotId: z.string().min(1).optional(),\n note: z.string().max(2000).optional(),\n});\nexport type AssetLinkCreateRequest = z.input<typeof assetLinkCreateSchema>;\n\nexport const assetLinkUpdateSchema = z\n .object({\n role: assetRoleSchema.optional(),\n sortOrder: z.number().int().min(0).max(1_000_000).optional(),\n /** `null` unpins (follow the current version). */\n pinnedVersionId: z.string().min(1).nullable().optional(),\n note: z.string().max(2000).optional(),\n })\n .refine((v) => Object.keys(v).length > 0, 'Nothing to update');\nexport type AssetLinkUpdateRequest = z.input<typeof assetLinkUpdateSchema>;\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\nexport const documentAssetLinksQuerySchema = z.object({\n targetKind: assetTargetKindSchema.optional(),\n targetId: z.string().min(1).optional(),\n role: assetRoleSchema.optional(),\n withStaleness: boolQuery.optional(),\n});\nexport type DocumentAssetLinksQuery = z.output<\n typeof documentAssetLinksQuerySchema\n>;\nexport type AssetLinkWithStaleness = AssetLink & { staleness?: Staleness };\n\nexport interface AssetLinkDeleteResponse {\n deletedAt: string;\n}\n\n// ─── staleness (spec 11 §4.5) ────────────────────────────────────────────────\n\nexport const STALENESS_TARGET_KINDS = [\n 'scene',\n 'element',\n 'shot',\n 'entity',\n] as const;\nexport const documentStalenessQuerySchema = z.object({\n targetKind: z.enum(STALENESS_TARGET_KINDS).optional(),\n});\nexport type DocumentStalenessQuery = z.output<\n typeof documentStalenessQuerySchema\n>;\n\n/** `GET /documents/:did/staleness`: per target with derived links, for badges. */\nexport interface TargetStaleness {\n targetKind: (typeof STALENESS_TARGET_KINDS)[number];\n targetId: string;\n fresh: number;\n stale: number;\n deleted: number;\n}\n\nexport interface LinkStaleness {\n staleness: Staleness;\n /** When the target's hash last changed (the normalizer's record); only for `stale`. */\n changedAt?: string;\n /** Snapshot-target links: how the live document compares (always `fresh` against the snapshot itself). */\n liveStaleness?: Staleness;\n /** Not built (needs the target's old element hashes, spec 11 §4.5's LCS diff); never sent. */\n diffSummary?: { added: number; removed: number; changed: number };\n}\n\n// ─── the `asset.derive` job (a documented stub: see the API's CLAUDE.md) ─────\n\nexport const assetDeriveInputSchema = z.object({\n assetVersionId: z.string().min(1),\n});\nexport type AssetDeriveInput = z.infer<typeof assetDeriveInputSchema>;\n","/**\n * Collaboration DTOs (spec 05 §6.15 notes/mentions/chat/activity, §6.16 notifications, §6.24 devices/push,\n * §6.26 `writingReminder` prefs; slice B12). Tables: `note_mentions`, `document_chat_messages`, `activity_events`,\n * `notifications`, `devices`.\n */\nimport { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\n\n// ─── Notification kinds and prefs (§6.16, §6.26) ────────────────────────────\n\nexport const NOTIFICATION_KINDS = [\n 'mention',\n 'note_reply',\n 'note_on_my_document',\n 'snapshot_comment',\n 'chat_mention',\n 'invitation',\n 'share_granted',\n 'snapshot_opened_by_collaborator',\n 'job_finished',\n 'job_failed',\n 'ai_suggestions_ready',\n 'ai_refunded',\n 'export_ready',\n 'watermark_batch_sent',\n 'writing_reminder',\n 'credits_low',\n 'purchase_completed',\n 'account_deletion_scheduled',\n] as const;\nexport type NotificationKind = (typeof NOTIFICATION_KINDS)[number];\n\nexport const NOTIFICATION_EMAIL_MODES = ['immediate', 'digest', 'off'] as const;\nexport type NotificationEmailMode = (typeof NOTIFICATION_EMAIL_MODES)[number];\n\nexport interface NotificationKindPrefs {\n inApp: boolean;\n push: boolean;\n email: NotificationEmailMode;\n}\n\n/** Kinds that default to an immediate email (the rest default to `digest` or `off`; see `defaultNotificationKindPrefs`). */\nconst DEFAULT_IMMEDIATE_EMAIL: ReadonlySet<NotificationKind> = new Set([\n 'mention',\n 'note_reply',\n 'chat_mention',\n 'invitation',\n 'share_granted',\n 'job_failed',\n 'export_ready',\n 'watermark_batch_sent',\n 'credits_low',\n 'purchase_completed',\n 'account_deletion_scheduled',\n]);\nconst DEFAULT_DIGEST_EMAIL: ReadonlySet<NotificationKind> = new Set([\n 'snapshot_comment',\n 'note_on_my_document',\n 'ai_suggestions_ready',\n 'ai_refunded',\n 'snapshot_opened_by_collaborator',\n]);\n/** Kinds a person is not plausibly interrupted for, off by default: no email, no push. */\nconst DEFAULT_QUIET: ReadonlySet<NotificationKind> = new Set([\n 'job_finished',\n 'writing_reminder',\n]);\n\n/** Every kind gets a sane default; a person may override any of `inApp`/`push`/`email` per kind. */\nexport function defaultNotificationKindPrefs(\n kind: NotificationKind\n): NotificationKindPrefs {\n const email: NotificationEmailMode = DEFAULT_IMMEDIATE_EMAIL.has(kind)\n ? 'immediate'\n : DEFAULT_DIGEST_EMAIL.has(kind)\n ? 'digest'\n : 'off';\n return { inApp: true, push: !DEFAULT_QUIET.has(kind), email };\n}\n\nexport interface NotificationPrefs {\n kinds: Record<NotificationKind, NotificationKindPrefs>;\n /** `HH:MM` local time (§6.26 `system.writingReminder`); `null` = the reminder job never fires for this user. */\n writingReminderTime: string | null;\n}\n\nexport function defaultNotificationPrefs(): NotificationPrefs {\n return {\n kinds: Object.fromEntries(\n NOTIFICATION_KINDS.map((k) => [k, defaultNotificationKindPrefs(k)])\n ) as Record<NotificationKind, NotificationKindPrefs>,\n writingReminderTime: null,\n };\n}\n\nconst notificationKindPrefsPatchSchema = z.object({\n inApp: z.boolean().optional(),\n push: z.boolean().optional(),\n email: z.enum(NOTIFICATION_EMAIL_MODES).optional(),\n});\n\nconst HHMM_RE = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\n/** `PUT /me/notification-prefs`: a sparse per-kind patch (only the kinds/fields given change) plus the reminder time. */\nexport const notificationPrefsSchema = z.object({\n kinds: z\n .record(z.string(), notificationKindPrefsPatchSchema)\n .refine(\n (obj) =>\n Object.keys(obj).every((k) =>\n (NOTIFICATION_KINDS as readonly string[]).includes(k)\n ),\n {\n message: 'unknown notification kind',\n }\n )\n .optional(),\n writingReminderTime: z\n .string()\n .regex(HHMM_RE, 'writingReminderTime must be HH:MM (24h, local)')\n .nullable()\n .optional(),\n});\nexport type NotificationPrefsUpdate = z.infer<typeof notificationPrefsSchema>;\n\n/** `{...current, ...update}` per kind (a patch's fields win); `writingReminderTime` replaces whole. */\nexport function mergeNotificationPrefs(\n current: NotificationPrefs,\n update: NotificationPrefsUpdate\n): NotificationPrefs {\n const kinds = { ...current.kinds };\n for (const [k, patch] of Object.entries(update.kinds ?? {})) {\n const kind = k as NotificationKind;\n kinds[kind] = {\n ...(kinds[kind] ?? defaultNotificationKindPrefs(kind)),\n ...patch,\n };\n }\n return {\n kinds,\n writingReminderTime:\n update.writingReminderTime === undefined\n ? current.writingReminderTime\n : update.writingReminderTime,\n };\n}\n\n// ─── Notifications (§6.16) ───────────────────────────────────────────────────\n\nexport interface Notification {\n id: string;\n kind: NotificationKind;\n /** Ids and display strings only; never document/script content (spec 05 §8.7). */\n payload: Record<string, unknown>;\n workspaceId: string | null;\n documentId: string | null;\n readAt: string | null;\n createdAt: string;\n}\n\nconst boolQuery = z.enum(['true', 'false']).transform((v) => v === 'true');\n\nexport const notificationsQuerySchema = cursorQuerySchema.extend({\n unread: boolQuery.optional(),\n});\nexport type NotificationsQuery = z.infer<typeof notificationsQuerySchema>;\n\nexport const notificationsReadSchema = z\n .object({\n ids: z.array(z.string().min(1)).max(200).optional(),\n all: z.literal(true).optional(),\n before: z.iso.datetime({ offset: true }).optional(),\n })\n .refine(\n (v) => v.ids !== undefined || v.all !== undefined || v.before !== undefined,\n {\n message: 'one of ids, all or before is required',\n }\n );\nexport type NotificationsReadRequest = z.infer<typeof notificationsReadSchema>;\nexport interface NotificationsReadResponse {\n updated: number;\n}\nexport interface NotificationDeleteResponse {\n deleted: true;\n}\n\n// ─── Notes mentions, mentions-without-access (§6.15) ────────────────────────\n\nexport interface MentionWithoutAccess {\n noteId: string;\n replyId?: string;\n userId: string;\n email: string | null;\n createdAt: string;\n}\n\n// ─── Chat (§6.15, §8.7 `document_chat_messages`) ────────────────────────────\n\nexport const CHAT_BODY_MAX = 4000;\nexport const CHAT_EDIT_WINDOW_MINUTES = 15;\n\n/** Y.Doc notes use plain `mentions: string[]` (user ids, no offset/length: writing_core's simplification); chat mirrors it in the DTO for consistency with the spec's shape, offset/length optional. */\nexport const mentionRefSchema = z.object({\n userId: z.string().min(1),\n offset: z.number().int().min(0).optional(),\n length: z.number().int().min(1).optional(),\n});\nexport type MentionRef = z.infer<typeof mentionRefSchema>;\n\nexport interface ChatMessage {\n id: string;\n documentId: string;\n authorId: string | null;\n body: string;\n mentions: MentionRef[];\n createdAt: string;\n editedAt: string | null;\n deletedAt: string | null;\n}\n\nexport const chatMessageCreateSchema = z.object({\n clientMessageId: z\n .string()\n .min(8)\n .max(64)\n .regex(/^msg_[0-9A-Za-z]+$/, 'clientMessageId must be a msg_ prefixed id'),\n body: z.string().trim().min(1).max(CHAT_BODY_MAX),\n mentions: z.array(mentionRefSchema).max(50).optional(),\n});\nexport type ChatMessageCreateRequest = z.infer<typeof chatMessageCreateSchema>;\n\nexport const chatMessageUpdateSchema = z.object({\n body: z.string().trim().min(1).max(CHAT_BODY_MAX),\n});\nexport type ChatMessageUpdateRequest = z.infer<typeof chatMessageUpdateSchema>;\n\nexport const chatQuerySchema = cursorQuerySchema.extend({\n before: z.iso.datetime({ offset: true }).optional(),\n});\nexport type ChatQuery = z.infer<typeof chatQuerySchema>;\n\nexport interface ChatMessageDeleteResponse {\n deletedAt: string;\n}\n\n// ─── Activity (§6.15, §8.7 `activity_events`) ───────────────────────────────\n\nexport const ACTIVITY_KINDS = [\n 'document.created',\n 'document.renamed',\n 'document.moved',\n 'document.trashed',\n 'document.restored',\n 'session.edited',\n 'snapshot.created',\n 'snapshot.opened',\n 'snapshot.forked',\n 'version.restored',\n 'template.applied',\n 'import.over',\n 'revision.setCreated',\n 'locks.changed',\n 'changes.decided',\n 'ai.jobCompleted',\n 'ai.suggestionsDecided',\n 'share.granted',\n 'share.linkCreated',\n 'member.joined',\n 'member.left',\n 'mcp.commandsApplied',\n] as const;\nexport type ActivityKind = (typeof ACTIVITY_KINDS)[number];\n\nexport const ACTOR_KINDS = ['user', 'mcp', 'api', 'ai', 'system'] as const;\nexport type ActorKind = (typeof ACTOR_KINDS)[number];\n\nexport interface ActivitySummary {\n i18nKey: string;\n params?: Record<string, unknown>;\n}\n\nexport interface ActivityEvent {\n id: string;\n kind: ActivityKind;\n actorId: string | null;\n actorKind: ActorKind;\n summary: ActivitySummary;\n targetIds: string[];\n createdAt: string;\n}\n/** `GET /workspaces/:wid/activity` items also carry the document they happened on. */\nexport interface WorkspaceActivityEvent extends ActivityEvent {\n documentId: string | null;\n}\n\nconst csvList = (v: unknown) =>\n typeof v === 'string'\n ? v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : v;\n\nexport const activityQuerySchema = cursorQuerySchema.extend({\n kinds: z.preprocess(csvList, z.array(z.string())).optional(),\n});\nexport type ActivityQuery = z.infer<typeof activityQuerySchema>;\n\nexport const workspaceActivityQuerySchema = cursorQuerySchema.extend({\n projectId: z.string().min(1).optional(),\n});\nexport type WorkspaceActivityQuery = z.infer<\n typeof workspaceActivityQuerySchema\n>;\n\n// ─── Devices, push tokens (§6.24) ────────────────────────────────────────────\n\nexport const DEVICE_PLATFORMS = [\n 'web',\n 'ios',\n 'ipados',\n 'android',\n 'macos',\n 'windows',\n] as const;\nexport type DevicePlatform = (typeof DEVICE_PLATFORMS)[number];\n\nexport const PUSH_PLATFORMS = ['apns', 'fcm', 'wns', 'webpush'] as const;\nexport type PushPlatform = (typeof PUSH_PLATFORMS)[number];\n\nexport interface Device {\n id: string;\n displayName: string;\n platform: DevicePlatform;\n appVersion: string;\n lastSeenAt: string;\n revokedAt: string | null;\n /** True for the device making the current request (matched by id). */\n current: boolean;\n /** Per-device: offline availability (F-SAFE-004), local-backup status; never per-user data. */\n settings: Record<string, unknown>;\n}\n\nexport const deviceCreateSchema = z.object({\n id: z\n .string()\n .min(8)\n .max(64)\n .regex(/^dev_[0-9A-Za-z]+$/, 'id must be a dev_ prefixed id'),\n installId: z.string().min(1).max(128),\n displayName: z.string().trim().min(1).max(80),\n platform: z.enum(DEVICE_PLATFORMS),\n appVersion: z.string().min(1).max(40),\n});\nexport type DeviceCreateRequest = z.infer<typeof deviceCreateSchema>;\nexport interface DeviceCreateResponse extends Device {\n /** A second live install presenting the same `id` gets a fresh one (spec 03 §12.8); this is that fresh id. */\n reassignedId?: string;\n}\n\nexport const deviceUpdateSchema = z.object({\n displayName: z.string().trim().min(1).max(80),\n});\nexport type DeviceUpdateRequest = z.infer<typeof deviceUpdateSchema>;\n\nexport interface DeviceRevokeResponse {\n revokedAt: string;\n}\n\nexport const pushTokenSetSchema = z.object({\n platform: z.enum(PUSH_PLATFORMS),\n token: z.string().min(1).max(4096),\n environment: z.enum(['production', 'sandbox']).optional(),\n});\nexport type PushTokenSetRequest = z.infer<typeof pushTokenSetSchema>;\nexport interface PushTokenSetResponse {\n registeredAt: string;\n}\nexport interface PushTokenDeleteResponse {\n deleted: true;\n}\n","import { z } from 'zod';\n\n/**\n * Credits (spec 05 §6.20, spec 06 §10): a thin re-export of `@sudobility/types`' generic consumables\n * shapes, plus the two things specific to ViaInk — the priced product catalog and the purchase\n * handoff for platforms that cannot buy in-app (spec 05 §6.21).\n *\n * The ledger itself (`consumable_balances/_purchases/_usages`) is `@sudobility/consumables_service`'s,\n * called in-process from `screenwriter_api` exactly as `music_api` does; this module never redefines it.\n */\nexport type {\n ConsumableBalanceResponse,\n ConsumablePurchaseRecord,\n ConsumablePurchaseRequest,\n ConsumableSource,\n ConsumableUsageRecord,\n ConsumableUseRequest,\n ConsumableUseResponse,\n} from '@sudobility/types';\n\nexport const CONSUMABLE_SOURCES = ['web', 'apple', 'google', 'free'] as const;\n\n/** `GET /consumables/products`: the priced catalog (`CREDIT_PRODUCTS`, spec 06 §10.1). */\nexport interface CreditProduct {\n productId: string;\n credits: number;\n}\n\n/** `POST /purchases/handoff` (spec 05 §6.21): lets a platform with no in-app purchase (Windows) send the user to the web to buy. */\nexport const purchaseHandoffRequestSchema = z.object({\n productId: z.string().optional(),\n returnTo: z.string().min(1).max(2000),\n});\nexport type PurchaseHandoffRequest = z.infer<\n typeof purchaseHandoffRequestSchema\n>;\n\nexport interface PurchaseHandoffResponse {\n handoffUrl: string;\n expiresAt: string;\n}\n\nexport interface CreditCouponHistoryItem {\n workspaceId: string;\n userId: string;\n credits: number;\n redeemedAt: string;\n}\nexport interface CreditCoupon {\n id: string;\n code: string;\n credits: number;\n expiresAt: string;\n email: string | null;\n createdAt: string;\n history: CreditCouponHistoryItem[];\n}\nexport interface CreditCouponCreateRequest {\n credits: number;\n expires_at: string;\n email?: string | null;\n}\nexport interface CreditCouponRedeemResponse {\n credits: number;\n balance: number;\n}\n","import { z } from 'zod';\n\n/**\n * Public routes (spec 05 §6.21, B18): no session needed. `/public/templates[/:key]` reuse `TemplateSummary`\n * (templates/index.ts) and writing_core's `TemplateJSON` for the full body.\n */\n\n/** `GET /public/config` (R31): the single client-policy route. Clients below `minClientVersion` show the update\n * prompt; a call from one is answered `CLIENT_TOO_OLD` (426), read from the `X-Client-Version` request header. */\nexport interface PublicConfig {\n uiLanguages: string[];\n scriptLanguages: string[];\n assetLimits: Record<string, unknown>;\n maxImportBytes: number;\n importFormats: string[];\n exportFormats: string[];\n aiTasks: { task: string; pricingBasis: string }[];\n aiConsentVersion: number;\n syncProtocolVersion: number;\n docSchemaVersion: number;\n minClientVersion: {\n web: string;\n ios: string;\n android: string;\n macos: string;\n windows: string;\n };\n namesDbVersion: number;\n features: { ocr: boolean; grammar: boolean; push: boolean };\n}\n\n/** `GET /public/names-db/:version` (spec 09): served gzipped with a far-future immutable Cache-Control. */\nexport interface NamesDbEntry {\n name: string;\n gender?: 'f' | 'm' | 'u';\n origins: string[];\n}\nexport interface NamesDbResponse {\n version: number;\n names: NamesDbEntry[];\n}\n\n/** `GET /public/health/deep`: readiness, no secrets. */\nexport interface DeepHealthResponse {\n db: 'ok' | 'error';\n storage: 'ok' | 'unconfigured' | 'error';\n ai: 'ok' | 'unconfigured';\n email: 'ok' | 'unconfigured';\n}\n\n/** `GET /public/watermarked/:exportId/:token`: the recipient's download page payload (never the file itself). */\nexport interface WatermarkedDownloadInfo {\n documentTitle: string;\n senderName: string;\n url: string;\n expiresAt: string;\n}\n\n/** `POST /public/purchases/handoff/redeem`: exchanges a handoff token for a Firebase custom token (same uid), so the web page signs in without a password. */\nexport const purchaseHandoffRedeemSchema = z.object({\n token: z.string().min(1),\n});\nexport type PurchaseHandoffRedeemRequest = z.infer<\n typeof purchaseHandoffRedeemSchema\n>;\nexport interface PurchaseHandoffRedeemResponse {\n customToken: string;\n}\n\n// ---- Telemetry (spec 05 §6.24) ----\n\nexport const telemetryEventSchema = z.object({\n name: z.string().min(1).max(120),\n ts: z.string(),\n /** Allow-listed, flat properties only: no script text, no free-form nesting. */\n properties: z\n .record(\n z.string(),\n z.union([z.string().max(500), z.number(), z.boolean(), z.null()])\n )\n .optional(),\n});\nexport type TelemetryEvent = z.infer<typeof telemetryEventSchema>;\n\nexport const clientErrorReportSchema = z.object({\n message: z.string().min(1).max(2000),\n stack: z.string().max(8000).optional(),\n context: z\n .record(\n z.string(),\n z.union([z.string().max(500), z.number(), z.boolean(), z.null()])\n )\n .optional(),\n});\nexport type ClientErrorReport = z.infer<typeof clientErrorReportSchema>;\n\nexport const telemetryRequestSchema = z.object({\n events: z.array(telemetryEventSchema).max(100),\n errors: z.array(clientErrorReportSchema).max(20).optional(),\n});\nexport type TelemetryRequest = z.infer<typeof telemetryRequestSchema>;\nexport interface TelemetryResponse {\n accepted: boolean;\n}\n","import { z } from 'zod';\nimport { cursorQuerySchema } from '../api/pagination.js';\nimport { JOB_STATUSES } from '../jobs/index.js';\n\n/**\n * Admin routes (spec 05 §6.23): `/api/v1/admin/*` requires `siteAdmin` on a user principal (never an API key).\n * Every call writes `audit_log`.\n */\n\nexport interface AdminUserLookup {\n id: string;\n email: string | null;\n emailVerified: boolean;\n displayName: string | null;\n siteAdmin: boolean;\n createdAt: string;\n lastSeenAt: string | null;\n deletionScheduledFor: string | null;\n deletedAt: string | null;\n}\n\nexport const adminJobListQuerySchema = cursorQuerySchema.extend({\n status: z.enum(JOB_STATUSES).optional(),\n kind: z.string().optional(),\n});\nexport interface AdminJobListQuery {\n limit?: number;\n cursor?: string;\n status?: (typeof JOB_STATUSES)[number];\n kind?: string;\n}\n\n/** `PATCH /admin/job-kinds/:kind`: a sparse patch onto `job_kind_config`. */\nexport const adminJobKindPatchSchema = z.object({\n enabled: z.boolean().optional(),\n maxAttempts: z.number().int().min(1).max(10).optional(),\n maxRetries: z.number().int().min(0).max(10).optional(),\n maxConcurrentPerUser: z.number().int().min(1).nullable().optional(),\n maxConcurrentGlobal: z.number().int().min(1).nullable().optional(),\n timeoutMs: z.number().int().min(1000).optional(),\n});\nexport type AdminJobKindPatchRequest = z.infer<typeof adminJobKindPatchSchema>;\n\nexport interface AdminJobKind {\n kind: string;\n enabled: boolean;\n adapter: string;\n lane: string;\n billable: boolean;\n maxAttempts: number;\n maxRetries: number;\n maxConcurrentPerUser: number | null;\n maxConcurrentGlobal: number | null;\n timeoutMs: number;\n updatedAt: string;\n}\n\n/** `POST /admin/jobs/:id/refund`: an optional partial amount; defaults to the job's full `chargedCredits`. */\nexport const adminJobRefundSchema = z.object({\n credits: z.number().int().positive().optional(),\n});\nexport type AdminJobRefundRequest = z.infer<typeof adminJobRefundSchema>;\nexport interface AdminJobRefundResponse {\n refundedCredits: number;\n balance: number;\n}\n\n/** `POST /admin/users/:uid/restore`. */\nexport interface AdminUserRestoreResponse {\n restored: true;\n}\n\n/**\n * `DELETE /admin/users/:uid`: schedules an IMMEDIATE deletion (no grace period) and revokes the user's API keys and\n * share links — the same bounded action `DELETE /me` takes, admin-triggered. **Not** a destructive data purge: no\n * `system.purge` job exists anywhere in this codebase yet to actually delete a user's workspaces/documents/content,\n * and `workspaces.created_by` is `ON DELETE RESTRICT`, so a raw row delete cannot work without first reassigning\n * or deleting every workspace the person created — real work for that job, not this route.\n */\nexport interface AdminUserPurgeResponse {\n deletionScheduledFor: string;\n}\n\n/** `GET /admin/documents/:did/meta`: metadata only, never content. */\nexport interface AdminDocumentMeta {\n id: string;\n title: string;\n kind: string;\n projectId: string;\n workspaceId: string;\n ownerEmail: string | null;\n epoch: number;\n schemaVersion: number;\n excludeFromAi: boolean;\n createdAt: string;\n trashedAt: string | null;\n}\n","/**\n * Spec 03 §3.2 write matrix as data, projected from spec 05's role matrix onto Y.Doc keys.\n * The server checks inbound updates against it; `markPermissionsFor` is what `subscribed` and\n * `roleChanged` send so a client can disable UI instead of being rejected.\n */\nimport type { Role } from '../tenancy/index.js';\n\n/** Top-level Y.Doc keys a commenter may change (notes and replies, R6). */\nexport const COMMENTER_WRITABLE_KEYS: readonly string[] = ['notes'];\n\n/** Inline marks a commenter may add or remove inside element text: note anchors `n:<NoteId>` and the highlighter. */\nexport const isCommenterMark = (name: string): boolean =>\n name === 'hl' || name.startsWith('n:');\n\n/** What a role may produce (courtesy for the UI; the server check is the authority). */\nexport interface MarkPermissions {\n /** Text, attributes, structure, tags, revisions, settings: everything an owner/admin/writer writes. */\n edit: boolean;\n /** Notes and replies (`notes` + `n:` marks). */\n comment: boolean;\n /** Highlighter (`hl` marks). */\n highlight: boolean;\n}\n\nexport function markPermissionsFor(role: Role | 'none'): MarkPermissions {\n const edit = role === 'owner' || role === 'admin' || role === 'writer';\n const comment = edit || role === 'commenter';\n return { edit, comment, highlight: comment };\n}\n\n/** Roles that may send `update` frames at all (a commenter's are filtered by the matrix). */\nexport const canSendUpdates = (role: Role): boolean => role !== 'viewer';\n","import { z } from 'zod';\n\n/** Spec 03 §2. Subprotocol string is `fadewright-sync.v1`. */\nexport const SYNC_PROTOCOL_VERSION = 1;\nexport const SYNC_SUBPROTOCOL = 'fadewright-sync.v1';\nexport const SYNC_PATH = '/api/v1/sync';\nexport const SYNC_HEARTBEAT_MS = 25_000;\nexport const SYNC_MAX_FRAME_BYTES = 1_048_576;\nexport const SYNC_AUTH_TIMEOUT_MS = 5_000;\n\n/** Numeric message-type codes (spec 03 §2.3). Frame = channelId, messageType, payload. */\nexport const SYNC_MESSAGE_TYPES = {\n auth: 0,\n authOk: 1,\n authError: 2,\n reauth: 3,\n ping: 4,\n pong: 4,\n subscribe: 10,\n subscribed: 11,\n subscribeError: 12,\n unsubscribe: 13,\n syncStep1: 20,\n syncStep2: 21,\n update: 22,\n ack: 23,\n reject: 24,\n awareness: 30,\n epochChanged: 40,\n roleChanged: 41,\n documentDeleted: 42,\n normalized: 43,\n serverShutdown: 50,\n} as const;\nexport type SyncMessageName = keyof typeof SYNC_MESSAGE_TYPES;\n\n/** Close codes (spec 03 §2.6). */\nexport const SYNC_CLOSE_CODES = {\n NORMAL: 1000,\n GOING_AWAY: 1001,\n MALFORMED_FRAME: 4400,\n AUTH_TIMEOUT_OR_INVALID: 4401,\n ACCOUNT_DISABLED_OR_DEVICE_REVOKED: 4403,\n PROTOCOL_UNSUPPORTED: 4406,\n HEARTBEAT_TIMEOUT: 4408,\n /** Document epoch changed (snapshot open / version restore): resubscribe at the new epoch. */\n EPOCH_CHANGED: 4409,\n FRAME_TOO_LARGE: 4413,\n RATE_LIMITED: 4429,\n} as const;\nexport type SyncCloseCode =\n (typeof SYNC_CLOSE_CODES)[keyof typeof SYNC_CLOSE_CODES];\n\n// ─── Vocabularies ───────────────────────────────────────────────────────────\n\nexport const SYNC_AUTH_SCHEMES = ['firebase', 'apikey', 'link'] as const;\nexport const SYNC_AUTH_ERROR_CODES = [\n 'UNAUTHENTICATED',\n 'ACCOUNT_DISABLED',\n 'DEVICE_REVOKED',\n 'LINK_EXPIRED',\n 'CLIENT_TOO_OLD',\n 'SERVER_TOO_OLD',\n] as const;\nexport const SYNC_SUBSCRIBE_ERROR_CODES = [\n 'NOT_FOUND',\n 'FORBIDDEN',\n 'DOCUMENT_DELETED',\n 'EPOCH_MISMATCH',\n 'DOCUMENT_LOCKED',\n 'CLIENT_TOO_OLD',\n] as const;\nexport const SYNC_REJECT_CODES = [\n 'FORBIDDEN',\n 'EPOCH_MISMATCH',\n 'UPDATE_INVALID',\n 'PAYLOAD_TOO_LARGE',\n 'SCHEMA_VIOLATION',\n] as const;\nexport const SYNC_SUBSCRIBE_MODES = ['edit', 'view'] as const;\nexport const SYNC_EPOCH_REASONS = [\n 'snapshot-open',\n 'import-over',\n 'version-restore',\n 'schema-migration',\n] as const;\n\nconst roleOrNone = z.enum([\n 'owner',\n 'admin',\n 'writer',\n 'commenter',\n 'viewer',\n 'none',\n]);\nconst bytes = z.instanceof(Uint8Array);\nconst uint = z.number().int().min(0);\n\n// ─── Payload schemas (JSON UTF-8 payloads) ──────────────────────────────────\n\nexport const authPayloadSchema = z.object({\n scheme: z.enum(SYNC_AUTH_SCHEMES),\n token: z.string(),\n deviceId: z.string(),\n installId: z.string(),\n clientVersion: z.string(),\n schemaVersion: uint,\n /** Unlock-session token (`POST /documents/:did/unlock-session`) for opening locked documents. */\n unlockToken: z.string().optional(),\n});\nexport const authOkPayloadSchema = z.object({\n userId: z.string(),\n sessionId: z.string(),\n serverSchemaVersion: uint,\n heartbeatMs: uint,\n maxFrameBytes: uint,\n});\nexport const authErrorPayloadSchema = z.object({\n code: z.enum(SYNC_AUTH_ERROR_CODES),\n message: z.string(),\n});\nexport const reauthPayloadSchema = z.object({ token: z.string() });\nexport const pingPayloadSchema = z.object({ t: z.number() });\nexport const subscribePayloadSchema = z.object({\n channelId: uint.min(1),\n documentId: z.string(),\n epoch: uint,\n /** base64 state vector */\n stateVector: z.string().optional(),\n mode: z.enum(SYNC_SUBSCRIBE_MODES),\n snapshotId: z.string().optional(),\n});\nexport const subscribedPayloadSchema = z.object({\n documentId: z.string(),\n role: roleOrNone,\n epoch: uint,\n markPermissions: z.unknown(),\n schemaVersion: uint,\n});\nexport const subscribeErrorPayloadSchema = z.object({\n code: z.enum(SYNC_SUBSCRIBE_ERROR_CODES),\n detail: z.unknown().optional(),\n});\nexport const unsubscribePayloadSchema = z.object({ channelId: uint.min(1) });\nexport const ackPayloadSchema = z.object({\n clientSeq: uint,\n serverSeq: uint,\n});\nexport const rejectPayloadSchema = z.object({\n clientSeq: uint,\n code: z.enum(SYNC_REJECT_CODES),\n detail: z.unknown().optional(),\n});\nexport const epochChangedPayloadSchema = z.object({\n newEpoch: uint,\n reason: z.enum(SYNC_EPOCH_REASONS),\n byUserId: z.string(),\n snapshotId: z.string().optional(),\n});\nexport const roleChangedPayloadSchema = z.object({\n role: roleOrNone,\n markPermissions: z.unknown(),\n});\nexport const documentDeletedPayloadSchema = z.object({\n byUserId: z.string(),\n recoverableUntil: z.string(),\n});\nexport const normalizedPayloadSchema = z.object({\n serverSeq: uint,\n contentHashes: z.record(z.string(), z.string()),\n});\nexport const serverShutdownPayloadSchema = z.object({\n reconnectAfterMs: uint,\n});\n\n// ─── Frame schemas: decoded `{channelId, type, payload}` ────────────────────\n\nconst ctl = z.literal(0);\nconst chan = uint.min(1);\n\nexport const syncFrameSchema = z.discriminatedUnion('type', [\n z.object({\n channelId: ctl,\n type: z.literal('auth'),\n payload: authPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('authOk'),\n payload: authOkPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('authError'),\n payload: authErrorPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('reauth'),\n payload: reauthPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('ping'),\n payload: pingPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('pong'),\n payload: pingPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('subscribe'),\n payload: subscribePayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('subscribed'),\n payload: subscribedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('subscribeError'),\n payload: subscribeErrorPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('unsubscribe'),\n payload: unsubscribePayloadSchema,\n }),\n z.object({ channelId: chan, type: z.literal('syncStep1'), payload: bytes }),\n z.object({ channelId: chan, type: z.literal('syncStep2'), payload: bytes }),\n z.object({\n channelId: chan,\n type: z.literal('update'),\n payload: z.object({ epoch: uint, clientSeq: uint, update: bytes }),\n }),\n z.object({\n channelId: chan,\n type: z.literal('ack'),\n payload: ackPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('reject'),\n payload: rejectPayloadSchema,\n }),\n z.object({ channelId: chan, type: z.literal('awareness'), payload: bytes }),\n z.object({\n channelId: chan,\n type: z.literal('epochChanged'),\n payload: epochChangedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('roleChanged'),\n payload: roleChangedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('documentDeleted'),\n payload: documentDeletedPayloadSchema,\n }),\n z.object({\n channelId: chan,\n type: z.literal('normalized'),\n payload: normalizedPayloadSchema,\n }),\n z.object({\n channelId: ctl,\n type: z.literal('serverShutdown'),\n payload: serverShutdownPayloadSchema,\n }),\n]);\nexport type SyncFrame = z.infer<typeof syncFrameSchema>;\nexport type SyncFrameOf<T extends SyncFrame['type']> = Extract<\n SyncFrame,\n { type: T }\n>;\n\nexport * from './permissions.js';\n","/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n","/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * Check whether n is negative, while considering the -0 edge case. While `-0 < 0` is false, this\n * function returns true for -0,-1,,.. and returns false for 0,1,2,...\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also distinguishes between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n","/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n","import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array<ArrayBuffer>}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n\n/**\n * Escape HTML characters &,<,>,',\" to their respective HTML entities &amp;,&lt;,&gt;,&#39;,&quot;\n *\n * @param {string} str\n */\nexport const escapeHTML = str =>\n str.replace(/[&<>'\"]/g, r => /** @type {string} */ ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n \"'\": '&#39;',\n '\"': '&quot;'\n }[r]))\n\n/**\n * Reverse of `escapeHTML`\n *\n * @param {string} str\n */\nexport const unescapeHTML = str =>\n str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, r => /** @type {string} */ ({\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&#39;': \"'\",\n '&quot;': '\"'\n }[r]))\n","/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n\n/**\n * @param {boolean} property\n * @return {asserts property is true}\n */\nexport const assert = property => { if (!property) throw create('Assert failed') }\n","/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array<Uint8Array>}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * @typedef {Array<AnyEncodable>} AnyEncodableArray\n */\n\n/**\n * @typedef {undefined|null|number|bigint|boolean|string|{[k:string]:AnyEncodable}|AnyEncodableArray|Uint8Array} AnyEncodable\n */\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array<any> | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {AnyEncodable} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array<string>}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n","/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n * @template {ArrayBufferLike} [Buf=ArrayBufferLike]\n */\nexport class Decoder {\n /**\n * @param {Uint8Array<Buf>} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array<Buf>}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Uint8Array<Buf>} uint8Array\n * @return {Decoder<Buf>}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array<Buf>}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @template {ArrayBufferLike} Buf\n * @param {Decoder<Buf>} decoder\n * @return {Uint8Array<Buf>}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array<function(Decoder):any>}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object<string,any>\n const len = readVarUint(decoder)\n /**\n * @type {Object<string,any>}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array<any>\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n","/**\n * Binary wire codec for sync frames (spec 03 §2.2). Shared by the API and the frontend client.\n * Platform-free: only `lib0` (pure JS), no Node built-ins, no DOM.\n *\n * frame := channelId:varuint messageType:varuint payload\n *\n * Payload by type:\n * - JSON UTF-8 (the JSON text fills the rest of the frame): auth, authOk, authError, reauth, ping/pong, subscribe, subscribed, subscribeError,\n * unsubscribe, ack, reject, epochChanged, roleChanged, documentDeleted, normalized,\n * serverShutdown.\n * - syncStep1 / syncStep2 / awareness: `varuint8array` (the y-protocols payload, which is\n * exactly what follows the message-type tag in y-protocols/sync and /awareness).\n * - update: `epoch:varuint clientSeq:varuint update:varuint8array`.\n *\n * ping and pong share code 4. `decodeFrame` returns type `ping` for it; a heartbeat frame is a\n * liveness signal only and must never be answered (otherwise the two sides would echo forever).\n */\nimport * as decoding from 'lib0/decoding';\nimport * as encoding from 'lib0/encoding';\nimport * as string from 'lib0/string';\nimport {\n SYNC_MESSAGE_TYPES,\n syncFrameSchema,\n type SyncFrame,\n} from './index.js';\n\nexport class SyncCodecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SyncCodecError';\n }\n}\n\nconst BINARY_TYPES = new Set(['syncStep1', 'syncStep2', 'awareness']);\n\nconst NAME_BY_CODE = new Map<number, SyncFrame['type']>();\nfor (const [name, code] of Object.entries(SYNC_MESSAGE_TYPES)) {\n // ping and pong share a code: the first registration (ping) wins on decode.\n if (!NAME_BY_CODE.has(code))\n NAME_BY_CODE.set(code, name as SyncFrame['type']);\n}\n\nexport function encodeFrame(frame: SyncFrame): Uint8Array {\n const enc = encoding.createEncoder();\n encoding.writeVarUint(enc, frame.channelId);\n encoding.writeVarUint(enc, SYNC_MESSAGE_TYPES[frame.type]);\n if (BINARY_TYPES.has(frame.type)) {\n encoding.writeVarUint8Array(enc, frame.payload as Uint8Array);\n } else if (frame.type === 'update') {\n encoding.writeVarUint(enc, frame.payload.epoch);\n encoding.writeVarUint(enc, frame.payload.clientSeq);\n encoding.writeVarUint8Array(enc, frame.payload.update);\n } else {\n encoding.writeUint8Array(\n enc,\n string.encodeUtf8(JSON.stringify(frame.payload))\n );\n }\n return encoding.toUint8Array(enc);\n}\n\n/** Throws `SyncCodecError` on any malformed or schema-invalid frame. */\nexport function decodeFrame(bytes: Uint8Array): SyncFrame {\n let candidate: unknown;\n try {\n const dec = decoding.createDecoder(bytes);\n const channelId = decoding.readVarUint(dec);\n const code = decoding.readVarUint(dec);\n const type = NAME_BY_CODE.get(code);\n if (!type) throw new SyncCodecError(`unknown message type ${code}`);\n let payload: unknown;\n if (BINARY_TYPES.has(type)) {\n payload = decoding.readVarUint8Array(dec);\n if (decoding.hasContent(dec)) throw new SyncCodecError('trailing bytes');\n } else if (type === 'update') {\n const epoch = decoding.readVarUint(dec);\n const clientSeq = decoding.readVarUint(dec);\n const update = decoding.readVarUint8Array(dec);\n if (decoding.hasContent(dec)) throw new SyncCodecError('trailing bytes');\n payload = { epoch, clientSeq, update };\n } else {\n const rest = decoding.readTailAsUint8Array(dec);\n payload = JSON.parse(string.decodeUtf8(rest));\n }\n candidate = { channelId, type, payload };\n } catch (e) {\n if (e instanceof SyncCodecError) throw e;\n throw new SyncCodecError(\n `malformed frame: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n const parsed = syncFrameSchema.safeParse(candidate);\n if (!parsed.success)\n throw new SyncCodecError(`invalid frame: ${parsed.error.message}`);\n return parsed.data;\n}\n"],"names":["r","boolQuery","max","sha256HexSchema","bytes","binary.BITS7","binary.BIT8","math.floor","string.utf8TextEncoder","string.encodeUtf8","math.min","math.max","error.create","number.MAX_SAFE_INTEGER","encoding.createEncoder","encoding.writeVarUint","encoding.writeVarUint8Array","encoding.writeUint8Array","encoding.toUint8Array","decoding.createDecoder","decoding.readVarUint","decoding.readVarUint8Array","decoding.hasContent","decoding.readTailAsUint8Array","string.decodeUtf8"],"mappings":";;;;AAMA,MAAM,cAAc;AAAA,EAClB,CAAC,gBAAgB,GAAG;AAAA,EACpB,CAAC,mBAAmB,GAAG;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