@powerhousedao/reactor-browser 6.4.0-next.2 → 6.4.0-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-0E5S0hZ6.d.ts → attachment-service-DdLM0Yf5.d.ts} +40 -9
- package/dist/attachment-service-DdLM0Yf5.d.ts.map +1 -0
- package/dist/auth-Ryem1MiX.d.ts +53 -0
- package/dist/auth-Ryem1MiX.d.ts.map +1 -0
- package/dist/{client-BFnMV-EO.js → client-DMCO2IaR.js} +3 -2
- package/dist/client-DMCO2IaR.js.map +1 -0
- package/dist/{document-model-modules-DCC6DjOP.js → document-model-modules-CHo9NZhj.js} +37 -5
- package/dist/document-model-modules-CHo9NZhj.js.map +1 -0
- package/dist/{document-operations-BUbpyfSf.js → document-operations-Dj0fTOHE.js} +113 -14
- package/dist/document-operations-Dj0fTOHE.js.map +1 -0
- package/dist/{global-DfeQC3Fg.d.ts → global-DMTXzdRf.d.ts} +28 -2
- package/dist/{global-DfeQC3Fg.d.ts.map → global-DMTXzdRf.d.ts.map} +1 -1
- package/dist/{index-BlCYgfht.d.ts → index-C5bsy9EC.d.ts} +127 -4
- package/dist/index-C5bsy9EC.d.ts.map +1 -0
- package/dist/index.d.ts +13 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/local-sign-in-D2zVzXgm.js +12 -0
- package/dist/local-sign-in-D2zVzXgm.js.map +1 -0
- package/dist/{renown-BlvHEYjM.js → renown-BwJ9oWxt.js} +414 -64
- package/dist/renown-BwJ9oWxt.js.map +1 -0
- package/dist/src/ai/index.d.ts +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/graphql-client/entry.d.ts +4 -4
- package/dist/src/graphql-client/entry.js +3 -3
- package/dist/src/renown/index.d.ts +2 -2
- package/dist/src/renown/index.js +2 -2
- package/dist/src/rpc/index.d.ts +17 -11
- package/dist/src/rpc/index.d.ts.map +1 -1
- package/dist/src/rpc/index.js +4 -3
- package/dist/src/rpc/index.js.map +1 -1
- package/dist/{switchboard-directory-CwT34q4g.js → switchboard-directory-7KPHB5Tz.js} +2 -2
- package/dist/{switchboard-directory-CwT34q4g.js.map → switchboard-directory-7KPHB5Tz.js.map} +1 -1
- package/package.json +11 -11
- package/dist/attachment-service-0E5S0hZ6.d.ts.map +0 -1
- package/dist/auth-DRbzRdeC.d.ts +0 -32
- package/dist/auth-DRbzRdeC.d.ts.map +0 -1
- package/dist/client-BFnMV-EO.js.map +0 -1
- package/dist/document-model-modules-DCC6DjOP.js.map +0 -1
- package/dist/document-operations-BUbpyfSf.js.map +0 -1
- package/dist/index-BlCYgfht.d.ts.map +0 -1
- package/dist/renown-BlvHEYjM.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-operations-Dj0fTOHE.js","names":["addFolder","baseAddFolder","baseMoveNode","moveNode","copyNode","baseCopyNode","DEFAULT_LIMIT","createClient"],"sources":["../src/hooks/url-state.ts","../src/hooks/link-props.ts","../src/hooks/modals.ts","../src/utils/documents.ts","../src/utils/user.ts","../src/actions/document.ts","../src/graphql-client/errors.ts","../src/constants.ts","../src/remote-controller/utils.ts","../src/graphql-client/adapter.ts","../src/graphql-client/drive-nodes.ts","../src/graphql-client/transport.ts","../src/graphql-client/create-defaults.ts","../src/graphql-client/operations.ts","../src/graphql-client/signing.ts","../src/graphql-client/static-package-manager.ts","../src/graphql-client/system-actions.ts","../src/graphql-client/subgraph.ts","../src/graphql-client/subscriptions.ts","../src/graphql-client/write-handles.ts","../src/graphql-client/graphql-reactor-client.ts","../src/hooks/backend-auth.ts","../src/hooks/config/editor.ts","../src/hooks/config/connect.ts","../src/hooks/attachment-service.ts","../src/hooks/features.ts","../src/hooks/use-drop-target.ts","../src/hooks/node-drag-and-drop.ts","../src/hooks/graphql-reactor-client.ts","../src/hooks/package-discovery.ts","../src/hooks/sync-selection.ts","../src/hooks/selected-timeline-item.ts","../src/hooks/timeline-revision.ts","../src/hooks/toast.ts","../src/hooks/add-ph-event-handlers.ts","../src/graphql-client/graphql-reactor-provider.tsx","../src/graphql-client/switchboard-backend.ts","../src/hooks/document-operations.ts"],"sourcesContent":["import type {\n PHNavigation,\n SetSearchParams,\n} from \"@powerhousedao/reactor-browser\";\nimport { getPHNavigation } from \"./navigation.js\";\nimport { usePHStore } from \"./ph-store.js\";\n\n/** The nearest store's navigation, else the bound store's, else the browser's.\n * Hosts set it once, so hook order holds. */\nexport function usePHNavigation(): PHNavigation {\n return usePHStore()?.navigation ?? getPHNavigation();\n}\n\n/** The current query params. */\nexport function useSearchParams(): Record<string, string> {\n return usePHNavigation().useSearchParams();\n}\n\n/** Sets query params: an object merges into them, a function returns them all. */\nexport function useSetSearchParams(): SetSearchParams {\n return usePHNavigation().useSetSearchParams();\n}\n","import type { PHNavigationTarget } from \"@powerhousedao/reactor-browser\";\nimport type { MouseEvent } from \"react\";\nimport { openTargetWith, targetPathname } from \"./navigation.js\";\nimport { usePHNavigation } from \"./url-state.js\";\n\ntype ClickLike = Pick<\n MouseEvent,\n | \"button\"\n | \"metaKey\"\n | \"ctrlKey\"\n | \"shiftKey\"\n | \"altKey\"\n | \"defaultPrevented\"\n | \"preventDefault\"\n>;\n\n/** A plain primary click; modified and other-button clicks stay the browser's. */\nexport function isPlainClick(event: ClickLike) {\n return (\n !event.defaultPrevented &&\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey\n );\n}\n\nexport type LinkProps = {\n href: string;\n onClick: (event: ClickLike) => void;\n onMouseEnter: () => void;\n onFocus: () => void;\n \"aria-current\"?: \"page\";\n};\n\n/** Props for an `<a>` that opens `target` in the app on a plain click, and\n * leaves new tabs and windows to the browser; acts on the store in context. */\nexport function useLinkProps(\n target: PHNavigationTarget | undefined,\n open?: () => void,\n): LinkProps {\n const navigation = usePHNavigation();\n const href = navigation.hrefFor?.(target) ?? targetPathname(target);\n const isCurrent = navigation.useIsCurrent?.(target) ?? false;\n const preload = () => navigation.preload?.(target);\n const openTarget = open ?? (() => openTargetWith(navigation, target));\n return {\n href,\n onClick: (event) => {\n if (!isPlainClick(event)) return;\n event.preventDefault();\n openTarget();\n },\n onMouseEnter: preload,\n onFocus: preload,\n \"aria-current\": isCurrent ? \"page\" : undefined,\n };\n}\n","import type { PHModal, PHSearchUpdate } from \"@powerhousedao/reactor-browser\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { isPlainClick, type LinkProps } from \"./link-props.js\";\nimport { useSearchParams } from \"./url-state.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport {\n getPHNavigation,\n hasHostNavigation,\n recordToSearch,\n searchToRecord,\n} from \"./navigation.js\";\n\nconst modalEventFunctions = makePHEventFunctions(\"modal\");\n\n/** Returns the current modal */\nexport const usePHModal = modalEventFunctions.useValue;\n\n/** Sets the current modal */\nexport const setPHModal = modalEventFunctions.setValue;\n\n/** Adds an event handler for the modal */\nexport const addModalEventHandler = modalEventFunctions.addEventHandler;\n\n/** The query param that names a routed modal. */\nexport const MODAL_SEARCH_PARAM = \"modal\";\n\ntype ModalOf<T extends PHModal[\"type\"]> = Extract<PHModal, { type: T }>;\ntype ModalRoute<T extends PHModal[\"type\"]> = {\n /** Its `?modal=` value. */\n id: string;\n /** Its fields as query params, and back. */\n toSearch?: (modal: ModalOf<T>) => Record<string, string>;\n fromSearch?: (search: Record<string, string>) => Omit<ModalOf<T>, \"type\">;\n};\n\n// Modals a link can open; they replace the current entry, so Back leaves the\n// page rather than closing them. Confirmations stay in the store.\nconst MODAL_ROUTES: { [T in PHModal[\"type\"]]?: ModalRoute<T> } = {\n createDocument: {\n id: \"create-document\",\n toSearch: ({ documentType, documentModelVersion, driveId }) => ({\n documentType,\n ...(documentModelVersion !== undefined && {\n documentModelVersion: String(documentModelVersion),\n }),\n ...(driveId && { driveId }),\n }),\n fromSearch: (search) => ({\n documentType: search.documentType ?? \"\",\n ...(search.documentModelVersion && {\n documentModelVersion: Number(search.documentModelVersion),\n }),\n ...(search.driveId && { driveId: search.driveId }),\n }),\n },\n login: { id: \"login\" },\n addDrive: { id: \"add-drive\" },\n driveSettings: {\n id: \"drive-settings\",\n toSearch: ({ driveId }) => ({ driveId }),\n fromSearch: (search) => ({ driveId: search.driveId ?? \"\" }),\n },\n debugSettings: { id: \"debug-settings\" },\n inspector: { id: \"inspector\" },\n disclaimer: { id: \"disclaimer\" },\n cookiesPolicy: { id: \"cookies-policy\" },\n};\n\nconst routeOf = (type: PHModal[\"type\"]) =>\n MODAL_ROUTES[type] as ModalRoute<PHModal[\"type\"]> | undefined;\n\n/** Whether `modal` lives in the URL rather than the store. */\nexport function isRoutedModal(modal: PHModal | undefined) {\n return !!modal && !!routeOf(modal.type);\n}\n\n/** The query params that open `modal`; undefined for one the store holds. */\nexport function modalSearch(\n modal: PHModal,\n): Record<string, string> | undefined {\n const route = routeOf(modal.type);\n if (!route) return undefined;\n return { [MODAL_SEARCH_PARAM]: route.id, ...route.toSearch?.(modal) };\n}\n\n/** The routed modal `search` opens, if any. */\nexport function modalFromSearch(\n search: Record<string, unknown>,\n): PHModal | undefined {\n const id = search[MODAL_SEARCH_PARAM];\n if (typeof id !== \"string\") return undefined;\n const strings = Object.fromEntries(\n Object.entries(search).map(([key, value]) => [key, String(value)]),\n );\n for (const [type, route] of Object.entries(MODAL_ROUTES)) {\n if (route.id !== id) continue;\n return { type, ...route.fromSearch?.(strings) } as PHModal;\n }\n return undefined;\n}\n\n/** `search` without a routed modal's params. */\nexport function withoutModalSearch(\n search: Record<string, string>,\n): PHSearchUpdate {\n const modal = modalFromSearch(search);\n const own = modal ? Object.keys(modalSearch(modal) ?? {}) : [];\n return Object.fromEntries(\n Object.entries(search).filter(([key]) => !own.includes(key)),\n );\n}\n\n/** Shows a modal. With a host navigation, a routed one opens in the URL, in\n * place of the current entry. */\nexport function showPHModal(modal: PHModal) {\n const search = modalSearch(modal);\n if (search && hasHostNavigation()) {\n // A confirmation the store holds would hide it.\n if (!isRoutedModal(modalEventFunctions.getSnapshot()))\n setPHModal(undefined);\n getPHNavigation().setSearch(\n (prev) => ({ ...withoutModalSearch(prev), ...search }),\n { replace: true },\n );\n return;\n }\n setPHModal(modal);\n}\n\n/** Closes the current modal; a routed one leaves the URL in place of the entry,\n * and a confirmation opened over it closes with it. */\nexport function closePHModal() {\n if (hasHostNavigation()) {\n const navigation = getPHNavigation();\n if (modalFromSearch(searchToRecord(navigation.location().search))) {\n navigation.setSearch((prev) => withoutModalSearch(prev), {\n replace: true,\n });\n // The router clears a routed one once the URL changes.\n if (!isRoutedModal(modalEventFunctions.getSnapshot())) {\n setPHModal(undefined);\n }\n return;\n }\n }\n setPHModal(undefined);\n}\n\n/** The href that opens `modal` over the current page. */\nexport function modalHref(modal: PHModal) {\n const { pathname, search } = getPHNavigation().location();\n const next = {\n ...(withoutModalSearch(searchToRecord(search)) as Record<string, string>),\n ...modalSearch(modal),\n };\n return `${pathname}${recordToSearch(next)}`;\n}\n\n/** Props for an `<a>` that opens a routed `modal` over the current page on a\n * plain click; new tabs and copied links get its URL. */\nexport function useModalLinkProps(\n modal: PHModal,\n): Pick<LinkProps, \"href\" | \"onClick\"> {\n // Re-renders as the page's search changes, so the href stays current.\n useSearchParams();\n return {\n href: modalHref(modal),\n onClick: (event) => {\n if (!isPlainClick(event)) return;\n event.preventDefault();\n showPHModal(modal);\n },\n };\n}\n\n/** Shows the create document modal */\nexport function showCreateDocumentModal(\n documentType: string,\n documentModelVersion?: number,\n) {\n showPHModal({\n type: \"createDocument\",\n documentType,\n ...(documentModelVersion !== undefined && { documentModelVersion }),\n });\n}\n\n/** Shows the delete node modal */\nexport function showDeleteNodeModal(nodeOrId: Node | string) {\n const id = typeof nodeOrId === \"string\" ? nodeOrId : nodeOrId.id;\n setPHModal({ type: \"deleteItem\", id });\n}\n","export function isDocumentTypeSupported(\n documentType: string,\n supportedDocuments: string[] | null | undefined,\n): boolean {\n if (!supportedDocuments?.length) {\n return true;\n }\n\n return supportedDocuments.some((pattern) => {\n // Path wildcard: \"powerhouse/*\"\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -2);\n return documentType.startsWith(prefix + \"/\");\n }\n\n // Prefix wildcard: \"power*\"\n if (pattern.endsWith(\"*\") && !pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return documentType.startsWith(prefix);\n }\n\n // Exact match\n return pattern === documentType;\n });\n}\n","import { getPHStore } from \"../hooks/ph-store.js\";\nexport function getUserPermissions() {\n const user = getPHStore()?.renown?.user;\n const allowList = getPHStore()?.allowList;\n if (!allowList) {\n return {\n isAllowedToCreateDocuments: true,\n isAllowedToEditDocuments: true,\n };\n }\n return {\n isAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n isAllowedToEditDocuments: allowList.includes(user?.address ?? \"\"),\n };\n}\n","import {\n dropDriveNode,\n getDriveNode,\n invalidateDriveNodes,\n markLocalDriveWrite,\n} from \"../hooks/drive-nodes.js\";\nimport { getPHStore } from \"../hooks/ph-store.js\";\nimport type {\n IReactorReadClient,\n IReactorWriteClient,\n} from \"@powerhousedao/reactor\";\nimport type {\n ConflictResolution,\n DocumentTypeIcon,\n FileUploadProgressCallback,\n IReactorBrowserReadClient,\n PHGlobal,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n addFolder as baseAddFolder,\n copyNode as baseCopyNode,\n moveNode as baseMoveNode,\n updateFile as baseUpdateFile,\n generateNodesCopy,\n handleTargetNameCollisions,\n isFileNode,\n isFolderNode,\n updateNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelModule,\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n Reducer,\n VersionedReplayConfig,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertAuthPreservedOnDuplicate,\n baseLoadFromInput,\n baseLoadFromInputVersioned,\n baseSaveToFileHandle,\n createCopyHeader,\n createPresignedHeader,\n createZip,\n creationState,\n documentModelDocumentType,\n generateId,\n hasDerivedDocumentId,\n replayDocumentVersioned,\n setName,\n setPreferredEditor,\n signaturePolicyOf,\n UnsupportedDocumentModelVersionError,\n type UpgradeDocumentActionInput,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { conditional, constant, isDefined, isNot, isStrictEqual } from \"remeda\";\nimport {\n DocumentModelNotFoundError,\n UnsupportedDocumentTypeError,\n} from \"../errors.js\";\nimport { showPHModal } from \"../hooks/modals.js\";\nimport { getFullReactorClient } from \"../hooks/reactor.js\";\nimport { isDocumentTypeSupported } from \"../utils/documents.js\";\nimport { listAllDriveNodes } from \"../utils/nodes.js\";\nimport { getUserPermissions } from \"../utils/user.js\";\nimport { queueActions, queueOperations, uploadOperations } from \"./queue.js\";\n\nconst NON_DOMAIN_SCOPES = new Set([\"auth\", \"document\"]);\n\n/** Puts a node this tab just wrote into its drive's cache, so hooks show it\n * before the drive change that follows the write is processed. Best effort:\n * a client without a node reader is left to that change. */\nasync function rememberDriveNode(driveId: string, nodeId: string) {\n try {\n await getDriveNode(driveId, nodeId, { refresh: true });\n } catch (error) {\n logger.verbose(\n \"Caching the written node @id failed: @error\",\n nodeId,\n error,\n );\n }\n}\n\n/** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */\nasync function isDocumentInLocation(\n reactorClient: IReactorReadClient,\n document: PHDocument,\n driveId: string,\n parentFolder?: string,\n): Promise<{\n isDuplicate: boolean;\n duplicateType?: \"id\" | \"name\";\n nodeId?: string;\n}> {\n const siblings = await listAllDriveNodes(reactorClient.drives, driveId, {\n parentFolder: parentFolder ?? null,\n });\n\n // Case 1: Check for duplicate by ID\n const nodeById = siblings.find((node) => node.id === document.header.id);\n\n if (nodeById) {\n return {\n isDuplicate: true,\n duplicateType: \"id\",\n nodeId: nodeById.id,\n };\n }\n\n // Case 2: Check for duplicate by name + type in same parent folder\n const nodeByNameAndType = siblings.find(\n (node: Node) =>\n isFileNode(node) &&\n node.name === document.header.name &&\n node.documentType === document.header.documentType,\n );\n\n if (nodeByNameAndType) {\n return {\n isDuplicate: true,\n duplicateType: \"name\",\n nodeId: nodeByNameAndType.id,\n };\n }\n\n return { isDuplicate: false };\n}\n\nfunction getDocumentTypeIcon(\n document: PHDocument,\n): DocumentTypeIcon | undefined {\n const documentType = document.header.documentType;\n\n switch (documentType) {\n case \"powerhouse/document-model\":\n return \"document-model\";\n case \"powerhouse/app\":\n return \"app\";\n case \"powerhouse/document-editor\":\n return \"editor\";\n case \"powerhouse/subgraph\":\n return \"subgraph\";\n case \"powerhouse/package\":\n return \"package\";\n case \"powerhouse/processor\": {\n // Check the processor type from global state (safely)\n const globalState = (document.state as { global?: { type?: string } })\n .global;\n const processorType = globalState?.type;\n\n if (processorType === \"analytics\") return \"analytics-processor\";\n if (processorType === \"relational\") return \"relational-processor\";\n if (processorType === \"codegen\") return \"codegen-processor\";\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\nexport async function downloadFile(document: PHDocument, fileName: string) {\n try {\n const data = await createZip(document);\n const blob = new Blob([new Uint8Array(data)], { type: \"application/zip\" });\n const link = window.document.createElement(\"a\");\n link.style.display = \"none\";\n link.href = URL.createObjectURL(blob);\n link.download = fileName;\n\n window.document.body.appendChild(link);\n link.click();\n\n window.document.body.removeChild(link);\n } catch (e) {\n logger.error(e instanceof Error ? e.message : String(e));\n }\n}\n\nexport async function getDocumentExtension(\n document: PHDocument,\n): Promise<string> {\n const documentType = document.header.documentType;\n\n let rawExtension: string | undefined;\n\n if (documentType === documentModelDocumentType) {\n const globalState = (document.state as { global?: { extension?: string } })\n .global;\n rawExtension = globalState?.extension;\n } else {\n // document model modules are only available on the full reactor client\n const reactorClient = getFullReactorClient();\n if (reactorClient) {\n const { results: documentModelModules } =\n await reactorClient.read.getDocumentModelModules();\n const module = documentModelModules.find(\n (m: DocumentModelModule) => m.documentModel.global.id === documentType,\n );\n rawExtension = module?.utils.fileExtension;\n }\n }\n\n return (rawExtension ?? \"\").replace(/^\\.+|\\.+$/g, \"\");\n}\n\n/**\n * Fetches all operations for a document using cursor-based pagination.\n * The reactor client handles multi-scope cursors transparently via\n * composite cursors, so all scopes are fetched in a single paginated stream.\n */\nexport async function fetchDocumentOperations(\n reactorClient: IReactorBrowserReadClient,\n document: PHDocument,\n pageSize = 100,\n): Promise<DocumentOperations> {\n // includes auth: an export must carry the policy history\n const scopes = Object.keys(document.state);\n const operations: DocumentOperations = {};\n for (const scope of scopes) {\n operations[scope] = [];\n }\n\n let cursor = \"\";\n\n do {\n const page = await reactorClient.getOperations(\n document.header.id,\n { scopes },\n undefined,\n { cursor, limit: pageSize },\n );\n\n for (const op of page.results) {\n const scope = op.action.scope ?? \"global\";\n if (operations[scope]) {\n operations[scope].push(op);\n }\n }\n\n cursor = page.nextCursor ?? \"\";\n } while (cursor);\n\n return operations;\n}\n\nexport function extractInitialState(\n documentScopeOps: Operation[],\n): PHBaseState {\n const initialState = creationState(documentScopeOps);\n if (initialState) {\n return initialState;\n }\n throw new Error(\n documentScopeOps.some((op) => op.action.type === \"UPGRADE_DOCUMENT\")\n ? \"UPGRADE_DOCUMENT operation has no initialState — document is invalid\"\n : \"No UPGRADE_DOCUMENT operation found — document is invalid\",\n );\n}\n\nexport function filterDomainOperations(\n operations: DocumentOperations,\n): DocumentOperations {\n return Object.fromEntries(\n Object.entries(operations).filter(\n ([scope]) => !NON_DOMAIN_SCOPES.has(scope),\n ),\n );\n}\n\n/** Domain operations to replay, and the version to upgrade to afterwards. */\nexport interface ImportSegment {\n operations: DocumentOperations;\n /** Absent on the final segment. */\n upgradeTo?: number;\n}\n\nfunction countOperations(operations: DocumentOperations): number {\n let total = 0;\n for (const ops of Object.values(operations)) {\n total += ops?.length ?? 0;\n }\n return total;\n}\n\n/**\n * Split an imported document's domain operations at its mid-history upgrade\n * boundaries, so the caller can re-dispatch each upgrade between segments.\n *\n * The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation\n * path and must not be repeated. A later upgrade must be: it is where the\n * reducer version changes, and dropping it replays everything after it through\n * the module the document was created with.\n */\nexport function splitAtUpgradeBoundaries(\n operations: DocumentOperations,\n): ImportSegment[] {\n const upgrades = (operations.document ?? [])\n .filter((op) => op.action.type === \"UPGRADE_DOCUMENT\")\n .filter(\n (op) => (op.action.input as UpgradeDocumentActionInput).fromVersion > 0,\n )\n .sort((a, b) => a.index - b.index);\n\n const domain = filterDomainOperations(operations);\n if (upgrades.length === 0) {\n return [{ operations: domain }];\n }\n\n const segments: ImportSegment[] = [];\n const consumed = new Map<string, number>();\n\n const take = (until: (scope: string, ops: Operation[]) => number) => {\n const slice: DocumentOperations = {};\n for (const [scope, ops] of Object.entries(domain)) {\n if (!ops) continue;\n const from = consumed.get(scope) ?? 0;\n const stop = Math.max(from, until(scope, ops));\n const chunk = ops.slice(from, stop);\n if (chunk.length > 0) slice[scope] = chunk;\n consumed.set(scope, stop);\n }\n return slice;\n };\n\n for (const upgrade of upgrades) {\n const input = upgrade.action.input as UpgradeDocumentActionInput;\n const slice = take((scope, ops) => boundary(upgrade, scope, ops));\n segments.push({ operations: slice, upgradeTo: input.toVersion });\n }\n\n const tail = take((_scope, ops) => ops.length);\n if (countOperations(tail) > 0) {\n segments.push({ operations: tail });\n }\n\n return segments;\n}\n\n/**\n * How many of a scope's operations precede an upgrade. Must stay identical to\n * the boundary computation in `replayDocumentVersioned` — snapshots compare\n * against operation indices, not array positions, and the timestamp fallback\n * excludes the upgrade's own instant.\n */\nfunction boundary(upgrade: Operation, scope: string, ops: Operation[]): number {\n const snapshot = (upgrade.action.input as UpgradeDocumentActionInput)\n .revision;\n\n if (snapshot !== undefined) {\n const revision = snapshot[scope] ?? 0;\n let count = 0;\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].index < revision) count = i + 1;\n }\n return count;\n }\n\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) {\n return i;\n }\n }\n return ops.length;\n}\n\nexport async function exportFile(document: PHDocument, suggestedName?: string) {\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Fetch operations page-by-page (document from reactor has operations: {})\n const operations = await fetchDocumentOperations(\n reactorClient.read,\n document,\n );\n const initialState = extractInitialState(operations[\"document\"] ?? []);\n const documentWithOps = { ...document, operations, initialState };\n\n // Get the extension from the document model module\n const extension = await getDocumentExtension(documentWithOps);\n\n const baseName = suggestedName || documentWithOps.header.name || \"Untitled\";\n const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!window.showSaveFilePicker) {\n return await downloadFile(documentWithOps, name);\n }\n try {\n const fileHandle = await window.showSaveFilePicker({\n suggestedName: name,\n });\n\n await baseSaveToFileHandle(documentWithOps, fileHandle);\n return fileHandle;\n } catch (e) {\n // ignores error if user cancelled the file picker\n if (!(e instanceof DOMException && e.name === \"AbortError\")) {\n throw e;\n }\n }\n}\n\n/**\n * Loads a document file and replays it with version-aware reducers from the registry.\n * Falls back to single-version legacy replay when no upgrade manifest is registered for\n * the document type.\n */\nexport async function loadFile(path: string | File) {\n const baseDocument = await baseLoadFromInput(\n path,\n (state: PHDocument) => state,\n { checkHashes: true },\n );\n\n // document model modules are only available on the full reactor client\n const reactorClient = getFullReactorClient();\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const documentType = baseDocument.header.documentType;\n const { results: documentModelModules } =\n await reactorClient.read.getDocumentModelModules();\n const modulesForType = documentModelModules.filter(\n (module) => module.documentModel.global.id === documentType,\n );\n if (modulesForType.length === 0) {\n throw new DocumentModelNotFoundError(documentType);\n }\n\n const reducers: VersionedReplayConfig[\"reducers\"] = {};\n for (const module of modulesForType) {\n reducers[module.version ?? 1] = module.reducer as Reducer<PHBaseState>;\n }\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n let upgradeManifest: VersionedReplayConfig[\"upgradeManifest\"] | undefined;\n if (registry) {\n try {\n upgradeManifest = registry.getUpgradeManifest(documentType);\n } catch {\n // intentionally empty — missing manifest is normal for single-version documents\n }\n }\n\n const config: VersionedReplayConfig = { reducers, upgradeManifest };\n return baseLoadFromInputVersioned(path, config);\n}\n\nexport async function addDocument(\n driveId: string,\n name: string,\n documentType: string,\n parentFolder?: string,\n document?: PHDocument,\n id?: string,\n preferredEditor?: string,\n documentModelVersion?: number,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create documents\");\n }\n\n // document model modules and drive operations are only available on the full\n // reactor client\n const reactorClient = getFullReactorClient();\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // create - use passed document's state if available\n const newDocument =\n document ??\n (await reactorClient.read.newDocument(documentType, {\n parentIdentifier: driveId,\n documentModelVersion,\n }));\n newDocument.header.name = name;\n if (preferredEditor) {\n newDocument.header.meta = {\n ...newDocument.header.meta,\n preferredEditor,\n };\n }\n\n // Create document using ReactorClient. The new node shows at once: the\n // drive change that follows this write re-reads the drive without waiting\n // out the interval, and the node goes into the cache as soon as it exists.\n markLocalDriveWrite(driveId);\n let newDoc: PHDocument;\n try {\n const added = await reactorClient.write.drives.addFile(\n driveId,\n newDocument,\n parentFolder,\n );\n newDoc = await added.document();\n } catch (e) {\n logger.error(\"Error adding document: @error\", e);\n throw new Error(\"There was an error adding document\", { cause: e });\n }\n await rememberDriveNode(driveId, newDoc.header.id);\n\n // The throttled drive refresh can lag; cache the new node now.\n await getDriveNode(driveId, newDoc.header.id, { refresh: true }).catch(\n () => undefined,\n );\n\n // Return a file node structure for compatibility\n return {\n id: newDoc.header.id,\n name: newDoc.header.name,\n documentType,\n parentFolder: parentFolder ?? null,\n kind: \"file\" as const,\n };\n}\n\n/** The file node shape {@link addDocument} reports for a created document. */\nexport type AddedFileNode = {\n id: string;\n name: string;\n documentType: string;\n parentFolder: string | null;\n kind: \"file\";\n};\n\n/**\n * How many ids an import will try before giving up. The check before the create\n * catches an id that is already taken; this bound covers the window between the\n * two, where a create can still lose to a claim made in the meantime.\n */\nconst IMPORT_ID_ATTEMPTS = 3;\n\n/** True when this error, or anything it wraps, is a taken document id. */\nfunction isDocumentAlreadyExists(error: unknown): boolean {\n let current: unknown = error;\n while (current instanceof Error) {\n if (current.name === \"DocumentAlreadyExistsError\") {\n return true;\n }\n current = current.cause;\n }\n return false;\n}\n\n/**\n * Creates the imported document under an id that is free, retrying on a\n * collision.\n *\n * The check cannot stand on its own: it answers for the moment it ran, and the\n * create that follows can still land on an id claimed in between. The store\n * rejects that create as DocumentAlreadyExistsError, which is not retryable\n * under the same id and is resolved by minting another one. A create that\n * fails leaves the drive untouched, so a retry has nothing to clean up.\n */\nasync function createImportedDocument(\n write: IReactorWriteClient,\n document: PHDocument,\n driveId: string,\n name?: string,\n parentFolder?: string,\n): Promise<{ documentId: string; fileNode: AddedFileNode }> {\n // A v2-required import keeps the zip's id only while that id still derives\n // from the zip's header, so the signatures bound to it keep verifying.\n const v2Required = signaturePolicyOf(document.header) === \"v2-required\";\n const keepsId =\n (!v2Required || hasDerivedDocumentId(document.header)) &&\n !(await write.isDocumentIdTaken(document.header.id));\n let documentId = keepsId ? document.header.id : generateId();\n\n for (let attempt = 1; ; attempt++) {\n let header: PHDocumentHeader;\n if (!v2Required) {\n header = createPresignedHeader(\n documentId,\n document.header.documentType,\n document.header.protocolVersions,\n );\n } else if (keepsId && attempt === 1) {\n header = createPresignedHeader(documentId, document.header.documentType);\n header.createdAtUtcIso = document.header.createdAtUtcIso;\n header.sig = { ...header.sig, nonce: document.header.sig.nonce };\n header.protocolVersions = { ...document.header.protocolVersions };\n } else {\n header = createCopyHeader(document.header);\n documentId = header.id;\n }\n header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n header.meta = document.header.meta;\n header.name = name || document.header.name;\n\n // copy the document at it's initial state\n const initialDocument = {\n ...document,\n header,\n state: document.initialState,\n operations: Object.keys(document.operations).reduce((acc, key) => {\n acc[key] = [];\n return acc;\n }, {} as DocumentOperations),\n };\n\n try {\n const fileNode = await addDocument(\n driveId,\n name || document.header.name,\n document.header.documentType,\n parentFolder,\n initialDocument,\n documentId,\n document.header.meta?.preferredEditor,\n );\n\n if (!fileNode) {\n throw new Error(\"There was an error adding file\");\n }\n\n return { documentId, fileNode };\n } catch (error) {\n if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) {\n throw error;\n }\n\n logger.warn(\n `Document id ${documentId} was taken between the check and the create; importing under a new id`,\n );\n documentId = generateId();\n }\n }\n}\n\nexport async function addFileWithProgress(\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n) {\n logger.verbose(\n `addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`,\n );\n // importing a file into a drive is a full reactor client feature\n const reactor = getFullReactorClient();\n if (!reactor) {\n // Reported before it is thrown: a caller watching progress settles on a\n // terminal stage, and returning quietly here left it waiting forever.\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error: \"ReactorClient not initialized\",\n });\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create files\");\n }\n\n // Loading stage (0-10%)\n try {\n onProgress?.({ stage: \"loading\", progress: 0 });\n let document: PHDocument;\n try {\n document = await loadFile(file);\n } catch (loadError) {\n if (UnsupportedDocumentModelVersionError.isError(loadError)) {\n showPHModal({\n type: \"documentVersionUnsupported\",\n documentType: loadError.documentType,\n requiredVersion: loadError.requiredVersion,\n availableVersions: loadError.availableVersions,\n });\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error: loadError.message,\n });\n return;\n }\n\n // Only attempt discovery if the failure is specifically a missing\n // document model module, not for other errors like corrupt files.\n const discoveryService = getPHStore()?.packageDiscoveryService;\n if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {\n // Trigger discovery and retry without blocking the drop handler\n void retryAfterDiscovery(\n discoveryService,\n loadError.documentType,\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n ).catch((retryError: unknown) => {\n // Nothing awaits this call, so an unreported throw here is an\n // unhandled rejection and a caller that never settles.\n logger.error(\n \"Import retry after discovery failed: @error\",\n retryError,\n );\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error:\n retryError instanceof Error\n ? retryError.message\n : String(retryError),\n });\n });\n return;\n }\n throw loadError;\n }\n\n // Check for duplicate in same location\n const duplicateCheck = await isDocumentInLocation(\n reactor.read,\n document,\n driveId,\n parentFolder,\n );\n\n if (duplicateCheck.isDuplicate && !resolveConflict) {\n // Report conflict and return early\n onProgress?.({\n stage: \"conflict\",\n progress: 0,\n duplicateType: duplicateCheck.duplicateType,\n });\n return undefined;\n }\n\n // For \"duplicate\" resolution, we continue normally which creates a new document\n // with a different ID (the default behavior)\n\n // Send documentType info immediately after loading\n const documentType = getDocumentTypeIcon(document);\n if (documentType) {\n onProgress?.({ stage: \"loading\", progress: 10, documentType });\n } else {\n onProgress?.({ stage: \"loading\", progress: 10 });\n }\n\n if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${document.header.documentType} is not supported`,\n });\n throw new UnsupportedDocumentTypeError(document.header.documentType);\n }\n\n // ensure we have the module + can load it (throws if not found)\n await reactor.read.getDocumentModelModule(document.header.documentType);\n\n // Initializing stage (10-20%)\n onProgress?.({ stage: \"initializing\", progress: 10 });\n\n markLocalDriveWrite(driveId);\n const created = await createImportedDocument(\n reactor.write,\n document,\n driveId,\n name,\n parentFolder,\n );\n const documentId = created.documentId;\n const fileNode = created.fileNode;\n await rememberDriveNode(driveId, documentId);\n\n onProgress?.({ stage: \"initializing\", progress: 20 });\n\n const _doc = await reactor.read.get(documentId);\n console.log(\"Document created, starting upload of operations\");\n\n // Uploading stage (20-100%), re-dispatching each mid-history upgrade at\n // its boundary\n const segments = splitAtUpgradeBoundaries(document.operations);\n const totalOperations = segments.reduce(\n (total, segment) => total + countOperations(segment.operations),\n 0,\n );\n let uploadedBefore = 0;\n\n for (const segment of segments) {\n await uploadOperations(documentId, segment.operations, queueOperations, {\n onProgress: (uploadProgress) => {\n if (uploadProgress.uploadedOperations === undefined) {\n return;\n }\n const uploaded = uploadedBefore + uploadProgress.uploadedOperations;\n const uploadPercent =\n totalOperations > 0 ? uploaded / totalOperations : 0;\n onProgress?.({\n stage: \"uploading\",\n progress: 20 + Math.round(uploadPercent * 80),\n totalOperations,\n uploadedOperations: uploaded,\n });\n },\n });\n\n uploadedBefore += countOperations(segment.operations);\n\n if (segment.upgradeTo !== undefined) {\n await (\n await reactor.write.upgradeDocument(documentId, segment.upgradeTo)\n ).document();\n }\n }\n\n onProgress?.({ stage: \"complete\", progress: 100, fileNode });\n\n return fileNode;\n } catch (error) {\n // Don't override unsupported-document-type status\n if (!UnsupportedDocumentTypeError.isError(error)) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error: errorMessage,\n });\n }\n throw error;\n }\n}\n\nasync function retryAfterDiscovery(\n discoveryService: PHGlobal[\"packageDiscoveryService\"],\n documentType: string,\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n): Promise<void> {\n if (!discoveryService) return;\n try {\n await discoveryService.load(documentType);\n } catch {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${documentType} is not supported`,\n });\n return;\n }\n await addFileWithProgress(\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n );\n}\n\nexport async function updateFile(\n driveId: string,\n nodeId: string,\n documentType?: string,\n name?: string,\n parentFolder?: string,\n) {\n const reactor = getPHStore()?.reactorClient;\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to update files\");\n }\n const drive = await reactor.read.get<DocumentDriveDocument>(driveId);\n markLocalDriveWrite(driveId);\n await queueActions(\n drive,\n baseUpdateFile({\n id: nodeId,\n name: name ?? undefined,\n parentFolder,\n documentType,\n }),\n );\n\n const node = await getDriveNode(driveId, nodeId, { refresh: true });\n if (!node || !isFileNode(node)) {\n throw new Error(\"There was an error updating document\");\n }\n return node;\n}\n\nexport async function addFolder(\n driveId: string,\n name: string,\n parentFolder?: string,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create folders\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Get the drive document and add folder action\n const _drive = await reactorClient.read.get<DocumentDriveDocument>(driveId);\n const folderId = generateId();\n markLocalDriveWrite(driveId);\n const added = await reactorClient.write.execute(driveId, \"main\", [\n baseAddFolder({\n id: folderId,\n name,\n parentFolder,\n }),\n ]);\n await added.readable;\n\n const node = await getDriveNode(driveId, folderId, { refresh: true });\n if (!node || !isFolderNode(node)) {\n throw new Error(\"There was an error adding folder\");\n }\n return node;\n}\n\nexport async function deleteNode(driveId: string, nodeId: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to delete documents\");\n }\n\n // drive operations are only available on the full reactor client\n const reactorClient = getFullReactorClient();\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n markLocalDriveWrite(driveId);\n const removed = await reactorClient.write.drives.removeNode(driveId, nodeId);\n await removed.readable;\n dropDriveNode(driveId, nodeId);\n}\n\nexport async function renameNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const renamed = await reactorClient.write.execute(nodeId, \"main\", [\n setName({ name }),\n ]);\n const renameNodeResult = await renamed.document();\n\n if (renameNodeResult.header.name !== name) {\n throw new Error(\"There was an error renaming the node\");\n }\n\n // Rename the node in the drive document using updateNode action\n markLocalDriveWrite(driveId);\n const updated = await reactorClient.write.execute(driveId, \"main\", [\n updateNode({ id: nodeId, name }),\n ]);\n await updated.readable;\n\n const node = await getDriveNode(driveId, nodeId, { refresh: true });\n if (!node) {\n throw new Error(\"There was an error renaming node in the drive\");\n }\n return node;\n}\n\nexport async function renameDriveNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const renamed = await reactorClient.write.execute(nodeId, \"main\", [\n setName({ name }),\n ]);\n const renameNodeResult = await renamed.document();\n\n if (renameNodeResult.header.name !== name) {\n throw new Error(\"There was an error renaming the node\");\n }\n\n markLocalDriveWrite(driveId);\n const updated = await reactorClient.write.execute(driveId, \"main\", [\n updateNode({ id: nodeId, name }),\n ]);\n await updated.readable;\n return getDriveNode(driveId, nodeId, { refresh: true });\n}\n\nexport async function setPreferredEditorOnNode(\n nodeId: string,\n preferredEditor: string | null,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to modify documents\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const handle = await reactorClient.write.execute(nodeId, \"main\", [\n setPreferredEditor(preferredEditor),\n ]);\n return handle.document();\n}\n\nexport async function moveNodeById(args: {\n driveId: string | undefined;\n srcId: string | undefined;\n targetId?: string;\n}) {\n const { driveId, srcId, targetId } = args;\n if (!driveId || !srcId) return;\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to move documents\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n const targetParentFolder = conditional(\n targetId,\n [isNot(isDefined), constant(undefined)],\n [isStrictEqual(driveId), constant(undefined)],\n constant(targetId),\n );\n\n if (isStrictEqual(targetParentFolder, srcId)) return;\n\n markLocalDriveWrite(driveId);\n const handle = await reactorClient.write.execute(driveId, \"main\", [\n baseMoveNode({\n srcFolder: srcId,\n targetParentFolder,\n }),\n ]);\n const moved = await handle.document();\n await rememberDriveNode(driveId, srcId);\n return moved;\n}\n\nexport async function moveNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to move documents\");\n }\n\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n markLocalDriveWrite(driveId);\n const handle = await reactorClient.write.execute(driveId, \"main\", [\n baseMoveNode({\n srcFolder: src.id,\n targetParentFolder: target?.id,\n }),\n ]);\n const moved = await handle.document();\n await rememberDriveNode(driveId, src.id);\n return moved;\n}\n\n/**\n * Duplicates a document under a new id using version-aware replay.\n * Falls back gracefully when no upgrade manifest is registered for the document type.\n */\nasync function _duplicateDocument(\n reactor: IReactorReadClient,\n document: PHDocument,\n newId = generateId(),\n driveId?: string,\n) {\n const documentType = document.header.documentType;\n const { results: allModules } = await reactor.getDocumentModelModules();\n const modulesForType = allModules.filter(\n (m) => m.documentModel.global.id === documentType,\n );\n\n const reducers: VersionedReplayConfig[\"reducers\"] = {};\n for (const m of modulesForType) {\n reducers[m.version ?? 1] = m.reducer as Reducer<PHBaseState>;\n }\n\n if (Object.keys(reducers).length === 0) {\n throw new Error(\n `Document model module not found for type: ${documentType}`,\n );\n }\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n let upgradeManifest: VersionedReplayConfig[\"upgradeManifest\"] | undefined;\n if (registry) {\n try {\n upgradeManifest = registry.getUpgradeManifest(documentType);\n } catch {\n // intentionally empty — missing manifest is normal for single-version documents\n }\n }\n\n const config: VersionedReplayConfig = { reducers, upgradeManifest };\n // A copy keeps its source's versions; selection fills the keys it lacks.\n const selected = await reactor.getCreateProtocolVersions({\n documentType: document.header.documentType,\n parentIdentifier: driveId,\n });\n const header = createCopyHeader(\n {\n documentType: document.header.documentType,\n protocolVersions: document.header.protocolVersions\n ? { ...selected, ...document.header.protocolVersions }\n : undefined,\n },\n newId,\n await reactor.getCreateSignaturePolicy(),\n );\n\n const duplicated = replayDocumentVersioned(\n document.initialState,\n document.operations,\n config,\n header,\n );\n assertAuthPreservedOnDuplicate(\n document.header.id,\n document.state.auth,\n duplicated.state.auth,\n );\n return duplicated;\n}\n\nexport async function copyNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n // copying nodes duplicates documents and adds drive files, both of which are\n // only available on the full reactor client\n const reactor = getFullReactorClient();\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to copy documents\");\n }\n\n const drive = await reactor.read.get<DocumentDriveDocument>(driveId);\n const driveNodes = await listAllDriveNodes(reactor.read.drives, driveId);\n\n const copyNodesInput = generateNodesCopy(\n {\n srcId: src.id,\n targetParentFolder: target?.id,\n targetName: src.name,\n },\n () => generateId(),\n driveNodes,\n );\n\n // Pre-calculate collision-resolved names for all nodes to be copied\n const resolvedNamesMap = new Map<string, string>();\n for (const copyNodeInput of copyNodesInput) {\n const node = driveNodes.find((n) => n.id === copyNodeInput.srcId);\n if (node) {\n const resolvedName = handleTargetNameCollisions({\n nodes: driveNodes,\n srcName: copyNodeInput.targetName || node.name,\n srcKind: isFileNode(node) ? \"file\" : \"folder\",\n targetParentFolder: copyNodeInput.targetParentFolder || null,\n });\n resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);\n }\n }\n\n const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {\n const node = driveNodes.find((node) => node.id === copyNodeInput.srcId);\n return node !== undefined && isFileNode(node);\n });\n\n markLocalDriveWrite(driveId);\n for (const fileNodeToCopy of fileNodesToCopy) {\n try {\n const document = await reactor.read.get(fileNodeToCopy.srcId);\n\n const duplicatedDocument = await _duplicateDocument(\n reactor.read,\n document,\n fileNodeToCopy.targetId,\n driveId,\n );\n\n // Set the header name to match the collision-resolved node name\n const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);\n if (resolvedName) {\n duplicatedDocument.header.name = resolvedName;\n }\n // A v2-required copy takes a derived id, which the drive's node must name.\n fileNodeToCopy.targetId = duplicatedDocument.header.id;\n\n const added = await reactor.write.drives.addFile(\n driveId,\n duplicatedDocument,\n target?.id,\n );\n await added.readable;\n } catch (e) {\n logger.error(\n `Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`,\n );\n }\n }\n\n const copyActions = copyNodesInput.map((copyNodeInput) =>\n baseCopyNode(copyNodeInput),\n );\n // Many nodes land at once: re-list the drive rather than fetch each one.\n markLocalDriveWrite(driveId);\n const copied = await queueActions(drive, copyActions);\n invalidateDriveNodes(driveId);\n return copied;\n}\n\n/**\n * Upgrades a document to a newer document model version. Defaults to the\n * latest registered version for the document's type.\n */\nexport async function upgradeDocument(documentId: string, toVersion?: number) {\n const reactorClient = getFullReactorClient();\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n const handle = await reactorClient.write.upgradeDocument(\n documentId,\n toVersion,\n );\n return handle.document();\n}\n","import type { JobInfo } from \"@powerhousedao/reactor\";\n\n/** A call the Switchboard GraphQL surface cannot express. */\nexport class GraphQLOperationNotSupportedError extends Error {\n override readonly name = \"GraphQLOperationNotSupportedError\";\n readonly operation: string;\n\n constructor(operation: string, reason: string) {\n super(`GraphQLReactorClient.${operation} is not supported: ${reason}`);\n this.operation = operation;\n }\n\n static override isError(\n error: unknown,\n ): error is GraphQLOperationNotSupportedError {\n return (\n Error.isError(error) && error.name === \"GraphQLOperationNotSupportedError\"\n );\n }\n}\n\n/**\n * The Switchboard refused a request with 421 Misdirected Request: the\n * `Drive-Id` it carried names a drive that Switchboard does not own.\n */\nexport class GraphQLWrongBackendError extends Error {\n override readonly name = \"GraphQLWrongBackendError\";\n readonly status = 421;\n /** The drive the Switchboard refused, or `\"\"` when its answer names none. */\n readonly driveId: string;\n /** The response body, parsed when it is JSON. */\n readonly payload: unknown;\n\n constructor(driveId: string, payload: unknown, options?: ErrorOptions) {\n super(\n `The Switchboard does not serve drive ${driveId === \"\" ? \"(unnamed)\" : driveId}: 421 Misdirected Request`,\n options,\n );\n this.driveId = driveId;\n this.payload = payload;\n }\n\n static override isError(error: unknown): error is GraphQLWrongBackendError {\n return (\n Error.isError(error) &&\n error.name === \"GraphQLWrongBackendError\" &&\n typeof (error as Partial<GraphQLWrongBackendError>).driveId === \"string\"\n );\n }\n}\n\n/**\n * The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry\n * imports the reactor for types only. The shared name lets either `isError`\n * recognise it.\n */\nexport class BatchJobFailedError extends Error {\n override readonly name = \"BatchJobFailedError\";\n readonly key: string;\n readonly jobs: Readonly<Record<string, JobInfo>>;\n\n constructor(key: string, jobs: Record<string, JobInfo>) {\n const failure = jobs[key].error;\n const cause = new Error(failure?.message ?? \"Job failed\");\n cause.name = failure?.name ?? \"Error\";\n super(failure?.message ?? \"Job failed\", { cause });\n this.key = key;\n this.jobs = jobs;\n }\n\n static override isError(error: unknown): error is BatchJobFailedError {\n return (\n Error.isError(error) &&\n error.name === \"BatchJobFailedError\" &&\n typeof (error as Partial<BatchJobFailedError>).key === \"string\" &&\n typeof (error as Partial<BatchJobFailedError>).jobs === \"object\"\n );\n }\n}\n\n/** A validation error naming root field `field` unknown: a host from before it. */\nexport function queriesUnknownField(error: unknown, field: string): boolean {\n return hasErrorStarting(error, `Cannot query field \"${field}\" on type \"`);\n}\n\n/** A validation error naming `argument` unknown: a host from before it. */\nexport function queriesUnknownArgument(\n error: unknown,\n argument: string,\n): boolean {\n return hasErrorStarting(error, `Unknown argument \"${argument}\" on field \"`);\n}\n\nfunction hasErrorStarting(error: unknown, prefix: string): boolean {\n const errors = (error as { response?: { errors?: unknown } } | null)?.response\n ?.errors;\n if (!Array.isArray(errors)) {\n return false;\n }\n return errors.some(\n (entry) =>\n typeof (entry as { message?: unknown } | null)?.message === \"string\" &&\n (entry as { message: string }).message.startsWith(prefix),\n );\n}\n\n/**\n * The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported\n * FAILED; this entry imports the reactor for types only. A write handle's\n * stage rejects with it. The message is the job error's message, as the\n * reactor's is.\n */\nexport class JobFailedError extends Error {\n override readonly name = \"JobFailedError\";\n readonly job: JobInfo;\n\n constructor(job: JobInfo) {\n super(job.error?.message);\n this.job = job;\n }\n\n static override isError(error: unknown): error is JobFailedError {\n return (\n Error.isError(error) &&\n error.name === \"JobFailedError\" &&\n typeof (error as Partial<JobFailedError>).job === \"object\"\n );\n }\n}\n","export const DEFAULT_DRIVE_EDITOR_ID = \"powerhouse/generic-drive-explorer\";\nexport const COMMON_PACKAGE_ID = \"powerhouse/common\";\n\n/** Document types that represent a \"drive\": a container of nodes. */\nexport const DRIVE_DOCUMENT_TYPES = [\n \"powerhouse/document-drive\",\n \"powerhouse/reactor-drive\",\n] as const;\n","import type {\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type { SignaturePolicy } from \"@powerhousedao/shared/document-model\";\nimport {\n creationState,\n deserializeSignature,\n signaturePolicyOf,\n withSignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n ConflictInfo,\n RemoteDocumentData,\n RemoteOperation,\n} from \"./types.js\";\n\n/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. \"SET_MODEL_NAME\" → \"setModelName\"). */\nexport function screamingSnakeToCamel(s: string): string {\n return s\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** Error thrown when a push conflict is detected with the \"reject\" strategy. */\nexport class ConflictError extends Error {\n constructor(public readonly conflict: ConflictInfo) {\n super(\"Push conflict: remote has new operations since last pull\");\n this.name = \"ConflictError\";\n }\n}\n\n/** Convert a remote operation to the local Operation type. */\nexport function remoteOperationToLocal(remote: RemoteOperation): Operation {\n return {\n id: remote.id ?? \"\",\n index: remote.index,\n skip: remote.skip,\n timestampUtcMs: remote.timestampUtcMs,\n hash: remote.hash,\n error: remote.error ?? undefined,\n deniedReason: remote.deniedReason ?? undefined,\n action: {\n id: remote.action.id,\n type: remote.action.type,\n timestampUtcMs: remote.action.timestampUtcMs,\n input: remote.action.input,\n scope: remote.action.scope,\n context: remote.action.context?.signer\n ? {\n signer: {\n user: remote.action.context.signer.user ?? {\n address: \"\",\n networkId: \"\",\n chainId: 0,\n },\n app: remote.action.context.signer.app ?? {\n name: \"\",\n key: \"\",\n },\n signatures: remote.action.context.signer.signatures.map((s) =>\n deserializeSignature(s),\n ),\n },\n }\n : undefined,\n },\n };\n}\n\n/**\n * Re-exported from shared, where it sits beside the serializer it has to agree\n * with. Kept exported here because this module's consumers import it from here.\n */\nexport { deserializeSignature };\n\n/** Convert remote operations to local DocumentOperations format. */\nexport function convertRemoteOperations(\n operationsByScope: Record<string, RemoteOperation[]>,\n): DocumentOperations {\n const operations: DocumentOperations = {};\n for (const [scope, remoteOps] of Object.entries(operationsByScope)) {\n operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));\n }\n return operations;\n}\n\n/**\n * Reconstruct a PHDocument from remote document data and operations; the\n * header carries the remote protocol versions. `initialDoc` supplies the rest\n * of the header, and the initial state when the operations do not record one.\n */\nexport function buildPulledDocument(\n remoteDoc: RemoteDocumentData,\n operations: DocumentOperations,\n initialDoc: PHDocument<PHBaseState>,\n branch: string,\n): PHDocument<PHBaseState> {\n return {\n header: {\n ...initialDoc.header,\n id: remoteDoc.id,\n name: remoteDoc.name,\n slug: remoteDoc.slug ?? \"\",\n documentType: remoteDoc.documentType,\n createdAtUtcIso:\n typeof remoteDoc.createdAtUtcIso === \"string\"\n ? remoteDoc.createdAtUtcIso\n : remoteDoc.createdAtUtcIso.toISOString(),\n lastModifiedAtUtcIso:\n typeof remoteDoc.lastModifiedAtUtcIso === \"string\"\n ? remoteDoc.lastModifiedAtUtcIso\n : remoteDoc.lastModifiedAtUtcIso.toISOString(),\n revision: Object.fromEntries(\n remoteDoc.revisionsList.map((r) => [r.scope, r.revision]),\n ),\n branch,\n // The creator chose these; the local reducer must run what the host runs.\n ...(remoteDoc.protocolVersions != null\n ? {\n protocolVersions: remoteDoc.protocolVersions as Record<\n string,\n number\n >,\n }\n : {}),\n },\n state: remoteDoc.state as PHBaseState,\n // Undo re-derives a scope from here, so it must be the state the creator recorded.\n initialState:\n creationState(operations.document ?? []) ?? initialDoc.initialState,\n operations,\n clipboard: [],\n };\n}\n\n/** `document` as created: its header and initial state, without scope operations. */\nexport function uncreatedDocument(\n document: PHDocument<PHBaseState>,\n): PHDocument<PHBaseState> {\n const { header, initialState } = structuredClone({\n header: document.header,\n initialState: document.initialState,\n });\n return {\n header,\n state: initialState,\n initialState,\n operations: {},\n clipboard: [],\n };\n}\n\n/** An uncreated `document` under `policy`; a legacy one keeps its id. */\nexport function underSignaturePolicy(\n document: PHDocument<PHBaseState>,\n policy: SignaturePolicy,\n): PHDocument<PHBaseState> {\n if (signaturePolicyOf(document.header) === policy) {\n return document;\n }\n return withSignaturePolicy(document, policy, { id: document.header.id });\n}\n\n/** Extract revision map from a remote document's revisionsList. */\nexport function extractRevisionMap(\n revisionsList: RemoteDocumentData[\"revisionsList\"],\n): Record<string, number> {\n return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n\n/**\n * Check if any scope in currentRevision is ahead of knownRevision.\n * When `scopes` is provided, only those scopes are checked.\n */\nexport function hasRevisionConflict(\n currentRevision: Record<string, number>,\n knownRevision: Record<string, number>,\n scopes?: ReadonlySet<string>,\n): boolean {\n for (const scope in currentRevision) {\n if (scopes && !scopes.has(scope)) continue;\n if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) {\n return true;\n }\n }\n return false;\n}\n","import type {\n DocumentOperations,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n PHDocumentMeta,\n} from \"document-model\";\nimport type { GetDocumentQuery } from \"../graphql/gen/schema.js\";\nimport type { RemoteOperation } from \"../remote-controller/types.js\";\nimport { remoteOperationToLocal } from \"../remote-controller/utils.js\";\n\n/** The `document` payload of a `GetDocument` query, once the null case is handled. */\nexport type GetDocumentQueryResult = NonNullable<GetDocumentQuery[\"document\"]>;\n\n/** The `PHDocumentFields` fragment as returned by `GetDocument`. */\nexport type GetDocumentQueryFields = GetDocumentQueryResult[\"document\"];\n\n/** The `revisionsList` selection of the `PHDocumentFields` fragment. */\nexport type RevisionsListSelection = GetDocumentQueryFields[\"revisionsList\"];\n\n/**\n * Converts a `GetDocument` result into a `PHDocument`.\n *\n * Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope\n * revision map, which the write path needs to compute the `prevOpIndex` of a\n * signed action. `sig` is filled with the empty shape used by\n * `createPresignedHeader`: the creation signature is not fetchable over\n * GraphQL and is not part of the operation signing payload.\n *\n * The read path never fetches operation history, so `operations` maps each\n * scope of the document's state and revisions to an empty array.\n *\n * `branch` is the branch the document was read from. The GraphQL type does not\n * carry it, so it has to be passed back in by the caller; it defaults to the\n * server's own default branch.\n */\nexport function phDocumentFromGetDocument<\n TDocument extends PHDocument = PHDocument,\n>(document: GetDocumentQueryFields, branch?: string): TDocument {\n const state = document.state as PHBaseState;\n const phDocument: PHDocument = {\n header: phDocumentHeaderFromGetDocument(document, branch),\n state,\n initialState: state,\n operations: emptyOperationsForScopes(state, document.revisionsList),\n clipboard: [],\n };\n return phDocument as TDocument;\n}\n\n/**\n * Converts a mutation result into a `PHDocument`, carrying the operations the\n * mutation produced.\n *\n * `dispatchActions` reads per-action failures out of `operations[scope]`, so\n * unlike the read path this one must not return empty operation lists.\n */\nexport function phDocumentFromMutation<\n TDocument extends PHDocument = PHDocument,\n>(\n document: GetDocumentQueryFields,\n operations: readonly RemoteOperation[],\n branch?: string,\n): TDocument {\n const phDocument = phDocumentFromGetDocument<TDocument>(document, branch);\n const operationsByScope: DocumentOperations = { ...phDocument.operations };\n\n for (const remote of operations) {\n const operation = remoteOperationToLocal(remote);\n const scope = operation.action.scope;\n const scopeOperations = operationsByScope[scope] ?? [];\n scopeOperations.push(operation);\n operationsByScope[scope] = scopeOperations;\n }\n\n phDocument.operations = operationsByScope;\n return phDocument;\n}\n\n/** Turns a `revisionsList` selection into the header's per-scope revision map. */\nexport function revisionMapFromRevisionsList(\n revisionsList: RevisionsListSelection,\n): Record<string, number> {\n return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n\n/** The branch the server reads and writes when none is asked for. */\nconst defaultBranch = \"main\";\n\nfunction phDocumentHeaderFromGetDocument(\n document: GetDocumentQueryFields,\n branch?: string,\n): PHDocumentHeader {\n return {\n id: document.id,\n sig: {\n publicKey: {},\n nonce: \"\",\n },\n documentType: document.documentType,\n createdAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),\n slug: document.slug ?? \"\",\n name: document.name,\n branch: branch ?? defaultBranch,\n revision: revisionMapFromRevisionsList(document.revisionsList),\n lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso),\n ...(document.meta != null ? { meta: document.meta as PHDocumentMeta } : {}),\n ...(document.protocolVersions != null\n ? {\n protocolVersions: document.protocolVersions as Record<string, number>,\n }\n : {}),\n };\n}\n\nfunction emptyOperationsForScopes(\n state: PHBaseState,\n revisionsList: RevisionsListSelection,\n): DocumentOperations {\n const scopes = new Set([\n ...Object.keys(state),\n ...revisionsList.map((r) => r.scope),\n ]);\n return Object.fromEntries([...scopes].map((scope) => [scope, []]));\n}\n\n/** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */\nexport function isoStringFromDateTime(value: string | Date): string {\n return value instanceof Date ? value.toISOString() : value;\n}\n","import type {\n DriveNodeKind,\n DriveNodePage,\n DriveNodeRecord,\n IDriveNodeSource,\n IDriveReadClient,\n PagedResults,\n PagingOptions,\n} from \"@powerhousedao/reactor\";\nimport type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n DriveNodeKind as GqlDriveNodeKind,\n type DriveNodeFieldsFragment,\n type Sdk,\n} from \"../graphql/gen/schema.js\";\n\n/** The node queries a {@link GraphQLDriveNodeSource} runs. */\nexport type DriveNodeQueries = Pick<\n Sdk,\n \"GetDriveNodes\" | \"GetDriveNode\" | \"GetDriveDescendants\"\n>;\n\n/** Page size {@link GraphQLDriveNodeSource.listAll} reads a drive in. */\nconst LIST_ALL_PAGE_LIMIT = 1000;\n\nconst DEFAULT_LIMIT = 100;\n\n/**\n * The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,\n * `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a\n * legacy drive and a reactor-drive alike. The Switchboard serves only the\n * nodes the caller may read. Drive ids must be canonical ids, not slugs.\n */\nexport class GraphQLDriveNodeSource implements IDriveNodeSource {\n constructor(\n private readonly queries: DriveNodeQueries,\n private readonly headersFor: (\n driveId: string,\n ) => Record<string, string> | undefined = () => undefined,\n ) {}\n\n async getNode(\n driveId: string,\n nodeId: string,\n signal?: AbortSignal,\n ): Promise<DriveNodeRecord | undefined> {\n const result = await this.queries.GetDriveNode(\n { driveId, id: nodeId },\n this.headersFor(driveId),\n signal,\n );\n return result.driveNode ? toRecord(result.driveNode) : undefined;\n }\n\n async listChildren(\n driveId: string,\n parentFolder: string | null | undefined,\n paging?: PagingOptions,\n signal?: AbortSignal,\n kind?: DriveNodeKind,\n ): Promise<DriveNodePage> {\n const cursor = startCursor(paging?.cursor);\n const result = await this.queries.GetDriveNodes(\n {\n driveId,\n ...(parentFolder === undefined ? {} : { parentFolder }),\n paging: paging ? { cursor, limit: paging.limit } : undefined,\n kind:\n kind === undefined\n ? undefined\n : kind === \"file\"\n ? GqlDriveNodeKind.File\n : GqlDriveNodeKind.Folder,\n },\n this.headersFor(driveId),\n signal,\n );\n const page = result.driveNodes;\n const nextCursor = page.hasMore\n ? (page.nextCursor ?? undefined)\n : undefined;\n return {\n results: page.results.map(toRecord),\n options: { cursor, limit: paging?.limit ?? DEFAULT_LIMIT },\n ...(nextCursor !== undefined ? { nextCursor } : {}),\n };\n }\n\n async getDescendants(\n driveId: string,\n root: string,\n signal?: AbortSignal,\n ): Promise<DriveNodeRecord[]> {\n const result = await this.queries.GetDriveDescendants(\n { driveId, root },\n this.headersFor(driveId),\n signal,\n );\n return result.driveDescendants.map(toRecord);\n }\n\n async listAll(\n driveId: string,\n signal?: AbortSignal,\n ): Promise<DriveNodeRecord[]> {\n const nodes: DriveNodeRecord[] = [];\n let cursor = \"\";\n for (;;) {\n const page = await this.listChildren(\n driveId,\n undefined,\n { cursor, limit: LIST_ALL_PAGE_LIMIT },\n signal,\n );\n nodes.push(...page.results);\n if (page.nextCursor === undefined || page.nextCursor === cursor) {\n return nodes;\n }\n cursor = page.nextCursor;\n }\n }\n}\n\n/**\n * `read.drives` over a node source: the reactor's {@link IDriveReadClient},\n * answering in the legacy `Node` shape for every drive type.\n */\nexport class GraphQLDriveReadClient implements IDriveReadClient {\n constructor(private readonly nodes: IDriveNodeSource) {}\n\n async getNode(\n driveIdentifier: string,\n nodeId: string,\n signal?: AbortSignal,\n ): Promise<Node> {\n const record = await this.nodes.getNode(driveIdentifier, nodeId, signal);\n if (!record) {\n throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);\n }\n return toLegacyNode(record);\n }\n\n async listNodes(\n driveIdentifier: string,\n parentFolder?: string | null,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Node>> {\n const page = await this.nodes.listChildren(\n driveIdentifier,\n parentFolder,\n paging,\n signal,\n );\n const nextCursor = page.nextCursor;\n return {\n results: page.results.map(toLegacyNode),\n options: page.options,\n ...(nextCursor !== undefined\n ? {\n nextCursor,\n next: () =>\n this.listNodes(\n driveIdentifier,\n parentFolder,\n { cursor: nextCursor, limit: page.options.limit },\n signal,\n ),\n }\n : {}),\n };\n }\n}\n\n/** A node record in the legacy `Node` shape. */\nexport function toLegacyNode(node: DriveNodeRecord): Node {\n if (node.kind === \"file\") {\n const file: FileNode = {\n id: node.id,\n kind: \"file\",\n name: node.name,\n parentFolder: node.parentFolder,\n documentType: node.documentType ?? \"\",\n };\n return file;\n }\n const folder: FolderNode = {\n id: node.id,\n kind: \"folder\",\n name: node.name,\n parentFolder: node.parentFolder,\n };\n return folder;\n}\n\nfunction toRecord(node: DriveNodeFieldsFragment): DriveNodeRecord {\n const base = {\n id: node.id,\n driveId: node.driveId,\n name: node.name,\n parentFolder: node.parentFolder ?? null,\n };\n return \"documentType\" in node\n ? { ...base, kind: \"file\", documentType: node.documentType }\n : { ...base, kind: \"folder\" };\n}\n\n/** The offset-style \"0\" other listings start from means the first page here too. */\nfunction startCursor(cursor: string | undefined): string {\n return cursor === undefined || cursor === \"0\" ? \"\" : cursor;\n}\n","/** The `fetch` a client's HTTP requests go through. */\nexport type GraphQLFetch = typeof globalThis.fetch;\n\n/** The global `fetch`, read per call so a later replacement is honoured. */\nexport const globalFetch: GraphQLFetch = (input, init) =>\n globalThis.fetch(input, init);\n\n/**\n * Whether `fetch` here is Node's (undici), which resends a request answered\n * 421 and can fail the resend of a buffered body. A page, Electron's renderer\n * included, has a `document`.\n */\nexport function isNodeFetch(): boolean {\n const scope = globalThis as {\n process?: { versions?: { node?: unknown } };\n document?: unknown;\n };\n return (\n typeof scope.process?.versions?.node === \"string\" &&\n scope.document === undefined\n );\n}\n\n/**\n * Sends a string body as a stream, which fetch never resends, so a 421 comes\n * back as itself. Browsers keep buffered bodies: Chrome streams an upload only\n * over HTTP/2.\n */\nexport function withStreamedBodies(\n inner: GraphQLFetch = globalFetch,\n): GraphQLFetch {\n return (input, init) => {\n const body = init?.body;\n if (typeof body !== \"string\") {\n return inner(input, init);\n }\n // Not `new Blob([body]).stream()`: under Node 24 a Blob's stream keeps the\n // caller's async context alive for good.\n const bytes = new TextEncoder().encode(body);\n return inner(input, {\n ...init,\n body: new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes);\n controller.close();\n },\n }),\n duplex: \"half\",\n } as RequestInit);\n };\n}\n\nconst streamedGlobalFetch = withStreamedBodies(globalFetch);\n\n/** A Switchboard backend's default transport: streamed bodies under Node only. */\nexport const switchboardFetch: GraphQLFetch = (input, init) =>\n isNodeFetch() ? streamedGlobalFetch(input, init) : globalFetch(input, init);\n\n/** Bounds each request, headers through body; rejects with a `TimeoutError`. */\nexport function withRequestDeadline(\n timeoutMs: number,\n inner: GraphQLFetch = globalFetch,\n): GraphQLFetch {\n return (input, init) => {\n const deadline = AbortSignal.timeout(timeoutMs);\n const signal = init?.signal\n ? AbortSignal.any([init.signal, deadline])\n : deadline;\n return inner(input, { ...init, signal });\n };\n}\n\n/**\n * Whether a request failed at a deadline rather than by its caller's abort:\n * this transport's own (`TimeoutError`, a DOMException) or the router's probe\n * deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).\n */\nexport function isDeadlineError(error: unknown): boolean {\n const name = (error as { name?: unknown } | null)?.name;\n return name === \"TimeoutError\" || name === \"ProbeTimeoutError\";\n}\n","import type {\n CreateProtocolVersionsOptions,\n DocumentModelModule,\n ProtocolVersions,\n SignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n capSelection,\n fitCreateBaseReducer,\n FLAGS_FOR_EVERY_VERSION,\n isSignaturePolicy,\n localSupports,\n PEER_CAPABILITIES,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport type { GetCreateDefaultsQuery } from \"../graphql/gen/schema.js\";\nimport type { ReactorGraphQLClient } from \"../graphql/types.js\";\nimport {\n GraphQLOperationNotSupportedError,\n queriesUnknownArgument,\n queriesUnknownField,\n} from \"./errors.js\";\n\n/** The queries a light client reads a new document's defaults with. */\nexport type CreateDefaultsSdk = Pick<\n ReactorGraphQLClient,\n \"GetCreateDefaults\" | \"GetCreateProtocolVersions\"\n>;\n\n/** The host's policy for a new document; a host without `createDefaults` is refused, as a guess could under-sign. */\nexport async function readCreateSignaturePolicy(\n sdk: CreateDefaultsSdk,\n signal?: AbortSignal,\n): Promise<SignaturePolicy> {\n const defaults = await readCreateDefaults(sdk, undefined, signal);\n if (defaults === undefined) {\n throw new GraphQLOperationNotSupportedError(\n \"getCreateSignaturePolicy\",\n \"the Switchboard predates the createDefaults query\",\n );\n }\n const { signaturePolicy } = defaults;\n if (!isSignaturePolicy(signaturePolicy)) {\n throw new Error(\n `The Switchboard answered an unknown create signature policy: ${signaturePolicy}`,\n );\n }\n return signaturePolicy;\n}\n\n/** The host's per-type selection, capped at what this build runs and fitted to `modules`; baseline from an old host. */\nexport async function readCreateProtocolVersions(\n sdk: CreateDefaultsSdk,\n { documentType, parentIdentifier }: CreateProtocolVersionsOptions,\n modules: readonly DocumentModelModule[],\n signal?: AbortSignal,\n): Promise<ProtocolVersions> {\n const host = await hostCreateProtocolVersions(\n sdk,\n documentType,\n parentIdentifier,\n signal,\n );\n const selected = capSelection(\n host,\n PEER_CAPABILITIES,\n localSupports(PEER_CAPABILITIES, FLAGS_FOR_EVERY_VERSION),\n );\n return fitCreateBaseReducer(selected, documentType, modules, logger);\n}\n\n/** The Switchboard's selection; undefined from a host without `createDefaults`. */\nasync function hostCreateProtocolVersions(\n sdk: CreateDefaultsSdk,\n documentType: string | undefined,\n parentIdentifier: string | undefined,\n signal: AbortSignal | undefined,\n): Promise<ProtocolVersions | undefined> {\n if (documentType !== undefined) {\n try {\n const result = await sdk.GetCreateProtocolVersions(\n { documentType, parentIdOrSlug: parentIdentifier },\n undefined,\n signal,\n );\n return protocolVersionsFrom(result.createDefaults.protocolVersions);\n } catch (error) {\n if (queriesUnknownField(error, \"createDefaults\")) return undefined;\n if (!queriesUnknownArgument(error, \"documentType\")) throw error;\n }\n }\n const defaults = await readCreateDefaults(sdk, parentIdentifier, signal);\n return defaults && protocolVersionsFrom(defaults.protocolVersions);\n}\n\n/** The reactor-wide `createDefaults`; undefined from a host without the query. */\nasync function readCreateDefaults(\n sdk: CreateDefaultsSdk,\n parentIdentifier: string | undefined,\n signal: AbortSignal | undefined,\n): Promise<GetCreateDefaultsQuery[\"createDefaults\"] | undefined> {\n try {\n const result = await sdk.GetCreateDefaults(\n { parentIdOrSlug: parentIdentifier },\n undefined,\n signal,\n );\n return result.createDefaults;\n } catch (error) {\n if (queriesUnknownField(error, \"createDefaults\")) {\n return undefined;\n }\n throw error;\n }\n}\n\nfunction protocolVersionsFrom(value: unknown): ProtocolVersions {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\n \"The Switchboard answered malformed create protocol versions\",\n );\n }\n const versions: ProtocolVersions = {};\n for (const [protocol, version] of Object.entries(value)) {\n if (typeof version !== \"number\" || !Number.isInteger(version)) {\n throw new Error(\n `The Switchboard answered a malformed version for protocol ${protocol}`,\n );\n }\n versions[protocol] = version;\n }\n return versions;\n}\n","import { gql } from \"graphql-tag\";\nimport {\n PhDocumentFieldsFragmentDoc,\n type ActionInput,\n type PhDocumentFieldsFragment,\n type Scalars,\n type ViewFilterInput,\n} from \"../graphql/gen/schema.js\";\nimport type { RemoteOperation } from \"../remote-controller/types.js\";\n\n/**\n * The operation selection of `GetDocumentOperations`, lifted into a fragment so\n * the write path can reuse `remoteOperationToLocal` on the items it selects.\n */\nexport const ReactorOperationFieldsFragmentDoc = gql`\n fragment ReactorOperationFields on ReactorOperation {\n index\n timestampUtcMs\n hash\n skip\n error\n deniedReason\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n`;\n\n/**\n * `mutateDocument` plus the operations the mutation produced.\n *\n * The generated `MutateDocument` only selects the document fields, but\n * `dispatchActions` reads per-action failures out of `result.operations[scope]`\n * (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.\n *\n * The operations filter keeps the extra selection to the operations this call\n * could have appended rather than the whole history. All three of its fields\n * matter:\n * - `sinceRevision` is the lowest head revision across the targeted scopes, so\n * it is only a safe window when the selection is scope-limited as well;\n * - `scopes` limits the response to the scopes the pushed actions target,\n * without it the server walks every scope of the document\n * (`packages/reactor/src/core/reactor.ts` `getOperations`);\n * - `branch` selects the branch the operations are read from, and is the same\n * variable the mutation writes to. It used to be two - the write went through\n * a `view`, the filter took its own `branch` - and they had to be kept equal\n * by hand or the operations came from `main` while the actions were applied\n * elsewhere. One variable cannot disagree with itself.\n */\nexport const MutateDocumentWithOperationsDocument = gql`\n mutation MutateDocumentWithOperations(\n $documentIdOrSlug: String!\n $actions: [ActionInput!]!\n $sinceRevision: Int\n $scopes: [String!]\n $branch: String\n ) {\n mutateDocument: execute(\n documentIdOrSlug: $documentIdOrSlug\n actions: $actions\n branch: $branch\n ) {\n ...PHDocumentFields\n operations(\n filter: {\n sinceRevision: $sinceRevision\n scopes: $scopes\n branch: $branch\n }\n ) {\n items {\n ...ReactorOperationFields\n }\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n ${ReactorOperationFieldsFragmentDoc}\n`;\n\nexport type MutateDocumentWithOperationsVariables = {\n documentIdOrSlug: Scalars[\"String\"][\"input\"];\n actions: ReadonlyArray<ActionInput>;\n sinceRevision?: Scalars[\"Int\"][\"input\"];\n scopes?: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutateDocumentWithOperationsResult = {\n readonly mutateDocument: PhDocumentFieldsFragment & {\n readonly operations?: {\n readonly items: ReadonlyArray<RemoteOperation>;\n } | null;\n };\n};\n\n/**\n * `document`, bounded by a consistency token: the read waits until the\n * Switchboard's read models hold every operation the token names. The\n * `consistency` argument is additive on the Switchboard; one without it refuses\n * this document, and the client falls back to the plain `GetDocument`.\n */\nexport const GetDocumentAtConsistencyDocument = gql`\n query GetDocumentAtConsistency(\n $idOrSlug: String!\n $view: ViewFilterInput\n $consistency: ConsistencyTokenInput\n ) {\n document(idOrSlug: $idOrSlug, view: $view, consistency: $consistency) {\n document {\n ...PHDocumentFields\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\n\nexport type GetDocumentAtConsistencyVariables = {\n idOrSlug: Scalars[\"String\"][\"input\"];\n view?: ViewFilterInput;\n consistency: {\n version: number;\n createdAtUtcIso: string;\n coordinates: ReadonlyArray<{\n documentId: string;\n scope: string;\n branch: string;\n operationIndex: number;\n }>;\n };\n};\n\nexport type GetDocumentAtConsistencyResult = {\n readonly document?: {\n readonly document: PhDocumentFieldsFragment;\n readonly childIds: ReadonlyArray<string>;\n } | null;\n};\n","import type {\n Action,\n ActionSigningTarget,\n DocumentModelModule,\n ISigner,\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n actionSignerIdentity,\n actionSigningTarget,\n resolveBaseReducerVersion,\n hashDocumentStateForScope,\n} from \"@powerhousedao/shared/document-model\";\n\n/**\n * Stamps an action with the head of the scope it targets.\n *\n * `prevOpHash` is the hash of the scope state the action is meant to apply to;\n * for a document at head that is the hash of the last operation in the scope,\n * which the read path cannot fetch, so it is recomputed from the state.\n * `prevOpIndex` is the index of that last operation: revisions count\n * operations and indices are zero based, so an empty scope stamps `-1`, which\n * matches what the remote controller records.\n *\n * `revision` overrides the scope revision the index is derived from. Only a\n * batch needs it - {@link prepareSignedActions} stamps action N at the revision\n * the N actions before it will have produced, which the document itself does\n * not know yet. `prevOpHash` always comes from the supplied document's state.\n */\nexport function stampAction(\n action: Action,\n document: PHDocument,\n revision = document.header.revision[action.scope] ?? 0,\n): Action {\n return {\n ...action,\n context: {\n ...action.context,\n prevOpHash: hashDocumentStateForScope(document, action.scope),\n prevOpIndex: revision - 1,\n },\n };\n}\n\n/**\n * Signs a stamped action for `target`, keeping any signatures it already\n * carries. The signer reads `context.prevOpHash`, so this runs after\n * {@link stampAction}. A v2 tuple covers the signer's identity, so the context\n * takes the signer's user and app even when the action named others.\n */\nexport async function signStampedAction(\n action: Action,\n signer: ISigner,\n target: ActionSigningTarget,\n signal?: AbortSignal,\n): Promise<Action> {\n if (!signer.user || !signer.app) {\n throw new Error(\n \"cannot sign an action: the signer has no user or app identity\",\n );\n }\n\n const signature = await signer.signAction(action, target, signal);\n return {\n ...action,\n context: {\n ...action.context,\n signer: {\n ...actionSignerIdentity(signer),\n signatures: [...(action.context?.signer?.signatures ?? []), signature],\n },\n },\n };\n}\n\n/** The log a snapshot's action is written to; the snapshot names the branch read. */\nfunction snapshotTarget(\n action: Action,\n snapshot: PHDocument,\n): ActionSigningTarget {\n return actionSigningTarget(\n action,\n snapshot.header.id,\n snapshot.header.branch || \"main\",\n );\n}\n\n/**\n * Actions a snapshot batch cannot predict the next state for.\n *\n * `UNDO` and `REDO` rewrite history the light read path never fetched (and\n * the reducer appends no operation for them); `NOOP` is only ever produced\n * by an undo chain; a `RETRACT` names a target in that unfetched history; the\n * document-scope actions run through the reactor's\n * document-action handler rather than a document-model reducer\n * (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and\n * `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.\n */\nconst unsupportedBatchActions: ReadonlySet<string> = new Set([\n \"UNDO\",\n \"REDO\",\n \"NOOP\",\n \"RETRACT\",\n \"CREATE_DOCUMENT\",\n \"DELETE_DOCUMENT\",\n \"UPGRADE_DOCUMENT\",\n \"ADD_RELATIONSHIP\",\n \"REMOVE_RELATIONSHIP\",\n \"UPDATE_RELATIONSHIP\",\n]);\n\n/**\n * The base-reducer protocol version to predict with when the snapshot's header\n * carries none.\n *\n * `baseReducer` reads `baseReducerVersion(document.header)` for every action and\n * throws when the header has no `protocolVersions`, which a header built by\n * {@link phDocumentFromGetDocument} lacks when the server sends none. The\n * version only selects how UNDO, REDO and RETRACT apply, and every action\n * reaching the prediction loop is an\n * ordinary append-only one, so it cannot change the predicted state here; it is\n * passed purely so the lookup does not throw.\n */\nconst predictionProtocolVersion = 2;\n\n/**\n * Stamps and signs a batch of actions against one document snapshot, so every\n * action carries the head its predecessor will leave behind.\n *\n * The server executes the array in order, each action against the state the one\n * before it produced. The snapshot the light client reads has correct state and\n * per-scope revisions but NO operation history (see `adapter.ts`), so the chain\n * is predicted here: reduce action N over the working document to get the state\n * action N+1 hashes, and carry a virtual revision alongside it. The revision has\n * to be tracked separately because the reducer derives operation indices from\n * the last stored operation, and with an empty history that counts from zero\n * rather than from the document's real revision.\n *\n * A single action needs no prediction and therefore no `module`, which keeps\n * today's callers working unchanged. Two or more require the document's exact\n * reducer, one shared scope (the reactor rejects mixed-scope jobs) and only\n * append-only actions. Anything else rejects: a batch that cannot be predicted\n * must fail before the mutation, never be downgraded to unsigned.\n */\nexport async function prepareSignedActions(\n actions: readonly Action[],\n snapshot: PHDocument,\n signer: ISigner,\n module?: DocumentModelModule<any>,\n signal?: AbortSignal,\n): Promise<Action[]> {\n if (actions.length === 0) {\n return [];\n }\n\n if (actions.length === 1) {\n return [\n await signStampedAction(\n stampAction(actions[0], snapshot),\n signer,\n snapshotTarget(actions[0], snapshot),\n signal,\n ),\n ];\n }\n\n const scope = sharedScope(actions);\n assertSupportedBatch(actions);\n\n if (!module) {\n throw new Error(\n `cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`,\n );\n }\n\n // A working copy: the reducer never writes to its input, but the scope's\n // operation list is read back below, so it must exist even for a scope the\n // snapshot's `revisionsList` did not mention.\n let working: PHDocument = {\n ...snapshot,\n operations: {\n ...snapshot.operations,\n [scope]: [...(snapshot.operations[scope] ?? [])],\n },\n };\n let revision = snapshot.header.revision[scope] ?? 0;\n\n const signed: Action[] = [];\n for (const [index, action] of actions.entries()) {\n throwIfAborted(signal, index);\n\n const stamped = stampAction(action, working, revision);\n const signedAction = await signStampedAction(\n stamped,\n signer,\n snapshotTarget(stamped, snapshot),\n signal,\n );\n signed.push(signedAction);\n\n // The last action's state is never hashed by anything, but reducing it\n // anyway is what proves the whole batch is applicable before it is sent.\n const before = scopeOperationCount(working, scope);\n let next: PHDocument;\n try {\n next = module.reducer(working, signedAction, undefined, {\n protocolVersion:\n resolveBaseReducerVersion(working.header.protocolVersions) ??\n predictionProtocolVersion,\n });\n } catch (error) {\n throw new Error(\n `cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`,\n { cause: error },\n );\n }\n\n const after = scopeOperationCount(next, scope);\n if (after !== before + 1) {\n throw new Error(\n `cannot sign action ${index} (${action.type}): the reducer appended ${after - before} operations to ${scope}, expected exactly 1`,\n );\n }\n\n working = next;\n // Deliberately not `next.operations[scope].at(-1).index`: those indices\n // count from the snapshot's empty history, not from the document's head.\n revision += 1;\n }\n\n return signed;\n}\n\n/**\n * How many operations a scope holds.\n *\n * The index signature types the array as always present, but a module's reducer\n * is arbitrary code: one that hands back a document without the scope should\n * produce the actionable error above, not a `TypeError` on `.length`.\n */\nfunction scopeOperationCount(document: PHDocument, scope: string): number {\n const operations: Record<string, Operation[] | undefined> =\n document.operations;\n return operations[scope]?.length ?? 0;\n}\n\n/** The one scope a reactor job may span (`getSharedActionScope`). */\nfunction sharedScope(actions: readonly Action[]): string {\n const scope = actions[0].scope;\n const mixed = actions.find((action) => action.scope !== scope);\n if (mixed) {\n throw new Error(\n `cannot sign a batch spanning scopes \"${scope}\" and \"${mixed.scope}\": every action in one request must share a scope`,\n );\n }\n return scope;\n}\n\nfunction assertSupportedBatch(actions: readonly Action[]): void {\n const unsupported = actions.find((action) =>\n unsupportedBatchActions.has(action.type),\n );\n if (unsupported) {\n throw new Error(\n `cannot sign a batch containing ${unsupported.type}: it needs operation history or an alternate executor path, so send it as a single action`,\n );\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, index: number): void {\n if (signal?.aborted) {\n throw new Error(`signing aborted before action ${index}`, {\n cause: signal.reason as unknown,\n });\n }\n}\n","import type { DocumentModelSource } from \"@powerhousedao/reactor\";\nimport type { RegistryPackageSource } from \"@powerhousedao/shared\";\nimport type { DocumentModelLib, DocumentModelModule } from \"document-model\";\nimport type {\n IPackageManager,\n IPackageListerUnsubscribe,\n IPackagesListener,\n PackageManagerInstallResult,\n} from \"../types/vetra.js\";\n\n/**\n * A fixed set of packages presented through the `IPackageManager` interface,\n * so the package-derived hooks - `useDocumentModelModules`,\n * `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work\n * below `GraphQLReactorProvider` exactly as they do below Connect.\n *\n * Connect's package manager installs, updates and removes packages at runtime.\n * A light app instead declares its packages once, as code it imports itself\n * (every generated package root exports `manifest`, `documentModels`, `editors`\n * and `upgradeManifests` by name), so every mutating member throws and\n * `subscribe` never emits. For hand-picked modules without package artifacts,\n * {@link packageFromDocumentModels} wraps them in one synthetic package.\n */\nexport class StaticPackageManager implements IPackageManager {\n readonly registryUrl = null;\n readonly packages: DocumentModelLib[];\n\n // DocumentModelLib<any>: a real package's concrete modules are invariant in\n // their state generic, so the boundary needs the same escape the reactor\n // core uses for DocumentModelSource (packages/reactor/src/core/model-sources.ts).\n constructor(packages: readonly DocumentModelLib<any>[]) {\n this.packages = [...packages];\n }\n\n /**\n * Resolves a module by document type across all packages. Mirrors the\n * registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST\n * version wins, with `version ?? 1` as each module's default.\n */\n load(documentType: string): Promise<DocumentModelSource> {\n const modules = this.packages.flatMap((pkg) => pkg.documentModels);\n try {\n return Promise.resolve(resolveDocumentModelModule(modules, documentType));\n } catch (error) {\n return Promise.reject(error as Error);\n }\n }\n\n subscribe(_handler: IPackagesListener): IPackageListerUnsubscribe {\n return () => {};\n }\n\n getPackageSource(_packageName: string): RegistryPackageSource | null {\n return null;\n }\n\n getPackageVersion(_packageName: string): string | undefined {\n return undefined;\n }\n\n getPackageSpec(_packageName: string): string | undefined {\n return undefined;\n }\n\n getRegistryPackages(): { name: string; version: string | undefined }[] {\n return [];\n }\n\n addPackage(_packageName: string): PackageManagerInstallResult {\n throw staticPackageManagerError(\"addPackage\");\n }\n\n addPackages(_packageNames: string[]): PackageManagerInstallResult[] {\n throw staticPackageManagerError(\"addPackages\");\n }\n\n removePackage(_name: string): void {\n throw staticPackageManagerError(\"removePackage\");\n }\n\n updateLocalPackage(_pkg: DocumentModelLib, _version?: string): void {\n throw staticPackageManagerError(\"updateLocalPackage\");\n }\n\n addLocalPackage(\n _name: string,\n _loadedPackage: DocumentModelLib,\n _version?: string,\n ): void {\n throw staticPackageManagerError(\"addLocalPackage\");\n }\n}\n\n/**\n * Resolves one document-model module out of a flat module list, with the same\n * rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at\n * packages/reactor/src/registry/implementation.ts): with a `version`, only an\n * EXACT `version ?? 1` match resolves; without one, the LATEST version wins.\n *\n * Signing an existing document needs the exact rule. A document carries the\n * model version it was written with in `state.document.version`, and its\n * reducer is the only one whose operations that document's history can accept -\n * so \"latest\" is correct only when no version is asked for.\n *\n * Pure and dependency-free on purpose: this is reachable from the browser\n * entry, so it must not pull the reactor registry in as a value.\n */\nexport function resolveDocumentModelModule(\n modules: readonly DocumentModelModule<any>[],\n documentType: string,\n version?: number,\n): DocumentModelModule<any> {\n let latestModule: DocumentModelModule<any> | undefined;\n let latestVersion = -1;\n\n for (const module of modules) {\n if (module.documentModel.global.id !== documentType) {\n continue;\n }\n const moduleVersion = module.version ?? 1;\n if (version !== undefined && moduleVersion === version) {\n return module;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n\n if (version === undefined && latestModule) {\n return latestModule;\n }\n\n throw new Error(\n version === undefined\n ? `Unknown document type: ${documentType}`\n : `Unknown document model version: ${documentType} v${version}` +\n (latestModule\n ? ` (available: ${availableVersions(modules, documentType).join(\", \")})`\n : \" (no module for this document type)\"),\n );\n}\n\nfunction availableVersions(\n modules: readonly DocumentModelModule<any>[],\n documentType: string,\n): number[] {\n return modules\n .filter((module) => module.documentModel.global.id === documentType)\n .map((module) => module.version ?? 1)\n .sort((a, b) => a - b);\n}\n\nfunction staticPackageManagerError(member: string): Error {\n return new Error(\n `${member} is not supported: StaticPackageManager holds a fixed set of packages`,\n );\n}\n\n/**\n * Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that\n * assemble their model list from mixed sources instead of passing whole\n * packages. The manifest is fabricated - loose modules carry none - so prefer\n * the `packages` prop with the real package exports when you have them: a real\n * package also carries `editors`, which makes the editor hooks work.\n */\nexport function packageFromDocumentModels(\n documentModels: readonly DocumentModelModule<any>[],\n): DocumentModelLib {\n return {\n manifest: {\n name: \"graphql-reactor-provider\",\n description: \"Document models passed to GraphQLReactorProvider\",\n },\n documentModels,\n editors: [],\n };\n}\n","import type {\n Action,\n AddRelationshipActionInput,\n RemoveRelationshipActionInput,\n} from \"@powerhousedao/shared/document-model\";\nimport { generateActionId } from \"@powerhousedao/shared/document-model\";\n\n/**\n * The document-scope actions the reactor reduces itself, built here as\n * `packages/reactor/src/actions/index.ts` builds them, so the light client\n * signs and pushes them without importing the reactor as a value.\n *\n * Each names its source by id: the signature covers the log the action is\n * written to, which for a relationship is `sourceId`, and the executor writes\n * both ids as given.\n */\n\n/** An ADD_RELATIONSHIP edge from `sourceId` to `targetId`. */\nexport function addRelationshipAction(\n sourceId: string,\n targetId: string,\n relationshipType: string,\n metadata?: Record<string, unknown>,\n): Action {\n const input: AddRelationshipActionInput = {\n sourceId,\n targetId,\n relationshipType,\n ...(metadata !== undefined ? { metadata } : {}),\n };\n\n return {\n id: generateActionId(),\n type: \"ADD_RELATIONSHIP\",\n scope: \"document\",\n timestampUtcMs: new Date().toISOString(),\n input,\n };\n}\n\n/** A REMOVE_RELATIONSHIP of the edge from `sourceId` to `targetId`. */\nexport function removeRelationshipAction(\n sourceId: string,\n targetId: string,\n relationshipType: string,\n): Action {\n const input: RemoveRelationshipActionInput = {\n sourceId,\n targetId,\n relationshipType,\n };\n\n return {\n id: generateActionId(),\n type: \"REMOVE_RELATIONSHIP\",\n scope: \"document\",\n timestampUtcMs: new Date().toISOString(),\n input,\n };\n}\n","import { Kind, type DocumentNode } from \"graphql\";\nimport { GraphQLClient } from \"graphql-request\";\nimport type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\nimport type { GraphQLFetch } from \"./transport.js\";\n\n/**\n * The factory a GraphQL code generator produces for a schema.\n *\n * It is the signature of `getSdk` emitted by the `typescript-graphql-request`\n * plugin - the generated `getSdk` in `src/graphql/gen/schema.ts` is the\n * canonical example - so a project can hand its own generated function straight\n * to {@link SubgraphSdkRegistry.get} and keep every operation typed.\n */\nexport type SubgraphSdkFactory<TSdk> = (\n client: GraphQLClient,\n withWrapper?: SdkFunctionWrapper,\n) => TSdk;\n\n/**\n * The middleware a subgraph SDK is bound with. Re-exported here because a\n * hand-written SDK has to name it, while a generated one declares its own.\n */\nexport type { SdkFunctionWrapper };\n\n/**\n * A GraphQL document that carries its result and variable types.\n *\n * This is the shape a code generator gives a document (`TypedDocumentNode`),\n * declared structurally so that reactor-browser needs no dependency on\n * `@graphql-typed-document-node/core`. A plain `DocumentNode` satisfies it too,\n * with the result type falling back to whatever the caller passes explicitly.\n */\nexport type TypedGraphQLDocument<TResult, TVariables> = DocumentNode & {\n __apiType?: (variables: TVariables) => TResult;\n};\n\n/** Extras for a one-off request. */\nexport type GraphQLRequestOptions = {\n /**\n * The operation name reported to the auth and logging middleware. Read off\n * the document when it is not given.\n */\n operationName?: string;\n\n /**\n * The operation type reported to the middleware, e.g. `\"mutation\"`. Read off\n * the document when it is not given.\n */\n operationType?: string;\n\n signal?: AbortSignal;\n};\n\n/** What {@link describeGraphQLDocument} could not read off a document. */\nconst unnamedOperation = \"AnonymousOperation\";\nconst defaultOperationType = \"query\";\n\n/**\n * Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.\n *\n * Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so\n * `http://localhost:4001/graphql` plus `statements` is\n * `http://localhost:4001/graphql/statements`.\n */\nexport function subgraphUrlFromGraphqlUrl(url: string, name: string): string {\n const trimmed = name.trim();\n if (trimmed === \"\") {\n throw new Error(\"a subgraph name is required\");\n }\n return `${url.replace(/\\/+$/, \"\")}/${trimmed}`;\n}\n\n/**\n * Reads the operation name and type off a document, for the middleware.\n *\n * Nothing depends on getting this right - it is reported to the middleware, not\n * sent to the server - so an unreadable document falls back to an anonymous\n * query rather than throwing.\n */\nexport function describeGraphQLDocument(document: string | DocumentNode): {\n operationName: string;\n operationType: string;\n} {\n if (typeof document !== \"string\") {\n const operation = document.definitions.find(\n (definition) => definition.kind === Kind.OPERATION_DEFINITION,\n );\n if (!operation || operation.kind !== Kind.OPERATION_DEFINITION) {\n return {\n operationName: unnamedOperation,\n operationType: defaultOperationType,\n };\n }\n return {\n operationName: operation.name?.value ?? unnamedOperation,\n operationType: operation.operation,\n };\n }\n\n const match =\n /\\b(query|mutation|subscription)\\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);\n if (!match) {\n return {\n operationName: unnamedOperation,\n operationType: /\\bmutation\\b/.test(document)\n ? \"mutation\"\n : defaultOperationType,\n };\n }\n return { operationName: match[2], operationType: match[1] };\n}\n\n/** A subgraph transport and the SDK last bound to it. */\ntype SubgraphBinding = {\n transport: GraphQLClient;\n factory?: SubgraphSdkFactory<unknown>;\n sdk?: unknown;\n};\n\n/**\n * Binds typed subgraph SDKs to one Switchboard's transport and auth.\n *\n * Every capability a Switchboard exposes lives behind the same base URL, so an\n * app should not have to build a second client - with a second copy of the auth\n * configuration - to reach a project's own subgraph. The registry derives the\n * endpoint, reuses one transport per subgraph and hands the code generator's\n * `getSdk` the very middleware the reactor operations already go through.\n *\n * Transport and typing only: subgraph results are not cached and produce no\n * change events.\n */\nexport class SubgraphSdkRegistry {\n private readonly url: string;\n private readonly middleware: SdkFunctionWrapper | undefined;\n private readonly fetch: GraphQLFetch | undefined;\n private readonly bindings = new Map<string, SubgraphBinding>();\n\n constructor(\n url: string,\n middleware?: SdkFunctionWrapper,\n fetch?: GraphQLFetch,\n ) {\n this.url = url;\n this.middleware = middleware;\n this.fetch = fetch;\n }\n\n /**\n * Returns the subgraph's SDK, building it on first use.\n *\n * The transport is kept per subgraph name, so repeated calls do not rebuild\n * it. The SDK itself is only reused when the same factory is passed again -\n * two different generated SDKs over one subgraph each get their own, rather\n * than the second call being handed the first one's methods.\n */\n get<TSdk>(name: string, getSdk: SubgraphSdkFactory<TSdk>): TSdk {\n const binding = this.binding(name);\n if (binding.factory === getSdk) {\n return binding.sdk as TSdk;\n }\n\n const sdk = getSdk(binding.transport, this.middleware);\n binding.factory = getSdk as SubgraphSdkFactory<unknown>;\n binding.sdk = sdk;\n return sdk;\n }\n\n /** Returns the subgraph's endpoint, for diagnostics and tests. */\n urlFor(name: string): string {\n return subgraphUrlFromGraphqlUrl(this.url, name);\n }\n\n private binding(name: string): SubgraphBinding {\n const existing = this.bindings.get(name);\n if (existing) {\n return existing;\n }\n\n const binding: SubgraphBinding = {\n transport: new GraphQLClient(this.urlFor(name), { fetch: this.fetch }),\n };\n this.bindings.set(name, binding);\n return binding;\n }\n}\n","import { print } from \"graphql\";\nimport { createClient } from \"graphql-ws/client\";\nimport {\n DocumentChangesDocument,\n JobChangesDocument,\n type DocumentChangesSubscription,\n type JobChangesSubscription,\n} from \"../graphql/gen/schema.js\";\nimport type { BearerTokenProvider } from \"./auth.js\";\n\n/** The `documentChanges` payload, exactly as the Switchboard sends it. */\nexport type DocumentChangesEventPayload =\n DocumentChangesSubscription[\"documentChanges\"];\n\n/** The connection payload sent with the `ConnectionInit` message. */\nexport type ConnectionParams = Record<string, string>;\n\nexport type DocumentChangesSubscriptionOptions = {\n /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */\n wsUrl: string;\n\n /**\n * Resolves the `ConnectionInit` payload. Called again on every reconnect, so\n * a token that expired while the socket was down is refreshed on the way back\n * up.\n */\n connectionParams?: () => Promise<ConnectionParams>;\n\n /** Called once per server event. */\n onEvent: (event: DocumentChangesEventPayload) => void;\n\n /**\n * Called when the socket gives up: the retries built into `graphql-ws` are\n * exhausted, or the server rejected the subscription. Realtime is an\n * enhancement, so callers are expected to log and carry on.\n */\n onError: (error: unknown) => void;\n};\n\n/**\n * The 4403 close reasons a Switchboard refuses a handshake with.\n *\n * Mirrors `WS_AUTH_CLOSE_REASONS` in `@powerhousedao/reactor-api`\n * (`src/graphql/gateway/types.ts`). This package does not depend on that one,\n * so the strings are duplicated and are a wire contract: change them on both\n * sides or not at all.\n */\nconst authCloseReasons: readonly string[] = [\n \"authentication-required\",\n \"bearer-rejected\",\n];\n\n/** graphql-ws's own `isLikeCloseEvent`, which it does not export. */\nfunction isLikeCloseEvent(\n value: unknown,\n): value is { code: number; reason: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"code\" in value &&\n \"reason\" in value\n );\n}\n\n/**\n * Whether a socket failure is the Switchboard refusing the credentials sent.\n *\n * Keyed on the close reason, not the code: both refusals close 4403, because\n * `connectionParams` is resolved per connect and a reconnect carrying a fresh\n * token genuinely succeeds. What the reason adds is that *this* attempt cannot\n * be fixed by repeating it.\n */\nexport function isAuthRefusalClose(error: unknown): boolean {\n return isLikeCloseEvent(error) && authCloseReasons.includes(error.reason);\n}\n\n/**\n * Opens one `documentChanges` subscription and feeds every event to `onEvent`.\n *\n * The subscription is a firehose: no `search` argument, so the server sends\n * every change the connection is allowed to see and the caller filters. This is\n * the only module that knows about `graphql-ws`.\n *\n * Returns the stop function, which cancels the subscription and closes the\n * socket. It is safe to call more than once.\n */\nexport function startDocumentChangesSubscription(\n options: DocumentChangesSubscriptionOptions,\n): () => void {\n const client = createClient({\n url: options.wsUrl,\n connectionParams: options.connectionParams,\n // An auth refusal is not a transient fault: only a credential change clears\n // it, so decline instead of burning the five default attempts and then\n // reporting the same failure a half-minute later. Everything else - a\n // network drop, a 1006, a server restart - keeps graphql-ws's own default,\n // which retries close events and gives up on anything else.\n shouldRetry: (errOrCloseEvent) =>\n isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent),\n });\n\n const unsubscribe = client.subscribe<DocumentChangesSubscription>(\n {\n operationName: \"DocumentChanges\",\n query: print(DocumentChangesDocument),\n },\n {\n next: (result) => {\n const event = result.data?.documentChanges;\n if (event) {\n options.onEvent(event);\n }\n },\n error: (error) => options.onError(error),\n // The server never completes this subscription of its own accord; a\n // completion means the socket was closed, which needs no handling.\n complete: () => undefined,\n },\n );\n\n let stopped = false;\n return () => {\n if (stopped) {\n return;\n }\n stopped = true;\n unsubscribe();\n void client.dispose();\n };\n}\n\n/** The `jobChanges` payload, exactly as the Switchboard sends it. */\nexport type JobChangesEventPayload = JobChangesSubscription[\"jobChanges\"];\n\n/**\n * One socket carrying `jobChanges` subscriptions, one per watched job. The\n * socket opens on the first watch and closes when nothing is watched.\n */\nexport interface IJobChangesSocket {\n /**\n * Watches one job. `onEvent` is called per status change the Switchboard\n * reports; `onError` once if the subscription fails. Returns the stop\n * function, safe to call more than once.\n */\n watch(\n jobId: string,\n onEvent: (event: JobChangesEventPayload) => void,\n onError: (error: unknown) => void,\n ): () => void;\n /** Closes the socket; a later watch opens a new one. */\n dispose(): void;\n}\n\nexport type JobChangesSocketOptions = {\n /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */\n wsUrl: string;\n /** Resolves the `ConnectionInit` payload, per connect. */\n connectionParams?: () => Promise<ConnectionParams>;\n};\n\n/**\n * Opens the socket write handles wait on. `graphql-ws` multiplexes every\n * watched job over it and closes it once the last watch stops.\n */\nexport function createJobChangesSocket(\n options: JobChangesSocketOptions,\n): IJobChangesSocket {\n let client: ReturnType<typeof createClient> | undefined;\n const clientOf = () =>\n (client ??= createClient({\n url: options.wsUrl,\n connectionParams: options.connectionParams,\n shouldRetry: (errOrCloseEvent) =>\n isLikeCloseEvent(errOrCloseEvent) &&\n !isAuthRefusalClose(errOrCloseEvent),\n }));\n return {\n watch(jobId, onEvent, onError) {\n const unsubscribe = clientOf().subscribe<JobChangesSubscription>(\n {\n operationName: \"JobChanges\",\n query: print(JobChangesDocument),\n variables: { jobId },\n },\n {\n next: (result) => {\n const event = result.data?.jobChanges;\n if (event) {\n onEvent(event);\n }\n },\n error: (error) => onError(error),\n complete: () => undefined,\n },\n );\n let stopped = false;\n return () => {\n if (stopped) {\n return;\n }\n stopped = true;\n unsubscribe();\n };\n },\n dispose() {\n const current = client;\n client = undefined;\n void current?.dispose();\n },\n };\n}\n\n/**\n * Derives the websocket endpoint from the GraphQL http endpoint.\n *\n * `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is\n * where the Switchboard mounts its websocket server (`packages/reactor-api`\n * `startServer`). A URL that already speaks `ws`/`wss` only gets the path.\n */\nexport function subscriptionsUrlFromGraphqlUrl(url: string): string {\n const trimmed = url.replace(/\\/+$/, \"\");\n const wsUrl = trimmed.startsWith(\"https://\")\n ? `wss://${trimmed.slice(\"https://\".length)}`\n : trimmed.startsWith(\"http://\")\n ? `ws://${trimmed.slice(\"http://\".length)}`\n : trimmed;\n return `${wsUrl}/subscriptions`;\n}\n\n/**\n * Turns a bearer token provider into `connectionParams`.\n *\n * The header key is the lowercase `authorization` the Switchboard's websocket\n * context factory reads. Without a token the payload is empty: an open\n * Switchboard serves anonymous subscribers.\n */\nexport function makeAuthConnectionParams(\n tokenProvider: BearerTokenProvider,\n): () => Promise<ConnectionParams> {\n return async (): Promise<ConnectionParams> => {\n const token = await tokenProvider();\n if (!token) {\n return {};\n }\n return { authorization: `Bearer ${token}` };\n };\n}\n","import type {\n ConsistencyToken,\n JobInfo,\n JobStatus,\n ViewFilter,\n WriteHandle,\n WriteReceipt,\n} from \"@powerhousedao/reactor\";\nimport type { PHDocument } from \"document-model\";\nimport { JobFailedError } from \"./errors.js\";\n\n/** The two stages a write handle waits for. */\nexport type GraphQLJobStage = \"written\" | \"readable\";\n\n/** Waits for a job to settle a stage, resolving with a FAILED job too. */\nexport type GraphQLJobStageWaiter = (\n jobId: string,\n stage: GraphQLJobStage,\n signal: AbortSignal | undefined,\n) => Promise<JobInfo>;\n\n/** Reads the document a write targeted, bounded by its receipt's token. */\nexport type GraphQLHandleReader = <TDocument extends PHDocument>(\n receipt: WriteReceipt,\n view: ViewFilter | undefined,\n signal: AbortSignal | undefined,\n) => Promise<TDocument>;\n\n/** Whether a job status has reached a stage, FAILED counting as settled. */\nexport function settlesGraphQLJobStage(\n status: JobStatus | string,\n stage: GraphQLJobStage,\n): boolean {\n const value: string = status;\n if (value === \"FAILED\" || value === \"READ_READY\") {\n return true;\n }\n return stage === \"written\" && value === \"WRITE_READY\";\n}\n\nfunction emptyToken(): ConsistencyToken {\n return {\n version: 1,\n createdAtUtcIso: new Date().toISOString(),\n coordinates: [],\n };\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason: unknown = signal.reason;\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\n/** `promise`, rejected early when `signal` aborts. */\nfunction bounded<T>(\n promise: Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (!signal) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(abortError(signal));\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n\n/**\n * A write handle over a job the Switchboard accepted (`executeAsync`).\n *\n * Each stage is the waiter's: `jobStatus`, woken early by the `jobChanges`\n * subscription when the client has realtime. Stage promises are created on\n * first access, so a fire-and-forget caller never owns a rejection. A FAILED\n * job rejects a stage with {@link JobFailedError}.\n *\n * `document()` with no view is read once and shared, so the client's own\n * change announcement and the caller's read-back cost one request.\n */\nexport class GraphQLJobWriteHandle implements WriteHandle {\n readonly jobId: string;\n readonly documentId: string;\n readonly branch: string;\n\n private readonly wait: GraphQLJobStageWaiter;\n private readonly reader: GraphQLHandleReader;\n private readonly signal: AbortSignal | undefined;\n private writtenReceipt: Promise<WriteReceipt> | undefined;\n private readableReceipt: Promise<WriteReceipt> | undefined;\n private defaultDocument: Promise<PHDocument> | undefined;\n\n constructor(\n readonly job: JobInfo,\n documentId: string,\n branch: string,\n wait: GraphQLJobStageWaiter,\n reader: GraphQLHandleReader,\n signal: AbortSignal | undefined,\n ) {\n this.jobId = job.id;\n this.documentId = documentId;\n this.branch = branch;\n this.wait = wait;\n this.reader = reader;\n this.signal = signal;\n }\n\n get written(): Promise<WriteReceipt> {\n this.writtenReceipt ??= this.receiptAt(\"written\");\n return this.writtenReceipt;\n }\n\n get readable(): Promise<WriteReceipt> {\n this.readableReceipt ??= this.receiptAt(\"readable\");\n return this.readableReceipt;\n }\n\n async document<TDocument extends PHDocument = PHDocument>(\n view?: ViewFilter,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n if (view !== undefined) {\n const receipt = await bounded(this.readable, signal);\n return this.reader<TDocument>(receipt, view, signal);\n }\n this.defaultDocument ??= this.readable.then((receipt) =>\n this.reader(receipt, undefined, undefined),\n );\n return bounded(this.defaultDocument as Promise<TDocument>, signal);\n }\n\n private async receiptAt(stage: GraphQLJobStage): Promise<WriteReceipt> {\n const job = await this.wait(this.jobId, stage, this.signal);\n if ((job.status as string) === \"FAILED\") {\n throw new JobFailedError(job);\n }\n return {\n job,\n token: job.consistencyToken,\n documentId: this.documentId,\n branch: this.branch,\n };\n }\n}\n\n/**\n * A write handle for a write the Switchboard applied before answering: the\n * synchronous `createDocument` and `deleteDocument` mutations name no job. Both\n * stages are settled; `jobId` is empty and the receipt's job is a READ_READY\n * placeholder with an empty token, as the reactor's own settled handle has.\n */\nexport class GraphQLSettledWriteHandle implements WriteHandle {\n readonly jobId = \"\";\n readonly documentId: string;\n readonly branch: string;\n\n private readonly receipt: WriteReceipt;\n private readonly reader: GraphQLHandleReader;\n\n constructor(documentId: string, branch: string, reader: GraphQLHandleReader) {\n this.documentId = documentId;\n this.branch = branch;\n this.reader = reader;\n const token = emptyToken();\n this.receipt = {\n job: {\n id: \"\",\n documentId,\n status: \"READ_READY\" as JobStatus,\n createdAtUtcIso: token.createdAtUtcIso,\n consistencyToken: token,\n meta: { batchId: \"\", batchJobIds: [] },\n },\n token,\n documentId,\n branch,\n };\n }\n\n get written(): Promise<WriteReceipt> {\n return Promise.resolve(this.receipt);\n }\n\n get readable(): Promise<WriteReceipt> {\n return Promise.resolve(this.receipt);\n }\n\n document<TDocument extends PHDocument = PHDocument>(\n view?: ViewFilter,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n return this.reader<TDocument>(this.receipt, view, signal);\n }\n}\n","import { getPHStore } from \"../hooks/ph-store.js\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type {\n BatchExecutionRequest,\n BatchExecutionResult,\n ConsistencyToken,\n CreateProtocolVersionsOptions,\n DocumentChangeEvent,\n NewDocumentOptions,\n DocumentChangeType,\n DocumentRelationship,\n ExecutionJobPlan,\n IDriveNodeSource,\n IDriveReadClient,\n IReactorWriteClient,\n JobInfo,\n JobResultSummary,\n JobStatus,\n OperationFilter,\n PagedResults,\n PagingOptions,\n PropagationMode,\n SearchFilter,\n UndoRedoAvailability,\n UndoRedoTargets,\n ViewFilter,\n WriteHandle,\n WriteReceipt,\n} from \"@powerhousedao/reactor\";\nimport type {\n BaseReducerCapabilities,\n CreateDocumentActionInput,\n ISigner,\n PHDocumentState,\n ProtocolVersions,\n SignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n actions,\n actionSigningTarget,\n createVersionsOf,\n creationActions,\n headNewDocument,\n normalizeDocumentModelVersion,\n capabilitiesOf,\n serializeByKey,\n undoCapabilitiesOf,\n undoNeedsTargets,\n undoRedoActions,\n undoRedoAvailabilityOf,\n selectDocumentModelModule,\n toTransportAction,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n Action,\n DocumentModelModule,\n Operation,\n PHDocument,\n} from \"document-model\";\nimport { logger } from \"document-model\";\nimport { print } from \"graphql\";\nimport { GraphQLClient, type Variables } from \"graphql-request\";\nimport { createClient } from \"../graphql/client.js\";\nimport {\n DocumentChangeType as GqlDocumentChangeType,\n PropagationMode as GqlPropagationMode,\n PhDocumentFieldsFragmentDoc,\n type DocumentRelationshipFieldsFragment,\n type GetDocumentQuery,\n type JobInfoFieldsFragment,\n type OperationsFilterInput,\n type PagingInput,\n type PhDocumentFieldsFragment,\n type SdkFunctionWrapper,\n type ViewFilterInput,\n} from \"../graphql/gen/schema.js\";\nimport type { ReactorGraphQLClient } from \"../graphql/types.js\";\nimport { DRIVE_DOCUMENT_TYPES } from \"../constants.js\";\nimport { DOCUMENT_CHANGE_TYPE } from \"../reactor-interop.js\";\nimport { withRequestDeadline, type GraphQLFetch } from \"./transport.js\";\nimport { remoteOperationToLocal } from \"../remote-controller/utils.js\";\nimport type {\n IReactorBrowserClient,\n IReactorBrowserReadClient,\n IReactorBrowserWriteClient,\n} from \"../types/reactor-browser-client.js\";\nimport {\n isoStringFromDateTime,\n phDocumentFromGetDocument,\n phDocumentFromMutation,\n} from \"./adapter.js\";\nimport {\n ambientRenownTokenProvider,\n makeAuthMiddleware,\n type BearerTokenProvider,\n} from \"./auth.js\";\nimport {\n readCreateProtocolVersions,\n readCreateSignaturePolicy,\n} from \"./create-defaults.js\";\nimport {\n GraphQLDriveNodeSource,\n GraphQLDriveReadClient,\n} from \"./drive-nodes.js\";\nimport {\n BatchJobFailedError,\n GraphQLOperationNotSupportedError,\n GraphQLWrongBackendError,\n queriesUnknownField,\n} from \"./errors.js\";\nimport {\n GetDocumentAtConsistencyDocument,\n MutateDocumentWithOperationsDocument,\n type GetDocumentAtConsistencyResult,\n type GetDocumentAtConsistencyVariables,\n type MutateDocumentWithOperationsResult,\n type MutateDocumentWithOperationsVariables,\n} from \"./operations.js\";\nimport { prepareSignedActions, signStampedAction } from \"./signing.js\";\nimport { resolveDocumentModelModule } from \"./static-package-manager.js\";\nimport {\n addRelationshipAction,\n removeRelationshipAction,\n} from \"./system-actions.js\";\nimport {\n describeGraphQLDocument,\n SubgraphSdkRegistry,\n type GraphQLRequestOptions,\n type SubgraphSdkFactory,\n type TypedGraphQLDocument,\n} from \"./subgraph.js\";\nimport {\n createJobChangesSocket,\n isAuthRefusalClose,\n makeAuthConnectionParams,\n startDocumentChangesSubscription,\n subscriptionsUrlFromGraphqlUrl,\n type DocumentChangesEventPayload,\n type IJobChangesSocket,\n} from \"./subscriptions.js\";\nimport {\n GraphQLJobWriteHandle,\n GraphQLSettledWriteHandle,\n settlesGraphQLJobStage,\n type GraphQLHandleReader,\n type GraphQLJobStage,\n} from \"./write-handles.js\";\n\n/** A call the client asks {@link GraphQLReactorClientOptions.driveIdFor} about. */\nexport type DriveIdCall = {\n readonly method:\n | \"create\"\n | \"execute\"\n | \"executeBatch\"\n | \"deleteDocument\"\n | \"find\";\n readonly documentId?: string;\n readonly parentId?: string;\n readonly jobs?: readonly { readonly documentId: string }[];\n};\n\nexport type GraphQLReactorClientOptions = {\n /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */\n url: string;\n\n /**\n * A pre-built SDK to use instead of the transport derived from `url`.\n * Mainly a test seam.\n *\n * A client built this way carries no auth middleware and no 421 mapping:\n * the injected SDK owns its own transport, and therefore its own headers\n * and transport errors.\n */\n graphqlClient?: ReactorGraphQLClient;\n\n /**\n * Resolves the bearer token sent with every request, per request.\n *\n * Defaults to {@link ambientRenownTokenProvider}, i.e. the token of the\n * logged-in Renown user, or none when nobody is logged in.\n */\n tokenProvider?: BearerTokenProvider;\n\n /**\n * The Switchboard GraphQL subscriptions endpoint, e.g.\n * `ws://localhost:4001/graphql/subscriptions`.\n *\n * Defaults to the endpoint derived from `url` by\n * {@link subscriptionsUrlFromGraphqlUrl}.\n */\n subscriptionsUrl?: string;\n\n /**\n * Whether server-pushed changes are delivered to subscribers.\n *\n * On by default: the first `subscribe` call opens a websocket and every\n * change the Switchboard reports is emitted to matching subscribers, so\n * documents another user, tab or processor writes invalidate the cache.\n *\n * Set it to `false` where there is no websocket to talk to. The client then\n * only emits the changes it made itself.\n */\n realtime?: boolean;\n\n /**\n * The document model modules used to sign a batch of two or more actions.\n *\n * Signing action N+1 needs the state action N leaves behind, and only the\n * document's own reducer can predict it - so a batch is signable only when\n * the module matching the document's type AND its exact\n * `state.document.version` is here. One action needs no prediction and is\n * signed without any of this.\n *\n * An array is read once, when the client is built; a function is called at\n * every batch, for a registry that gains models later. Below\n * `GraphQLReactorProvider` this is its `documentModels` prop; a client\n * constructed directly passes its own.\n */\n documentModels?:\n | readonly DocumentModelModule<any>[]\n | (() => readonly DocumentModelModule<any>[]);\n\n /**\n * Signs the actions this client pushes, instead of the logged-in Renown user.\n *\n * Left out - the normal case - the signer is resolved per push from\n * `window.ph.renown`, so a page signs as whoever is logged in and pushes\n * unsigned when nobody is. Set it where there is no Renown to read: tests,\n * scripts, and integration suites that must sign deterministically. A\n * function is called per push, and pushes unsigned when it returns\n * `undefined`; it may resolve the signer asynchronously (one that must\n * first ask whom it signs for).\n *\n * With a signer, `create` builds and signs the document's creation itself\n * and submits it through `executeBatch`, so no action of it is signed by\n * the Switchboard. A create under a drive, and `deleteDocument`, still run\n * the Switchboard's own mutations, which build and sign those actions there.\n */\n signer?: ISigner | (() => ISigner | undefined | Promise<ISigner | undefined>);\n\n /**\n * Names the drive a call belongs to when the client cannot prove it itself,\n * for its `Drive-Id` header; `undefined` sends none. Return only a drive id\n * the caller knows: a Switchboard that does not own it answers 421. Where\n * the client has proof of its own and the two disagree, the proof is sent.\n */\n driveIdFor?: (call: DriveIdCall) => string | undefined;\n\n /**\n * Bounds each HTTP request, headers through body, in milliseconds; a request\n * past it rejects with a `TimeoutError`. Unset, requests are unbounded.\n */\n requestTimeoutMs?: number;\n\n /**\n * Bounds an `executeBatch` request in place of `requestTimeoutMs`. The\n * mutation answers once its jobs are readable, and it has no form that does\n * not wait, so one request lasts as long as the write does.\n */\n batchRequestTimeoutMs?: number;\n\n /** The `fetch` every HTTP request goes through; the global one by default. */\n fetch?: GraphQLFetch;\n};\n\n// Always known here, so a light client can head a drive without registering it.\nconst BUILT_IN_MODELS = [\n driveDocumentModelModule as unknown as DocumentModelModule,\n];\n\n/** Paging defaults, matching the reactor's own client. */\nconst defaultPaging: PagingOptions = { cursor: \"0\", limit: 100 };\n\nconst JOB_POLL_INTERVAL_MS = 250;\n\n/** The first `jobStatus` poll of a write handle's stage wait, doubling from here. */\nconst STAGE_POLL_START_MS = 25;\n\n/**\n * The longest a stage wait sleeps between `jobStatus` polls while the\n * `jobChanges` subscription is up: the subscription wakes it early, and the\n * poll is the safety net for an event that raced the subscription.\n */\nconst STAGE_POLL_REALTIME_MAX_MS = 1000;\n\n/** A registered `subscribe` call. */\ntype ChangeListener = {\n search: SearchFilter;\n callback: (event: DocumentChangeEvent) => void;\n};\n\n/**\n * The marker {@link isGraphQLReactorClient} looks for.\n *\n * A page can end up with two copies of this module - an app that bundles a\n * package carrying its own copy, or a dev server that hot-replaced it - and\n * then `instanceof` compares an instance against the other copy's class object\n * and answers `false`. A branded property survives both.\n */\nconst graphQLReactorClientBrand = \"__powerhouseGraphQLReactorClient\" as const;\n\n/** The read half of {@link GraphQLReactorClient}: the hooks' reads plus `drives`. */\nexport interface GraphQLReactorReadClient extends IReactorBrowserReadClient {\n /** A drive's nodes from the node queries, for every drive type. */\n readonly drives: IDriveReadClient;\n}\n\n/**\n * The write half of {@link GraphQLReactorClient}: the hooks' writes plus\n * `rename` and the relationship writes, each a client-signed action over\n * `executeAsync`.\n */\nexport interface GraphQLReactorWriteClient\n extends\n IReactorBrowserWriteClient,\n Pick<\n IReactorWriteClient,\n \"rename\" | \"addRelationship\" | \"removeRelationship\"\n > {}\n\n/**\n * A light implementation of {@link IReactorBrowserClient} that talks plain\n * GraphQL to a Switchboard, with no reactor in the bundle.\n *\n * It fills the same `window.ph` slots the full in-browser reactor client fills,\n * so the reactor-browser hooks cannot tell the two apart.\n */\nexport class GraphQLReactorClient implements IReactorBrowserClient {\n /** See {@link isGraphQLReactorClient}. */\n readonly [graphQLReactorClientBrand] = true;\n\n private readonly sdk: ReactorGraphQLClient;\n /** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */\n private readonly batchSdk: ReactorGraphQLClient;\n private readonly subgraphs: SubgraphSdkRegistry;\n private readonly listeners: ChangeListener[] = [];\n private readonly tokenProvider: BearerTokenProvider;\n private readonly subscriptionsUrl: string | undefined;\n private readonly documentModels: () => readonly DocumentModelModule<any>[];\n private readonly resolveSigner: () => Promise<ISigner | undefined>;\n private readonly driveIdFor: GraphQLReactorClientOptions[\"driveIdFor\"];\n private readonly undoRedoChains = new Map<string, Promise<unknown>>();\n private stopRealtime: (() => void) | undefined;\n private realtimeStarted = false;\n private realtimeGeneration = 0;\n private realtimeErrorLogged = false;\n /** Whether the last socket died because the Switchboard refused its credentials. */\n private realtimeRefusedCredentials = false;\n /** The socket write handles wait on; opened by the first stage wait. */\n private jobSocket: IJobChangesSocket | undefined;\n /** Set once the `jobChanges` subscription failed; stage waits then only poll. */\n private jobRealtimeBroken = false;\n /** Set once the Switchboard refused the `document` query's `consistency` argument. */\n private consistencyUnsupported = false;\n private readonly driveNodes: GraphQLDriveNodeSource;\n\n /**\n * The read half: the reads the hooks make. Every method is this client's\n * own; nothing that writes is reachable from it.\n */\n readonly read: GraphQLReactorReadClient;\n\n /**\n * The write half. `execute` submits through `executeAsync` and hands back a\n * handle whose `written` and `readable` resolve from `jobStatus`, woken by\n * the `jobChanges` subscription when realtime is on, and whose `document()`\n * runs the `document` query bounded by the receipt's token. `rename`,\n * `addRelationship` and `removeRelationship` are `execute`s of the action\n * the in-process client would sign. `create` and `deleteDocument` have no\n * asynchronous mutation: they run the synchronous ones and hand back a\n * settled handle.\n */\n readonly write: GraphQLReactorWriteClient;\n\n constructor(options: GraphQLReactorClientOptions) {\n this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;\n // An array is copied, not held: the caller's array must not be able to\n // change which reducer a later batch is signed with.\n const models = options.documentModels;\n if (typeof models === \"function\") {\n this.documentModels = models;\n } else {\n const copied = [...(models ?? [])];\n this.documentModels = () => copied;\n }\n const signer = options.signer;\n const resolve =\n typeof signer === \"function\"\n ? signer\n : signer\n ? () => signer\n : ambientRenownSigner;\n this.resolveSigner = async () => resolve();\n this.driveIdFor = options.driveIdFor;\n this.subscriptionsUrl =\n options.realtime === false\n ? undefined\n : (options.subscriptionsUrl ??\n subscriptionsUrlFromGraphqlUrl(options.url));\n\n // The middleware wraps the generated SDK methods AND `RunDocument`, so the\n // hand-authored mutation is authenticated by the same code path.\n const middleware = withWrongBackendErrors(\n makeAuthMiddleware(this.tokenProvider, { url: options.url }),\n );\n const fetch =\n options.requestTimeoutMs === undefined\n ? options.fetch\n : withRequestDeadline(options.requestTimeoutMs, options.fetch);\n this.sdk =\n options.graphqlClient ??\n createClient(new GraphQLClient(options.url, { fetch }), middleware);\n this.batchSdk =\n options.graphqlClient !== undefined ||\n options.batchRequestTimeoutMs === undefined\n ? this.sdk\n : createClient(\n new GraphQLClient(options.url, {\n fetch: withRequestDeadline(\n options.batchRequestTimeoutMs,\n options.fetch,\n ),\n }),\n middleware,\n );\n // Subgraph transports are always derived from `url` and always carry auth,\n // including when the reactor SDK above was injected: an injected SDK is a\n // test seam that owns its own transport, not a second endpoint.\n this.subgraphs = new SubgraphSdkRegistry(options.url, middleware, fetch);\n this.driveNodes = new GraphQLDriveNodeSource(this.sdk, driveIdHeaders);\n this.read = new GraphQLReadHalf(this, this.driveNodes);\n this.write = {\n execute: (documentIdentifier, branch, actions, signal) =>\n this.submitExecute(documentIdentifier, branch, actions, signal),\n create: (document, parentIdentifier, signal) =>\n this.submitCreate(document, parentIdentifier, signal),\n deleteDocument: (identifier, propagate, signal) =>\n this.submitDeleteDocument(identifier, propagate, signal),\n rename: (documentIdentifier, name, branch = \"main\", signal) =>\n this.submitExecute(\n documentIdentifier,\n branch,\n [actions.setName(name)],\n signal,\n ),\n addRelationship: (\n sourceIdentifier,\n targetIdentifier,\n relationshipType,\n metadata,\n branch = \"main\",\n signal,\n ) =>\n this.submitRelationship(\n sourceIdentifier,\n targetIdentifier,\n branch,\n (sourceId, targetId) =>\n addRelationshipAction(\n sourceId,\n targetId,\n relationshipType,\n metadata,\n ),\n signal,\n ),\n removeRelationship: (\n sourceIdentifier,\n targetIdentifier,\n relationshipType,\n branch = \"main\",\n signal,\n ) =>\n this.submitRelationship(\n sourceIdentifier,\n targetIdentifier,\n branch,\n (sourceId, targetId) =>\n removeRelationshipAction(sourceId, targetId, relationshipType),\n signal,\n ),\n };\n }\n\n /**\n * The Switchboard's drive node queries as a node source, for every drive\n * type. `read.drives` answers from it.\n */\n nodeSource(): IDriveNodeSource {\n return this.driveNodes;\n }\n\n /**\n * Reads a document. With a consistency token that names any coordinate, the\n * Switchboard waits until its read models hold them; one without the\n * `document` query's `consistency` argument is read without it, which after\n * a write's `readable` stage still sees the write on a single node.\n */\n async get<TDocument extends PHDocument>(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ): Promise<TDocument> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const result =\n consistencyToken && consistencyToken.coordinates.length > 0\n ? await this.getDocumentAtConsistency(\n identifier,\n viewInput,\n consistencyToken,\n signal,\n )\n : await this.sdk.GetDocument(\n { idOrSlug: identifier, view: viewInput },\n undefined,\n signal,\n );\n\n const document = result.document;\n if (!document) {\n throw new Error(`Document not found: ${identifier}`);\n }\n\n return phDocumentFromGetDocument<TDocument>(\n document.document,\n view?.branch,\n );\n }\n\n /**\n * Reads documents by id, in the order given; throws if any is missing. Each\n * chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased\n * `document` field per id, with the selection and arguments `get` sends.\n */\n async getMany<TDocument extends PHDocument>(\n documentIds: string[],\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ): Promise<TDocument[]> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const token =\n consistencyToken && consistencyToken.coordinates.length > 0\n ? consistencyToken\n : undefined;\n const chunks: string[][] = [];\n for (let i = 0; i < documentIds.length; i += GET_MANY_CHUNK_SIZE) {\n chunks.push(documentIds.slice(i, i + GET_MANY_CHUNK_SIZE));\n }\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.getDocumentChunk(chunk, viewInput, token, signal),\n ),\n );\n return pages\n .flat()\n .map((document) =>\n phDocumentFromGetDocument<TDocument>(document, view?.branch),\n );\n }\n\n /** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */\n private async getDocumentChunk(\n identifiers: string[],\n view: ViewFilterInput | undefined,\n token: ConsistencyToken | undefined,\n signal: AbortSignal | undefined,\n ): Promise<PhDocumentFieldsFragment[]> {\n if (token && !this.consistencyUnsupported) {\n try {\n return await this.runGetDocuments(\n identifiers,\n view,\n consistencyInputFromToken(token),\n signal,\n );\n } catch (error) {\n if (!refusesConsistencyArgument(error)) {\n throw error;\n }\n this.consistencyUnsupported = true;\n }\n }\n return this.runGetDocuments(identifiers, view, undefined, signal);\n }\n\n private async runGetDocuments(\n identifiers: string[],\n view: ViewFilterInput | undefined,\n consistency: GetDocumentAtConsistencyVariables[\"consistency\"] | undefined,\n signal: AbortSignal | undefined,\n ): Promise<PhDocumentFieldsFragment[]> {\n const variables: Record<string, unknown> = { view };\n const definitions = [\"$view: ViewFilterInput\"];\n let consistencyArgument = \"\";\n if (consistency) {\n variables.consistency = consistency;\n definitions.push(\"$consistency: ConsistencyTokenInput\");\n consistencyArgument = \", consistency: $consistency\";\n }\n const fields = identifiers.map((identifier, i) => {\n variables[`id${i}`] = identifier;\n definitions.push(`$id${i}: String!`);\n return `d${i}: document(idOrSlug: $id${i}, view: $view${consistencyArgument}) { document { ...PHDocumentFields } childIds }`;\n });\n const query = [\n `query GetDocuments(${definitions.join(\", \")}) {`,\n ...fields,\n \"}\",\n PH_DOCUMENT_FIELDS_SOURCE,\n ].join(\"\\n\");\n const data = await this.sdk.RunDocument<\n Record<string, GetDocumentQuery[\"document\"]>\n >({\n operationName: \"GetDocuments\",\n operationType: \"query\",\n document: query,\n variables,\n signal,\n });\n return identifiers.map((identifier, i) => {\n const result = data[`d${i}`];\n if (!result) {\n throw new Error(`Document not found: ${identifier}`);\n }\n return result.document;\n });\n }\n\n /**\n * Whether the Switchboard would serve the document to this client's caller,\n * from its `documentServed` query: the same read gate `find` passes. Absent\n * or withheld is `false`; a failure to decide throws.\n *\n * A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as\n * does a Switchboard without the query.\n */\n async isServed(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const viewInput = viewFilterInputFromViewFilter(view);\n try {\n const result = await this.sdk.GetDocumentServed(\n { idOrSlug: identifier, view: viewInput },\n undefined,\n signal,\n );\n return result.documentServed;\n } catch (error) {\n if (queriesUnknownField(error, \"documentServed\")) {\n throw new GraphQLOperationNotSupportedError(\n \"isServed\",\n \"the Switchboard predates the documentServed query\",\n );\n }\n throw error;\n }\n }\n\n async getOperations(\n documentIdentifier: string,\n view?: ViewFilter,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const operationsFilter: OperationsFilterInput = {\n documentIdOrSlug: documentIdentifier,\n branch: viewInput?.branch,\n scopes: viewInput?.scopes,\n actionTypes: filter?.actionTypes,\n timestampFrom: filter?.timestampFrom,\n timestampTo: filter?.timestampTo,\n sinceRevision: filter?.sinceRevision,\n };\n const result = await this.sdk.GetDocumentOperations(\n { filter: operationsFilter, paging: pagingInputFromPaging(paging) },\n undefined,\n signal,\n );\n\n const page = result.documentOperations;\n const nextCursor = page.hasNextPage\n ? (page.cursor ?? undefined)\n : undefined;\n const effectivePaging = paging ?? defaultPaging;\n\n return {\n results: page.items.map((item) => remoteOperationToLocal(item)),\n options: effectivePaging,\n nextCursor,\n next: nextCursor\n ? () =>\n this.getOperations(\n documentIdentifier,\n view,\n filter,\n { cursor: nextCursor, limit: effectivePaging.limit },\n signal,\n )\n : undefined,\n };\n }\n\n /**\n * Filters documents by criteria over the Switchboard's `findDocuments` query.\n *\n * The query filters by `type` and `parentId` only, at head. A search naming\n * `ids` or `slugs` (present, whatever its length) and a point-in-time view are\n * each by-contract limitations the query cannot express -- running it anyway\n * would return every document instead of the named ones, or head instead of\n * the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}\n * is the single predicate that decides this, and an unservable `find` throws\n * {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters\n * by `type` at head, which is served.\n */\n async find<TDocument extends PHDocument = PHDocument>(\n search: SearchFilter,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<TDocument>> {\n if (!findIsServableOverGraphQL(search, view)) {\n throw new GraphQLOperationNotSupportedError(\n \"find\",\n searchNamesIdentifiers(search)\n ? \"it cannot filter by ids or slugs: the Switchboard findDocuments query filters only by type and parentId\"\n : \"point-in-time views are not supported by GraphQLReactorClient\",\n );\n }\n\n const viewInput = viewFilterInputFromViewFilter(view);\n const effectivePaging = paging ?? defaultPaging;\n const result = await this.sdk.FindDocuments(\n {\n search: { type: search.type, parentId: search.parentId },\n view: viewInput,\n paging: pagingInputFromPaging(effectivePaging),\n },\n search.parentId === undefined\n ? undefined\n : this.driveIdHeaders({ method: \"find\", parentId: search.parentId }),\n signal,\n );\n\n return this.toDocumentResults<TDocument>(\n result.findDocuments,\n effectivePaging,\n view?.branch,\n (cursor, limit) =>\n this.find<TDocument>(search, view, { cursor, limit }, signal),\n );\n }\n\n async getOutgoingRelationships(\n sourceIdentifier: string,\n relationshipType: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const result = await this.sdk.GetDocumentOutgoingRelationships(\n {\n sourceIdOrSlug: sourceIdentifier,\n relationshipType,\n view: viewInput,\n paging: pagingInputFromPaging(paging),\n },\n undefined,\n signal,\n );\n\n return this.toDocumentResults(\n result.documentOutgoingRelationships,\n paging ?? defaultPaging,\n view?.branch,\n (cursor, limit) =>\n this.getOutgoingRelationships(\n sourceIdentifier,\n relationshipType,\n view,\n { cursor, limit },\n signal,\n ),\n );\n }\n\n async getIncomingRelationships(\n targetIdentifier: string,\n relationshipType: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const result = await this.sdk.GetDocumentIncomingRelationships(\n {\n targetIdOrSlug: targetIdentifier,\n relationshipType,\n view: viewInput,\n paging: pagingInputFromPaging(paging),\n },\n undefined,\n signal,\n );\n\n return this.toDocumentResults(\n result.documentIncomingRelationships,\n paging ?? defaultPaging,\n view?.branch,\n (cursor, limit) =>\n this.getIncomingRelationships(\n targetIdentifier,\n relationshipType,\n view,\n { cursor, limit },\n signal,\n ),\n );\n }\n\n async getOutgoingRelationshipEdges(\n sourceIdentifier: string,\n relationshipType?: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<DocumentRelationship>> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const result = await this.sdk.GetDocumentOutgoingRelationshipEdges(\n {\n sourceIdOrSlug: sourceIdentifier,\n relationshipType,\n view: viewInput,\n paging: pagingInputFromPaging(paging),\n },\n undefined,\n signal,\n );\n\n return this.toRelationshipResults(\n result.documentOutgoingRelationshipEdges,\n paging ?? defaultPaging,\n (cursor, limit) =>\n this.getOutgoingRelationshipEdges(\n sourceIdentifier,\n relationshipType,\n view,\n { cursor, limit },\n signal,\n ),\n );\n }\n\n async getIncomingRelationshipEdges(\n targetIdentifier: string,\n relationshipType?: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<DocumentRelationship>> {\n const viewInput = viewFilterInputFromViewFilter(view);\n const result = await this.sdk.GetDocumentIncomingRelationshipEdges(\n {\n targetIdOrSlug: targetIdentifier,\n relationshipType,\n view: viewInput,\n paging: pagingInputFromPaging(paging),\n },\n undefined,\n signal,\n );\n\n return this.toRelationshipResults(\n result.documentIncomingRelationshipEdges,\n paging ?? defaultPaging,\n (cursor, limit) =>\n this.getIncomingRelationshipEdges(\n targetIdentifier,\n relationshipType,\n view,\n { cursor, limit },\n signal,\n ),\n );\n }\n\n /**\n * Creates `document`, under `parentIdentifier` when given.\n *\n * With a signer the creation is built and signed here, as the in-process\n * client builds it, and submitted through `executeBatch`; the Switchboard\n * signs none of it. A create under a drive still runs the Switchboard's\n * `createDocument`, which files the document in the drive and signs that\n * itself, as does a create without a signer.\n */\n async create<TDocument extends PHDocument = PHDocument>(\n document: PHDocument,\n parentIdentifier?: string,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const signer = await this.resolveSigner();\n if (signer) {\n const parent =\n parentIdentifier === undefined\n ? undefined\n : await this.parentOf(parentIdentifier, signal);\n if (!parent || !isDriveType(parent.documentType)) {\n return this.createSigned<TDocument>(\n document,\n parentIdentifier,\n parent?.id,\n signer,\n signal,\n );\n }\n }\n // A new top-level drive is pinned to the backend its own id routes to;\n // under a parent it goes where the parent is, which only the hook knows.\n const result = await this.sdk.CreateDocument(\n { document, parentIdOrSlug: parentIdentifier },\n this.driveIdHeaders(\n {\n method: \"create\",\n documentId: document.header.id || undefined,\n parentId: parentIdentifier,\n },\n isDrive(document) && parentIdentifier === undefined\n ? document.header.id\n : undefined,\n ),\n signal,\n );\n\n const created = phDocumentFromGetDocument<TDocument>(result.createDocument);\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Created,\n documents: [created],\n });\n return created;\n }\n\n /**\n * The signed creation of `document`: its CREATE_DOCUMENT and\n * UPGRADE_DOCUMENT, then the parent's ADD_RELATIONSHIP, one batch, as the\n * in-process client's `buildCreateJobs` makes it. The slug is checked as the\n * Switchboard's `createDocument` checks it.\n */\n private async createSigned<TDocument extends PHDocument>(\n document: PHDocument,\n parentIdentifier: string | undefined,\n parentId: string | undefined,\n signer: ISigner,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const documentId = document.header.id;\n const branch = document.header.branch || \"main\";\n await this.assertSlugAvailable(document.header.slug, documentId, signal);\n const protocolVersions = await createVersionsOf(\n document,\n (options) => this.getCreateProtocolVersions(options, signal),\n parentIdentifier,\n );\n const jobs: ExecutionJobPlan[] = [\n {\n key: \"create\",\n documentId,\n scope: \"document\",\n branch,\n actions: creationActions(document, protocolVersions),\n dependsOn: [],\n },\n ];\n if (parentId) {\n jobs.push({\n key: \"parent\",\n documentId: parentId,\n scope: \"document\",\n branch: \"main\",\n actions: [addRelationshipAction(parentId, documentId, \"child\")],\n dependsOn: [\"create\"],\n });\n }\n const { jobs: settled } = await this.executeBatchAs(\n { jobs },\n signer,\n signal,\n // A new top-level drive is pinned to the backend its own id routes to.\n isDrive(document) && parentIdentifier === undefined\n ? documentId\n : undefined,\n );\n return this.get<TDocument>(\n documentId,\n { branch },\n signal,\n settled.create?.consistencyToken,\n );\n }\n\n /** The id and type of the document a create names as its parent. */\n private async parentOf(\n identifier: string,\n signal: AbortSignal | undefined,\n ): Promise<{ id: string; documentType: string }> {\n const result = await this.sdk.GetDocument(\n { idOrSlug: identifier, view: { branch: \"main\", scopes: [\"document\"] } },\n undefined,\n signal,\n );\n const parent = result.document?.document;\n if (!parent) {\n throw new Error(`Failed to create document: no parent ${identifier}`);\n }\n return { id: parent.id, documentType: parent.documentType };\n }\n\n /** Refuses a slug another document holds, as `createDocument` does. */\n private async assertSlugAvailable(\n slug: string | undefined,\n documentId: string,\n signal: AbortSignal | undefined,\n ): Promise<void> {\n if (!slug || slug === documentId) return;\n // Asked first, so a free slug costs no NOT_FOUND on the Switchboard.\n let served: boolean | undefined;\n try {\n served = await this.isServed(slug, { branch: \"main\" }, signal);\n } catch (error) {\n if (!(error instanceof GraphQLOperationNotSupportedError)) throw error;\n }\n if (served === false) return;\n let holder: string | undefined;\n try {\n const result = await this.sdk.GetDocument(\n { idOrSlug: slug, view: { branch: \"main\", scopes: [\"document\"] } },\n undefined,\n signal,\n );\n holder = result.document?.document.id;\n } catch (error) {\n if (answersNotFound(error)) return;\n throw error;\n }\n if (holder && holder !== documentId) {\n throw new Error(\n `The slug \"${slug}\" is taken by document ${holder}; choose another.`,\n );\n }\n }\n\n /**\n * Pushes actions to the Switchboard and returns the updated document.\n *\n * The document is fetched first: the response is the baseline for the\n * `sinceRevision` filter that narrows the returned operations to the ones\n * this call appended, and it carries the state hash a signed action is\n * stamped with.\n *\n * The emitted `Updated` event carries the document's id, never the\n * identifier this was called with: subscribers - including `DocumentCache` -\n * work in id space.\n *\n * `IReactorClient.execute`'s trailing `subject` is deliberately not accepted\n * here. It names the subject a local read gate answers as, and this client\n * runs no gate: the Switchboard decides what to serve from the bearer on the\n * request. Declaring it would suggest a per-call choice that does not exist.\n */\n async execute<TDocument extends PHDocument>(\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const document = await this.get(documentIdentifier, { branch }, signal);\n const preparedActions = await prepareActionsForPush(\n actions,\n document,\n this.documentModels(),\n await this.resolveSigner(),\n signal,\n );\n\n const variables: MutateDocumentWithOperationsVariables = {\n documentIdOrSlug: documentIdentifier,\n // Projected onto the fields the schema declares, so a stamped or signed\n // action does not carry a field the input rejects the whole request for.\n actions: preparedActions.map(toTransportAction),\n sinceRevision: sinceRevisionForActions(document, actions),\n scopes: scopesForActions(actions),\n branch,\n };\n const result =\n await this.sdk.RunDocument<MutateDocumentWithOperationsResult>({\n operationName: \"MutateDocumentWithOperations\",\n operationType: \"mutation\",\n document: MutateDocumentWithOperationsDocument,\n variables,\n requestHeaders: this.driveIdHeaders(\n { method: \"execute\", documentId: documentIdentifier },\n isDrive(document) ? document.header.id : undefined,\n ),\n signal,\n });\n\n const mutated = result.mutateDocument;\n const updated = phDocumentFromMutation<TDocument>(\n mutated,\n mutated.operations?.items ?? [],\n branch,\n );\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Updated,\n documents: [updated],\n });\n return updated;\n }\n\n /**\n * What `execute` writes, without waiting: returns the job once the Switchboard\n * holds it, so a write slower than one request's deadline still lands and is\n * reported. It is announced as the write half's `execute` announces it.\n */\n async executeAsync(\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ): Promise<JobInfo> {\n const handle = await this.submitExecute(\n documentIdentifier,\n branch,\n actions,\n signal,\n );\n return handle.job;\n }\n\n /**\n * Undoes the last applied operation of `scope` under this client's own\n * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the\n * Switchboard resolves with {@link undoRedoTargets}. One at a time per\n * document, scope and branch. A stale target is refused, not re-resolved.\n */\n undo<TDocument extends PHDocument = PHDocument>(\n documentIdentifier: string,\n scope: string = \"global\",\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<TDocument> {\n return this.undoOrRedo<TDocument>(\n \"UNDO\",\n documentIdentifier,\n scope,\n branch,\n signal,\n );\n }\n\n /** Redoes the last undo of `scope`; see {@link undo}. */\n redo<TDocument extends PHDocument = PHDocument>(\n documentIdentifier: string,\n scope: string = \"global\",\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<TDocument> {\n return this.undoOrRedo<TDocument>(\n \"REDO\",\n documentIdentifier,\n scope,\n branch,\n signal,\n );\n }\n\n /** Exact on base-reducer 3, from the targets the Switchboard resolves. */\n async undoRedoAvailability(\n documentIdentifier: string,\n scope: string = \"global\",\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<UndoRedoAvailability> {\n const { caps, document } = await this.undoCapabilities(\n documentIdentifier,\n branch,\n signal,\n );\n const targets = undoNeedsTargets(caps)\n ? await this.undoRedoTargets(\n documentIdentifier,\n scope,\n { branch },\n signal,\n )\n : undefined;\n // The Switchboard serves only the scopes the caller may read.\n return undoRedoAvailabilityOf(\n caps,\n targets,\n document.header.revision[scope] ?? 0,\n scope in document.state,\n );\n }\n\n /**\n * The rows a base-reducer 3 undo and redo would retract, resolved by the\n * Switchboard as the caller. A Switchboard without the query is refused\n * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not\n * sent: the Switchboard reads the caller from the bearer.\n */\n async undoRedoTargets(\n documentIdentifier: string,\n scope: string = \"global\",\n view?: ViewFilter,\n signal?: AbortSignal,\n ): Promise<UndoRedoTargets> {\n try {\n const { undoRedoTargets } = await this.sdk.GetUndoRedoTargets(\n { documentIdOrSlug: documentIdentifier, scope, branch: view?.branch },\n undefined,\n signal,\n );\n return {\n ...(undoRedoTargets.undoTarget\n ? { undoTarget: undoRedoTargets.undoTarget }\n : {}),\n ...(undoRedoTargets.redoTarget\n ? { redoTarget: undoRedoTargets.redoTarget }\n : {}),\n };\n } catch (error) {\n if (queriesUnknownField(error, \"undoRedoTargets\")) {\n throw new GraphQLOperationNotSupportedError(\n \"undoRedoTargets\",\n \"the Switchboard predates the undoRedoTargets query\",\n );\n }\n throw error;\n }\n }\n\n private undoOrRedo<TDocument extends PHDocument>(\n type: \"UNDO\" | \"REDO\",\n documentIdentifier: string,\n scope: string,\n branch: string,\n signal: AbortSignal | undefined,\n ): Promise<TDocument> {\n return serializeByKey(\n this.undoRedoChains,\n JSON.stringify([documentIdentifier, scope, branch]),\n async () => {\n const { caps } = await this.undoCapabilities(\n documentIdentifier,\n branch,\n signal,\n );\n const targets = undoNeedsTargets(caps)\n ? await this.undoRedoTargets(\n documentIdentifier,\n scope,\n { branch },\n signal,\n )\n : undefined;\n return this.execute<TDocument>(\n documentIdentifier,\n branch,\n undoRedoActions(caps, type, scope, targets),\n signal,\n );\n },\n signal,\n );\n }\n\n /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */\n private async undoCapabilities(\n documentIdentifier: string,\n branch: string,\n signal: AbortSignal | undefined,\n ): Promise<{ caps: BaseReducerCapabilities; document: PHDocument }> {\n const document = await this.get(documentIdentifier, { branch }, signal);\n const { header } = document;\n const fromHeader = undoCapabilitiesOf(header);\n if (fromHeader) {\n return { caps: fromHeader, document };\n }\n const page = await this.getOperations(\n documentIdentifier,\n { branch, scopes: [\"document\"] },\n undefined,\n { cursor: \"0\", limit: 1 },\n signal,\n );\n const create = page.results.at(0)?.action;\n const input =\n create?.type === \"CREATE_DOCUMENT\"\n ? (create.input as Partial<CreateDocumentActionInput>)\n : undefined;\n return {\n caps: undoCapabilitiesOf(header, input) ?? capabilitiesOf(1),\n document,\n };\n }\n\n /**\n * Runs multiple mutation jobs in dependency order over the Switchboard's\n * `executeBatch` mutation and waits for all to settle, returning the result\n * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`\n * consumes it unchanged.\n *\n * Not atomic: each job commits on its own and a failed job still releases\n * its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the\n * first failed plan key and carrying every job's final state.\n *\n * Each job's actions are signed independently for the job's own\n * `(documentId, branch)` target -- the per-action signing the reactor's own\n * `signActions` does, not the batch state-prediction `execute` uses for a\n * multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +\n * `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects\n * outright and which has no fetchable baseline to stamp against. The reactor\n * records but does not verify the stamped previous-state head, so signing\n * each action bare is exactly what the in-process `DriveClient` relies on.\n *\n * The mutation is synchronous server-side: a job it returns is already\n * settled, so {@link waitForJob} resolves from it without polling.\n */\n async executeBatch(\n request: BatchExecutionRequest,\n signal?: AbortSignal,\n ): Promise<BatchExecutionResult> {\n return this.executeBatchAs(request, await this.resolveSigner(), signal);\n }\n\n /** {@link executeBatch} signed by `signer`; `proven` names its drive. */\n private async executeBatchAs(\n request: BatchExecutionRequest,\n signer: ISigner | undefined,\n signal?: AbortSignal,\n proven?: string,\n ): Promise<BatchExecutionResult> {\n const jobInputs = await Promise.all(\n request.jobs.map(async (job, index) => {\n const documentId = await this.batchWriteTarget(\n job,\n request.jobs.slice(0, index),\n signer,\n signal,\n );\n const actions = await this.signBatchJobActions(\n { ...job, documentId },\n signer,\n signal,\n );\n return {\n key: job.key,\n documentIdOrSlug: documentId,\n scope: job.scope,\n branch: job.branch,\n actions: actions.map(toTransportAction),\n dependsOn: job.dependsOn,\n };\n }),\n );\n\n const result = await this.batchSdk.ExecuteBatch(\n { jobs: jobInputs },\n this.driveIdHeaders(\n {\n method: \"executeBatch\",\n jobs: jobInputs.map((job) => ({ documentId: job.documentIdOrSlug })),\n },\n proven,\n ),\n signal,\n );\n\n const jobs: Record<string, JobInfo> = {};\n for (const entry of result.executeBatch.jobs) {\n jobs[entry.key] = jobInfoFromGql(entry.job);\n }\n await this.announceBatch(request, jobs, signal);\n const failed = request.jobs.find(\n (job) => (jobs[job.key]?.status as string | undefined) === \"FAILED\",\n );\n if (failed) {\n throw new BatchJobFailedError(failed.key, jobs);\n }\n return { jobs };\n }\n\n /** The job as `jobStatus` reports it now; `undefined` when it reports none. */\n async getJob(\n jobId: string,\n signal?: AbortSignal,\n ): Promise<JobInfo | undefined> {\n const result = await this.sdk.GetJobStatus({ jobId }, undefined, signal);\n return result.jobStatus ? jobInfoFromGql(result.jobStatus) : undefined;\n }\n\n /** The job as `jobStatus` reports it now; throws when it reports none. */\n async getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo> {\n const job = await this.getJob(jobId, signal);\n if (!job) {\n throw new Error(`Job not found: ${jobId}`);\n }\n return job;\n }\n\n /** Polls `jobStatus` until the job is READ_READY or FAILED. */\n async waitForJob(\n jobOrId: string | JobInfo,\n signal?: AbortSignal,\n ): Promise<JobInfo> {\n if (typeof jobOrId !== \"string\" && isSettled(jobOrId)) {\n return jobOrId;\n }\n const jobId = typeof jobOrId === \"string\" ? jobOrId : jobOrId.id;\n for (;;) {\n const result = await this.sdk.GetJobStatus({ jobId }, undefined, signal);\n if (!result.jobStatus) {\n throw new Error(`Job not found: ${jobId}`);\n }\n const job = jobInfoFromGql(result.jobStatus);\n if (isSettled(job)) {\n return job;\n }\n await delay(JOB_POLL_INTERVAL_MS, signal);\n }\n }\n\n /** See {@link readCreateSignaturePolicy}. */\n getCreateSignaturePolicy(): Promise<SignaturePolicy> {\n return readCreateSignaturePolicy(this.sdk);\n }\n\n /** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */\n getCreateProtocolVersions(\n options: CreateProtocolVersionsOptions,\n signal?: AbortSignal,\n ): Promise<ProtocolVersions> {\n return readCreateProtocolVersions(\n this.sdk,\n options,\n this.documentModels(),\n signal,\n );\n }\n\n /** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */\n async newDocument<TDocument extends PHDocument = PHDocument>(\n documentType: string,\n options?: NewDocumentOptions,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const module = selectDocumentModelModule(\n [...this.documentModels(), ...BUILT_IN_MODELS],\n documentType,\n options?.documentModelVersion,\n );\n const [policy, versions] = await Promise.all([\n options?.signaturePolicy ?? this.getCreateSignaturePolicy(),\n this.getCreateProtocolVersions(\n { documentType, parentIdentifier: options?.parentIdentifier },\n signal,\n ),\n ]);\n return headNewDocument(module, options, policy, versions) as TDocument;\n }\n\n /**\n * Sets or, with `null`, clears the preferred editor as a client-signed\n * action, as the in-process client does.\n */\n setPreferredEditor(\n documentIdentifier: string,\n preferredEditor: string | null,\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<PHDocument> {\n return this.execute(\n documentIdentifier,\n branch,\n [actions.setPreferredEditor(preferredEditor)],\n signal,\n );\n }\n\n /**\n * Renames a document with a client-signed `SET_NAME`, as the in-process\n * client does: the write half's `rename`, read back once readable.\n */\n async rename(\n documentIdentifier: string,\n name: string,\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<PHDocument> {\n const handle = await this.write.rename(\n documentIdentifier,\n name,\n branch,\n signal,\n );\n return handle.document();\n }\n\n /**\n * Adds a relationship with a client-signed `ADD_RELATIONSHIP` on the\n * source, as the in-process client does: the write half's\n * `addRelationship`, resolving with the source once readable. The\n * Switchboard's own `addRelationship` mutation is not used: it signs with\n * the Switchboard's key.\n */\n async addRelationship(\n sourceIdentifier: string,\n targetIdentifier: string,\n relationshipType: string,\n metadata?: Record<string, unknown>,\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<PHDocument> {\n const handle = await this.write.addRelationship(\n sourceIdentifier,\n targetIdentifier,\n relationshipType,\n metadata,\n branch,\n signal,\n );\n return handle.document();\n }\n\n /**\n * Removes a relationship with a client-signed `REMOVE_RELATIONSHIP` on the\n * source; see {@link addRelationship}.\n */\n async removeRelationship(\n sourceIdentifier: string,\n targetIdentifier: string,\n relationshipType: string,\n branch: string = \"main\",\n signal?: AbortSignal,\n ): Promise<PHDocument> {\n const handle = await this.write.removeRelationship(\n sourceIdentifier,\n targetIdentifier,\n relationshipType,\n branch,\n signal,\n );\n return handle.document();\n }\n\n /** The `Drive-Id` header for a call: the client's own proof, else the hook's. */\n private driveIdHeaders(\n call: DriveIdCall,\n proven?: string,\n ): Record<string, string> | undefined {\n const hinted = this.driveIdFor?.(call);\n if (proven) {\n if (hinted && hinted !== proven) {\n logger.warn(\n \"GraphQLReactorClient: driveIdFor named @hinted for @method, which belongs to drive @proven; sending the proven drive\",\n hinted,\n call.method,\n proven,\n );\n }\n return driveIdHeaders(proven);\n }\n return hinted ? driveIdHeaders(hinted) : undefined;\n }\n\n /**\n * Emits the changes the batch's settled jobs made, as `create` and `execute`\n * do, so a cache is invalidated without a realtime socket. The documents a\n * job wrote to are its own and those its consistency token names.\n */\n private async announceBatch(\n request: BatchExecutionRequest,\n jobs: Record<string, JobInfo>,\n signal?: AbortSignal,\n ): Promise<void> {\n if (this.listeners.length === 0) {\n return;\n }\n type Written = { documentId: string; branch: string };\n const deleted = new Set<string>();\n const created = new Map<string, Written>();\n const touched = new Map<string, Written>();\n const keyOf = (written: Written) =>\n `${written.branch}\\u0000${written.documentId}`;\n for (const job of request.jobs) {\n const info = jobs[job.key] as JobInfo | undefined;\n if (!info || (info.status as string) !== \"READ_READY\") continue;\n const types = new Set(job.actions.map((action) => action.type));\n if (types.has(\"DELETE_DOCUMENT\")) {\n deleted.add(info.documentId);\n continue;\n }\n const own = { documentId: info.documentId, branch: job.branch };\n if (types.has(\"CREATE_DOCUMENT\")) {\n created.set(keyOf(own), own);\n }\n touched.set(keyOf(own), own);\n for (const { documentId, branch } of info.consistencyToken.coordinates) {\n touched.set(keyOf({ documentId, branch }), { documentId, branch });\n }\n }\n\n for (const documentId of deleted) {\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Deleted,\n documents: [],\n context: { childId: documentId },\n });\n }\n\n const read = async ({ documentId, branch }: Written) => {\n try {\n return await this.get(documentId, { branch }, signal);\n } catch (error) {\n logger.warn(\n \"GraphQLReactorClient: could not read @documentId on @branch to announce a batch change: @error\",\n documentId,\n branch,\n error,\n );\n return undefined;\n }\n };\n const readAll = async (written: Written[]) =>\n (await Promise.all(written.map(read))).filter(\n (document) => document !== undefined,\n );\n // Read concurrently, emit in order: Created before Updated.\n const [createdDocuments, updatedDocuments] = await Promise.all([\n readAll([...created.values()].filter((w) => !deleted.has(w.documentId))),\n readAll(\n [...touched.entries()]\n .filter(([key, w]) => !deleted.has(w.documentId) && !created.has(key))\n .map(([, w]) => w),\n ),\n ]);\n if (createdDocuments.length > 0) {\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Created,\n documents: createdDocuments,\n });\n }\n if (updatedDocuments.length > 0) {\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Updated,\n documents: updatedDocuments,\n });\n }\n }\n\n /**\n * The id a job's actions are signed for: a signature covers the document id,\n * and the server resolves a slug before verifying. A document created by this\n * job or an earlier one is named by its id. When the server has no such\n * document the identifier is used as given, and the server decides; any\n * other failure to read it throws, so nothing is signed for a slug.\n */\n private async batchWriteTarget(\n job: ExecutionJobPlan,\n earlier: readonly ExecutionJobPlan[],\n signer: ISigner | undefined,\n signal?: AbortSignal,\n ): Promise<string> {\n const creates = (plan: ExecutionJobPlan) =>\n plan.documentId === job.documentId &&\n plan.actions.some((action) => action.type === \"CREATE_DOCUMENT\");\n if (\n !signer ||\n job.actions.every(isActionSigned) ||\n creates(job) ||\n earlier.some(creates)\n ) {\n return job.documentId;\n }\n const result = await this.sdk.GetDocument(\n {\n idOrSlug: job.documentId,\n view: viewFilterInputFromViewFilter({ branch: job.branch }),\n },\n undefined,\n signal,\n );\n return result.document?.document.id ?? job.documentId;\n }\n\n /**\n * Signs one batch job's actions for the job's own log.\n *\n * Each action is signed on its own for `(documentId, branch)`, the same\n * per-action signing the reactor's `signActions` does: no state prediction\n * across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction\n * path rejects still signs. An action already signed under a key is left\n * as it is: the reference `DriveClient` signs its jobs before handing them\n * here. With no signer the actions pass through unsigned, matching\n * {@link execute}.\n */\n private async signBatchJobActions(\n job: ExecutionJobPlan,\n signer: ISigner | undefined,\n signal?: AbortSignal,\n ): Promise<Action[]> {\n if (!signer) {\n return job.actions;\n }\n return Promise.all(\n job.actions.map((action) =>\n isActionSigned(action)\n ? Promise.resolve(action)\n : signStampedAction(\n action,\n signer,\n actionSigningTarget(action, job.documentId, job.branch),\n signal,\n ),\n ),\n );\n }\n\n /**\n * Deletes a document and announces it as a `Deleted` event.\n *\n * Pass a document id. The server resolves a slug just as happily, but\n * `deleteDocument` returns a boolean - there is no document left to read an\n * id off - so the identifier is announced verbatim on `context.childId`. A\n * subscriber keyed by id, `DocumentCache` included, therefore only reacts to\n * a delete by id.\n */\n async deleteDocument(\n identifier: string,\n propagate?: PropagationMode,\n signal?: AbortSignal,\n ): Promise<void> {\n await this.sdk.DeleteDocument(\n { idOrSlug: identifier, propagate: propagationModeInput(propagate) },\n this.driveIdHeaders({ method: \"deleteDocument\", documentId: identifier }),\n signal,\n );\n\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Deleted,\n documents: [],\n context: { childId: identifier },\n });\n }\n\n /**\n * Registers a change subscriber and returns its unsubscribe function.\n *\n * Two things produce the events delivered here. Every successful `create`,\n * `execute` and `deleteDocument` emits one, which is what makes a\n * `DocumentCache` built on this client invalidate after a dispatch. And,\n * unless realtime is switched off, the first call to this method opens a\n * websocket to the Switchboard and every change it reports - from another\n * user, another tab or a server-side processor - is emitted too. A write of\n * this client's own is therefore announced twice, once locally and once by\n * the server; the cache refetches twice, which is harmless.\n *\n * A websocket that cannot be opened or is refused is logged once and then\n * ignored: realtime is an enhancement, never a dependency. The failed socket\n * is closed, so the next subscriber to arrive tries again.\n *\n * `view` is accepted for interface compatibility and ignored: the emitted\n * documents are whatever the write returned, so there is nothing to re-scope.\n *\n * Events live in id space: `search.ids` is matched against the resolved\n * document id, never against the identifier the write was issued with. The\n * one exception is `deleteDocument`, which has no document to resolve an id\n * from - see its own note. A `DocumentCache` on this client must therefore\n * be read by id: a slug-keyed entry is never invalidated.\n */\n subscribe(\n search: SearchFilter,\n callback: (event: DocumentChangeEvent) => void,\n view?: ViewFilter,\n ): () => void {\n const listener: ChangeListener = { search, callback };\n this.listeners.push(listener);\n this.startRealtime();\n\n return () => {\n const index = this.listeners.indexOf(listener);\n if (index !== -1) {\n this.listeners.splice(index, 1);\n }\n };\n }\n\n /**\n * Closes the realtime socket, if one was opened.\n *\n * Registered subscribers are left in place: they still receive the events\n * this client produces itself.\n *\n * Disposing is NOT final - a later `subscribe` opens a new socket. React\n * remounts a tree by running an effect's cleanup and then the effect again,\n * on the same client, and `StrictMode` does exactly that on every mount; a\n * terminal flag here would leave those pages without realtime for good, with\n * nothing logged.\n */\n dispose(): void {\n this.teardownRealtime();\n this.jobSocket?.dispose();\n this.jobSocket = undefined;\n }\n\n /**\n * Binds a project's generated SDK to this client's transport and auth.\n *\n * Subgraphs are served next to the reactor's own supergraph, so the endpoint\n * is derived from the client's `url` by appending the name, and the SDK is\n * handed the same auth middleware every reactor call goes through. An app\n * therefore configures one URL and one token provider, and reaches every\n * capability of its Switchboard through this one client.\n *\n * `getSdk` is the function a GraphQL code generator emits for the subgraph's\n * schema - see the README in this folder for the codegen recipe.\n *\n * Transport and typing only. Subgraph results are not cached, produce no\n * change events and never reach `useDocument`.\n */\n subgraph<TSdk>(name: string, getSdk: SubgraphSdkFactory<TSdk>): TSdk {\n return this.subgraphs.get(name, getSdk);\n }\n\n /**\n * Runs a one-off GraphQL document against the Switchboard's own endpoint,\n * through the same transport and auth as everything else.\n *\n * The escape hatch for an operation not worth generating an SDK for. Pass a\n * document a code generator typed and the result type follows; pass a plain\n * `gql` document or a string and name the result type at the call site.\n */\n async request<TResult = unknown, TVariables extends Variables = Variables>(\n document: TypedGraphQLDocument<TResult, TVariables> | string,\n variables?: TVariables,\n options?: GraphQLRequestOptions,\n ): Promise<TResult> {\n const described = describeGraphQLDocument(document);\n return this.sdk.RunDocument<TResult>({\n operationName: options?.operationName ?? described.operationName,\n operationType: options?.operationType ?? described.operationType,\n document,\n variables,\n signal: options?.signal,\n });\n }\n\n /**\n * Shapes a document result page into the reactor's {@link PagedResults}.\n *\n * The items carry the same `PHDocumentFields` fragment as `get`, so the same\n * adapter rebuilds each one. `hasNextPage` gates the cursor exactly as\n * `getOperations` does: no cursor means no `next`.\n */\n private toDocumentResults<TDocument extends PHDocument = PHDocument>(\n page: {\n items: ReadonlyArray<PhDocumentFieldsFragment>;\n hasNextPage: boolean;\n cursor?: string | null;\n },\n effectivePaging: PagingOptions,\n branch: string | undefined,\n next: (cursor: string, limit: number) => Promise<PagedResults<TDocument>>,\n ): PagedResults<TDocument> {\n const nextCursor = page.hasNextPage\n ? (page.cursor ?? undefined)\n : undefined;\n return {\n results: page.items.map((item) =>\n phDocumentFromGetDocument<TDocument>(item, branch),\n ),\n options: effectivePaging,\n nextCursor,\n next: nextCursor\n ? () => next(nextCursor, effectivePaging.limit)\n : undefined,\n };\n }\n\n /**\n * Shapes a relationship-edge result page into the reactor's\n * {@link PagedResults}, restoring each edge's `Date` fields.\n */\n private toRelationshipResults(\n page: {\n items: ReadonlyArray<DocumentRelationshipFieldsFragment>;\n hasNextPage: boolean;\n cursor?: string | null;\n },\n effectivePaging: PagingOptions,\n next: (\n cursor: string,\n limit: number,\n ) => Promise<PagedResults<DocumentRelationship>>,\n ): PagedResults<DocumentRelationship> {\n const nextCursor = page.hasNextPage\n ? (page.cursor ?? undefined)\n : undefined;\n return {\n results: page.items.map((edge) => documentRelationshipFromEdge(edge)),\n options: effectivePaging,\n nextCursor,\n next: nextCursor\n ? () => next(nextCursor, effectivePaging.limit)\n : undefined,\n };\n }\n\n /**\n * The write half's `execute`: signs as the facade's `execute` does, submits\n * through `executeAsync` and returns once the job is accepted. When anyone\n * subscribes, the document is read back once the job is readable and\n * announced as `Updated`, as the facade's `execute` announces it; the handle\n * shares that read with its own `document()`.\n */\n private async submitExecute(\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ): Promise<GraphQLJobWriteHandle> {\n const document = await this.get(documentIdentifier, { branch }, signal);\n return this.submitOnDocument(\n documentIdentifier,\n document,\n branch,\n actions,\n signal,\n );\n }\n\n /**\n * The write half's relationship writes: the source is read for the id the\n * action names and is signed for, and the target is resolved by\n * {@link relationshipTargetId}, as the in-process write client resolves\n * both before it signs.\n */\n private async submitRelationship(\n sourceIdentifier: string,\n targetIdentifier: string,\n branch: string,\n build: (sourceId: string, targetId: string) => Action,\n signal?: AbortSignal,\n ): Promise<GraphQLJobWriteHandle> {\n const source = await this.get(sourceIdentifier, { branch }, signal);\n const targetId = await this.relationshipTargetId(\n targetIdentifier,\n branch,\n signal,\n );\n return this.submitOnDocument(\n source.header.id,\n source,\n branch,\n [build(source.header.id, targetId)],\n signal,\n );\n }\n\n /**\n * The id a relationship's target names: a slug becomes its document's id,\n * and an identifier the Switchboard answers NOT_FOUND for is taken as\n * given, so a document still in flight names itself, as on the in-process\n * write side. Only the `document` scope is read.\n */\n private async relationshipTargetId(\n identifier: string,\n branch: string,\n signal: AbortSignal | undefined,\n ): Promise<string> {\n let result: GetDocumentQuery;\n try {\n result = await this.sdk.GetDocument(\n { idOrSlug: identifier, view: { branch, scopes: [\"document\"] } },\n undefined,\n signal,\n );\n } catch (error) {\n if (answersNotFound(error)) {\n return identifier;\n }\n throw error;\n }\n return result.document?.document.id ?? identifier;\n }\n\n /** Signs `actions` against `document` and submits them through `executeAsync`. */\n private async submitOnDocument(\n documentIdentifier: string,\n document: PHDocument,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ): Promise<GraphQLJobWriteHandle> {\n const preparedActions = await prepareActionsForPush(\n actions,\n document,\n this.documentModels(),\n await this.resolveSigner(),\n signal,\n );\n const result = await this.sdk.MutateDocumentAsync(\n {\n documentIdOrSlug: documentIdentifier,\n actions: preparedActions.map(toTransportAction),\n branch,\n },\n this.driveIdHeaders(\n { method: \"execute\", documentId: documentIdentifier },\n isDrive(document) ? document.header.id : undefined,\n ),\n signal,\n );\n const job = jobInfoFromGql(result.mutateDocumentAsync);\n const handle = new GraphQLJobWriteHandle(\n job,\n document.header.id,\n branch,\n (jobId, stage, stageSignal) =>\n this.waitForStage(jobId, stage, stageSignal),\n this.handleReader(document.header.id),\n signal,\n );\n if (this.listeners.length > 0) {\n void this.announceWrite(handle);\n }\n return handle;\n }\n\n /** The write half's `create`: the synchronous mutation, a settled handle. */\n private async submitCreate(\n document: PHDocument,\n parentIdentifier?: string,\n signal?: AbortSignal,\n ): Promise<WriteHandle> {\n const created = await this.create(document, parentIdentifier, signal);\n return new GraphQLSettledWriteHandle(\n created.header.id,\n created.header.branch || \"main\",\n this.handleReader(created.header.id),\n );\n }\n\n /** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */\n private async submitDeleteDocument(\n identifier: string,\n propagate?: PropagationMode,\n signal?: AbortSignal,\n ): Promise<WriteHandle> {\n await this.deleteDocument(identifier, propagate, signal);\n return new GraphQLSettledWriteHandle(\n identifier,\n \"main\",\n this.handleReader(identifier),\n );\n }\n\n /** Reads a write's document back, bounded by its receipt's token. */\n private handleReader(documentId: string): GraphQLHandleReader {\n return <TDocument extends PHDocument>(\n receipt: WriteReceipt,\n view: ViewFilter | undefined,\n signal: AbortSignal | undefined,\n ) =>\n this.get<TDocument>(\n documentId,\n { ...view, branch: receipt.branch },\n signal,\n receipt.token,\n );\n }\n\n /** Announces a write's document as `Updated` once it is readable. */\n private async announceWrite(handle: GraphQLJobWriteHandle): Promise<void> {\n let document: PHDocument;\n try {\n document = await handle.document();\n } catch (error) {\n logger.warn(\n \"GraphQLReactorClient: could not read @documentId back to announce a write: @error\",\n handle.documentId,\n error,\n );\n return;\n }\n this.emitChange({\n type: DOCUMENT_CHANGE_TYPE.Updated,\n documents: [document],\n });\n }\n\n /**\n * Waits for a job to settle a stage, resolving with a FAILED job too. Polls\n * `jobStatus` with a doubling interval; with realtime on, a `jobChanges`\n * event for the job wakes the wait early and the interval is only a safety\n * net. A failed subscription is logged once and the wait keeps polling.\n */\n private async waitForStage(\n jobId: string,\n stage: GraphQLJobStage,\n signal: AbortSignal | undefined,\n ): Promise<JobInfo> {\n const wakers = new Set<() => void>();\n const stopWatching = this.watchJob(jobId, () => {\n for (const wake of [...wakers]) wake();\n });\n try {\n let interval = STAGE_POLL_START_MS;\n for (;;) {\n const job = await this.getJobStatus(jobId, signal);\n if (settlesGraphQLJobStage(job.status, stage)) {\n return job;\n }\n await sleepUntilWoken(interval, wakers, signal);\n const max =\n stopWatching && !this.jobRealtimeBroken\n ? STAGE_POLL_REALTIME_MAX_MS\n : JOB_POLL_INTERVAL_MS;\n interval = Math.min(interval * 2, max);\n }\n } finally {\n stopWatching?.();\n }\n }\n\n /**\n * Subscribes to one job's `jobChanges` when realtime is on and the\n * subscription has not failed before. Returns the stop function, or\n * undefined when nothing was subscribed.\n */\n private watchJob(\n jobId: string,\n onChange: () => void,\n ): (() => void) | undefined {\n if (!this.subscriptionsUrl || this.jobRealtimeBroken) {\n return undefined;\n }\n this.jobSocket ??= createJobChangesSocket({\n wsUrl: this.subscriptionsUrl,\n connectionParams: makeAuthConnectionParams(this.tokenProvider),\n });\n return this.jobSocket.watch(\n jobId,\n () => onChange(),\n (error) => {\n if (this.jobRealtimeBroken) {\n return;\n }\n this.jobRealtimeBroken = true;\n logger.warn(\n \"GraphQLReactorClient: realtime job changes are unavailable, write handles fall back to polling jobStatus\",\n error,\n );\n },\n );\n }\n\n /**\n * The `document` query with the `consistency` argument, or without it once\n * the Switchboard has refused the argument.\n */\n private async getDocumentAtConsistency(\n identifier: string,\n view: ViewFilterInput | undefined,\n token: ConsistencyToken,\n signal: AbortSignal | undefined,\n ): Promise<GetDocumentAtConsistencyResult> {\n if (!this.consistencyUnsupported) {\n const variables: GetDocumentAtConsistencyVariables = {\n idOrSlug: identifier,\n view,\n consistency: consistencyInputFromToken(token),\n };\n try {\n return await this.sdk.RunDocument<GetDocumentAtConsistencyResult>({\n operationName: \"GetDocumentAtConsistency\",\n operationType: \"query\",\n document: GetDocumentAtConsistencyDocument,\n variables,\n signal,\n });\n } catch (error) {\n if (!refusesConsistencyArgument(error)) {\n throw error;\n }\n this.consistencyUnsupported = true;\n }\n }\n return this.sdk.GetDocument(\n { idOrSlug: identifier, view },\n undefined,\n signal,\n );\n }\n\n /**\n * Opens the realtime socket on the first subscriber.\n *\n * The subscription is a firehose - no `search` argument - and this client\n * applies each subscriber's own filter on the way out, exactly as it does for\n * its own emissions.\n */\n private startRealtime(): void {\n if (!this.subscriptionsUrl || this.realtimeStarted) {\n return;\n }\n\n this.realtimeStarted = true;\n const generation = this.realtimeGeneration;\n const stop = startDocumentChangesSubscription({\n wsUrl: this.subscriptionsUrl,\n connectionParams: makeAuthConnectionParams(this.tokenProvider),\n onEvent: (event) => this.emitServerEvent(event),\n onError: (error) => this.handleRealtimeFailure(generation, error),\n });\n\n if (this.realtimeGeneration !== generation) {\n // The socket failed while it was being opened, so the failure was handled\n // before this stop function existed. Close what it holds.\n stop();\n return;\n }\n this.stopRealtime = stop;\n }\n\n /**\n * Gives up on a failed socket so that a later subscriber can try again.\n *\n * `graphql-ws` retries on its own and only reports here once it has given up,\n * or once the Switchboard refused the credentials the socket carried - which\n * `shouldRetry` declines to retry at all. Keeping the dead stop function\n * would make every later `subscribe` a no-op, so realtime would stay off for\n * the life of the page even after the user signs in.\n *\n * Why it died is recorded: a refusal is undone by a credential change and\n * nothing else, and {@link notifyCredentialsChanged} acts only on that.\n *\n * The generation stamp discards a report from a socket that has already been\n * replaced or disposed.\n */\n private handleRealtimeFailure(generation: number, error: unknown): void {\n if (generation !== this.realtimeGeneration) {\n return;\n }\n this.teardownRealtime();\n this.realtimeRefusedCredentials = isAuthRefusalClose(error);\n this.logRealtimeError(error);\n }\n\n /**\n * Reopens realtime after a sign-in, a sign-out or a token swap.\n *\n * Call it whenever the credentials this client authenticates with change.\n *\n * A live socket is replaced. `connectionParams` are resolved once, when the\n * socket opens, so a socket keeps presenting the credentials it was opened\n * with until something closes it - and a sign-out closes nothing. That left\n * a signed-out tab still receiving the previous identity's document changes,\n * on a shared machine, for as long as the socket happened to survive.\n *\n * A refused socket is reopened, for the same reason from the other side:\n * otherwise it stays closed until an unrelated component happens to\n * `subscribe`, so signing in leaves realtime off with nothing said - the\n * state `handleRealtimeFailure` resets to avoid.\n *\n * A socket that died for any other reason is left alone: a network failure\n * is not something a new token fixes, and reopening one here would turn a\n * credential change into a reconnect loop.\n */\n notifyCredentialsChanged(): void {\n if (!this.realtimeStarted && !this.realtimeRefusedCredentials) {\n return;\n }\n // Drops the old socket, and with it the old credentials, before any new\n // one opens. `teardownRealtime` clears the refusal flag too.\n this.teardownRealtime();\n if (this.listeners.length === 0) {\n // Nobody to deliver to. The next `subscribe` opens a socket anyway.\n return;\n }\n this.startRealtime();\n }\n\n /** Closes the socket and lets a later subscriber open a new one. */\n private teardownRealtime(): void {\n this.realtimeGeneration += 1;\n this.realtimeStarted = false;\n this.realtimeRefusedCredentials = false;\n this.stopRealtime?.();\n this.stopRealtime = undefined;\n }\n\n /** Maps a server event onto the client-side event and emits it. */\n private emitServerEvent(event: DocumentChangesEventPayload): void {\n this.emitChange({\n type: documentChangeTypes[event.type],\n // The subscription carries no branch, so the documents are read as being\n // on the server's default branch - which is the only branch the\n // Switchboard pushes changes for today.\n documents: event.documents.map((document) =>\n phDocumentFromGetDocument(document),\n ),\n context: event.context\n ? {\n parentId: event.context.parentId ?? undefined,\n childId: event.context.childId ?? undefined,\n }\n : undefined,\n });\n }\n\n /**\n * Reports a broken realtime socket once per client, however many sockets it\n * goes through.\n *\n * `graphql-ws` retries on its own, and a Switchboard without a websocket\n * endpoint would otherwise fill the console for as long as the page is open.\n */\n private logRealtimeError(error: unknown): void {\n if (this.realtimeErrorLogged) {\n return;\n }\n this.realtimeErrorLogged = true;\n logger.warn(\n \"GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events\",\n error,\n );\n }\n\n /**\n * Delivers an event to every matching subscriber.\n *\n * A subscriber that throws is logged and skipped so one bad listener cannot\n * stop the others from being notified.\n */\n private emitChange(event: DocumentChangeEvent): void {\n for (const listener of [...this.listeners]) {\n if (!eventMatchesSearch(event, listener.search)) {\n continue;\n }\n\n try {\n listener.callback(event);\n } catch (error) {\n logger.error(\n \"GraphQLReactorClient: a document change subscriber threw\",\n error,\n );\n }\n }\n }\n}\n\n/**\n * The read half of {@link GraphQLReactorClient}: every read is the client's\n * own, and nothing that writes is reachable from it.\n */\nclass GraphQLReadHalf implements GraphQLReactorReadClient {\n readonly drives: IDriveReadClient;\n\n constructor(\n private readonly client: GraphQLReactorClient,\n nodes: IDriveNodeSource,\n ) {\n this.drives = new GraphQLDriveReadClient(nodes);\n }\n\n get<TDocument extends PHDocument>(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ): Promise<TDocument> {\n return this.client.get<TDocument>(\n identifier,\n view,\n signal,\n consistencyToken,\n );\n }\n\n getMany<TDocument extends PHDocument>(\n documentIds: string[],\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ): Promise<TDocument[]> {\n return this.client.getMany<TDocument>(\n documentIds,\n view,\n signal,\n consistencyToken,\n );\n }\n\n find(\n search: SearchFilter,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n return this.client.find(search, view, paging, signal);\n }\n\n getOperations(\n documentIdentifier: string,\n view?: ViewFilter,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n return this.client.getOperations(\n documentIdentifier,\n view,\n filter,\n paging,\n signal,\n );\n }\n\n subscribe(\n search: SearchFilter,\n callback: (event: DocumentChangeEvent) => void,\n view?: ViewFilter,\n ): () => void {\n return this.client.subscribe(search, callback, view);\n }\n\n waitForJob(jobId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo> {\n return this.client.waitForJob(jobId, signal);\n }\n\n getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo> {\n return this.client.getJobStatus(jobId, signal);\n }\n}\n\n/**\n * Sleeps for `ms`, or less when a waker in `wakers` fires first. Each sleep\n * adds its own waker and removes it when it ends.\n */\nfunction sleepUntilWoken(\n ms: number,\n wakers: Set<() => void>,\n signal: AbortSignal | undefined,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n const finish = () => {\n clearTimeout(timer);\n wakers.delete(finish);\n signal?.removeEventListener(\"abort\", onAbort);\n };\n const wake = () => {\n finish();\n resolve();\n };\n const onAbort = () => {\n finish();\n if (signal) reject(abortReason(signal));\n };\n const timer = setTimeout(wake, ms);\n wakers.add(wake);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/**\n * Whether a request failed because the Switchboard's `document` query has no\n * `consistency` argument, or its schema no `ConsistencyTokenInput`.\n */\n/** The most ids one `getMany` request reads. */\nconst GET_MANY_CHUNK_SIZE = 50;\n\nconst PH_DOCUMENT_FIELDS_SOURCE = print(PhDocumentFieldsFragmentDoc);\n\nfunction consistencyInputFromToken(\n token: ConsistencyToken,\n): GetDocumentAtConsistencyVariables[\"consistency\"] {\n return {\n version: token.version,\n createdAtUtcIso: token.createdAtUtcIso,\n coordinates: token.coordinates.map((coordinate) => ({\n documentId: coordinate.documentId,\n scope: coordinate.scope,\n branch: coordinate.branch,\n operationIndex: coordinate.operationIndex,\n })),\n };\n}\n\nfunction refusesConsistencyArgument(error: unknown): boolean {\n const errors = (error as { response?: { errors?: unknown } } | null)?.response\n ?.errors;\n if (!Array.isArray(errors)) {\n return false;\n }\n return errors.some((entry) => {\n const message = (entry as { message?: unknown } | null)?.message;\n return (\n typeof message === \"string\" &&\n (message.includes('\"consistency\"') ||\n message.includes('\"ConsistencyTokenInput\"'))\n );\n });\n}\n\n/** Whether the Switchboard refused a read because the document does not exist. */\nfunction answersNotFound(error: unknown): boolean {\n const errors = (error as { response?: { errors?: unknown } } | null)?.response\n ?.errors;\n if (!Array.isArray(errors)) {\n return false;\n }\n return errors.some(\n (entry) =>\n (entry as { extensions?: { code?: unknown } } | null)?.extensions\n ?.code === \"NOT_FOUND\",\n );\n}\n\n/** {@link GraphQLReactorClient.nodeSource}, as a function. */\nexport function createGraphQLDriveNodeSource(\n client: GraphQLReactorClient,\n): IDriveNodeSource {\n return client.nodeSource();\n}\n\n/**\n * Whether a value is a {@link GraphQLReactorClient}, including one built by\n * another copy of this module.\n *\n * Use this rather than `instanceof`: the brand it tests for is shared by every\n * copy of the class, so a client built by a hot-replaced module or by a package\n * that bundled its own copy is still recognised.\n */\nexport function isGraphQLReactorClient(\n client: unknown,\n): client is GraphQLReactorClient {\n return (\n (client as Partial<GraphQLReactorClient> | null | undefined)?.[\n graphQLReactorClientBrand\n ] === true\n );\n}\n\n/** The schema's change types, mapped onto the reactor's. */\nconst documentChangeTypes: Record<GqlDocumentChangeType, DocumentChangeType> = {\n [GqlDocumentChangeType.Created]: DOCUMENT_CHANGE_TYPE.Created,\n [GqlDocumentChangeType.Deleted]: DOCUMENT_CHANGE_TYPE.Deleted,\n [GqlDocumentChangeType.Updated]: DOCUMENT_CHANGE_TYPE.Updated,\n [GqlDocumentChangeType.ParentAdded]: DOCUMENT_CHANGE_TYPE.ParentAdded,\n [GqlDocumentChangeType.ParentRemoved]: DOCUMENT_CHANGE_TYPE.ParentRemoved,\n [GqlDocumentChangeType.ChildAdded]: DOCUMENT_CHANGE_TYPE.ChildAdded,\n [GqlDocumentChangeType.ChildRemoved]: DOCUMENT_CHANGE_TYPE.ChildRemoved,\n};\n\n/**\n * Decides whether an event reaches a subscriber.\n *\n * Every populated field of the search filter is an AND condition, matching the\n * reactor's own subscription manager - which also treats an empty array as a\n * filter that nothing satisfies. `parentId` is a drive concept and is ignored.\n *\n * A `Deleted` event carries no documents, so it is matched on its\n * `context.childId` for identifier filters and delivered unconditionally to\n * type and slug filters: there is no document left to check them against.\n */\nfunction eventMatchesSearch(\n event: DocumentChangeEvent,\n search: SearchFilter,\n): boolean {\n const deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;\n const { ids, slugs, type } = search;\n\n if (ids) {\n const eventIds = deleted\n ? [event.context?.childId]\n : event.documents.map((document) => document.header.id);\n if (!eventIds.some((id) => id !== undefined && ids.includes(id))) {\n return false;\n }\n }\n\n if (slugs && !deleted) {\n const eventSlugs = event.documents.map((document) => document.header.slug);\n if (!eventSlugs.some((slug) => slugs.includes(slug))) {\n return false;\n }\n }\n\n if (type && !deleted) {\n const eventTypes = event.documents.map(\n (document) => document.header.documentType,\n );\n if (!eventTypes.includes(type)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.\n *\n * Point-in-time reads are rejected: the Switchboard read API has no revision\n * argument, so silently returning the head state would be wrong.\n */\nexport function viewFilterInputFromViewFilter(\n view?: ViewFilter,\n): ViewFilterInput | undefined {\n if (!view) {\n return undefined;\n }\n\n if (viewIsPointInTime(view)) {\n throw new GraphQLOperationNotSupportedError(\n \"view\",\n \"point-in-time views are not supported by GraphQLReactorClient\",\n );\n }\n\n if (view.branch === undefined && view.scopes === undefined) {\n return undefined;\n }\n\n return { branch: view.branch, scopes: view.scopes };\n}\n\nfunction pagingInputFromPaging(\n paging?: PagingOptions,\n): PagingInput | undefined {\n if (!paging) {\n return undefined;\n }\n return { cursor: paging.cursor, limit: paging.limit };\n}\n\n/**\n * Whether a search names `ids` or `slugs`, which the Switchboard `findDocuments`\n * query cannot honour (it filters by `type` and `parentId`).\n *\n * The test is PRESENCE, not length: the reactor `find` contract\n * (`packages/reactor/src/core/reactor.ts`) dispatches on `search.ids` /\n * `search.slugs` being present, so `find({ ids: [] })` is an identifier search\n * that must yield the empty set -- not a plain type query over every document.\n * The GraphQL surface cannot express an identifier search at all, so a present\n * (even empty) `ids`/`slugs` is refused rather than served as the wrong query.\n */\nfunction searchNamesIdentifiers(search: SearchFilter): boolean {\n return search.ids !== undefined || search.slugs !== undefined;\n}\n\n/** Whether a view asks for a point-in-time read the GraphQL surface cannot express. */\nfunction viewIsPointInTime(view?: ViewFilter): boolean {\n return view?.revision !== undefined;\n}\n\n/**\n * The single source of truth for whether the Switchboard `findDocuments` query\n * can serve a `find`. It is servable iff the search names neither `ids` nor\n * `slugs` (present, regardless of length) AND the view is not point-in-time:\n * each is a by-contract limitation of a surface that filters only by\n * `type`/`parentId` at head. Exported so a caller can route around an\n * unservable search instead of catching the error `find` throws for it.\n */\nexport function findIsServableOverGraphQL(\n search: SearchFilter,\n view?: ViewFilter,\n): boolean {\n return !searchNamesIdentifiers(search) && !viewIsPointInTime(view);\n}\n\n/** Rebuilds a relationship edge from its GraphQL fields. */\nfunction documentRelationshipFromEdge(\n edge: DocumentRelationshipFieldsFragment,\n): DocumentRelationship {\n const relationship: DocumentRelationship = {\n sourceId: edge.sourceId,\n targetId: edge.targetId,\n relationshipType: edge.relationshipType,\n createdAt: dateFromDateTime(edge.createdAt),\n updatedAt: dateFromDateTime(edge.updatedAt),\n };\n const metadata = edge.metadata;\n if (isPlainObject(metadata)) {\n relationship.metadata = metadata;\n }\n return relationship;\n}\n\n/**\n * Restores a `Date` from the `DateTime` scalar, which deserializes as either an\n * ISO string or a `Date`, reusing the get-path's {@link isoStringFromDateTime}.\n *\n * A null, absent or unparseable value is a malformed timestamp from the server,\n * not something to coerce to the epoch or an `Invalid Date`: it throws, so the\n * malformed edge surfaces as a genuine failure rather than a silently-wrong\n * `DocumentRelationship`.\n */\nfunction dateFromDateTime(value: string | Date | null | undefined): Date {\n if (value === null || value === undefined) {\n throw new Error(\n \"relationship edge is missing a required DateTime timestamp\",\n );\n }\n const date = new Date(isoStringFromDateTime(value));\n if (Number.isNaN(date.getTime())) {\n throw new Error(\n `relationship edge carries an unparseable DateTime timestamp: ${String(value)}`,\n );\n }\n return date;\n}\n\n/**\n * Whether a JSON value is a plain object, so relationship `metadata` is assigned\n * only when it is one. A non-object JSON scalar (string, number, array, null)\n * is dropped exactly as a null is, rather than cast to `Record` and trusted.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The reactor and the GraphQL schema disagree on the enum: the reactor's\n * `None` is the schema's `ORPHAN`. This is the inverse of the server's\n * `toReactorPropagationMode`.\n */\nconst propagationModeInputs: Record<PropagationMode, GqlPropagationMode> = {\n cascade: GqlPropagationMode.Cascade,\n none: GqlPropagationMode.Orphan,\n};\n\nfunction propagationModeInput(\n propagate?: PropagationMode,\n): GqlPropagationMode | undefined {\n return propagate === undefined ? undefined : propagationModeInputs[propagate];\n}\n\n/**\n * Stamps and signs the actions about to be pushed.\n *\n * With no signer the actions go out exactly as given, batch or not - this\n * client does not require signatures. With one, every action is signed:\n * {@link prepareSignedActions} predicts the chain a batch will produce by\n * running the document's own reducer between signatures, which is why a batch\n * needs the module matching the document's type and exact version.\n *\n * A batch that cannot be predicted - no matching module, mixed scopes, an\n * action needing history - throws here, before the mutation. Sending it\n * unsigned instead would silently drop the signatures the caller asked for.\n */\nasync function prepareActionsForPush(\n actions: Action[],\n document: PHDocument,\n documentModels: readonly DocumentModelModule<any>[],\n signer: ISigner | undefined,\n signal?: AbortSignal,\n): Promise<Action[]> {\n if (!signer || actions.length === 0) {\n return actions;\n }\n\n // Only a batch needs the reducer, and it needs the EXACT one the document was\n // written with - the same rule the server applies in `SimpleJobExecutor`.\n const module =\n actions.length > 1\n ? resolveDocumentModelModule(\n documentModels,\n document.header.documentType,\n documentModelVersion(document),\n )\n : undefined;\n\n return prepareSignedActions(actions, document, signer, module, signal);\n}\n\n/**\n * The document-model version the document's actions must be reduced with.\n *\n * `state` arrives as JSON over GraphQL, so its `document` scope is only as\n * reliable as the server that sent it - one written before that scope existed\n * carries no version at all. `normalizeDocumentModelVersion` maps that, and 0,\n * to 1: the same rule `SimpleJobExecutor` applies before asking the registry\n * for a module, so client and server cannot resolve different reducers.\n */\nfunction documentModelVersion(document: PHDocument): number {\n const documentScope = document.state.document as PHDocumentState | undefined;\n return normalizeDocumentModelVersion(documentScope?.version);\n}\n\n/**\n * Rebuilds a reactor {@link JobInfo} from what the server reported. An unknown\n * job arrives as the reactor's own: FAILED with an empty `documentId`.\n */\nfunction jobInfoFromGql(job: JobInfoFieldsFragment): JobInfo {\n const token = job.consistencyToken;\n if (token.version !== 1) {\n throw new Error(\n `Job ${job.id} carries consistency token version ${token.version}, which this client cannot read`,\n );\n }\n const info: JobInfo = {\n id: job.id,\n documentId: job.documentId,\n status: job.status as JobStatus,\n createdAtUtcIso: isoStringFromDateTime(job.createdAt),\n consistencyToken: {\n version: 1,\n createdAtUtcIso: token.createdAtUtcIso,\n coordinates: token.coordinates.map((coordinate) => ({ ...coordinate })),\n },\n meta: {\n batchId: job.meta.batchId,\n batchJobIds: [...job.meta.batchJobIds],\n },\n };\n if (job.completedAt != null) {\n info.completedAtUtcIso = isoStringFromDateTime(job.completedAt);\n }\n if (job.result != null) {\n info.result = job.result as JobResultSummary;\n }\n if (job.error != null) {\n // The server keeps stacks to itself; a message always comes with its name.\n info.error = {\n name: job.errorName ?? \"Error\",\n message: job.error,\n stack: \"\",\n };\n }\n return info;\n}\n\n/**\n * The header a Switchboard's drive middleware and load balancer key on. A\n * request carries it only when it is known to belong to that one drive: the\n * server answers any drive it does not own with 421.\n */\nconst DRIVE_ID_HEADER = \"Drive-Id\";\n\nfunction driveIdHeaders(driveId: string): Record<string, string> | undefined {\n return driveId === \"\" ? undefined : { [DRIVE_ID_HEADER]: driveId };\n}\n\nfunction isDrive(document: PHDocument): boolean {\n return isDriveType(document.header.documentType);\n}\n\nfunction isDriveType(documentType: string): boolean {\n return (DRIVE_DOCUMENT_TYPES as readonly string[]).includes(documentType);\n}\n\n/**\n * Surfaces a 421 from the Switchboard's drive middleware, which graphql-request\n * reports as a `ClientError`, as {@link GraphQLWrongBackendError}.\n */\nfunction withWrongBackendErrors(\n middleware: SdkFunctionWrapper,\n): SdkFunctionWrapper {\n return async (action, ...rest) => {\n try {\n return await middleware(action, ...rest);\n } catch (error) {\n throw wrongBackendErrorOf(error) ?? error;\n }\n };\n}\n\nfunction wrongBackendErrorOf(\n error: unknown,\n): GraphQLWrongBackendError | undefined {\n const response = (\n error as {\n response?: { status?: unknown; body?: unknown; [key: string]: unknown };\n } | null\n )?.response;\n if (response?.status !== 421) {\n return undefined;\n }\n let payload: unknown = response.body;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n // Not JSON: kept as the text the server sent.\n }\n }\n const driveId = (payload as { driveId?: unknown } | null)?.driveId;\n return new GraphQLWrongBackendError(\n typeof driveId === \"string\" ? driveId : \"\",\n payload,\n { cause: error },\n );\n}\n\nfunction isSettled(job: JobInfo): boolean {\n const status: string = job.status;\n return status === \"READ_READY\" || status === \"FAILED\";\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n const reason: unknown = signal.reason;\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n if (signal) reject(abortReason(signal));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/** As the reactor's `signAction` reads it: the last tuple names a key. */\nfunction isActionSigned(action: Action): boolean {\n const signer = action.context?.signer;\n return Boolean(signer?.app?.key && signer.signatures.at(-1)?.[1]);\n}\n\n/**\n * The logged-in Renown user's signer, read per call; none when nobody is.\n * Nobody logged in, the signer is asked to sign someone in first (hosted\n * Connect's browser pseudonym).\n */\nexport async function ambientRenownSigner(): Promise<ISigner | undefined> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n const renown = getPHStore()?.renown;\n if (!renown) return undefined;\n const signer = renown.signer as ISigner & {\n ensureUser?: () => Promise<void>;\n };\n if (!renown.user && signer.ensureUser) {\n await signer.ensureUser().catch(() => undefined);\n }\n return renown.user ? renown.signer : undefined;\n}\n\n/**\n * The revision the pushed operations start from: the lowest head revision\n * across the scopes the actions target.\n *\n * The baseline is only meaningful together with {@link scopesForActions}: a\n * batch that touches a scope at revision 1 and one at revision 5000 would\n * otherwise re-download the whole history of every scope of the document.\n */\nfunction sinceRevisionForActions(\n document: PHDocument,\n actions: Action[],\n): number {\n const revisions = actions.map(\n (action) => document.header.revision[action.scope] ?? 0,\n );\n return revisions.length > 0 ? Math.min(...revisions) : 0;\n}\n\n/** The distinct scopes the pushed actions target, in first-seen order. */\nfunction scopesForActions(actions: Action[]): string[] | undefined {\n if (actions.length === 0) {\n return undefined;\n }\n return [...new Set(actions.map((action) => action.scope))];\n}\n","import type {\n BackendAuthState,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst backendAuthEventFunctions = makePHEventFunctions(\"backendAuth\");\n\n/** Whether the app's backend refused this tab's caller, and how. */\nexport const useBackendAuth: UsePHGlobalValue<BackendAuthState> =\n backendAuthEventFunctions.useValue;\n\n/** Records (or clears, with `undefined`) a backend's refusal of the caller. */\nexport const setBackendAuth: SetPHGlobalValue<BackendAuthState> =\n backendAuthEventFunctions.setValue;\n\nexport const addBackendAuthEventHandler =\n backendAuthEventFunctions.addEventHandler;\n\nconst STATUS_IN_MESSAGE = /\\(Code: (401|403)\\)/;\n\n/**\n * The messages a Switchboard's GraphQL layer refuses with, without an HTTP\n * status (the sync layer's `DRIVE_AUTH_ERROR_MESSAGES`). Inlined: this file\n * is reachable from the browser entry, which must not import the reactor\n * package as a value.\n */\nconst GRAPHQL_REFUSALS = [\n \"Forbidden: insufficient permissions\",\n \"Forbidden: authentication required\",\n \"Authentication required\",\n] as const;\n\n/**\n * The HTTP status with which a backend refused the caller, or null when the\n * error is something else.\n *\n * Covers every shape a refusal reaches the browser in: the sync layer's\n * errors (`isDriveAuthError`), graphql-request's `ClientError` from the\n * remote GraphQL client (`response.status`, and \"(Code: 401)\" in its\n * message), and the router's partial-failure error that wraps one such\n * failure per backend.\n */\nexport function backendAuthStatusOf(error: unknown): 401 | 403 | null {\n if (!error || typeof error !== \"object\") return null;\n const e = error as {\n response?: { status?: unknown };\n statusCode?: unknown;\n message?: unknown;\n failures?: unknown;\n };\n const direct = [e.response?.status, e.statusCode].find(\n (s) => s === 401 || s === 403,\n );\n if (direct === 401 || direct === 403) return direct;\n if (typeof e.message === \"string\") {\n const m = STATUS_IN_MESSAGE.exec(e.message);\n if (m) return m[1] === \"401\" ? 401 : 403;\n }\n if (Array.isArray(e.failures)) {\n for (const failure of e.failures as { error?: unknown }[]) {\n const status = backendAuthStatusOf(failure.error);\n if (status) return status;\n }\n }\n // A Forbidden/authentication GraphQL error without a status.\n if (\n typeof e.message === \"string\" &&\n GRAPHQL_REFUSALS.some((m) => (e.message as string).includes(m))\n ) {\n return /authentication required/i.test(e.message) ? 401 : 403;\n }\n return null;\n}\n\n/** True when a backend refused the caller as unauthenticated or unauthorized. */\nexport function isBackendAuthError(error: unknown): boolean {\n return backendAuthStatusOf(error) !== null;\n}\n\n/** Records the refusal `error` carries, if it is one; returns whether it was. */\nexport function recordBackendAuthError(\n error: unknown,\n backend?: string,\n): boolean {\n const status = backendAuthStatusOf(error);\n if (status === null) return false;\n setBackendAuth({\n requiresAuth: true,\n status,\n backend,\n at: new Date().toISOString(),\n });\n return true;\n}\n","import type {\n PHAppConfigHooks,\n PHAppConfigSetters,\n PHDocumentEditorConfigHooks,\n PHDocumentEditorConfigSetters,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\n\nexport const isExternalControlsEnabledEventFunctions = makePHEventFunctions(\n \"isExternalControlsEnabled\",\n);\n\n/** Sets whether external controls are enabled for a given editor. */\nexport const setIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.setValue;\n\n/** Gets whether external controls are enabled for a given editor. */\nexport const useIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the external controls enabled state changes. */\nexport const addIsExternalControlsEnabledEventHandler =\n isExternalControlsEnabledEventFunctions.addEventHandler;\n\nconst isDragAndDropEnabledEventFunctions = makePHEventFunctions(\n \"isDragAndDropEnabled\",\n);\n\n/** Sets whether drag and drop is enabled for a given app. */\nexport const setIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.setValue;\n\n/** Gets whether drag and drop is enabled for a given app. */\nexport const useIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the drag and drop enabled state changes. */\nexport const addIsDragAndDropEnabledEventHandler =\n isDragAndDropEnabledEventFunctions.addEventHandler;\n\nconst allowedDocumentTypesEventFunctions = makePHEventFunctions(\n \"allowedDocumentTypes\",\n);\n\n/** Sets the allowed document types for a given app. */\nexport const setAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.setValue;\n\n/** Defines the document types a drive supports.\n *\n * Unset or empty, it means every document type registered in the reactor.\n */\nexport function useAllowedDocumentTypes() {\n const definedAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.useValue();\n return definedAllowedDocumentTypes;\n}\n\n/** Adds an event handler for when the allowed document types for a given app changes. */\nexport const addAllowedDocumentTypesEventHandler =\n allowedDocumentTypesEventFunctions.addEventHandler;\n\nexport const phAppConfigSetters: PHAppConfigSetters = {\n allowedDocumentTypes: setAllowedDocumentTypes,\n isDragAndDropEnabled: setIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigSetters: PHDocumentEditorConfigSetters = {\n isExternalControlsEnabled: setIsExternalControlsEnabled,\n};\n\nexport const phAppConfigHooks: PHAppConfigHooks = {\n allowedDocumentTypes: useAllowedDocumentTypes,\n isDragAndDropEnabled: useIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigHooks: PHDocumentEditorConfigHooks = {\n isExternalControlsEnabled: useIsExternalControlsEnabled,\n};\n","import type {\n PHAppConfigKey,\n PHDocumentEditorConfigKey,\n PHGlobalConfigHooks,\n PHGlobalConfigHooksForKey,\n PHGlobalConfigKey,\n PHGlobalConfigSetters,\n PHGlobalConfigSettersForKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\nimport {\n phAppConfigHooks,\n phAppConfigSetters,\n phDocumentEditorConfigHooks,\n phDocumentEditorConfigSetters,\n} from \"./editor.js\";\n\nexport const {\n useValue: useRouterBasename,\n setValue: setRouterBasename,\n addEventHandler: addRouterBasenameEventHandler,\n} = makePHEventFunctions(\"routerBasename\");\n\nexport const {\n useValue: useWarnOutdatedApp,\n setValue: setWarnOutdatedApp,\n addEventHandler: addWarnOutdatedAppEventHandler,\n} = makePHEventFunctions(\"warnOutdatedApp\");\n\nexport const {\n useValue: useStudioMode,\n setValue: setStudioMode,\n addEventHandler: addStudioModeEventHandler,\n} = makePHEventFunctions(\"studioMode\");\n\nexport const {\n useValue: useBasePath,\n setValue: setBasePath,\n addEventHandler: addBasePathEventHandler,\n} = makePHEventFunctions(\"basePath\");\n\nexport const {\n useValue: useDefaultDrivesUrl,\n setValue: setDefaultDrivesUrl,\n addEventHandler: addDefaultDrivesUrlEventHandler,\n} = makePHEventFunctions(\"defaultDrivesUrl\");\n\nexport const {\n useValue: useIsAddDriveEnabled,\n setValue: setIsAddDriveEnabled,\n addEventHandler: addIsAddDriveEnabledEventHandler,\n} = makePHEventFunctions(\"isAddDriveEnabled\");\n\nexport const {\n useValue: useRenownUrl,\n setValue: setRenownUrl,\n addEventHandler: addRenownUrlEventHandler,\n} = makePHEventFunctions(\"renownUrl\");\n\nexport const {\n useValue: useSwitchboardUrl,\n setValue: setSwitchboardUrl,\n addEventHandler: addSwitchboardUrlEventHandler,\n} = makePHEventFunctions(\"switchboardUrl\");\n\nconst disabledEditorsEventFunctions = makePHEventFunctions(\"disabledEditors\");\n\n/** Sets the disabled editors for Connect. */\nexport const setDisabledEditors = disabledEditorsEventFunctions.setValue;\n\n/** Gets the disabled editors for Connect. */\nexport const useDisabledEditors = disabledEditorsEventFunctions.useValue;\n\n/** Adds an event handler for when the disabled editors for Connect changes. */\nexport const addDisabledEditorsEventHandler =\n disabledEditorsEventFunctions.addEventHandler;\n\nconst logLevelEventFunctions = makePHEventFunctions(\"logLevel\");\n\n/** Sets the log level for Connect. */\nexport const setLogLevel = logLevelEventFunctions.setValue;\n\n/** Gets the log level for Connect. */\nexport const useLogLevel = logLevelEventFunctions.useValue;\n\n/** Adds an event handler for when the log level for Connect changes. */\nexport const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;\n\nconst allowListEventFunctions = makePHEventFunctions(\"allowList\");\n\n/** Sets the allow list for Connect. */\nexport const setAllowList = allowListEventFunctions.setValue;\n\n/** Gets the allow list for Connect. */\nexport const useAllowList = allowListEventFunctions.useValue;\n\n/** Adds an event handler for when the allow list for Connect changes. */\nexport const addAllowListEventHandler = allowListEventFunctions.addEventHandler;\n\ntype NonUserConfigKey = Exclude<\n PHGlobalConfigKey,\n PHAppConfigKey | PHDocumentEditorConfigKey\n>;\ntype NonUserConfigSetters = PHGlobalConfigSettersForKey<NonUserConfigKey>;\ntype NonUserConfigHooks = PHGlobalConfigHooksForKey<NonUserConfigKey>;\n\nconst nonUserConfigSetters: NonUserConfigSetters = {\n routerBasename: setRouterBasename,\n warnOutdatedApp: setWarnOutdatedApp,\n studioMode: setStudioMode,\n basePath: setBasePath,\n defaultDrivesUrl: setDefaultDrivesUrl,\n isAddDriveEnabled: setIsAddDriveEnabled,\n renownUrl: setRenownUrl,\n switchboardUrl: setSwitchboardUrl,\n allowList: setAllowList,\n logLevel: setLogLevel,\n disabledEditors: setDisabledEditors,\n};\n\nexport const phGlobalConfigSetters: PHGlobalConfigSetters = {\n ...phAppConfigSetters,\n ...phDocumentEditorConfigSetters,\n ...nonUserConfigSetters,\n};\n\nconst nonUserConfigHooks: NonUserConfigHooks = {\n routerBasename: useRouterBasename,\n warnOutdatedApp: useWarnOutdatedApp,\n studioMode: useStudioMode,\n basePath: useBasePath,\n defaultDrivesUrl: useDefaultDrivesUrl,\n isAddDriveEnabled: useIsAddDriveEnabled,\n renownUrl: useRenownUrl,\n switchboardUrl: useSwitchboardUrl,\n allowList: useAllowList,\n logLevel: useLogLevel,\n disabledEditors: useDisabledEditors,\n};\n\nexport const phGlobalConfigHooks: PHGlobalConfigHooks = {\n ...phAppConfigHooks,\n ...phDocumentEditorConfigHooks,\n ...nonUserConfigHooks,\n};\n","import type { IAttachmentService } from \"@powerhousedao/reactor-attachments/client\";\nimport type {\n AddPHGlobalEventHandler,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst attachmentServiceEventFunctions =\n makePHEventFunctions(\"attachmentService\");\n\n/** Returns the attachment service from window.ph */\nexport const useAttachmentService: UsePHGlobalValue<IAttachmentService> =\n attachmentServiceEventFunctions.useValue;\n\n/** Sets the attachment service on window.ph */\nexport const setAttachmentService: SetPHGlobalValue<IAttachmentService> =\n attachmentServiceEventFunctions.setValue;\n\n/** Registers the attachmentService window event handler */\nexport const addAttachmentServiceEventHandler: AddPHGlobalEventHandler =\n attachmentServiceEventFunctions.addEventHandler;\n","import type {\n AddPHGlobalEventHandler,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst featuresEventFunctions = makePHEventFunctions(\"features\");\n\nexport const useFeatures: UsePHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.useValue;\n\nexport const setFeatures: SetPHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.setValue;\n\nexport const addFeaturesEventHandler: AddPHGlobalEventHandler =\n featuresEventFunctions.addEventHandler;\n","import { useState } from \"react\";\nimport { funnel } from \"remeda\";\nimport { useIsDragAndDropEnabled } from \"./config/editor.js\";\n\nexport function useDropTarget() {\n const [isDropTarget, setIsDropTarget] = useState(false);\n const isDragAndDropEnabled = useIsDragAndDropEnabled();\n\n const targetSetter = funnel(() => setIsDropTarget(true), {\n triggerAt: \"start\",\n minQuietPeriodMs: 100,\n });\n\n const targetUnsetter = funnel(() => setIsDropTarget(false), {\n triggerAt: \"start\",\n minQuietPeriodMs: 100,\n });\n\n function setTarget() {\n if (!isDragAndDropEnabled) return;\n targetUnsetter.cancel();\n targetSetter.call();\n }\n\n function unsetTarget() {\n if (!isDragAndDropEnabled) return;\n targetSetter.cancel();\n targetUnsetter.call();\n }\n\n return {\n isDropTarget,\n setTarget,\n unsetTarget,\n };\n}\n","import { type DragEventHandler } from \"react\";\nimport {\n allPass,\n conditional,\n constant,\n funnel,\n isDefined,\n isNot,\n isStrictEqual,\n isString,\n isTruthy,\n once,\n} from \"remeda\";\nimport { moveNodeById } from \"../actions/document.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\nimport { useDropTarget } from \"./use-drop-target.js\";\nexport type DraggingNode = {\n srcId: string;\n parentId: string | null | undefined;\n};\n\nconst draggingNodeEventFunctions = makePHEventFunctions(\"draggingNode\");\nconst useDraggingNode = draggingNodeEventFunctions.useValue;\nconst setDraggingNode = draggingNodeEventFunctions.setValue;\nexport const addDraggingNodeEventHandler =\n draggingNodeEventFunctions.addEventHandler;\n\nconst draggingNodeSetter = funnel(\n (node: DraggingNode) => setDraggingNode(node),\n {\n reducer: (_, newNode: DraggingNode) => newNode,\n triggerAt: \"start\",\n minQuietPeriodMs: 100,\n },\n);\n\nconst draggingNodeUnsetter = funnel(() => setDraggingNode(undefined), {\n triggerAt: \"start\",\n minQuietPeriodMs: 100,\n});\n\nfunction setDragging(node: DraggingNode) {\n draggingNodeUnsetter.cancel();\n draggingNodeSetter.call(node);\n}\n\nfunction unsetDragging() {\n draggingNodeSetter.cancel();\n draggingNodeUnsetter.call();\n}\n\n/* Decide if a node is being dragged based on its id, parent and drive */\nconst isNodeDrag = (params: {\n srcId: string | undefined;\n driveId: string | undefined;\n parentId: string | null | undefined;\n}): params is {\n srcId: string;\n driveId: string;\n parentId: string | null | undefined;\n} =>\n conditional(\n params,\n // no drag if no src\n [({ srcId }) => isNot(isTruthy)(srcId), constant(false)],\n // no drag if no drive\n [({ driveId }) => isNot(isTruthy)(driveId), constant(false)],\n // no drag drive\n [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)],\n constant(true),\n );\n\n/* Allows a node to be dragged */\nexport function useDragNode(args: {\n srcId: string | undefined;\n parentId: string | null | undefined;\n}) {\n const { srcId, parentId } = args;\n const driveId = useSelectedDriveId();\n const draggingNodeId = useDraggingNode()?.srcId;\n\n const params = {\n driveId,\n srcId,\n parentId,\n };\n const draggable = isNodeDrag(params);\n\n const isDragging = allPass({ srcId, draggingNodeId }, [\n () => draggable,\n ({ srcId }) => isString(srcId),\n ({ draggingNodeId }) => isString(draggingNodeId),\n ({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId),\n ]);\n\n const onDragStart: DragEventHandler = () => {\n if (!draggable) return;\n setDragging(params);\n };\n\n const onDragEnd: DragEventHandler = () => {\n if (!draggable) return;\n unsetDragging();\n };\n\n return {\n isDragging,\n draggable,\n onDragStart,\n onDragEnd,\n };\n}\n\n/* Decide if a node can and should be dropped on the target based on the\n * dragged node's id, the target node's id, the dragged node's current parent, \nand the drive id. */\nconst isNodeDrop = (params: {\n driveId: string | undefined;\n parentId: string | undefined | null;\n targetId: string | undefined;\n srcId: string | undefined;\n}): params is {\n driveId: string;\n srcId: string;\n parentId: string | undefined | null;\n targetId: string | undefined;\n} =>\n conditional(\n params,\n // no drop if no src\n [({ srcId }) => isNot(isTruthy)(srcId), constant(false)],\n // no drop if no drive\n [({ driveId }) => isNot(isDefined)(driveId), constant(false)],\n // no drop into self\n [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)],\n // no drop into drive if already in top level of drive\n [\n ({ driveId, parentId, targetId }) =>\n isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId),\n constant(false),\n ],\n // no drop into current parent\n [\n ({ targetId, parentId }) => isStrictEqual(targetId, parentId),\n constant(false),\n ],\n constant(true),\n );\n\n/* Allows a node to be a drop target */\nexport function useDropNode(targetId: string | undefined) {\n const driveId = useSelectedDriveId();\n const { srcId, parentId } = useDraggingNode() ?? {};\n const { isDropTarget, setTarget, unsetTarget } = useDropTarget();\n\n const params = {\n driveId,\n parentId,\n targetId,\n srcId,\n };\n\n function handleNodeDrop(event: React.DragEvent<Element>, cb?: () => void) {\n if (!isNodeDrop(params)) return;\n\n event.preventDefault();\n event.stopPropagation();\n\n cb?.();\n }\n\n const onDragEnter: DragEventHandler = (event) => handleNodeDrop(event);\n\n const onDragOver: DragEventHandler = (event) =>\n handleNodeDrop(event, once(setTarget));\n\n const onDragLeave: DragEventHandler = (event) =>\n handleNodeDrop(event, once(unsetTarget));\n\n const onDrop: DragEventHandler = (event) =>\n handleNodeDrop(\n event,\n once(() => {\n unsetDragging();\n unsetTarget();\n moveNodeById(params).catch(console.error);\n }),\n );\n\n return { isDropTarget, onDragEnter, onDragOver, onDragLeave, onDrop };\n}\n","import type { ReactorGraphQLClient } from \"../graphql/types.js\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst graphQLReactorClientEventFunctions = makePHEventFunctions(\n \"reactorGraphQLClient\",\n);\n\nexport const useGraphQLReactorClient: UsePHGlobalValue<ReactorGraphQLClient> =\n graphQLReactorClientEventFunctions.useValue;\n\nexport const setGraphQLReactorClient: SetPHGlobalValue<ReactorGraphQLClient> =\n graphQLReactorClientEventFunctions.setValue;\nexport const addGraphQLReactorClientEventHandler =\n graphQLReactorClientEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst packageDiscoveryFunctions = makePHEventFunctions(\n \"packageDiscoveryService\",\n);\n\nexport const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;\nexport const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;\nexport const addPackageDiscoveryServiceEventHandler =\n packageDiscoveryFunctions.addEventHandler;\n","import { getPHStore } from \"./ph-store.js\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n extractNodeSlugFromPath,\n findDriveBySlug,\n} from \"../utils/url.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n setBrowserOpenSync,\n} from \"./navigation.js\";\nimport { selectDrive, setSelectedDriveId } from \"./selected-drive.js\";\nimport { setSelectedNodeId } from \"./set-selected-node.js\";\n\n/** Applies a path's selection without writing the URL; idempotent.\n * @deprecated Set the store's `navigation`; its route loaders write the selection. */\nexport function syncSelectionFromPath(pathname = getCurrentPathname()) {\n // Boot runs the first sync once drives are loaded.\n const drives = getPHStore()?.drives;\n if (!drives) return;\n\n const driveSlug = extractDriveSlugFromPath(pathname);\n const selectedDriveId = getPHStore()?.selectedDriveId;\n if (!driveSlug) {\n if (selectedDriveId) selectDrive(undefined);\n return;\n }\n\n // URLs carry the drive's raw slug, as written by setSelectedDrive.\n const drive = findDriveBySlug(drives, driveSlug);\n const selectedIsUnlisted =\n !!selectedDriveId && !drives.some((d) => d.header.id === selectedDriveId);\n if (drive) {\n if (drive.header.id !== selectedDriveId) {\n setSelectedDriveId(drive.header.id);\n }\n } else if (!selectedIsUnlisted) {\n // Defers until the drive syncs in, or redirects home.\n selectDrive(driveSlug);\n return;\n }\n // Otherwise keep a just-created drive selected before the list includes it.\n\n const nodeId = extractNodeIdFromSlug(extractNodeSlugFromPath(pathname));\n if (nodeId !== getPHStore()?.selectedNodeId) {\n setSelectedNodeId(nodeId);\n }\n}\n\nsetBrowserOpenSync(() => syncSelectionFromPath());\n\nfunction syncOnPopState() {\n // A host navigation syncs from its own location subscription.\n if (hasHostNavigation()) return;\n syncSelectionFromPath(window.location.pathname);\n}\n\nlet popStateHandlerAdded = false;\n\n/** Syncs the selection on back/forward when no host navigation is set.\n * @deprecated Set the store's `navigation`; its router handles back/forward. */\nexport function addSyncSelectionOnPopStateEventHandler() {\n if (popStateHandlerAdded) return;\n popStateHandlerAdded = true;\n window.addEventListener(\"popstate\", syncOnPopState);\n}\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineItemEventFunctions = makePHEventFunctions(\n \"selectedTimelineItem\",\n);\n\n/** Returns the selected timeline item */\nexport const useSelectedTimelineItem =\n selectedTimelineItemEventFunctions.useValue;\n\n/** Sets the selected timeline item */\nexport const setSelectedTimelineItem =\n selectedTimelineItemEventFunctions.setValue;\n\n/** Adds event handler for selected timeline item */\nexport const addSelectedTimelineItemEventHandler =\n selectedTimelineItemEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineRevisionEventFunctions = makePHEventFunctions(\n \"selectedTimelineRevision\",\n);\n\n/** Returns the selected timeline revision. */\nexport const useSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.useValue;\n\n/** Sets the selected timeline revision. */\nexport const setSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.setValue;\n\n/** Adds an event handler for the selected timeline revision. */\nexport const addSelectedTimelineRevisionEventHandler =\n selectedTimelineRevisionEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst toastEventFunctions = makePHEventFunctions(\"toast\");\n\n/** Returns the toast function */\nexport const usePHToast = toastEventFunctions.useValue;\n\n/** Sets the toast function */\nexport const setPHToast = toastEventFunctions.setValue;\n\n/** Adds an event handler for the toast */\nexport const addToastEventHandler = toastEventFunctions.addEventHandler;\n","import type { PHGlobalEventHandlerAdders } from \"../types/global.js\";\nimport { addBackendAuthEventHandler } from \"./backend-auth.js\";\nimport { addLocalSignInEventHandler } from \"./local-sign-in.js\";\nimport {\n addAllowListEventHandler,\n addBasePathEventHandler,\n addDefaultDrivesUrlEventHandler,\n addDisabledEditorsEventHandler,\n addIsAddDriveEnabledEventHandler,\n addLogLevelEventHandler,\n addRenownUrlEventHandler,\n addRouterBasenameEventHandler,\n addStudioModeEventHandler,\n addSwitchboardUrlEventHandler,\n addWarnOutdatedAppEventHandler,\n} from \"./config/connect.js\";\nimport { addAttachmentServiceEventHandler } from \"./attachment-service.js\";\nimport { addFeaturesEventHandler } from \"./features.js\";\n\nimport { forEachObj } from \"remeda\";\nimport {\n addAllowedDocumentTypesEventHandler,\n addIsDragAndDropEnabledEventHandler,\n addIsExternalControlsEnabledEventHandler,\n} from \"./config/editor.js\";\nimport { addDocumentCacheEventHandler } from \"./document-cache.js\";\nimport { addDraggingNodeEventHandler } from \"./node-drag-and-drop.js\";\nimport { addDrivesEventHandler } from \"./drives.js\";\nimport { addDriveNodesEventHandler } from \"./drive-nodes.js\";\nimport { addGraphQLReactorClientEventHandler } from \"./graphql-reactor-client.js\";\nimport { addLoadingEventHandler } from \"./loading.js\";\nimport { addModalEventHandler } from \"./modals.js\";\nimport { addPackageDiscoveryServiceEventHandler } from \"./package-discovery.js\";\nimport {\n addFullReactorClientEventHandler,\n addReactorClientEventHandler,\n addReactorClientModuleEventHandler,\n addReactorHalvesEventHandler,\n} from \"./reactor.js\";\nimport { addRenownEventHandler } from \"./renown.js\";\nimport { addSelectedDriveIdEventHandler } from \"./selected-drive.js\";\nimport { addSwitchboardsEventHandler } from \"./switchboards.js\";\nimport { addResetSelectedNodeEventHandler } from \"./selected-node.js\";\nimport { addSelectedNodeIdEventHandler } from \"./set-selected-node.js\";\nimport { addSyncSelectionOnPopStateEventHandler } from \"./sync-selection.js\";\nimport { addSelectedTimelineItemEventHandler } from \"./selected-timeline-item.js\";\nimport { addSelectedTimelineRevisionEventHandler } from \"./timeline-revision.js\";\nimport { addToastEventHandler } from \"./toast.js\";\nimport { addVetraPackageManagerEventHandler } from \"./vetra-packages.js\";\n\nexport const commonGlobalEventHandlerFunctions = {\n loading: addLoadingEventHandler,\n drives: addDrivesEventHandler,\n backendAuth: addBackendAuthEventHandler,\n localSignIn: addLocalSignInEventHandler,\n driveNodes: addDriveNodesEventHandler,\n selectedDriveId: () => {\n addSelectedDriveIdEventHandler();\n addSyncSelectionOnPopStateEventHandler();\n addResetSelectedNodeEventHandler();\n },\n selectedNodeId: () => {\n addSelectedNodeIdEventHandler();\n },\n documentCache: addDocumentCacheEventHandler,\n reactorGraphQLClient: addGraphQLReactorClientEventHandler,\n draggingNode: addDraggingNodeEventHandler,\n};\n\nconst phGlobalEventHandlerRegisterFunctions: PHGlobalEventHandlerAdders = {\n ...commonGlobalEventHandlerFunctions,\n reactorClientModule: addReactorClientModuleEventHandler,\n reactorClient: addReactorClientEventHandler,\n reactor: addReactorHalvesEventHandler,\n fullReactorClient: addFullReactorClientEventHandler,\n attachmentService: addAttachmentServiceEventHandler,\n switchboards: addSwitchboardsEventHandler,\n features: addFeaturesEventHandler,\n modal: addModalEventHandler,\n renown: addRenownEventHandler,\n vetraPackageManager: addVetraPackageManagerEventHandler,\n packageDiscoveryService: addPackageDiscoveryServiceEventHandler,\n selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,\n selectedTimelineItem: addSelectedTimelineItemEventHandler,\n routerBasename: addRouterBasenameEventHandler,\n logLevel: addLogLevelEventHandler,\n warnOutdatedApp: addWarnOutdatedAppEventHandler,\n studioMode: addStudioModeEventHandler,\n basePath: addBasePathEventHandler,\n allowList: addAllowListEventHandler,\n defaultDrivesUrl: addDefaultDrivesUrlEventHandler,\n allowedDocumentTypes: addAllowedDocumentTypesEventHandler,\n disabledEditors: addDisabledEditorsEventHandler,\n isAddDriveEnabled: addIsAddDriveEnabledEventHandler,\n isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,\n isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,\n renownUrl: addRenownUrlEventHandler,\n switchboardUrl: addSwitchboardUrlEventHandler,\n toast: addToastEventHandler,\n // Set once by the host on its store; no event to listen for.\n navigation: () => {},\n aiTools: () => {},\n};\nexport function addPHEventHandlers() {\n callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);\n}\n\nexport function callEventHandlerRegisterFunctions(\n registerFunctions: Record<string, () => void>,\n) {\n forEachObj(registerFunctions, (fn) => fn());\n}\n","\"use client\";\n\nimport type { DocumentModelModule } from \"document-model\";\nimport { type ReactNode, useEffect, useState } from \"react\";\nimport { DocumentCache } from \"../document-cache.js\";\nimport { addPHEventHandlers } from \"../hooks/add-ph-event-handlers.js\";\nimport { setAttachmentService } from \"../hooks/attachment-service.js\";\nimport { setDocumentCache } from \"../hooks/document-cache.js\";\nimport { setReactorClient, useReactorClient } from \"../hooks/reactor.js\";\nimport { setVetraPackageManager } from \"../hooks/vetra-packages.js\";\nimport type { PHGlobal } from \"../types/global.js\";\nimport {\n packageFromDocumentModels,\n StaticPackageManager,\n} from \"./static-package-manager.js\";\nimport {\n GraphQLReactorClient,\n isGraphQLReactorClient,\n type GraphQLReactorClientOptions,\n} from \"./graphql-reactor-client.js\";\n\ndeclare global {\n interface Window {\n /** Set by {@link ensurePHEventHandlers}; see its doc comment. */\n __phEventHandlersRegistered?: boolean;\n }\n}\n\n/**\n * Registers the `window.ph` event handlers once per page.\n *\n * The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`\n * until `addPHEventHandlers` has registered the listeners that do. Registration\n * is guarded by a marker on `window` rather than a module-level flag so that a\n * hot module replacement, or two copies of this module, still register once.\n */\nexport function ensurePHEventHandlers(): void {\n if (typeof window === \"undefined\" || window.__phEventHandlersRegistered) {\n return;\n }\n addPHEventHandlers();\n window.__phEventHandlersRegistered = true;\n}\n\nexport type GraphQLReactorProviderProps = {\n /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */\n url: string;\n\n /**\n * Resolves the bearer token sent with every request, per request. Defaults to\n * the token of the logged-in Renown user, or none when nobody is logged in.\n */\n tokenProvider?: GraphQLReactorClientOptions[\"tokenProvider\"];\n\n /**\n * The Switchboard GraphQL subscriptions endpoint, e.g.\n * `ws://localhost:4001/graphql/subscriptions`. Defaults to the endpoint\n * derived from `url`.\n */\n subscriptionsUrl?: GraphQLReactorClientOptions[\"subscriptionsUrl\"];\n\n /**\n * Whether server-pushed changes are delivered. On by default; set it to\n * `false` where there is no websocket to talk to.\n */\n realtime?: GraphQLReactorClientOptions[\"realtime\"];\n\n /**\n * The attachment service the editors below this provider read attachments\n * through, published into the same `window.ph` slot Connect publishes it in.\n *\n * The app constructs it: attachments are a separate package, and which\n * storage an app talks to is the app's business. Leave it out and the slot\n * stays empty, exactly as it is without this provider.\n */\n attachmentService?: PHGlobal[\"attachmentService\"];\n\n /**\n * The document model modules the app works with, imported from its generated\n * package's `document-models` SUBPATH:\n *\n * ```tsx\n * import { TodoV1, TodoV2 } from \"my-models/document-models\";\n * <GraphQLReactorProvider url={url} documentModels={[TodoV1, TodoV2]}>\n * ```\n *\n * Wrapped via {@link packageFromDocumentModels} and published through a\n * {@link StaticPackageManager} into the same `window.ph.vetraPackageManager`\n * slot Connect fills, so `useDocumentModelModules` and\n * `useDocumentModelModuleById` work below this provider.\n *\n * Modules only, deliberately - not whole packages. Editors are not portable\n * outside Connect yet (they read the selected document from Connect's\n * drive/node selection) and would inflate the bundle; a light app that needs\n * an editor imports the React component directly.\n *\n * Import from the `document-models` subpath, never from the package ROOT:\n * the root entry also exports the package's `processorFactory`, and module\n * resolution happens before tree-shaking, so a root import drags processor\n * (server-side) code into the browser bundle and can break the build.\n *\n * They are also what lets the client SIGN a batch of two or more actions:\n * signing the second action needs the state the first one leaves behind, and\n * only the document's own reducer can predict it, so a batch is signable only\n * while the module matching the document's type and exact version is here.\n * Single actions are signed without any of this.\n *\n * Optional on purpose: a light app may equally ship NO modules and let the\n * Switchboard own the model entirely - both modes are supported.\n *\n * Like `url`, this is read once, when the client is built.\n */\n documentModels?: readonly DocumentModelModule<any>[];\n\n children: ReactNode;\n};\n\n/**\n * Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the\n * reactor-browser hooks read, so `useDocument`, `useDispatch` and\n * `useReactorClient` work below it against a Switchboard, with no reactor in\n * the bundle.\n *\n * It fills the document slots, plus `window.ph.vetraPackageManager` when\n * `documentModels` is given (a fixed {@link StaticPackageManager}, which makes\n * the document-model hooks work). The same modules go to the client itself, so\n * a dispatch of two or more actions is signed rather than refused.\n * `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces\n * (drives, jobs, editor auto-discovery) find nothing - an app below this\n * provider renders components it imports itself.\n *\n * The client is built on the client only: on the server the slots stay empty\n * and the hooks report their normal loading states. The props are read once,\n * when the client is built - changing `url` afterwards does not rebuild it.\n *\n * The effect's cleanup disposes the cache and the client's socket, and the\n * effect rebuilds both if it runs again on the same client - which is what a\n * `StrictMode` mount does.\n */\nexport function GraphQLReactorProvider({\n url,\n tokenProvider,\n subscriptionsUrl,\n realtime,\n attachmentService,\n documentModels,\n children,\n}: GraphQLReactorProviderProps) {\n const [client] = useState(() =>\n typeof window === \"undefined\"\n ? undefined\n : new GraphQLReactorClient({\n url,\n tokenProvider,\n subscriptionsUrl,\n realtime,\n documentModels,\n }),\n );\n\n useEffect(() => {\n if (!client) {\n return;\n }\n ensurePHEventHandlers();\n setReactorClient(client);\n const documentCache = new DocumentCache(client);\n setDocumentCache(documentCache);\n // Only the cache and the client's realtime socket are torn down. The window\n // slots are deliberately left populated, matching how Connect never unsets\n // them: consumers may read them while React is unmounting, and the next\n // mount overwrites them.\n return () => {\n documentCache.dispose();\n client.dispose();\n };\n }, [client]);\n\n // Published from an effect of its own so that a service the app builds\n // asynchronously still reaches the slot. Rebuilding the client and its cache\n // for it - which sharing the effect above would do - would throw away every\n // open document instead.\n useEffect(() => {\n if (!attachmentService) {\n return;\n }\n ensurePHEventHandlers();\n setAttachmentService(attachmentService);\n }, [attachmentService]);\n\n // Its own effect for the same reason as the attachment service above: the\n // modules must not rebuild the client and its cache. The slot stays\n // populated on unmount, matching the other slots. setVetraPackageManager's\n // reactor side effects no-op here - there is no reactorClientModule to\n // register modules on.\n useEffect(() => {\n if (!documentModels || documentModels.length === 0) {\n return;\n }\n ensurePHEventHandlers();\n setVetraPackageManager(\n new StaticPackageManager([packageFromDocumentModels(documentModels)]),\n );\n }, [documentModels]);\n\n return <>{children}</>;\n}\n\n/**\n * Returns the {@link GraphQLReactorClient} mounted by\n * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something\n * else - the full in-browser reactor client, or nothing yet.\n *\n * `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both\n * implementations share. This is how a component reaches the light client's own\n * surface, i.e. `subgraph` and `request`.\n *\n * The narrowing is by brand, not by `instanceof`: a page can carry two copies\n * of this module - a bundled package with its own copy, or a hot-replaced one -\n * and `instanceof` would then answer `false` for a perfectly good client and\n * leave the component silently without one.\n */\nexport function useSwitchboardClient(): GraphQLReactorClient | undefined {\n const client = useReactorClient();\n return isGraphQLReactorClient(client) ? client : undefined;\n}\n","import type {\n ConsistencyToken,\n JobInfo,\n PagedResults,\n ReactorInfo,\n ViewFilter,\n} from \"@powerhousedao/reactor\";\nimport { DRIVE_CHILD_RELATIONSHIP_TYPE } from \"@powerhousedao/reactor-drive\";\nimport type {\n BackendHealth,\n IRoutableBackend,\n ReactorReach,\n RoutableBackendConfig,\n} from \"@powerhousedao/reactor-router\";\nimport type {\n Action,\n DocumentModelModule,\n ISigner,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { DRIVE_DOCUMENT_TYPES } from \"../constants.js\";\nimport { JOB_NOT_FOUND_ERROR_NAME } from \"../reactor-interop.js\";\nimport type { BearerTokenProvider } from \"./auth.js\";\nimport { GraphQLWrongBackendError } from \"./errors.js\";\nimport {\n findIsServableOverGraphQL,\n GraphQLReactorClient,\n type DriveIdCall,\n} from \"./graphql-reactor-client.js\";\nimport {\n isDeadlineError,\n switchboardFetch,\n type GraphQLFetch,\n} from \"./transport.js\";\n\nexport type SwitchboardBackendDescriptor = {\n /** Router backend name; unique and stable for the router's life. */\n readonly name: string;\n /** `<origin>[/<prefix>]/graphql`. */\n readonly url: string;\n /** Resolves the bearer per request and for the realtime socket. */\n readonly tokenProvider: BearerTokenProvider;\n /** Read per push when a function; `undefined` pushes unsigned, never ambient. */\n readonly signer:\n | ISigner\n | (() => ISigner | undefined | Promise<ISigner | undefined>)\n | undefined;\n /** Models for signing a batch, read per batch. */\n readonly documentModels: () => readonly DocumentModelModule<any>[];\n readonly realtime?: boolean;\n /** Default `\"rpc\"`. */\n readonly inspection?: ReactorReach[\"inspection\"];\n /** Bound on one request, headers through body. Default 30_000. */\n readonly requestTimeoutMs?: number;\n /** Bound on a batch, which waits for its jobs. Default 120_000. */\n readonly batchRequestTimeoutMs?: number;\n /** Unset fields take {@link DEFAULT_BREAKER}; `false` never opens. */\n readonly breaker?: SwitchboardBreaker;\n /** The transport under the deadline and the breaker; {@link switchboardFetch} by default. */\n readonly fetch?: GraphQLFetch;\n};\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nexport const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 120_000;\nexport const DEFAULT_BREAKER = Object.freeze({ failures: 3, openMs: 30_000 });\n\n/** After `failures` failed requests in a row, send nothing for `openMs`. */\nexport type SwitchboardBreaker =\n | false\n | { readonly failures?: number; readonly openMs?: number };\n\nfunction breakerSettings(breaker: SwitchboardBreaker | undefined): {\n failures: number;\n openMs: number;\n} {\n if (breaker === false) return { failures: Infinity, openMs: 0 };\n return { ...DEFAULT_BREAKER, ...breaker };\n}\n\nexport type SwitchboardBackend = {\n /** reach `{hosting: \"remote\", inspection}`; `refusesMisroutes: false`. */\n readonly config: RoutableBackendConfig;\n /** Reopens the realtime socket on the new credentials. */\n notifyCredentialsChanged(): void;\n /** Closes the realtime socket. */\n dispose(): void;\n};\n\nconst FACTS_QUERY = /* GraphQL */ `\n query SwitchboardFacts {\n inspection {\n info {\n storage {\n engine\n persistence\n durable\n selfHeal\n }\n workflows\n syncChannels\n access {\n admin\n sql\n }\n }\n documentModels {\n documentType\n }\n }\n queries: __type(name: \"Query\") {\n fields {\n name\n }\n }\n inspectionFields: __type(name: \"ReactorInspection\") {\n fields {\n name\n }\n }\n }\n`;\n\nconst MODEL_LOADING_QUERY = /* GraphQL */ `\n query SwitchboardModelLoading {\n inspection {\n loadsModelsOnDemand\n }\n }\n`;\n\ntype TypeFields = { fields: readonly { name: string }[] | null } | null;\n\ntype FactsAnswer = {\n inspection: {\n info: Omit<ReactorInfo, \"access\"> & {\n access: ReactorInfo[\"access\"] | null;\n };\n documentModels: readonly { documentType: string }[];\n };\n queries: TypeFields;\n inspectionFields: TypeFields;\n};\n\ntype SwitchboardFacts = {\n readonly info: ReactorInfo;\n /** Undefined: the Switchboard loads models on demand, or does not say. */\n readonly documentTypes: readonly string[] | undefined;\n};\n\n/** Queries this backend sends that a Switchboard serves only from some version. */\nconst REQUIRED_QUERIES = [\"documentServed\", \"createDefaults\", \"inspection\"];\n\n/** The Switchboard's circuit is open: nothing was sent. */\nexport class SwitchboardUnreachableError extends Error {\n override readonly name = \"SwitchboardUnreachableError\";\n\n constructor(\n readonly backend: string,\n readonly retryAt: number,\n ) {\n super(\n `Switchboard backend ${JSON.stringify(backend)} is unreachable; nothing is sent until ${new Date(retryAt).toISOString()}`,\n );\n }\n}\n\n/**\n * Opens after `failures` transport failures in a row (a network error, a\n * deadline or a 5xx) and sends nothing for `openMs`. Any other answer, a\n * GraphQL error included, closes it. The first request after `openMs` goes\n * through; one more failure opens it again.\n */\nclass Breaker {\n private consecutive = 0;\n private openUntil: number | undefined;\n\n constructor(\n private readonly backend: string,\n private readonly settings: { failures: number; openMs: number },\n ) {}\n\n health(): BackendHealth {\n return this.isOpen() ? \"down\" : \"up\";\n }\n\n wrap(inner: GraphQLFetch): GraphQLFetch {\n return async (input, init) => {\n const openUntil = this.openUntil;\n if (openUntil !== undefined && Date.now() < openUntil) {\n throw new SwitchboardUnreachableError(this.backend, openUntil);\n }\n let response: Response;\n try {\n response = await inner(input, init);\n } catch (error) {\n if (!abortedByCaller(init?.signal)) {\n this.fail();\n }\n throw error;\n }\n if (response.status >= 500) {\n this.fail();\n } else {\n this.consecutive = 0;\n this.openUntil = undefined;\n }\n return response;\n };\n }\n\n private isOpen(): boolean {\n return this.openUntil !== undefined && Date.now() < this.openUntil;\n }\n\n private fail(): void {\n this.consecutive += 1;\n if (this.consecutive >= this.settings.failures) {\n this.openUntil = Date.now() + this.settings.openMs;\n }\n }\n}\n\nfunction abortedByCaller(signal: AbortSignal | null | undefined): boolean {\n return Boolean(signal?.aborted) && !isDeadlineError(signal?.reason);\n}\n\nconst NO_ACCESS: ReactorInfo[\"access\"] = Object.freeze({\n admin: false,\n sql: false,\n});\n\n/** Ids and slugs of documents this backend answered as drives, by drive id. */\nclass KnownDrives {\n private readonly ids = new Map<string, string>();\n\n learn<T extends PHDocument>(document: T): T {\n const { id, slug, documentType } = document.header;\n if ((DRIVE_DOCUMENT_TYPES as readonly string[]).includes(documentType)) {\n this.ids.set(id, id);\n if (slug) {\n this.ids.set(slug, id);\n }\n }\n return document;\n }\n\n learnPage<T extends PHDocument>(page: PagedResults<T>): PagedResults<T> {\n for (const document of page.results) {\n this.learn(document);\n }\n return page;\n }\n\n /** Drops a drive the Switchboard refused, by id and by slug. */\n forget(driveId: string): void {\n for (const [identifier, id] of this.ids) {\n if (id === driveId) {\n this.ids.delete(identifier);\n }\n }\n }\n\n driveOf(identifier: string | undefined): string | undefined {\n return identifier === undefined ? undefined : this.ids.get(identifier);\n }\n\n /** Names a drive only when this backend proved it is one. */\n driveIdFor = (call: DriveIdCall): string | undefined => {\n switch (call.method) {\n case \"create\":\n case \"find\":\n return this.driveOf(call.parentId);\n case \"execute\":\n case \"deleteDocument\":\n return this.driveOf(call.documentId);\n case \"executeBatch\":\n for (const job of call.jobs ?? []) {\n const drive = this.driveOf(job.documentId);\n if (drive !== undefined) {\n return drive;\n }\n }\n return undefined;\n }\n };\n\n /** Runs a call that may carry `Drive-Id`; a 421 forgets the drive it named. */\n async refusable<T>(call: Promise<T>): Promise<T> {\n try {\n return await call;\n } catch (error) {\n if (GraphQLWrongBackendError.isError(error)) {\n this.forget(error.driveId);\n }\n throw error;\n }\n }\n}\n\nfunction isUnknownJob(job: JobInfo): boolean {\n const status: string = job.status;\n return status === \"FAILED\" && job.error?.name === JOB_NOT_FOUND_ERROR_NAME;\n}\n\n/** A Switchboard as a router backend; members GraphQL cannot serve are absent. */\nexport function createSwitchboardBackend(\n descriptor: SwitchboardBackendDescriptor,\n): SwitchboardBackend {\n const drives = new KnownDrives();\n const breaker = new Breaker(\n descriptor.name,\n breakerSettings(descriptor.breaker),\n );\n const signer = descriptor.signer;\n const gql = new GraphQLReactorClient({\n url: descriptor.url,\n tokenProvider: descriptor.tokenProvider,\n signer: typeof signer === \"function\" ? signer : () => signer,\n documentModels: descriptor.documentModels,\n realtime: descriptor.realtime,\n driveIdFor: drives.driveIdFor,\n requestTimeoutMs: descriptor.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n batchRequestTimeoutMs:\n descriptor.batchRequestTimeoutMs ?? DEFAULT_BATCH_REQUEST_TIMEOUT_MS,\n fetch: breaker.wrap(descriptor.fetch ?? switchboardFetch),\n });\n const backend: IRoutableBackend = {\n supports: { find: findIsServableOverGraphQL, pointInTimeViews: false },\n health: () => breaker.health(),\n drives: gql.read.drives,\n driveNodes: gql.nodeSource(),\n // A file added through the reactor has the one; one a drive migration or\n // the reactor-drive client linked has the other.\n driveFileLinkTypes: [\"child\", DRIVE_CHILD_RELATIONSHIP_TYPE],\n // A write is submitted and its job polled: the waiting mutation is one\n // request, which a slow write outlives, and it would be aborted having landed.\n submit: {\n execute: (identifier, branch, actions, signal) =>\n drives.refusable(gql.executeAsync(identifier, branch, actions, signal)),\n },\n get: async <TDocument extends PHDocument>(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ) =>\n drives.learn(\n await gql.get<TDocument>(identifier, view, signal, consistencyToken),\n ),\n getMany: async <TDocument extends PHDocument>(\n ids: string[],\n view?: ViewFilter,\n signal?: AbortSignal,\n ) =>\n (await gql.getMany<TDocument>(ids, view, signal)).map((document) =>\n drives.learn(document),\n ),\n getOperations: (identifier, view, filter, paging, signal) =>\n gql.getOperations(identifier, view, filter, paging, signal),\n find: async (search, view, paging, signal) =>\n drives.learnPage(\n await drives.refusable(gql.find(search, view, paging, signal)),\n ),\n isServed: (identifier, view, signal) =>\n gql.isServed(identifier, view, signal),\n getOutgoingRelationships: (source, type, view, paging, signal) =>\n gql.getOutgoingRelationships(source, type, view, paging, signal),\n getIncomingRelationships: (target, type, view, paging, signal) =>\n gql.getIncomingRelationships(target, type, view, paging, signal),\n getOutgoingRelationshipEdges: (source, type, view, paging, signal) =>\n gql.getOutgoingRelationshipEdges(source, type, view, paging, signal),\n getIncomingRelationshipEdges: (target, type, view, paging, signal) =>\n gql.getIncomingRelationshipEdges(target, type, view, paging, signal),\n subscribe: (search, callback, view) =>\n gql.subscribe(search, callback, view),\n getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),\n getCreateProtocolVersions: (options, signal) =>\n gql.getCreateProtocolVersions(options, signal),\n create: async <TDocument extends PHDocument = PHDocument>(\n document: PHDocument,\n parent?: string,\n signal?: AbortSignal,\n ) =>\n drives.learn(\n await drives.refusable(gql.create<TDocument>(document, parent, signal)),\n ),\n execute: async <TDocument extends PHDocument>(\n identifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ) =>\n drives.learn(\n await drives.refusable(\n gql.execute<TDocument>(identifier, branch, actions, signal),\n ),\n ),\n executeBatch: (request, signal) =>\n drives.refusable(gql.executeBatch(request, signal)),\n deleteDocument: (identifier, propagate, signal) =>\n drives.refusable(gql.deleteDocument(identifier, propagate, signal)),\n setPreferredEditor: (identifier, editor, branch, signal) =>\n gql.setPreferredEditor(identifier, editor, branch, signal),\n getJob: async (jobId, signal) => {\n const job = await gql.getJob(jobId, signal);\n return job && isUnknownJob(job) ? undefined : job;\n },\n waitForJob: (job, signal) => gql.waitForJob(job, signal),\n undo: async <TDocument extends PHDocument = PHDocument>(\n identifier: string,\n scope?: string,\n branch?: string,\n signal?: AbortSignal,\n ) =>\n drives.learn(\n await drives.refusable(\n gql.undo<TDocument>(identifier, scope, branch, signal),\n ),\n ),\n redo: async <TDocument extends PHDocument = PHDocument>(\n identifier: string,\n scope?: string,\n branch?: string,\n signal?: AbortSignal,\n ) =>\n drives.learn(\n await drives.refusable(\n gql.redo<TDocument>(identifier, scope, branch, signal),\n ),\n ),\n undoRedoTargets: (identifier, scope, view, signal) =>\n gql.undoRedoTargets(identifier, scope, view, signal),\n undoRedoAvailability: (identifier, scope, branch, signal) =>\n gql.undoRedoAvailability(identifier, scope, branch, signal),\n };\n // The router reads the facts and the types together; they share one query.\n let reading: Promise<SwitchboardFacts> | undefined;\n const read = () =>\n (reading ??= readFacts(gql, descriptor.url).finally(() => {\n reading = undefined;\n }));\n return {\n config: {\n name: descriptor.name,\n backend,\n facts: async () => (await read()).info,\n documentTypes: async () => (await read()).documentTypes,\n reach: { hosting: \"remote\", inspection: descriptor.inspection ?? \"rpc\" },\n refusesMisroutes: false,\n },\n notifyCredentialsChanged: () => gql.notifyCredentialsChanged(),\n dispose: () => gql.dispose(),\n };\n}\n\nfunction fieldNames(type: TypeFields): Set<string> {\n return new Set(type?.fields?.map((field) => field.name));\n}\n\nasync function readFacts(\n gql: GraphQLReactorClient,\n url: string,\n): Promise<SwitchboardFacts> {\n const answer = await gql.request<FactsAnswer>(FACTS_QUERY);\n const served = fieldNames(answer.queries);\n const missing = REQUIRED_QUERIES.filter((query) => !served.has(query));\n if (missing.length > 0) {\n throw new Error(\n `The Switchboard at ${url} does not serve ${missing.join(\", \")}; it is older than this client`,\n );\n }\n const { info, documentModels } = answer.inspection;\n // A Switchboard too old to say how it loads models gets no constraint.\n const closed =\n fieldNames(answer.inspectionFields).has(\"loadsModelsOnDemand\") &&\n !(\n await gql.request<{ inspection: { loadsModelsOnDemand: boolean } }>(\n MODEL_LOADING_QUERY,\n )\n ).inspection.loadsModelsOnDemand;\n return {\n info: { ...info, access: info.access ?? NO_ACCESS },\n documentTypes: closed\n ? documentModels.map((model) => model.documentType)\n : undefined,\n };\n}\n","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport { useCallback, useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport { IDLE_OPERATIONS_ENTRY, isOperationCache } from \"../document-cache.js\";\nimport type { IOperationCache } from \"../types/documents.js\";\nimport { useDocumentCache } from \"./document-cache.js\";\n\nexport type UseDocumentOperationsOptions = {\n /**\n * Operations per page. Default 100. Applies to the next first-page load;\n * changing it while pages are already loaded has no effect until the next\n * invalidation or `refetch`.\n */\n limit?: number;\n /** Whether to fetch at all. Default true. Pass false until the operations are needed. */\n enabled?: boolean;\n};\n\n/** What `useDocumentOperations` returns; exported so consumers can name it. */\nexport type DocumentOperationsResult = {\n /** Every operation of the scope loaded so far, oldest first. */\n operations: readonly Operation[];\n /** A page is in flight. */\n isLoading: boolean;\n /** The last page failed. Operations loaded before it stay available. */\n error: Error | undefined;\n /** The last page reported a further page. */\n hasNextPage: boolean;\n /** Loads the next page and appends it. No-op while loading or when there is none. */\n fetchNextPage: () => void;\n /** Drops the document's cached operations and reloads from the first page. */\n refetch: () => void;\n};\n\nconst DEFAULT_LIMIT = 100;\n\nfunction toError(reason: unknown): Error {\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\n/**\n * Operation history of one scope of a document, read from the document cache\n * and kept in step with it: a change event for the document drops the cached\n * pages and the hook loads the first page again.\n *\n * Pages arrive oldest first. A view that wants the whole history calls\n * `fetchNextPage` while `hasNextPage` is true.\n *\n * An empty first page is a final result; there is no retry. When the active\n * document cache does not serve operations, the result is empty and not\n * loading.\n *\n * @param documentId - The document id, or null/undefined to skip fetching\n * @param scope - The operation scope, for example \"global\" or \"local\"\n * @param options - Page size and whether fetching is enabled\n */\nexport function useDocumentOperations(\n documentId: string | null | undefined,\n scope: string,\n options: UseDocumentOperationsOptions = {},\n): DocumentOperationsResult {\n const { limit = DEFAULT_LIMIT, enabled = true } = options;\n const documentCache = useDocumentCache();\n const cache: IOperationCache | undefined =\n documentCache && isOperationCache(documentCache)\n ? documentCache\n : undefined;\n const activeId = enabled && cache && documentId ? documentId : undefined;\n\n const getEntry = () =>\n activeId && cache\n ? cache.getOperationsState(activeId, scope)\n : IDLE_OPERATIONS_ENTRY;\n const entry = useSyncExternalStore(\n (onChange) =>\n activeId && cache\n ? cache.subscribeOperations(activeId, onChange)\n : () => {},\n getEntry,\n getEntry,\n );\n\n useEffect(() => {\n if (activeId && cache && entry.status === \"idle\") {\n cache.loadOperations(activeId, scope, limit);\n }\n }, [activeId, cache, scope, limit, entry.status]);\n\n const fetchNextPage = useCallback(() => {\n if (activeId && cache) {\n cache.loadMoreOperations(activeId, scope);\n }\n }, [activeId, cache, scope]);\n\n const refetch = useCallback(() => {\n if (activeId && cache) {\n cache.invalidateOperations(activeId);\n }\n }, [activeId, cache]);\n\n const error = useMemo(\n () => (entry.status === \"error\" ? toError(entry.error) : undefined),\n [entry.status, entry.error],\n );\n\n return {\n operations: entry.operations,\n // `idle` while active is a load about to be kicked off by the effect\n // above (on mount, and right after `invalidateOperations` clears the\n // entry synchronously) - report it as loading so consumers never see a\n // \"no operations\" flash before the first page request goes out.\n isLoading:\n entry.status === \"pending\" || (!!activeId && entry.status === \"idle\"),\n error,\n hasNextPage: entry.hasNextPage,\n fetchNextPage,\n refetch,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AASA,SAAgB,kBAAgC;CAC9C,OAAO,WAAW,CAAC,EAAE,cAAc,gBAAgB;AACrD;;AAGA,SAAgB,kBAA0C;CACxD,OAAO,gBAAgB,CAAC,CAAC,gBAAgB;AAC3C;;AAGA,SAAgB,qBAAsC;CACpD,OAAO,gBAAgB,CAAC,CAAC,mBAAmB;AAC9C;;;;ACJA,SAAgB,aAAa,OAAkB;CAC7C,OACE,CAAC,MAAM,oBACP,MAAM,WAAW,KACjB,CAAC,MAAM,WACP,CAAC,MAAM,WACP,CAAC,MAAM,YACP,CAAC,MAAM;AAEX;;;AAYA,SAAgB,aACd,QACA,MACW;CACX,MAAM,aAAa,gBAAgB;CACnC,MAAM,OAAO,WAAW,UAAU,MAAM,KAAK,eAAe,MAAM;CAClE,MAAM,YAAY,WAAW,eAAe,MAAM,KAAK;CACvD,MAAM,gBAAgB,WAAW,UAAU,MAAM;CACjD,MAAM,aAAa,eAAe,eAAe,YAAY,MAAM;CACnE,OAAO;EACL;EACA,UAAU,UAAU;GAClB,IAAI,CAAC,aAAa,KAAK,GAAG;GAC1B,MAAM,eAAe;GACrB,WAAW;EACb;EACA,cAAc;EACd,SAAS;EACT,gBAAgB,YAAY,SAAS,KAAA;CACvC;AACF;;;AC9CA,MAAM,sBA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