@powerhousedao/reactor-browser 6.2.3 → 6.3.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/{attachment-service-But1Xljo.d.ts → attachment-service-B-AmTrs2.d.ts} +605 -56
  2. package/dist/attachment-service-B-AmTrs2.d.ts.map +1 -0
  3. package/dist/auth-DRbzRdeC.d.ts +32 -0
  4. package/dist/auth-DRbzRdeC.d.ts.map +1 -0
  5. package/dist/{client-BiJAJ9dW.js → client-BFnMV-EO.js} +39 -22
  6. package/dist/client-BFnMV-EO.js.map +1 -0
  7. package/dist/{client-CngU4mtn.d.ts → client-BP0hXjqq.d.ts} +3 -2
  8. package/dist/client-BP0hXjqq.d.ts.map +1 -0
  9. package/dist/client-wwavHFfs.js +135 -0
  10. package/dist/client-wwavHFfs.js.map +1 -0
  11. package/dist/{dispatch-qRXS70fh.js → dispatch-Cylwl2Dk.js} +363 -44
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/{document-by-id-B_8DA4yZ.js → document-by-id-DdvqanGR.js} +2 -2
  14. package/dist/{document-by-id-B_8DA4yZ.js.map → document-by-id-DdvqanGR.js.map} +1 -1
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/{document-operations-Bt-1-ThH.js → document-operations-DRMMwmGZ.js} +2160 -181
  18. package/dist/document-operations-DRMMwmGZ.js.map +1 -0
  19. package/dist/global-iARBhxNI.d.ts +612 -0
  20. package/dist/global-iARBhxNI.d.ts.map +1 -0
  21. package/dist/{index-BABMK8cO.d.ts → index-CNS_9THu.d.ts} +14 -4
  22. package/dist/index-CNS_9THu.d.ts.map +1 -0
  23. package/dist/index.d.ts +560 -79
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +790 -317
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/{relational-ChC_AWAK.js → relational-DZuyKp2y.js} +65 -5
  32. package/dist/relational-DZuyKp2y.js.map +1 -0
  33. package/dist/{renown-C9pYZRqf.js → renown-B3MUaiq7.js} +56 -25
  34. package/dist/renown-B3MUaiq7.js.map +1 -0
  35. package/dist/renown-CBoTdGrg.js +394 -0
  36. package/dist/renown-CBoTdGrg.js.map +1 -0
  37. package/dist/{client-VV9M73s_.js → schema-B5lftDPf.js} +295 -195
  38. package/dist/schema-B5lftDPf.js.map +1 -0
  39. package/dist/{types-B7-_l_wE.d.ts → schema-C6ECceaN.d.ts} +272 -82
  40. package/dist/schema-C6ECceaN.d.ts.map +1 -0
  41. package/dist/src/ai/index.d.ts +269 -24
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +1028 -168
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.js +3 -3
  46. package/dist/src/graphql/client.d.ts +2 -2
  47. package/dist/src/graphql/client.js +1 -1
  48. package/dist/src/graphql-client/entry.d.ts +6 -4
  49. package/dist/src/graphql-client/entry.js +4 -4
  50. package/dist/src/relational/index.d.ts +8 -1
  51. package/dist/src/relational/index.d.ts.map +1 -1
  52. package/dist/src/relational/index.js +1 -1
  53. package/dist/src/renown/index.d.ts +2 -2
  54. package/dist/src/renown/index.js +3 -3
  55. package/dist/src/rpc/index.d.ts +201 -144
  56. package/dist/src/rpc/index.d.ts.map +1 -1
  57. package/dist/src/rpc/index.js +562 -634
  58. package/dist/src/rpc/index.js.map +1 -1
  59. package/dist/switchboard-directory-vH6qtkh-.js +435 -0
  60. package/dist/switchboard-directory-vH6qtkh-.js.map +1 -0
  61. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  62. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  63. package/dist/types-BWx6FPO4.d.ts +63 -0
  64. package/dist/types-BWx6FPO4.d.ts.map +1 -0
  65. package/package.json +19 -17
  66. package/dist/attachment-service-But1Xljo.d.ts.map +0 -1
  67. package/dist/client-BiJAJ9dW.js.map +0 -1
  68. package/dist/client-CngU4mtn.d.ts.map +0 -1
  69. package/dist/client-VV9M73s_.js.map +0 -1
  70. package/dist/dispatch-qRXS70fh.js.map +0 -1
  71. package/dist/document-model-modules-D6I-UUXq.js +0 -386
  72. package/dist/document-model-modules-D6I-UUXq.js.map +0 -1
  73. package/dist/document-operations-Bt-1-ThH.js.map +0 -1
  74. package/dist/global-fql2bmb0.d.ts +0 -438
  75. package/dist/global-fql2bmb0.d.ts.map +0 -1
  76. package/dist/index-BABMK8cO.d.ts.map +0 -1
  77. package/dist/inspector-proxy-DCowaeeH.d.ts +0 -264
  78. package/dist/inspector-proxy-DCowaeeH.d.ts.map +0 -1
  79. package/dist/make-ph-event-functions-FzpvQtj6.js +0 -53
  80. package/dist/make-ph-event-functions-FzpvQtj6.js.map +0 -1
  81. package/dist/relational-ChC_AWAK.js.map +0 -1
  82. package/dist/renown-C9pYZRqf.js.map +0 -1
  83. package/dist/renown-Def5iO8k.js +0 -97
  84. package/dist/renown-Def5iO8k.js.map +0 -1
  85. package/dist/switchboard-CFyD_5_e.js +0 -323
  86. package/dist/switchboard-CFyD_5_e.js.map +0 -1
  87. package/dist/types-B7-_l_wE.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dispatch-qRXS70fh.js","names":[],"sources":["../src/actions/queue.ts","../src/actions/sign.ts","../src/actions/dispatch.ts","../src/document-refetcher.ts","../src/reactor-interop.ts","../src/document-cache.ts","../src/hooks/document-cache.ts","../src/hooks/dispatch.ts"],"sourcesContent":["import type { FileUploadProgressCallback } from \"@powerhousedao/reactor-browser\";\nimport type {\n Action,\n DocumentOperations,\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport async function queueActions(\n document: PHDocument | undefined,\n actionOrActions: Action[] | Action | undefined,\n) {\n if (!document) {\n throw new Error(\"No document provided\");\n }\n if (!actionOrActions) {\n throw new Error(\"No actions provided\");\n }\n const actions = Array.isArray(actionOrActions)\n ? actionOrActions\n : [actionOrActions];\n\n if (actions.length === 0) {\n throw new Error(\"No actions provided\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n return await reactorClient.execute(document.header.id, \"main\", actions);\n}\n\nexport async function queueOperations(\n documentId: string,\n operationOrOperations: Operation[] | Operation | undefined,\n) {\n if (!documentId) {\n throw new Error(\"No documentId provided\");\n }\n if (!operationOrOperations) {\n throw new Error(\"No operations provided\");\n }\n const operations = Array.isArray(operationOrOperations)\n ? operationOrOperations\n : [operationOrOperations];\n\n if (operations.length === 0) {\n throw new Error(\"No operations provided\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const actions = operations.map((op) => op.action);\n return await reactorClient.execute(documentId, \"main\", actions);\n}\n\nexport function deduplicateOperations(\n existingOperations: Record<string, Operation[]>,\n operationsToDeduplicate: Operation[],\n) {\n // make a set of all the operation indices for each scope to avoid duplicates\n const operationIndicesByScope = {} as Record<string, Set<number>>;\n for (const scope of Object.keys(existingOperations)) {\n operationIndicesByScope[scope] = new Set(\n existingOperations[scope].map((op) => op.index),\n );\n }\n\n const newOperations: Operation[] = [];\n\n for (const operation of operationsToDeduplicate) {\n const scope = operation.action.scope;\n const index = operation.index;\n if (operationIndicesByScope[scope].has(index)) {\n const duplicatedExistingOperation = existingOperations[scope].find(\n (op) => op.index === index,\n );\n const duplicatedNewOperation = newOperations.find(\n (op) => op.index === index,\n );\n console.warn(\"skipping duplicate operation\");\n if (duplicatedExistingOperation) {\n console.warn(\n \"duplicate existing operation\",\n duplicatedExistingOperation,\n );\n }\n if (duplicatedNewOperation) {\n console.warn(\"duplicate new operation\", duplicatedNewOperation);\n }\n continue;\n }\n newOperations.push(operation);\n operationIndicesByScope[scope].add(index);\n }\n\n const uniqueOperationIds = new Set<string>();\n const operationsDedupedById: Operation[] = [];\n\n for (const [scope, operations] of Object.entries(existingOperations)) {\n for (const operation of operations) {\n const id = operation.id;\n if (!id) {\n console.warn(\"skipping operation with no id\", operation);\n continue;\n }\n if (uniqueOperationIds.has(id)) {\n console.warn(\n \"skipping existing operation with duplicate id in scope\",\n scope,\n operation,\n );\n continue;\n }\n uniqueOperationIds.add(id);\n }\n }\n\n for (const operation of newOperations) {\n const id = operation.id;\n if (!id) {\n console.warn(\"skipping operation with no id\", operation);\n continue;\n }\n if (uniqueOperationIds.has(id)) {\n console.warn(\n \"skipping new operation with duplicate id in scope\",\n operation.action.scope,\n operation,\n );\n continue;\n }\n uniqueOperationIds.add(id);\n operationsDedupedById.push(operation);\n }\n return operationsDedupedById;\n}\n\nexport async function uploadOperations(\n documentId: string,\n allOperations: DocumentOperations,\n pushOperations: (\n documentId: string,\n operations: Operation[],\n ) => Promise<PHDocument | undefined>,\n options?: {\n operationsLimit?: number;\n onProgress?: FileUploadProgressCallback;\n },\n) {\n const operationsLimit = options?.operationsLimit || 50;\n const onProgress = options?.onProgress;\n\n logger.verbose(\n `uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(\",\")}, limit:${operationsLimit})`,\n );\n\n // Calculate total operations for progress tracking\n const allOperationsArray = Object.values(allOperations).filter(\n (ops): ops is Operation[] => ops !== undefined,\n );\n const totalOperations = allOperationsArray.reduce(\n (total, operations) => total + operations.length,\n 0,\n );\n let uploadedOperations = 0;\n\n for (const operations of allOperationsArray) {\n for (let i = 0; i < operations.length; i += operationsLimit) {\n logger.verbose(\n `uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`,\n );\n const chunk = operations.slice(i, i + operationsLimit);\n const operation = chunk.at(-1);\n if (!operation) {\n break;\n }\n const scope = operation.action.scope;\n\n await pushOperations(documentId, chunk);\n\n uploadedOperations += chunk.length;\n\n // Report progress\n if (onProgress) {\n const progress = Math.round(\n (uploadedOperations / totalOperations) * 100,\n );\n onProgress({\n stage: \"uploading\",\n progress,\n totalOperations,\n uploadedOperations,\n });\n }\n\n logger.verbose(\n `uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`,\n );\n }\n }\n\n logger.verbose(\n `uploadDocumentOperations:for:waitForUpdate(${documentId}): END`,\n );\n}\n","import type {\n Action,\n ActionSigner,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport function addActionContext(action: Action) {\n const renown = window.ph?.renown;\n if (!renown?.user) return action;\n\n const signer: ActionSigner = {\n app: {\n name: \"Connect\",\n key: renown.did,\n },\n user: {\n address: renown.user.address,\n networkId: renown.user.networkId,\n chainId: renown.user.chainId,\n },\n signatures: [],\n };\n\n return {\n context: { signer },\n ...action,\n };\n}\n\nfunction makeSignedActionWithContext(\n action: Action | undefined,\n document: PHDocument | undefined,\n) {\n if (!action) {\n logger.error(\"No action found\");\n return;\n }\n if (!document) {\n logger.error(\"No document found\");\n return;\n }\n // The reactor client signs it: an empty signer is filled in for the log the\n // write lands in, which only the client knows.\n return addActionContext(action);\n}\n\nexport function makeSignedActionsWithContext(\n actionOrActions: Action[] | Action | undefined,\n document: PHDocument | undefined,\n) {\n if (!actionOrActions) {\n logger.error(\"No actions found\");\n return;\n }\n const actions = Array.isArray(actionOrActions)\n ? actionOrActions\n : [actionOrActions];\n\n const signedActionsWithContext = actions.map((action) =>\n makeSignedActionWithContext(action, document),\n );\n return signedActionsWithContext.filter((a) => a !== undefined);\n}\n","import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { queueActions } from \"./queue.js\";\nimport { makeSignedActionsWithContext } from \"./sign.js\";\n\nasync function getDocument(\n documentId: string,\n): Promise<PHDocument | undefined> {\n try {\n return await window.ph?.reactorClient?.get(documentId);\n } catch (error) {\n logger.debug(`Failed to get document with id ${documentId}:`, error);\n return undefined;\n }\n}\n\nfunction getActionErrors(result: PHDocument, actions: Action[]) {\n return actions.reduce((errors, a) => {\n const scopeOperations = result.operations[a.scope];\n if (!scopeOperations) {\n return errors;\n }\n const op = scopeOperations.findLast((op) => op.action.id === a.id);\n\n if (op?.error) {\n errors.push(new Error(op.error));\n }\n return errors;\n }, new Array<Error>());\n}\n\n/**\n * Dispatches actions to a document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param document - The document to dispatch actions to.\n * @param onErrors - Callback invoked with any errors that occurred during action execution,\n * or with why nothing was dispatched.\n * @returns The updated document, or undefined if the dispatch failed.\n */\nexport async function dispatchActions<TDocument = PHDocument, TAction = Action>(\n actionOrActions: TAction[] | TAction | undefined,\n document: TDocument | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined>;\n/**\n * Dispatches actions to a document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param documentId - The ID of the document to dispatch actions to.\n * @param onErrors - Callback invoked with any errors that occurred during action execution.\n * @returns The updated document, or undefined if the dispatch failed.\n */\nexport async function dispatchActions(\n actionOrActions: Action[] | Action | undefined,\n documentId: string,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined>;\nexport async function dispatchActions(\n actionOrActions: Action[] | Action | undefined,\n documentOrDocumentId: PHDocument | string | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined> {\n const document =\n typeof documentOrDocumentId === \"string\"\n ? await getDocument(documentOrDocumentId)\n : documentOrDocumentId;\n\n if (!document) {\n const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;\n logger.error(message);\n onErrors?.([new Error(message)]);\n return;\n }\n\n const signedActionsWithContext = makeSignedActionsWithContext(\n actionOrActions,\n document,\n );\n if (!signedActionsWithContext) {\n const message = \"No signed actions with context found\";\n logger.error(message);\n onErrors?.([new Error(message)]);\n return;\n }\n const result = await queueActions(document, signedActionsWithContext);\n\n if (onErrors && result) {\n const errors = getActionErrors(result, signedActionsWithContext);\n if (errors.length) {\n onErrors(errors);\n }\n }\n\n if (onSuccess && result) {\n onSuccess(result);\n }\n\n return result;\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type {\n DocumentRefetchState,\n FulfilledPromise,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.js\";\n\n/** The refetch snapshot of a document with nothing in flight and no kept failure. */\nexport const IDLE_REFETCH_STATE: DocumentRefetchState = Object.freeze({\n isRefetching: false,\n error: undefined,\n});\n\nfunction fulfilledPromise<T>(value: T): FulfilledPromise<T> {\n const promise = Promise.resolve(value) as FulfilledPromise<T>;\n promise.status = \"fulfilled\";\n promise.value = value;\n return promise;\n}\n\nfunction rejectedPromise<T>(reason: unknown): RejectedPromise<T> {\n const promise = Promise.reject(reason as Error) as RejectedPromise<T>;\n promise.status = \"rejected\";\n promise.reason = reason;\n // Readers get the reason from `status`; the refetch caller gets the rejection.\n promise.catch(() => undefined);\n return promise;\n}\n\nconst MISSING_DOCUMENT_ERRORS = [\n \"DocumentNotFoundError\",\n \"DocumentDeletedError\",\n];\n\n// The document is gone, so its last loaded state must not stay on screen.\n// The document view and GraphQL client throw a plain \"Document not found\" Error.\nexport function isMissingDocumentError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (\n MISSING_DOCUMENT_ERRORS.includes(error.name) ||\n error.message.startsWith(\"Document not found\")\n );\n}\n\nconst noop = () => undefined;\n\n/** One refetch running per cache key, and at most one queued behind it. */\ntype Refetch = {\n running: Promise<PHDocument> | undefined;\n queued: Promise<PHDocument> | undefined;\n};\n\nexport type DocumentRefetcherHost = {\n /** The cache's stored promises; an entry is replaced only once its refetch settles. */\n documents: Map<string, PromiseWithState<PHDocument>>;\n fetch(id: string): Promise<PHDocument>;\n notify(id: string): void;\n onFetched?(id: string, document: PHDocument): void;\n};\n\n/** Background refetch of loaded documents: readers keep the loaded promise until it settles. */\nexport class DocumentRefetcher {\n private refetches = new Map<string, Refetch>();\n private states = new Map<string, DocumentRefetchState>();\n\n constructor(private readonly host: DocumentRefetcherHost) {}\n\n getState(id: string): DocumentRefetchState {\n return this.states.get(id) ?? IDLE_REFETCH_STATE;\n }\n\n /** Serializes refetches per key: one runs, later requests share one queued run. */\n refetch(id: string): Promise<PHDocument> {\n let entry = this.refetches.get(id);\n if (!entry) {\n entry = { running: undefined, queued: undefined };\n this.refetches.set(id, entry);\n const current = this.host.documents.get(id);\n if (current?.status !== \"pending\") {\n return this.start(id, entry);\n }\n // A pending first load may predate the change, so refetch after it.\n entry.running = current;\n }\n const inFlight = entry;\n inFlight.queued ??= (inFlight.running ?? Promise.resolve())\n .then(noop, noop)\n .then(() => this.start(id, inFlight));\n return inFlight.queued;\n }\n\n /** Stops any refetch of `id` from writing back, e.g. on deletion. */\n forget(id: string): void {\n this.refetches.delete(id);\n this.states.delete(id);\n }\n\n clear(): void {\n this.refetches.clear();\n this.states.clear();\n }\n\n private start(id: string, entry: Refetch): Promise<PHDocument> {\n entry.queued = undefined;\n entry.running = this.run(id, entry);\n return entry.running;\n }\n\n private async run(id: string, entry: Refetch): Promise<PHDocument> {\n const isCurrent = () => this.refetches.get(id) === entry;\n // Superseded: answer the caller without touching the cache.\n if (!isCurrent()) {\n return this.host.fetch(id);\n }\n const started = this.setState(id, {\n isRefetching: true,\n error: this.getState(id).error,\n });\n if (started) {\n this.host.notify(id);\n }\n try {\n const document = await this.host.fetch(id);\n if (isCurrent()) {\n this.host.onFetched?.(id, document);\n this.host.documents.set(id, fulfilledPromise(document));\n this.finish(id, entry, undefined);\n }\n return document;\n } catch (error) {\n if (isCurrent()) {\n if (isMissingDocumentError(error)) {\n this.host.documents.set(id, rejectedPromise(error));\n this.finish(id, entry, undefined);\n } else {\n console.warn(\n \"[DocumentCache] Refetch failed; keeping the loaded document:\",\n error,\n );\n this.finish(id, entry, error);\n }\n }\n throw error;\n }\n }\n\n private finish(id: string, entry: Refetch, error: unknown): void {\n if (!entry.queued) {\n this.refetches.delete(id);\n }\n this.setState(id, { isRefetching: entry.queued !== undefined, error });\n this.host.notify(id);\n }\n\n /** Returns whether the snapshot changed; the caller notifies. */\n private setState(id: string, state: DocumentRefetchState): boolean {\n const current = this.getState(id);\n if (\n current.isRefetching === state.isRefetching &&\n current.error === state.error\n ) {\n return false;\n }\n if (!state.isRefetching && state.error === undefined) {\n this.states.delete(id);\n } else {\n this.states.set(id, Object.freeze({ ...state }));\n }\n return true;\n }\n}\n","import type {\n DocumentChangeType,\n DuplicateManifestError,\n DuplicateModuleError,\n} from \"@powerhousedao/reactor\";\n\n/**\n * The handful of runtime values the browser-safe surface needs from\n * `@powerhousedao/reactor`, mirrored so that nothing on that surface has to\n * import the package as a value.\n *\n * `@powerhousedao/reactor` has a single entry point, and it reaches `pg`\n * (`dns`/`fs`/`net`/`tls`), `@electric-sql/pglite` and `node:worker_threads`. A\n * browser bundler must resolve all of those the moment any module imports a\n * VALUE from the package, which is what previously forced every consuming app\n * to alias the reactor away in its own build config. Type imports are erased\n * before the bundler ever sees them, so types keep coming from the reactor and\n * only these values are mirrored.\n *\n * Drift is a compile error rather than a runtime surprise - see the assertions\n * below.\n */\n\nconst DOCUMENT_CHANGE_TYPE_VALUES = {\n Created: \"created\",\n Deleted: \"deleted\",\n Updated: \"updated\",\n ParentAdded: \"parent_added\",\n ParentRemoved: \"parent_removed\",\n ChildAdded: \"child_added\",\n ChildRemoved: \"child_removed\",\n} as const satisfies Record<string, `${DocumentChangeType}`>;\n\n/**\n * `satisfies` above rejects a mirrored value the enum does not declare. This\n * rejects the other direction: a member the reactor added and this mirror does\n * not cover.\n */\ntype MissingDocumentChangeTypeMembers = Exclude<\n `${DocumentChangeType}`,\n (typeof DOCUMENT_CHANGE_TYPE_VALUES)[keyof typeof DOCUMENT_CHANGE_TYPE_VALUES]\n>;\ntype AssertNoMissingDocumentChangeTypeMembers = [\n MissingDocumentChangeTypeMembers,\n] extends [never]\n ? true\n : [\n \"DOCUMENT_CHANGE_TYPE is missing DocumentChangeType members\",\n MissingDocumentChangeTypeMembers,\n ];\nconst documentChangeTypeMirrorIsComplete: AssertNoMissingDocumentChangeTypeMembers = true;\nvoid documentChangeTypeMirrorIsComplete;\n\n/**\n * The reactor's `DocumentChangeType` members, typed as the enum so they can be\n * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a\n * TypeScript string enum is nominal, so no string literal is assignable to it\n * without one - and the two checks above are what make it safe.\n */\nexport const DOCUMENT_CHANGE_TYPE = DOCUMENT_CHANGE_TYPE_VALUES as unknown as {\n readonly [K in keyof typeof DOCUMENT_CHANGE_TYPE_VALUES]: DocumentChangeType;\n};\n\n/**\n * Structural equivalents of the reactor error classes' own static `isError`\n * guards. Those guards match on `error.name` rather than the prototype chain\n * (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is\n * behaviour-preserving and does not need the class at runtime.\n */\nexport function isDuplicateModuleError(\n error: unknown,\n): error is DuplicateModuleError {\n return Error.isError(error) && error.name === \"DuplicateModuleError\";\n}\n\nexport function isDuplicateManifestError(\n error: unknown,\n): error is DuplicateManifestError {\n return Error.isError(error) && error.name === \"DuplicateManifestError\";\n}\n","import type { DocumentChangeEvent, PagedResults } from \"@powerhousedao/reactor\";\nimport { DocumentRefetcher } from \"./document-refetcher.js\";\nimport { DOCUMENT_CHANGE_TYPE } from \"./reactor-interop.js\";\nimport type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n DocumentRefetchState,\n FulfilledPromise,\n IDocumentCache,\n IOperationCache,\n OperationsCacheEntry,\n PromiseState,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.js\";\nimport type { IReactorBrowserClient } from \"./types/reactor-browser-client.js\";\n\nexport function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T> {\n if (\"status\" in promise) {\n return promise as PromiseWithState<T>;\n }\n\n const promiseWithState = promise as PromiseWithState<T>;\n promiseWithState.status = \"pending\";\n promiseWithState.then(\n (value) => {\n promiseWithState.status = \"fulfilled\";\n (promiseWithState as FulfilledPromise<T>).value = value;\n },\n (reason) => {\n promiseWithState.status = \"rejected\";\n (promiseWithState as RejectedPromise<T>).reason = reason;\n // Re-throw to preserve unhandled rejection behavior\n // This allows React's error boundaries to catch the error\n throw reason;\n },\n );\n\n return promiseWithState;\n}\n\nexport function readPromiseState<T>(\n promise: Promise<T> | PromiseWithState<T>,\n): PromiseState<T> {\n return \"status\" in promise ? promise : { status: \"pending\" };\n}\n\n/**\n * Resolves an array of document promises using `Promise.allSettled`,\n * returning only the fulfilled values. A single missing/rejected\n * document does not poison the whole batch. Rejected entries are\n * logged at warn level so developers can see dangling references.\n */\nfunction fulfilledOnly(promises: Promise<PHDocument>[]): Promise<PHDocument[]> {\n return Promise.allSettled(promises).then((results) => {\n const documents: PHDocument[] = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n documents.push(result.value);\n } else {\n console.warn(\n \"[DocumentCache] Skipped unavailable document:\",\n result.reason,\n );\n }\n }\n return documents;\n });\n}\n\n/** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */\nexport const IDLE_OPERATIONS_ENTRY: OperationsCacheEntry = Object.freeze({\n status: \"idle\",\n operations: Object.freeze([]) as readonly Operation[],\n error: undefined,\n hasNextPage: false,\n});\n\n/** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */\nexport function isOperationCache(cache: unknown): cache is IOperationCache {\n if (typeof cache !== \"object\" || cache === null) return false;\n const candidate = cache as Partial<IOperationCache>;\n return (\n typeof candidate.getOperationsState === \"function\" &&\n typeof candidate.loadOperations === \"function\" &&\n typeof candidate.loadMoreOperations === \"function\" &&\n typeof candidate.invalidateOperations === \"function\" &&\n typeof candidate.subscribeOperations === \"function\"\n );\n}\n\n/**\n * Page size used to refresh a scope whose request record has gone missing.\n * A loaded scope always has one, so this is a floor rather than a default.\n */\nconst FALLBACK_REFRESH_LIMIT = 100;\n\n/**\n * The highest revision among the operations loaded so far, or -1 for none.\n * Pages arrive oldest first, so this is normally the last entry; it is\n * computed rather than assumed because nothing in the cache enforces that.\n */\nfunction highestOperationIndex(operations: readonly Operation[]): number {\n let highest = -1;\n for (const operation of operations) {\n if (operation.index > highest) highest = operation.index;\n }\n return highest;\n}\n\n/** Bookkeeping for one document scope that is not part of its snapshot. */\ntype OperationsRequest = {\n /** Aborts the request in flight, or marks a settled one as superseded. */\n controller: AbortController;\n /** The cursor for the page after the last loaded one; `undefined` when there is none. */\n nextCursor: string | undefined;\n /** The page size the scope was loaded with, reused for every subsequent page. */\n limit: number;\n};\n\n/**\n * Document cache implementation that uses the new ReactorClient API.\n *\n * This cache subscribes to document change events via IReactorBrowserClient.subscribe()\n * and automatically updates the cache when documents are created, updated, or deleted.\n * It also holds paginated operation history per document scope (see `IOperationCache`),\n * which is dropped for a document whenever a change event for it arrives.\n */\nexport class DocumentCache implements IDocumentCache, IOperationCache {\n private documents = new Map<string, PromiseWithState<PHDocument>>();\n private batchPromises = new Map<\n string,\n { promises: Promise<PHDocument>[]; promise: Promise<PHDocument[]> }\n >();\n private listeners = new Map<string, (() => void)[]>();\n\n private refetcher = new DocumentRefetcher({\n documents: this.documents,\n fetch: (id) => this.client.get(id),\n notify: (id) => this.notifyListeners(id),\n onFetched: (id, document) => {\n if (document.header.id !== id) {\n this.recordAlias(document.header.id, id);\n }\n },\n });\n\n /**\n * Cache keys that fetched a document under a name other than its id --\n * slugs, which `client.get` resolves. Change events dispatch by `header.id`,\n * so without this mapping a slug-keyed entry (and its listeners) would never\n * see an update: keyed by the id the events carry, valued by the other keys\n * the same document is cached under.\n */\n private aliasKeys = new Map<string, Set<string>>();\n\n /** Operations by document id, then scope. Entries are replaced, never mutated. */\n private operationEntries = new Map<\n string,\n Map<string, OperationsCacheEntry>\n >();\n /** In-flight controllers and the next page's cursor/limit, by document id then scope. */\n private operationRequests = new Map<string, Map<string, OperationsRequest>>();\n private operationListeners = new Map<string, (() => void)[]>();\n\n private unsubscribe: (() => void) | null = null;\n\n constructor(private client: IReactorBrowserClient) {\n this.unsubscribe = client.subscribe({}, (event: DocumentChangeEvent) => {\n this.handleDocumentChange(event);\n });\n }\n\n private handleDocumentChange(event: DocumentChangeEvent): void {\n if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {\n const documentId = event.context?.childId;\n if (documentId) {\n // Read the alias keys before `handleDocumentDeleted` clears them, so a\n // slug-keyed operations entry is invalidated too.\n const keys = this.cacheKeysFor(documentId);\n this.handleDocumentDeleted(documentId);\n for (const key of keys) {\n this.invalidateOperations(key);\n }\n }\n } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) {\n for (const doc of event.documents) {\n const keys = this.cacheKeysFor(doc.header.id);\n this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n for (const key of keys) {\n this.refreshOperations(key);\n }\n }\n }\n }\n\n private handleDocumentDeleted(documentId: string): void {\n for (const key of this.cacheKeysFor(documentId)) {\n const listeners = this.listeners.get(key);\n this.documents.delete(key);\n this.refetcher.forget(key);\n this.invalidateBatchesContaining(key);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n this.listeners.delete(key);\n }\n this.aliasKeys.delete(documentId);\n }\n\n // The refetch notifies listeners itself once it settles.\n private async handleDocumentUpdated(documentId: string): Promise<void> {\n const refetches = this.cacheKeysFor(documentId)\n .filter((key) => this.documents.has(key))\n .map((key) => this.get(key, true));\n await Promise.all(refetches);\n }\n\n private notifyListeners(key: string): void {\n for (const listener of this.listeners.get(key) ?? []) {\n listener();\n }\n }\n\n /** The id an event dispatches by, plus every alias the document is cached under. */\n private cacheKeysFor(documentId: string): string[] {\n return [documentId, ...(this.aliasKeys.get(documentId) ?? [])];\n }\n\n /** Records that `key` cached the document change events know as `header.id`. */\n private recordAlias(documentId: string, key: string): void {\n const keys = this.aliasKeys.get(documentId) ?? new Set<string>();\n keys.add(key);\n this.aliasKeys.set(documentId, keys);\n }\n\n private invalidateBatchesContaining(documentId: string): void {\n for (const key of this.batchPromises.keys()) {\n if (key.split(\",\").includes(documentId)) {\n this.batchPromises.delete(key);\n }\n }\n }\n\n get(id: string, refetch?: boolean): Promise<PHDocument> {\n const currentData = this.documents.get(id);\n if (currentData && !refetch) {\n return currentData;\n }\n // A loaded document stays served while it refetches; a pending first load\n // may predate the change, so it gets a refetch queued behind it.\n if (currentData && currentData.status !== \"rejected\") {\n return this.refetcher.refetch(id);\n }\n\n this.refetcher.forget(id);\n const documentPromise = this.client.get(id);\n documentPromise.then(\n (doc) => {\n if (doc.header.id !== id) {\n this.recordAlias(doc.header.id, id);\n }\n },\n // Rejections are surfaced by the stored promise; this chain only learns aliases.\n () => undefined,\n );\n this.documents.set(id, addPromiseState(documentPromise));\n return documentPromise;\n }\n\n getRefetchState(id: string): DocumentRefetchState {\n return this.refetcher.getState(id);\n }\n\n getBatch(ids: string[]): Promise<PHDocument[]> {\n const key = ids.join(\",\");\n const cached = this.batchPromises.get(key);\n\n const hasDeletedDocuments = ids.some((id) => !this.documents.has(id));\n const currentPromises = ids.map((id) => this.get(id));\n\n if (hasDeletedDocuments) {\n const batchPromise = fulfilledOnly(currentPromises);\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n if (cached) {\n const samePromises = currentPromises.every(\n (p, i) => p === cached.promises[i],\n );\n if (samePromises) {\n return cached.promise;\n }\n }\n\n const states = currentPromises.map((p) =>\n readPromiseState(p as PromiseWithState<PHDocument>),\n );\n const allSettled = states.every((s) => s.status !== \"pending\");\n\n if (allSettled) {\n const values = states\n .filter(\n (s): s is { status: \"fulfilled\"; value: PHDocument } =>\n s.status === \"fulfilled\",\n )\n .map((s) => s.value);\n const batchPromise = Promise.resolve(values) as PromiseWithState<\n PHDocument[]\n >;\n batchPromise.status = \"fulfilled\";\n (batchPromise as FulfilledPromise<PHDocument[]>).value = values;\n\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n if (cached) {\n return cached.promise;\n }\n\n const batchPromise = fulfilledOnly(currentPromises);\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n subscribe(id: string | string[], callback: () => void): () => void {\n const ids = Array.isArray(id) ? id : [id];\n for (const docId of ids) {\n const listeners = this.listeners.get(docId) ?? [];\n this.listeners.set(docId, [...listeners, callback]);\n }\n return () => {\n for (const docId of ids) {\n const listeners = this.listeners.get(docId) ?? [];\n this.listeners.set(\n docId,\n listeners.filter((listener) => listener !== callback),\n );\n }\n };\n }\n\n getOperationsState(documentId: string, scope: string): OperationsCacheEntry {\n return (\n this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY\n );\n }\n\n loadOperations(documentId: string, scope: string, limit: number): void {\n const current = this.getOperationsState(documentId, scope);\n if (current.status !== \"idle\") {\n return;\n }\n const controller = new AbortController();\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: undefined,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n undefined,\n { cursor: \"\", limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n\n loadMoreOperations(documentId: string, scope: string): void {\n const current = this.getOperationsState(documentId, scope);\n const request = this.operationRequests.get(documentId)?.get(scope);\n if (\n current.status !== \"success\" ||\n !current.hasNextPage ||\n !request?.nextCursor\n ) {\n return;\n }\n // Each page gets its own controller, so invalidation can abort whichever\n // page is currently in flight.\n const controller = new AbortController();\n const { nextCursor, limit } = request;\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n undefined,\n { cursor: nextCursor, limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n\n /**\n * Bring a document's cached scopes up to date after it changed, without\n * throwing away what is already loaded.\n *\n * The operation stream is append-only: an update adds operations at higher\n * revisions and never rewrites the ones below, so history already paged in\n * is still correct. Dropping it meant a panel showing a fully loaded\n * document re-walked every page on each edit -- the cost of which grows\n * with the document, exactly where it hurts most. Each scope instead asks\n * only for what comes after the newest revision it holds, using the\n * `sinceRevision` filter, and appends the answer.\n *\n * A scope that has not finished paging is dropped as before: it has no\n * meaningful \"newest revision\" to resume from, since asking for everything\n * past the newest row it happens to hold would skip the pages between that\n * row and the end of the stream.\n */\n private refreshOperations(documentId: string): void {\n const scopes = this.operationEntries.get(documentId);\n if (!scopes) return;\n\n for (const [scope, entry] of [...scopes.entries()]) {\n if (entry.status !== \"success\" || entry.hasNextPage) {\n this.invalidateOperationsScope(documentId, scope);\n continue;\n }\n\n const previous = this.operationRequests.get(documentId)?.get(scope);\n const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;\n // Marks the settled page superseded, so a late arrival cannot append\n // on top of the refresh.\n previous?.controller.abort();\n\n const controller = new AbortController();\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: undefined,\n limit,\n });\n // Pending, but the operations stay in the entry: consumers keep\n // rendering the history they have instead of flashing empty while the\n // tail is fetched.\n this.setOperationsEntry(documentId, scope, {\n ...entry,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n { sinceRevision: highestOperationIndex(entry.operations) + 1 },\n { cursor: \"\", limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n }\n\n /** Drops one scope of a document, aborting its request if one is in flight. */\n private invalidateOperationsScope(documentId: string, scope: string): void {\n const requests = this.operationRequests.get(documentId);\n const request = requests?.get(scope);\n if (request && requests) {\n request.controller.abort();\n requests.delete(scope);\n if (requests.size === 0) {\n this.operationRequests.delete(documentId);\n }\n }\n const scopes = this.operationEntries.get(documentId);\n if (scopes?.delete(scope)) {\n if (scopes.size === 0) {\n this.operationEntries.delete(documentId);\n }\n this.notifyOperationListeners(documentId);\n }\n }\n\n invalidateOperations(documentId: string): void {\n const requests = this.operationRequests.get(documentId);\n if (requests) {\n for (const request of requests.values()) {\n request.controller.abort();\n }\n this.operationRequests.delete(documentId);\n }\n if (this.operationEntries.delete(documentId)) {\n this.notifyOperationListeners(documentId);\n }\n }\n\n subscribeOperations(documentId: string, callback: () => void): () => void {\n const listeners = this.operationListeners.get(documentId) ?? [];\n this.operationListeners.set(documentId, [...listeners, callback]);\n return () => {\n const current = this.operationListeners.get(documentId) ?? [];\n this.operationListeners.set(\n documentId,\n current.filter((listener) => listener !== callback),\n );\n };\n }\n\n private settleOperationsPage(\n documentId: string,\n scope: string,\n page: Promise<PagedResults<Operation>>,\n controller: AbortController,\n limit: number,\n ): void {\n page.then(\n (result) => {\n if (controller.signal.aborted) return;\n const current = this.getOperationsState(documentId, scope);\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: result.nextCursor,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n status: \"success\",\n operations: [...current.operations, ...result.results],\n error: undefined,\n hasNextPage: !!result.nextCursor,\n });\n },\n (reason: unknown) => {\n if (controller.signal.aborted) return;\n const current = this.getOperationsState(documentId, scope);\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"error\",\n error: reason,\n });\n },\n );\n }\n\n private setOperationsEntry(\n documentId: string,\n scope: string,\n entry: OperationsCacheEntry,\n ): void {\n const scopes =\n this.operationEntries.get(documentId) ??\n new Map<string, OperationsCacheEntry>();\n scopes.set(scope, entry);\n this.operationEntries.set(documentId, scopes);\n this.notifyOperationListeners(documentId);\n }\n\n private setOperationsRequest(\n documentId: string,\n scope: string,\n request: OperationsRequest,\n ): void {\n const scopes =\n this.operationRequests.get(documentId) ??\n new Map<string, OperationsRequest>();\n scopes.set(scope, request);\n this.operationRequests.set(documentId, scopes);\n }\n\n private notifyOperationListeners(documentId: string): void {\n for (const listener of this.operationListeners.get(documentId) ?? []) {\n listener();\n }\n }\n\n /**\n * Disposes of the cache and unsubscribes from document change events.\n */\n dispose(): void {\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = null;\n }\n for (const requests of this.operationRequests.values()) {\n for (const request of requests.values()) {\n request.controller.abort();\n }\n }\n this.operationRequests.clear();\n this.operationEntries.clear();\n this.refetcher.clear();\n this.operationListeners.clear();\n }\n}\n\nexport { IDLE_REFETCH_STATE } from \"./document-refetcher.js\";\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n use,\n useCallback,\n useEffect,\n useReducer,\n useSyncExternalStore,\n} from \"react\";\nimport { IDLE_REFETCH_STATE, readPromiseState } from \"../document-cache.js\";\nimport type {\n DocumentRefetchState,\n IDocumentCache,\n} from \"../types/documents.js\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst documentEventFunctions = makePHEventFunctions(\"documentCache\");\n\n/** Returns all documents in the reactor. */\nexport const useDocumentCache: UsePHGlobalValue<IDocumentCache> =\n documentEventFunctions.useValue;\n\n/** Sets all of the documents in the reactor. */\nexport const setDocumentCache: SetPHGlobalValue<IDocumentCache> =\n documentEventFunctions.setValue;\n\n/** Adds an event handler for all of the documents in the reactor. */\nexport const addDocumentCacheEventHandler =\n documentEventFunctions.addEventHandler;\n\n/**\n * Reads the state of a document promise and converts it to a query state object.\n * @param promise - The document promise to read\n * @returns An object containing the status, data, error, and isPending flag\n */\nfunction getDocumentQueryState(promise: Promise<PHDocument>) {\n const state = readPromiseState(promise);\n switch (state.status) {\n case \"pending\":\n return {\n status: \"pending\",\n isPending: true,\n error: undefined,\n data: undefined,\n } as const;\n case \"fulfilled\":\n return {\n status: \"success\",\n isPending: false,\n error: undefined,\n data: state.value,\n } as const;\n case \"rejected\":\n return {\n status: \"error\",\n isPending: false,\n error: state.reason,\n data: undefined,\n } as const;\n }\n}\n\n/**\n * Retrieves a document from the reactor and subscribes to changes using React Suspense.\n * This hook will suspend rendering while the document is loading.\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns The document if found, or undefined if id is null/undefined\n */\nexport function useDocument(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n const document = useSyncExternalStore(\n (cb) => (id && documentCache ? documentCache.subscribe(id, cb) : () => {}),\n () => (id ? documentCache?.get(id) : undefined),\n );\n return document ? use(document) : undefined;\n}\n\n/**\n * Retrieves a document from the reactor and subscribes to changes without\n * suspending or throwing. Use this when the ID might be stale (e.g., a\n * previously selected node that has since been deleted) and the consumer\n * wants to render a placeholder instead of crashing.\n *\n * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache\n * updates, so the returned state stays in sync with reactor changes.\n *\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns An object containing:\n * - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n * - data: The document if successfully loaded\n * - isPending: Whether the document is currently loading\n * - error: Any error that occurred during loading (e.g., document not found)\n * - reload: Function to force a refetch, or undefined when no id is supplied\n * - isRefetching: A loaded document is being refetched; `data` is the loaded one\n * - refetchError: The last refetch failure that kept the loaded document\n */\nexport function useDocumentSafe(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n const subscribe = (cb: () => void) =>\n id && documentCache ? documentCache.subscribe(id, cb) : () => {};\n const promise = useSyncExternalStore(subscribe, () =>\n id ? documentCache?.get(id) : undefined,\n );\n const refetch = useSyncExternalStore(subscribe, () =>\n readRefetchState(documentCache, id),\n );\n\n // The cache notifies subscribers only when a document CHANGES (its stored\n // promise is replaced); the INITIAL fetch settles without a notification,\n // and since the snapshot above is the promise itself - same identity before\n // and after settling - nothing re-renders this hook past \"pending\" on a\n // page that is otherwise quiet. Watch the pending promise and bump local\n // state when it settles, so the state below is re-read. The promise is\n // captured at render time: if it settles before the effect runs, `.then`\n // still fires the bump on the next microtask, so the race loses nothing.\n // `useDocument` needs none of this - React itself resumes a component\n // suspended on `use(promise)`.\n const [, bumpOnSettle] = useReducer((count: number) => count + 1, 0);\n const pendingPromise =\n promise && readPromiseState(promise).status === \"pending\" ? promise : null;\n useEffect(() => {\n if (!pendingPromise) return;\n let active = true;\n const settled = () => {\n if (active) bumpOnSettle();\n };\n pendingPromise.then(settled, settled);\n return () => {\n active = false;\n };\n }, [pendingPromise]);\n\n if (!promise || !documentCache || !id) {\n return {\n status: \"initial\",\n isPending: false,\n error: undefined,\n data: undefined,\n reload: undefined,\n isRefetching: false,\n refetchError: undefined,\n } as const;\n }\n\n const state = getDocumentQueryState(promise);\n return {\n ...state,\n reload: () => documentCache.get(id, true),\n isRefetching: refetch.isRefetching,\n refetchError: refetch.error,\n } as const;\n}\n\nfunction readRefetchState(\n documentCache: IDocumentCache | undefined,\n id: string | null | undefined,\n): DocumentRefetchState {\n return (id && documentCache?.getRefetchState?.(id)) || IDLE_REFETCH_STATE;\n}\n\n/**\n * Retrieves multiple documents from the reactor using React Suspense.\n * This hook will suspend rendering while any of the documents are loading.\n *\n * Uses getBatch from the document cache which handles promise caching internally,\n * ensuring stable references for useSyncExternalStore.\n *\n * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval\n * @returns An array of documents if found, or empty array if ids is null/undefined\n */\nexport function useDocuments(ids: string[] | null | undefined) {\n const documentCache = useDocumentCache();\n\n const documents = useSyncExternalStore(\n (cb) =>\n ids?.length && documentCache\n ? documentCache.subscribe(ids, cb)\n : () => {},\n () =>\n ids?.length && documentCache ? documentCache.getBatch(ids) : undefined,\n );\n\n return documents ? use(documents) : [];\n}\n\n/**\n * Returns a function to retrieve a document from the cache.\n * The returned function fetches and returns a document by ID.\n * @returns A function that takes a document ID and returns a Promise of the document\n */\nexport function useGetDocument() {\n const documentCache = useDocumentCache();\n\n return useCallback(\n (id: string) => {\n if (!documentCache) {\n return Promise.reject(new Error(\"Document cache not initialized\"));\n }\n return documentCache.get(id);\n },\n [documentCache],\n );\n}\n\n/**\n * Returns a function to retrieve multiple documents from the cache.\n * The returned function fetches and returns documents by their IDs.\n * @returns A function that takes an array of document IDs and returns a Promise of the documents\n */\nexport function useGetDocuments() {\n const documentCache = useDocumentCache();\n\n return useCallback(\n (ids: string[]) => {\n if (!documentCache) {\n return Promise.reject(new Error(\"Document cache not initialized\"));\n }\n return documentCache.getBatch(ids);\n },\n [documentCache],\n );\n}\n\n/**\n * Retrieves a document from the reactor without suspending rendering.\n * Returns the current state of the document loading operation.\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns An object containing:\n * - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n * - data: The document if successfully loaded\n * - isPending: Boolean indicating if the document is currently loading\n * - error: Any error that occurred during loading\n * - reload: Function to force reload the document from cache\n * - isRefetching: A loaded document is being refetched; `data` is the loaded one\n * - refetchError: The last refetch failure that kept the loaded document\n */\nexport function useGetDocumentAsync(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n if (!id || !documentCache) {\n return {\n status: \"initial\",\n data: undefined,\n isPending: false,\n error: undefined,\n reload: undefined,\n isRefetching: false,\n refetchError: undefined,\n } as const;\n }\n\n const promise = documentCache.get(id);\n const state = getDocumentQueryState(promise);\n const refetch = readRefetchState(documentCache, id);\n\n return {\n ...state,\n reload: () => documentCache.get(id, true),\n isRefetching: refetch.isRefetching,\n refetchError: refetch.error,\n } as const;\n}\n","import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { dispatchActions } from \"../actions/dispatch.js\";\n\n/**\n * Returns a dispatch function for dispatching actions to a document.\n * Used internally by other hooks to provide action dispatching capabilities.\n * @param document - The document to dispatch actions to.\n * @returns A tuple containing the document and a dispatch function.\n */\nexport type DispatchFn<TAction> = (\n actionOrActions: TAction[] | TAction | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n) => void;\n\nexport type UseDispatchResult<TDocument, TAction> = readonly [\n TDocument | undefined,\n DispatchFn<TAction>,\n];\n\nexport function useDispatch<TDocument = PHDocument, TAction = Action>(\n document: TDocument | undefined,\n): UseDispatchResult<TDocument, TAction> {\n /**\n * Dispatches actions to the document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param onErrors - Callback invoked with any errors that occurred during action execution,\n * or with the failure when the dispatch itself did not complete.\n */\n function dispatch(\n actionOrActions: TAction[] | TAction | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n ) {\n // A caller waiting on a callback hears exactly once, even on a rejection.\n let answered = false;\n const reportErrors =\n onErrors &&\n ((errors: Error[]) => {\n answered = true;\n onErrors(errors);\n });\n const reportSuccess =\n onSuccess &&\n ((result: PHDocument) => {\n answered = true;\n onSuccess(result);\n });\n dispatchActions(\n actionOrActions,\n document,\n reportErrors,\n reportSuccess,\n ).catch((error: unknown) => {\n logger.error(\"Failed to dispatch actions: @error\", error);\n if (!answered) {\n onErrors?.([error instanceof Error ? error : new Error(String(error))]);\n }\n });\n }\n return [document, dispatch] as const;\n}\n"],"mappings":";;;;AASA,eAAsB,aACpB,UACA,iBACA;CACA,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,sBAAsB;CAExC,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,qBAAqB;CAEvC,MAAM,UAAU,MAAM,QAAQ,eAAe,IACzC,kBACA,CAAC,eAAe;CAEpB,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,qBAAqB;CAGvC,MAAM,gBAAgB,OAAO,IAAI;CACjC,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,+BAA+B;CAGjD,OAAO,MAAM,cAAc,QAAQ,SAAS,OAAO,IAAI,QAAQ,OAAO;AACxE;AAEA,eAAsB,gBACpB,YACA,uBACA;CACA,IAAI,CAAC,YACH,MAAM,IAAI,MAAM,wBAAwB;CAE1C,IAAI,CAAC,uBACH,MAAM,IAAI,MAAM,wBAAwB;CAE1C,MAAM,aAAa,MAAM,QAAQ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CAOvC,SAAS,SACP,iBACA,UACA,WACA;EAEA,IAAI,WAAW;EAaf,gBACE,iBACA,UAbA,cACE,WAAoB;GACpB,WAAW;GACX,SAAS,MAAM;EACjB,IAEA,eACE,WAAuB;GACvB,WAAW;GACX,UAAU,MAAM;EAClB,EAMF,CAAC,CAAC,OAAO,UAAmB;GAC1B,OAAO,MAAM,sCAAsC,KAAK;GACxD,IAAI,CAAC,UACH,WAAW,CAAC,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC,CAAC;EAE1E,CAAC;CACH;CACA,OAAO,CAAC,UAAU,QAAQ;AAC5B"}
@@ -1,386 +0,0 @@
1
- import { _ as isDuplicateManifestError, t as useDispatch, v as isDuplicateModuleError } from "./dispatch-qRXS70fh.js";
2
- import { t as makePHEventFunctions } from "./make-ph-event-functions-FzpvQtj6.js";
3
- import { isDerivedDocumentId } from "@powerhousedao/shared/document-model";
4
- import { useSyncExternalStore } from "react";
5
- import slug from "slug";
6
- //#region src/graphql-client/auth.ts
7
- /** Lifetime requested for an ambient Renown token, in seconds. */
8
- const ambientTokenExpiresInSeconds = 600;
9
- /**
10
- * The default token provider: the token of the currently logged-in Renown user.
11
- *
12
- * It is deliberately resolved from `window.ph` on every call rather than
13
- * captured at construction time, so a client built before login starts sending
14
- * the token as soon as there is one.
15
- *
16
- * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
17
- * rejects tokens that carry an audience.
18
- */
19
- async function ambientRenownTokenProvider() {
20
- if (typeof window === "undefined") return;
21
- const renown = window.ph?.renown;
22
- if (!renown?.user) return;
23
- return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });
24
- }
25
- /**
26
- * Builds the SDK middleware that authenticates every request.
27
- *
28
- * The token is resolved per request and never cached, so a login, a logout or
29
- * an expiry between two calls is picked up by the next one. When no token is
30
- * available the request goes out unauthenticated.
31
- */
32
- function makeAuthMiddleware(tokenProvider) {
33
- return async (action) => {
34
- const token = await tokenProvider();
35
- if (!token) return action();
36
- return action({ authorization: `Bearer ${token}` });
37
- };
38
- }
39
- //#endregion
40
- //#region src/errors.ts
41
- var UnsupportedDocumentTypeError = class extends Error {
42
- constructor(documentType) {
43
- super(`Document type ${documentType} is not supported`);
44
- this.name = "UnsupportedDocumentTypeError";
45
- }
46
- static isError(error) {
47
- return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
48
- }
49
- };
50
- var DocumentModelNotFoundError = class extends Error {
51
- documentType;
52
- name = "DocumentModelNotFoundError";
53
- constructor(documentType) {
54
- super(`Document model module for type ${documentType} not found`);
55
- this.documentType = documentType;
56
- }
57
- static isError(error) {
58
- return Error.isError(error) && error.name === "DocumentModelNotFoundError";
59
- }
60
- };
61
- var DocumentTypeMismatchError = class extends Error {
62
- constructor(documentId, expectedType, actualType) {
63
- super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
64
- }
65
- };
66
- var NoSelectedDocumentError = class extends Error {
67
- constructor() {
68
- super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
69
- }
70
- };
71
- //#endregion
72
- //#region src/utils/url.ts
73
- const DERIVED_ID_LENGTH = 43;
74
- function resolveUrlPathname(path) {
75
- return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
76
- }
77
- /** Returns the current path without the base path */
78
- function getPathWithoutBase(path) {
79
- const basePath = window.ph?.basePath ?? "/";
80
- return path.replace(basePath, basePath.endsWith("/") ? "/" : "");
81
- }
82
- /** Makes a URL component for a drive. */
83
- function makeDriveUrlComponent(drive) {
84
- if (!drive) return "";
85
- return `/d/${slug(drive.header.slug)}`;
86
- }
87
- /**
88
- * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept
89
- * verbatim, since a v2-required id is case-sensitive base64url.
90
- */
91
- function makeNodeSlug(node) {
92
- if (!node) return "";
93
- const nameSlug = node.name ? slug(node.name) : "";
94
- return nameSlug ? `${nameSlug}-${node.id}` : node.id;
95
- }
96
- /** Extracts the node slug from a path.
97
- *
98
- * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.
99
- */
100
- function extractNodeSlugFromPath(path) {
101
- const currentPath = getPathWithoutBase(path);
102
- return /^\/d\/[^/]+\/([^/]+)$/.exec(currentPath)?.[1];
103
- }
104
- /** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */
105
- function findUuid(input) {
106
- if (!input) return void 0;
107
- return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
108
- }
109
- /** The v2-required document id a slug ends with, if any. */
110
- function findDerivedId(input) {
111
- if (!input || input.length < DERIVED_ID_LENGTH) return void 0;
112
- const start = input.length - DERIVED_ID_LENGTH;
113
- if (start > 0 && input[start - 1] !== "-") return void 0;
114
- const candidate = input.slice(start);
115
- return isDerivedDocumentId(candidate) ? candidate : void 0;
116
- }
117
- function extractNodeIdFromSlug(nodeSlug) {
118
- return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);
119
- }
120
- function extractNodeIdFromPath(path) {
121
- return extractNodeIdFromSlug(extractNodeSlugFromPath(path));
122
- }
123
- /** Extracts the drive slug from a path.
124
- * Used for extracting drive ids from drive slugs in the URL.
125
- * Expects the path to be in the format `/d/<drive-slug>`.
126
- */
127
- function extractDriveSlugFromPath(path) {
128
- const currentPath = getPathWithoutBase(path);
129
- return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
130
- }
131
- function extractDriveIdFromSlug(driveSlug) {
132
- return findUuid(driveSlug) ?? findDerivedId(driveSlug);
133
- }
134
- function extractDriveIdFromPath(path) {
135
- return extractDriveIdFromSlug(extractDriveSlugFromPath(path));
136
- }
137
- /**
138
- * Creates a URL string with the given pathname while preserving existing query parameters.
139
- */
140
- function createUrlWithPreservedParams(pathname) {
141
- const search = window.location.search;
142
- return search ? `${pathname}${search}` : pathname;
143
- }
144
- //#endregion
145
- //#region src/hooks/drives.ts
146
- const drivesEventFunctions = makePHEventFunctions("drives");
147
- /** Returns all of the drives in the reactor */
148
- const useDrives = drivesEventFunctions.useValue;
149
- /** Sets the drives in the reactor */
150
- const setDrives = drivesEventFunctions.setValue;
151
- /** Adds an event handler for the drives */
152
- const addDrivesEventHandler = drivesEventFunctions.addEventHandler;
153
- //#endregion
154
- //#region src/hooks/set-selected-node.ts
155
- const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
156
- const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;
157
- const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
158
- const addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;
159
- /** Sets the selected node (file or folder). */
160
- function setSelectedNode(nodeOrNodeSlug) {
161
- const nodeSlug = typeof nodeOrNodeSlug === "string" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);
162
- const nodeId = extractNodeIdFromSlug(nodeSlug);
163
- setSelectedNodeId(nodeId);
164
- const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);
165
- if (!driveSlugFromPath) return;
166
- if (!nodeSlug) {
167
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);
168
- if (pathname === window.location.pathname) return;
169
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
170
- return;
171
- }
172
- const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);
173
- if (pathname === window.location.pathname) return;
174
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
175
- }
176
- function addResetSelectedNodeEventHandler() {
177
- window.addEventListener("ph:selectedDriveIdUpdated", () => {
178
- setSelectedNodeId(void 0);
179
- });
180
- }
181
- function addSetSelectedNodeOnPopStateEventHandler() {
182
- window.addEventListener("popstate", () => {
183
- const pathname = window.location.pathname;
184
- const nodeSlug = extractNodeSlugFromPath(pathname);
185
- if (extractNodeIdFromSlug(nodeSlug) !== window.ph?.selectedNodeId) setSelectedNode(nodeSlug);
186
- });
187
- }
188
- //#endregion
189
- //#region src/hooks/selected-drive.ts
190
- const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
191
- /** Returns the selected drive id */
192
- const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;
193
- /** Sets the selected drive id */
194
- const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
195
- /** Adds an event handler for the selected drive id */
196
- const addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;
197
- /** Returns the selected drive */
198
- function useSelectedDrive() {
199
- const drive = useSelectedDriveSafe();
200
- if (!drive[0]) throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");
201
- return drive;
202
- }
203
- /** Returns the selected drive, or undefined if no drive is selected */
204
- function useSelectedDriveSafe() {
205
- const selectedDriveId = useSelectedDriveId();
206
- const selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);
207
- const [drive, dispatch] = useDispatch(selectedDrive);
208
- if (!selectedDrive) return [void 0, void 0];
209
- return [drive, dispatch];
210
- }
211
- function setSelectedDrive(driveOrDriveSlug) {
212
- const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;
213
- const drives = window.ph?.drives;
214
- const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;
215
- if (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {
216
- if (window.ph?.selectedDriveId) setSelectedDriveId(void 0);
217
- deferDriveSelection(driveSlug);
218
- return;
219
- }
220
- cancelPendingDriveSelection();
221
- setSelectedDriveId(driveId);
222
- if (!driveId) {
223
- const pathname = resolveUrlPathname("/");
224
- if (pathname === window.location.pathname) return;
225
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
226
- return;
227
- }
228
- const pathname = resolveUrlPathname(`/d/${driveSlug}`);
229
- if (pathname === window.location.pathname) return;
230
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
231
- }
232
- const DEFERRED_DRIVE_TICK_MS = 2e3;
233
- const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
234
- function isInitialSyncInFlight() {
235
- const remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();
236
- if (!remotes?.length) return false;
237
- return remotes.some((remote) => {
238
- try {
239
- const snapshot = remote.channel.getConnectionState();
240
- return snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== "error";
241
- } catch {
242
- return false;
243
- }
244
- });
245
- }
246
- let pendingHandler;
247
- let pendingTimeout;
248
- function cancelPendingDriveSelection() {
249
- if (pendingHandler) {
250
- window.removeEventListener("ph:drivesUpdated", pendingHandler);
251
- pendingHandler = void 0;
252
- }
253
- if (pendingTimeout) {
254
- clearTimeout(pendingTimeout);
255
- pendingTimeout = void 0;
256
- }
257
- }
258
- function deferDriveSelection(driveSlug) {
259
- cancelPendingDriveSelection();
260
- const nodeSlug = extractNodeSlugFromPath(window.location.pathname);
261
- const handler = () => {
262
- if (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;
263
- cancelPendingDriveSelection();
264
- setSelectedDrive(driveSlug);
265
- setSelectedNode(nodeSlug);
266
- };
267
- pendingHandler = handler;
268
- window.addEventListener("ph:drivesUpdated", handler);
269
- const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
270
- const scheduleTick = () => {
271
- pendingTimeout = setTimeout(() => {
272
- if (Date.now() < deadline && isInitialSyncInFlight()) {
273
- scheduleTick();
274
- return;
275
- }
276
- cancelPendingDriveSelection();
277
- const pathname = resolveUrlPathname("/");
278
- if (pathname === window.location.pathname) return;
279
- window.history.pushState(null, "", createUrlWithPreservedParams(pathname));
280
- }, DEFERRED_DRIVE_TICK_MS);
281
- };
282
- scheduleTick();
283
- }
284
- function addSetSelectedDriveOnPopStateEventHandler() {
285
- window.addEventListener("popstate", () => {
286
- const pathname = window.location.pathname;
287
- const driveId = extractDriveIdFromPath(pathname);
288
- if (driveId !== window.ph?.selectedDriveId) setSelectedDrive(driveId);
289
- });
290
- }
291
- //#endregion
292
- //#region src/hooks/vetra-packages.ts
293
- const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
294
- const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
295
- const EMPTY_VETRA_PACKAGES = [];
296
- const noPackageManagerUnsubscribe = () => {};
297
- /**
298
- * Returns all of the Vetra packages loaded by the Connect instance.
299
- *
300
- * The snapshot and subscription must keep stable identity while no package
301
- * manager is registered: `useSyncExternalStore` loops when the snapshot
302
- * changes on every read, which a fresh `[]` does.
303
- */
304
- const useVetraPackages = () => {
305
- const packageManager = useVetraPackageManager();
306
- return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES);
307
- };
308
- /** Adds the Vetra package manager event handler */
309
- const addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;
310
- /** Sets the Vetra package manager and registers its packages */
311
- function setVetraPackageManager(packageManager) {
312
- vetraPackageManagerFunctions.setValue(packageManager);
313
- updateReactorClientDocumentModels(packageManager.packages);
314
- updateReactorClientUpgradeManifests(packageManager.packages);
315
- packageManager.subscribe(({ packages }) => {
316
- updateReactorClientDocumentModels(packages);
317
- updateReactorClientUpgradeManifests(packages);
318
- });
319
- }
320
- function updateReactorClientDocumentModels(packages) {
321
- const documentModelModules = packages.flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && (m.version ?? 1) === (module.version ?? 1)) === index);
322
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
323
- if (!registry || documentModelModules.length === 0) return;
324
- const results = registry.registerModules(...documentModelModules);
325
- const duplicateTypes = /* @__PURE__ */ new Set();
326
- for (const result of results) if (result.status === "error") {
327
- if (isDuplicateModuleError(result.error)) duplicateTypes.add(result.item.documentModel.global.id);
328
- else console.error("Failed to register document model module:", result.error);
329
- }
330
- if (duplicateTypes.size > 0) {
331
- registry.unregisterModules(...duplicateTypes);
332
- registry.registerModules(...documentModelModules.filter((module) => duplicateTypes.has(module.documentModel.global.id)));
333
- }
334
- }
335
- function updateReactorClientUpgradeManifests(packages) {
336
- const upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);
337
- const registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;
338
- if (!registry || upgradeManifests.length === 0) return;
339
- const results = registry.registerUpgradeManifests(...upgradeManifests);
340
- const duplicates = [];
341
- for (const result of results) if (result.status === "error") {
342
- if (isDuplicateManifestError(result.error)) duplicates.push(result);
343
- else console.error("Failed to register upgrade manifest:", result.error);
344
- }
345
- if (duplicates.length > 0) {
346
- const duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);
347
- registry.unregisterUpgradeManifests(...duplicateTypes);
348
- registry.registerUpgradeManifests(...duplicates.map((r) => r.item));
349
- }
350
- }
351
- //#endregion
352
- //#region src/hooks/document-model-modules.ts
353
- function useDocumentModelModules() {
354
- return useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
355
- }
356
- /**
357
- * Resolves a document model module by document type, mirroring the registry's
358
- * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
359
- * LATEST version of the type wins (`version ?? 1` as each module's default),
360
- * with `version` given only an exact match is returned. The reactor resolves
361
- * modules the same way when a document is created, so metadata read through
362
- * this hook and the version a creation actually uses cannot disagree.
363
- */
364
- function useDocumentModelModuleById(id, version) {
365
- const documentModelModules = useDocumentModelModules();
366
- if (!id || !documentModelModules) return void 0;
367
- let latestModule;
368
- let latestVersion = -1;
369
- for (const module of documentModelModules) {
370
- if (module.documentModel.global.id !== id) continue;
371
- const moduleVersion = module.version ?? 1;
372
- if (version !== void 0) {
373
- if (moduleVersion === version) return module;
374
- continue;
375
- }
376
- if (moduleVersion > latestVersion) {
377
- latestVersion = moduleVersion;
378
- latestModule = module;
379
- }
380
- }
381
- return latestModule;
382
- }
383
- //#endregion
384
- export { findUuid as A, makeAuthMiddleware as B, extractDriveIdFromPath as C, extractNodeIdFromSlug as D, extractNodeIdFromPath as E, DocumentModelNotFoundError as F, DocumentTypeMismatchError as I, NoSelectedDocumentError as L, makeDriveUrlComponent as M, makeNodeSlug as N, extractNodeSlugFromPath as O, resolveUrlPathname as P, UnsupportedDocumentTypeError as R, createUrlWithPreservedParams as S, extractDriveSlugFromPath as T, setSelectedNode as _, useVetraPackageManager as a, setDrives as b, addSetSelectedDriveOnPopStateEventHandler as c, useSelectedDrive as d, useSelectedDriveId as f, addSetSelectedNodeOnPopStateEventHandler as g, addSelectedNodeIdEventHandler as h, setVetraPackageManager as i, getPathWithoutBase as j, findDerivedId as k, setSelectedDrive as l, addResetSelectedNodeEventHandler as m, useDocumentModelModules as n, useVetraPackages as o, useSelectedDriveSafe as p, addVetraPackageManagerEventHandler as r, addSelectedDriveIdEventHandler as s, useDocumentModelModuleById as t, setSelectedDriveId as u, useSelectedNodeId as v, extractDriveIdFromSlug as w, useDrives as x, addDrivesEventHandler as y, ambientRenownTokenProvider as z };
385
-
386
- //# sourceMappingURL=document-model-modules-D6I-UUXq.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"document-model-modules-D6I-UUXq.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/errors.ts","../src/utils/url.ts","../src/hooks/drives.ts","../src/hooks/set-selected-node.ts","../src/hooks/selected-drive.ts","../src/hooks/vetra-packages.ts","../src/hooks/document-model-modules.ts"],"sourcesContent":["import type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\n\n/**\n * Resolves the bearer token to send with a request.\n *\n * Returning `undefined` (or an empty string) means \"send this request\n * anonymously\": open Switchboards must keep serving reads to logged-out users.\n */\nexport type BearerTokenProvider = () => Promise<string | undefined>;\n\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n\n/**\n * The default token provider: the token of the currently logged-in Renown user.\n *\n * It is deliberately resolved from `window.ph` on every call rather than\n * captured at construction time, so a client built before login starts sending\n * the token as soon as there is one.\n *\n * The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n * rejects tokens that carry an audience.\n */\nexport async function ambientRenownTokenProvider(): Promise<\n string | undefined\n> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const renown = window.ph?.renown;\n if (!renown?.user) {\n return undefined;\n }\n\n return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n\n/**\n * Builds the SDK middleware that authenticates every request.\n *\n * The token is resolved per request and never cached, so a login, a logout or\n * an expiry between two calls is picked up by the next one. When no token is\n * available the request goes out unauthenticated.\n */\nexport function makeAuthMiddleware(\n tokenProvider: BearerTokenProvider,\n): SdkFunctionWrapper {\n return async (action) => {\n const token = await tokenProvider();\n if (!token) {\n return action();\n }\n\n return action({ authorization: `Bearer ${token}` });\n };\n}\n","export class UnsupportedDocumentTypeError extends Error {\n constructor(documentType: string) {\n super(`Document type ${documentType} is not supported`);\n this.name = \"UnsupportedDocumentTypeError\";\n }\n\n static isError(error: unknown): error is UnsupportedDocumentTypeError {\n return (\n Error.isError(error) && error.name === \"UnsupportedDocumentTypeError\"\n );\n }\n}\n\nexport class DocumentModelNotFoundError extends Error {\n readonly documentType: string;\n readonly name = \"DocumentModelNotFoundError\";\n\n constructor(documentType: string) {\n super(`Document model module for type ${documentType} not found`);\n this.documentType = documentType;\n }\n\n static isError(error: unknown): error is DocumentModelNotFoundError {\n return Error.isError(error) && error.name === \"DocumentModelNotFoundError\";\n }\n}\n\nexport class DocumentTypeMismatchError extends Error {\n constructor(documentId: string, expectedType: string, actualType: string) {\n super(\n `Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`,\n );\n }\n}\n\nexport class NoSelectedDocumentError extends Error {\n constructor() {\n super(\n \"There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?\",\n );\n }\n}\n","import type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (window.ph?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the current path without the base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = window.ph?.basePath ?? \"/\";\n return path.replace(basePath, basePath.endsWith(\"/\") ? \"/\" : \"\");\n}\n\n/** Makes a URL component for a drive. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n const nameSlug = node.name ? slug(node.name) : \"\";\n return nameSlug ? `${nameSlug}-${node.id}` : node.id;\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/**\n * Creates a URL string with the given pathname while preserving existing query parameters.\n */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n\n/** Returns all of the drives in the reactor */\nexport const useDrives: UsePHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.useValue;\n\n/** Sets the drives in the reactor */\nexport const setDrives: SetPHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.setValue;\n\n/** Adds an event handler for the drives */\nexport const addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n extractNodeSlugFromPath,\n makeNodeSlug,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nexport const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\n/** Sets the selected node (file or folder). */\nexport function setSelectedNode(nodeOrNodeSlug: Node | string | undefined) {\n const nodeSlug =\n typeof nodeOrNodeSlug === \"string\"\n ? nodeOrNodeSlug\n : makeNodeSlug(nodeOrNodeSlug);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n setSelectedNodeId(nodeId);\n const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);\n if (!driveSlugFromPath) {\n return;\n }\n if (!nodeSlug) {\n const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n return;\n }\n const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\n\nexport function addResetSelectedNodeEventHandler() {\n window.addEventListener(\"ph:selectedDriveIdUpdated\", () => {\n setSelectedNodeId(undefined);\n });\n}\n\nexport function addSetSelectedNodeOnPopStateEventHandler() {\n window.addEventListener(\"popstate\", () => {\n const pathname = window.location.pathname;\n const nodeSlug = extractNodeSlugFromPath(pathname);\n // The slug embeds the id (`<name>-<uuid>`); compare ids, not slug vs id.\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n const selectedNodeId = window.ph?.selectedNodeId;\n if (nodeId !== selectedNodeId) {\n setSelectedNode(nodeSlug);\n }\n });\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveIdFromPath,\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDrives } from \"./drives.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport { setSelectedNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n\n/** Returns the selected drive id */\nexport const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id */\nexport const addSelectedDriveIdEventHandler =\n selectedDriveIdEventFunctions.addEventHandler;\n\n/** Returns the selected drive */\nexport function useSelectedDrive() {\n const drive = useSelectedDriveSafe();\n if (!drive[0]) {\n throw new Error(\n \"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\",\n );\n }\n\n return drive;\n}\n\n/** Returns the selected drive, or undefined if no drive is selected */\nexport function useSelectedDriveSafe() {\n const selectedDriveId = useSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = drives?.find(\n (drive) => drive.header.id === selectedDriveId,\n );\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\nexport function setSelectedDrive(\n driveOrDriveSlug: string | DocumentDriveDocument | undefined,\n) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug?.header.slug;\n\n // A full drive document is selected directly — a just-created drive\n // navigates before the collection refresh. Slugs go through the lookup.\n const drives = window.ph?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : drives?.find((d) => d.header.slug === driveSlug);\n const driveId = drive?.header.id;\n\n // A URL-pinned slug with no matching drive: the deep link may predate\n // remote drive registration, so defer instead of rewriting the URL.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(window.location.pathname) === driveSlug\n ) {\n // Clear the previous selection so a stale drive doesn't render against\n // the new URL; the selected node resets with it, the URL is untouched.\n if (window.ph?.selectedDriveId) {\n setSelectedDriveId(undefined);\n }\n deferDriveSelection(driveSlug);\n return;\n }\n\n // Any resolved selection supersedes a pending deferred lookup.\n cancelPendingDriveSelection();\n\n setSelectedDriveId(driveId);\n\n if (!driveId) {\n const pathname = resolveUrlPathname(\"/\");\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n return;\n }\n const pathname = resolveUrlPathname(`/d/${driveSlug}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\n\n// Tick between unresolved-slug checks; re-armed while a sync is in flight.\nconst DEFERRED_DRIVE_TICK_MS = 2_000;\n// Hard cap so a wedged remote can't pin the deep link forever.\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15_000;\n\n// True while any sync remote has not completed its first successful pull —\n// a drive may still be on its way in, so the deferred lookup keeps waiting.\nfunction isInitialSyncInFlight(): boolean {\n const remotes =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();\n if (!remotes?.length) {\n return false;\n }\n return remotes.some((remote) => {\n try {\n const snapshot = remote.channel.getConnectionState();\n return (\n snapshot.receivingPages ||\n (!snapshot.lastSuccessUtcMs && snapshot.state !== \"error\")\n );\n } catch {\n return false;\n }\n });\n}\n\nlet pendingHandler: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (pendingHandler) {\n window.removeEventListener(\"ph:drivesUpdated\", pendingHandler);\n pendingHandler = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Re-runs the slug lookup on each drives update until it resolves, then\n// restores the URL-pinned node. Unresolved slugs redirect once syncs settle.\nfunction deferDriveSelection(driveSlug: string) {\n cancelPendingDriveSelection();\n\n // Capture the node pinned in the deep link before setSelectedDrive\n // rewrites the URL to /d/<driveSlug>, dropping the node segment.\n const nodeSlug = extractNodeSlugFromPath(window.location.pathname);\n const handler = () => {\n const drive = window.ph?.drives?.find((d) => d.header.slug === driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n setSelectedDrive(driveSlug);\n setSelectedNode(nodeSlug);\n };\n pendingHandler = handler;\n window.addEventListener(\"ph:drivesUpdated\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight()) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n const pathname = resolveUrlPathname(\"/\");\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(\n null,\n \"\",\n createUrlWithPreservedParams(pathname),\n );\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n\nexport function addSetSelectedDriveOnPopStateEventHandler() {\n window.addEventListener(\"popstate\", () => {\n const pathname = window.location.pathname;\n const driveId = extractDriveIdFromPath(pathname);\n const selectedDriveId = window.ph?.selectedDriveId;\n if (driveId !== selectedDriveId) {\n setSelectedDrive(driveId);\n }\n });\n}\n","import type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n isDuplicateManifestError,\n isDuplicateModuleError,\n} from \"../reactor-interop.js\";\nimport type { IPackageManager } from \"../types/vetra.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst vetraPackageManagerFunctions = makePHEventFunctions(\n \"vetraPackageManager\",\n);\n\nexport const useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n\nconst EMPTY_VETRA_PACKAGES: DocumentModelLib[] = [];\nconst noPackageManagerUnsubscribe = () => {};\n\n/**\n * Returns all of the Vetra packages loaded by the Connect instance.\n *\n * The snapshot and subscription must keep stable identity while no package\n * manager is registered: `useSyncExternalStore` loops when the snapshot\n * changes on every read, which a fresh `[]` does.\n */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/** Sets the Vetra package manager and registers its packages */\nexport function setVetraPackageManager(packageManager: IPackageManager) {\n vetraPackageManagerFunctions.setValue(packageManager);\n updateReactorClientDocumentModels(packageManager.packages);\n updateReactorClientUpgradeManifests(packageManager.packages);\n packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n updateReactorClientUpgradeManifests(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // dedupe by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n (m.version ?? 1) === (module.version ?? 1),\n ) === index,\n );\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n const results = registry.registerModules(...documentModelModules);\n const duplicateTypes = new Set<string>();\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateModuleError(result.error)) {\n duplicateTypes.add(result.item.documentModel.global.id);\n } else {\n console.error(\n \"Failed to register document model module:\",\n result.error,\n );\n }\n }\n }\n if (duplicateTypes.size > 0) {\n // unregisterModules is type-scoped, so replace the whole version family\n // with the incoming package's modules: re-registering only the duplicated\n // items would purge any new version that registered successfully above.\n registry.unregisterModules(...duplicateTypes);\n registry.registerModules(\n ...documentModelModules.filter((module) =>\n duplicateTypes.has(module.documentModel.global.id),\n ),\n );\n }\n}\n\nfunction updateReactorClientUpgradeManifests(packages: DocumentModelLib[]) {\n const upgradeManifests = packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter((u) => u !== undefined);\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || upgradeManifests.length === 0) return;\n\n const results = registry.registerUpgradeManifests(...upgradeManifests);\n const duplicates = [];\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateManifestError(result.error)) {\n duplicates.push(result);\n } else {\n console.error(\"Failed to register upgrade manifest:\", result.error);\n }\n }\n }\n if (duplicates.length > 0) {\n const duplicateTypes = duplicates\n .map((r) => r.item.documentType)\n .filter((t): t is string => !!t);\n registry.unregisterUpgradeManifests(...duplicateTypes);\n registry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n }\n}\n","import type { DocumentModelModule } from \"document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useDocumentModelModules(): DocumentModelModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n}\n\n/**\n * Resolves a document model module by document type, mirroring the registry's\n * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n * LATEST version of the type wins (`version ?? 1` as each module's default),\n * with `version` given only an exact match is returned. The reactor resolves\n * modules the same way when a document is created, so metadata read through\n * this hook and the version a creation actually uses cannot disagree.\n */\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n version?: number,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n if (!id || !documentModelModules) return undefined;\n\n let latestModule: DocumentModelModule | undefined;\n let latestVersion = -1;\n for (const module of documentModelModules) {\n if (module.documentModel.global.id !== id) continue;\n const moduleVersion = module.version ?? 1;\n if (version !== undefined) {\n if (moduleVersion === version) return module;\n continue;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n return latestModule;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,OAAO,IAAI;CAC1B,IAAI,CAAC,QAAQ,MACX;CAGF,OAAO,OAAO,eAAe,EAAE,WAAW,6BAA6B,CAAC;AAC1E;;;;;;;;AASA,SAAgB,mBACd,eACoB;CACpB,OAAO,OAAO,WAAW;EACvB,MAAM,QAAQ,MAAM,cAAc;EAClC,IAAI,CAAC,OACH,OAAO,OAAO;EAGhB,OAAO,OAAO,EAAE,eAAe,UAAU,QAAQ,CAAC;CACpD;AACF;;;ACxDA,IAAa,+BAAb,cAAkD,MAAM;CACtD,YAAY,cAAsB;EAChC,MAAM,iBAAiB,aAAa,kBAAkB;EACtD,KAAK,OAAO;CACd;CAEA,OAAO,QAAQ,OAAuD;EACpE,OACE,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS;CAE3C;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA,OAAgB;CAEhB,YAAY,cAAsB;EAChC,MAAM,kCAAkC,aAAa,WAAW;EAChE,KAAK,eAAe;CACtB;CAEA,OAAO,QAAQ,OAAqD;EAClE,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS;CAChD;AACF;AAEA,IAAa,4BAAb,cAA+C,MAAM;CACnD,YAAY,YAAoB,cAAsB,YAAoB;EACxE,MACE,YAAY,WAAW,kBAAkB,aAAa,iBAAiB,YACzE;CACF;AACF;AAEA,I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