@powerhousedao/reactor-browser 6.2.3-dev.78 → 6.2.3-dev.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-C_8_poEv.d.ts → attachment-service-BoLudaH0.d.ts} +53 -25
- package/dist/attachment-service-BoLudaH0.d.ts.map +1 -0
- package/dist/{client-D_cBN8L-.js → client-BUpynoY6.js} +25 -1
- package/dist/client-BUpynoY6.js.map +1 -0
- package/dist/{client-Cx43uuSO.d.ts → client-XPGQrO4a.d.ts} +2 -2
- package/dist/client-XPGQrO4a.d.ts.map +1 -0
- package/dist/{dispatch-DLD1E-9L.js → dispatch-C8J9jQ-o.js} +10 -8
- package/dist/dispatch-C8J9jQ-o.js.map +1 -0
- package/dist/{document-by-id-BGTnMWiG.js → document-by-id-Dpp76ZNE.js} +2 -2
- package/dist/{document-by-id-BGTnMWiG.js.map → document-by-id-Dpp76ZNE.js.map} +1 -1
- package/dist/{document-model-modules-D_kT09sv.js → document-model-modules-XrYfGXt8.js} +2 -2
- package/dist/{document-model-modules-D_kT09sv.js.map → document-model-modules-XrYfGXt8.js.map} +1 -1
- package/dist/{document-operations-BdCl99y6.js → document-operations-B0GZilXW.js} +190 -148
- package/dist/document-operations-B0GZilXW.js.map +1 -0
- package/dist/{global-C4kaLEPb.d.ts → global-BlOVLagj.d.ts} +3 -3
- package/dist/{global-C4kaLEPb.d.ts.map → global-BlOVLagj.d.ts.map} +1 -1
- package/dist/{index-CROGY3XV.d.ts → index-Ck5Q0beA.d.ts} +2 -2
- package/dist/{index-CROGY3XV.d.ts.map → index-Ck5Q0beA.d.ts.map} +1 -1
- package/dist/index.d.ts +25 -31
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +106 -51
- package/dist/index.js.map +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/analytics/index.js +1 -1
- package/dist/src/graphql/client.d.ts +2 -2
- package/dist/src/graphql/client.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +4 -4
- package/dist/src/graphql-client/entry.js +4 -4
- package/dist/src/renown/index.d.ts +1 -1
- package/dist/{switchboard-CqUq5pIZ.js → switchboard-CYTCYt4Z.js} +4 -4
- package/dist/{switchboard-CqUq5pIZ.js.map → switchboard-CYTCYt4Z.js.map} +1 -1
- package/dist/{types-Vb8q55oM.d.ts → types-BNVqRNli.d.ts} +11 -1
- package/dist/types-BNVqRNli.d.ts.map +1 -0
- package/package.json +9 -9
- package/dist/attachment-service-C_8_poEv.d.ts.map +0 -1
- package/dist/client-Cx43uuSO.d.ts.map +0 -1
- package/dist/client-D_cBN8L-.js.map +0 -1
- package/dist/dispatch-DLD1E-9L.js.map +0 -1
- package/dist/document-operations-BdCl99y6.js.map +0 -1
- package/dist/types-Vb8q55oM.d.ts.map +0 -1
|
@@ -217,11 +217,9 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
|
|
|
217
217
|
return;
|
|
218
218
|
}
|
|
219
219
|
const result = await queueActions(document, signedActionsWithContext);
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
if (onSuccess && result) onSuccess(result);
|
|
220
|
+
const rejected = onErrors || onSuccess ? await getActionErrors(document, result, signedActionsWithContext) : [];
|
|
221
|
+
if (onErrors && rejected.length) onErrors(rejected);
|
|
222
|
+
onSuccess?.(result, { rejected });
|
|
225
223
|
return result;
|
|
226
224
|
}
|
|
227
225
|
//#endregion
|
|
@@ -1140,6 +1138,9 @@ function createDispatch(getDocument) {
|
|
|
1140
1138
|
* @param actionOrActions - The action or actions to dispatch.
|
|
1141
1139
|
* @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
|
|
1142
1140
|
* document did not apply, or with the failure when the dispatch itself did not complete.
|
|
1141
|
+
* Runs before `onSuccess`.
|
|
1142
|
+
* @param onSuccess - Callback invoked with the document once the write lands, after
|
|
1143
|
+
* `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
|
|
1143
1144
|
*/
|
|
1144
1145
|
return function dispatch(actionOrActions, onErrors, onSuccess) {
|
|
1145
1146
|
let answered = false;
|
|
@@ -1147,9 +1148,9 @@ function createDispatch(getDocument) {
|
|
|
1147
1148
|
answered = true;
|
|
1148
1149
|
onErrors(errors);
|
|
1149
1150
|
});
|
|
1150
|
-
const reportSuccess = onSuccess && ((result) => {
|
|
1151
|
+
const reportSuccess = onSuccess && ((result, outcome) => {
|
|
1151
1152
|
answered = true;
|
|
1152
|
-
onSuccess(result);
|
|
1153
|
+
onSuccess(result, outcome);
|
|
1153
1154
|
});
|
|
1154
1155
|
dispatchActions(actionOrActions, getDocument(), reportErrors, reportSuccess).catch((error) => {
|
|
1155
1156
|
logger.error("Failed to dispatch actions: @error", error);
|
|
@@ -1157,6 +1158,7 @@ function createDispatch(getDocument) {
|
|
|
1157
1158
|
});
|
|
1158
1159
|
};
|
|
1159
1160
|
}
|
|
1161
|
+
/** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
|
|
1160
1162
|
function useDispatch(document) {
|
|
1161
1163
|
const latest = useRef(document);
|
|
1162
1164
|
latest.current = document;
|
|
@@ -1166,4 +1168,4 @@ function useDispatch(document) {
|
|
|
1166
1168
|
//#endregion
|
|
1167
1169
|
export { DocumentTypeMismatchError as A, DocumentRefetcher as C, queueOperations as D, queueActions as E, OperationRejectedError as M, UnsupportedDocumentTypeError as N, uploadOperations as O, isDuplicateModuleError as S, dispatchActions as T, isDocumentTypeCache as _, useDocument as a, DOCUMENT_CHANGE_TYPE as b, useDocuments as c, useGetDocuments as d, DocumentCache as f, addPromiseState as g, IDLE_OPERATIONS_ENTRY as h, setDocumentCache as i, NoSelectedDocumentError as j, DocumentModelNotFoundError as k, useGetDocument as l, IDLE_DOCUMENTS_OF_TYPE_ENTRY as m, useDispatch as n, useDocumentCache as o, GET_MANY_CHUNK_SIZE as p, addDocumentCacheEventHandler as r, useDocumentSafe as s, createDispatch as t, useGetDocumentAsync as u, isOperationCache as v, IDLE_REFETCH_STATE as w, isDuplicateManifestError as x, readPromiseState as y };
|
|
1168
1170
|
|
|
1169
|
-
//# sourceMappingURL=dispatch-
|
|
1171
|
+
//# sourceMappingURL=dispatch-C8J9jQ-o.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispatch-C8J9jQ-o.js","names":["fulfilledPromise"],"sources":["../src/errors.ts","../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 {\n operationOutcome,\n type Operation,\n type OperationOutcome,\n} from \"@powerhousedao/shared/document-model\";\n\ntype RejectedOutcome = Exclude<OperationOutcome, { kind: \"applied\" }>;\n\nexport 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\n/** A dispatched action the document did not apply: its operation is stored at `index`, state\n * unchanged, because the reducer threw (`reducer-error`) or the write was denied (`denied`). */\nexport class OperationRejectedError extends Error {\n readonly name = \"OperationRejectedError\";\n readonly actionId: string;\n readonly actionType: string;\n readonly index: number;\n readonly kind: \"reducer-error\" | \"denied\";\n\n private constructor(\n readonly documentId: string,\n readonly scope: string,\n operation: Operation,\n outcome: RejectedOutcome,\n ) {\n super(outcome.kind === \"denied\" ? outcome.reason : outcome.message);\n this.actionId = operation.action.id;\n this.actionType = operation.action.type;\n this.index = operation.index;\n this.kind = outcome.kind;\n }\n\n /** The rejection `operation` records, or undefined when it applied. */\n static fromOperation(\n documentId: string,\n scope: string,\n operation: Operation,\n ): OperationRejectedError | undefined {\n const outcome = operationOutcome(operation);\n return outcome.kind === \"applied\"\n ? undefined\n : new OperationRejectedError(documentId, scope, operation, outcome);\n }\n\n static isError(error: unknown): error is OperationRejectedError {\n return Error.isError(error) && error.name === \"OperationRejectedError\";\n }\n}\n","import { getPHStore } from \"../hooks/ph-store.js\";\nimport 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 = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const handle = await reactorClient.write.execute(\n document.header.id,\n \"main\",\n actions,\n );\n return await handle.document();\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 = getPHStore()?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const actions = operations.map((op) => op.action);\n const handle = await reactorClient.write.execute(documentId, \"main\", actions);\n return await handle.document();\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 { getPHStore } from \"../hooks/ph-store.js\";\nimport 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 = getPHStore()?.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 { getPHStore } from \"../hooks/ph-store.js\";\nimport type { PagingOptions } from \"@powerhousedao/reactor\";\nimport type {\n Action,\n DispatchOutcome,\n DocumentOperations,\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { OperationRejectedError } from \"../errors.js\";\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 getPHStore()?.reactorClient?.get(documentId);\n } catch (error) {\n logger.debug(`Failed to get document with id ${documentId}:`, error);\n return undefined;\n }\n}\n\nasync function getOperationsSince(\n documentId: string,\n scope: string,\n sinceRevision: number,\n): Promise<Operation[]> {\n const reactorClient = getPHStore()?.reactorClient;\n if (!reactorClient) {\n return [];\n }\n const operations: Operation[] = [];\n let paging: PagingOptions | undefined;\n do {\n const page = await reactorClient.getOperations(\n documentId,\n { branch: \"main\", scopes: [scope] },\n { sinceRevision },\n paging,\n );\n operations.push(...page.results);\n paging =\n page.nextCursor && page.results.length\n ? { cursor: page.nextCursor, limit: page.options.limit }\n : undefined;\n } while (paging);\n return operations;\n}\n\n/** The operations the dispatch produced in `scope`: a remote client returns them on the\n * document, the local clients do not, so they are read from the revision before it. */\nasync function getDispatchedOperations(\n before: PHDocument,\n result: PHDocument,\n scope: string,\n actionIds: Set<string>,\n): Promise<readonly Operation[]> {\n const returned = (result.operations as DocumentOperations | undefined)?.[\n scope\n ];\n if (returned?.some((op) => actionIds.has(op.action.id))) {\n return returned;\n }\n return getOperationsSince(\n result.header.id,\n scope,\n before.header.revision[scope] ?? 0,\n );\n}\n\nasync function getActionErrors(\n before: PHDocument,\n result: PHDocument,\n actions: Action[],\n): Promise<OperationRejectedError[]> {\n const actionIds = new Set(actions.map((action) => action.id));\n const errors: OperationRejectedError[] = [];\n for (const scope of new Set(actions.map((action) => action.scope))) {\n let operations: readonly Operation[];\n try {\n operations = await getDispatchedOperations(\n before,\n result,\n scope,\n actionIds,\n );\n } catch (error) {\n logger.warn(\n \"Could not read the dispatched operations of @scope: @error\",\n scope,\n error,\n );\n continue;\n }\n for (const action of actions) {\n if (action.scope !== scope) continue;\n const operation = operations.findLast((op) => op.action.id === action.id);\n const error =\n operation &&\n OperationRejectedError.fromOperation(\n result.header.id,\n scope,\n operation,\n );\n if (error) {\n errors.push(error);\n }\n }\n }\n return errors;\n}\n\n/** Called once the write lands; `outcome.rejected` is empty when every action applied. */\nexport type DispatchSuccessCallback = (\n result: PHDocument,\n outcome: DispatchOutcome,\n) => void;\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 an `OperationRejectedError` for each action the\n * document did not apply, or with why nothing was dispatched. Runs before `onSuccess`.\n * @param onSuccess - Callback invoked with the updated document once the write lands, after\n * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.\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?: DispatchSuccessCallback,\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 an `OperationRejectedError` for each action the\n * document did not apply. Runs before `onSuccess`.\n * @param onSuccess - Callback invoked with the updated document once the write lands, after\n * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.\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?: DispatchSuccessCallback,\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?: DispatchSuccessCallback,\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 const rejected =\n onErrors || onSuccess\n ? await getActionErrors(document, result, signedActionsWithContext)\n : [];\n if (onErrors && rejected.length) {\n onErrors(rejected);\n }\n onSuccess?.(result, { rejected });\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 \"DocumentPurgedError\",\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 DocumentsOfTypeEntry,\n FulfilledPromise,\n IDocumentCache,\n IDocumentTypeCache,\n IOperationCache,\n OperationsCacheEntry,\n PromiseState,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.js\";\nimport type {\n IReactorBrowserClient,\n IReactorBrowserReadClient,\n} from \"./types/reactor-browser-client.js\";\n\n/**\n * The reads a {@link DocumentCache} makes. `getMany` is optional: without it,\n * a batch reads each uncached id with `get`.\n */\nexport interface IDocumentCacheReader\n extends\n Pick<\n IReactorBrowserReadClient,\n \"get\" | \"find\" | \"getOperations\" | \"subscribe\"\n >,\n Partial<Pick<IReactorBrowserReadClient, \"getMany\">> {}\n\n/** The most ids one `getMany` call is asked for. */\nexport const GET_MANY_CHUNK_SIZE = 100;\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/** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */\nexport const IDLE_DOCUMENTS_OF_TYPE_ENTRY: DocumentsOfTypeEntry = Object.freeze(\n {\n status: \"idle\",\n ids: Object.freeze([]) as readonly string[],\n error: undefined,\n hasNextPage: false,\n },\n);\n\n/** Whether a document cache also lists documents by type. */\nexport function isDocumentTypeCache(\n cache: unknown,\n): cache is IDocumentTypeCache {\n if (typeof cache !== \"object\" || cache === null) return false;\n const candidate = cache as Partial<IDocumentTypeCache>;\n return (\n typeof candidate.getDocumentsOfTypeState === \"function\" &&\n typeof candidate.loadDocumentsOfType === \"function\" &&\n typeof candidate.loadMoreDocumentsOfType === \"function\" &&\n typeof candidate.subscribeDocumentsOfType === \"function\"\n );\n}\n\ntype Deferred<T> = {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason: unknown) => void;\n};\n\nfunction createDeferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/** A promise already settled with `value`, readable without awaiting. */\nfunction fulfilledPromise<T>(value: T): PromiseWithState<T> {\n const promise = Promise.resolve(value) as PromiseWithState<T>;\n promise.status = \"fulfilled\";\n (promise as FulfilledPromise<T>).value = value;\n return promise;\n}\n\nconst typeKey = (type: string, limit: number) => `${limit}:${type}`;\n\n/** Bookkeeping for one type's pages that is not part of its snapshot. */\ntype DocumentsOfTypeRequest = {\n type: string;\n limit: number;\n /** The first page's load, which a suspending reader waits on; reloads keep it. */\n firstPage: PromiseWithState<void>;\n /** Marks a page superseded by a reload. */\n controller: AbortController;\n nextCursor: string | undefined;\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 through the client's read half\n * and automatically updates the cache when documents are created, updated, or deleted.\n * It is built over a browser client, whose `read` half it uses, or over a read\n * half directly.\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\n implements IDocumentCache, IOperationCache, IDocumentTypeCache\n{\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 /** Documents by type and page size, keyed by typeKey. */\n private typeEntries = new Map<string, DocumentsOfTypeEntry>();\n private typeRequests = new Map<string, DocumentsOfTypeRequest>();\n private typeListeners = new Map<string, (() => void)[]>();\n\n private unsubscribe: (() => void) | null = null;\n private readonly client: IDocumentCacheReader;\n\n constructor(client: IReactorBrowserClient | IDocumentCacheReader) {\n this.client = readerOf(client);\n this.unsubscribe = this.client.subscribe(\n {},\n (event: DocumentChangeEvent) => {\n this.handleDocumentChange(event);\n },\n );\n }\n\n private handleDocumentChange(event: DocumentChangeEvent): void {\n this.reloadTypesChangedBy(event);\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 if (hasDeletedDocuments) {\n this.loadMany(ids);\n }\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 /**\n * Reserves an entry for every id not yet cached and fills them from\n * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own\n * entry, settled as `get` would settle it.\n */\n private loadMany(ids: string[]): void {\n const getMany = this.client.getMany?.bind(this.client);\n const missing = [...new Set(ids)].filter((id) => !this.documents.has(id));\n if (!getMany || missing.length < 2) {\n return;\n }\n const pending = new Map<string, Deferred<PHDocument>>();\n for (const id of missing) {\n const deferred = createDeferred<PHDocument>();\n pending.set(id, deferred);\n this.refetcher.forget(id);\n this.documents.set(id, addPromiseState(deferred.promise));\n }\n for (let i = 0; i < missing.length; i += GET_MANY_CHUNK_SIZE) {\n void this.settleMany(\n missing.slice(i, i + GET_MANY_CHUNK_SIZE),\n pending,\n getMany,\n );\n }\n }\n\n /**\n * `getMany` rejects when any id is unavailable, so a failed chunk is split\n * in half and retried; a single id is read with `get`, so it settles exactly\n * as a single read would.\n */\n private async settleMany(\n ids: string[],\n pending: Map<string, Deferred<PHDocument>>,\n getMany: NonNullable<IDocumentCacheReader[\"getMany\"]>,\n ): Promise<void> {\n if (ids.length === 1) {\n const id = ids[0];\n try {\n this.settleFetched(id, await this.client.get(id), pending);\n } catch (error) {\n pending.get(id)?.reject(error);\n }\n return;\n }\n let documents: PHDocument[];\n try {\n documents = await getMany(ids);\n } catch {\n const half = Math.ceil(ids.length / 2);\n await Promise.all([\n this.settleMany(ids.slice(0, half), pending, getMany),\n this.settleMany(ids.slice(half), pending, getMany),\n ]);\n return;\n }\n if (documents.length !== ids.length) {\n await Promise.all(\n ids.map((id) => this.settleMany([id], pending, getMany)),\n );\n return;\n }\n ids.forEach((id, i) => this.settleFetched(id, documents[i], pending));\n }\n\n private settleFetched(\n id: string,\n document: PHDocument,\n pending: Map<string, Deferred<PHDocument>>,\n ): void {\n if (document.header.id !== id) {\n this.recordAlias(document.header.id, id);\n }\n pending.get(id)?.resolve(document);\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 getDocumentsOfTypeState(type: string, limit: number): DocumentsOfTypeEntry {\n return (\n this.typeEntries.get(typeKey(type, limit)) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY\n );\n }\n\n loadDocumentsOfType(type: string, limit: number): Promise<void> {\n const key = typeKey(type, limit);\n const request = this.typeRequests.get(key);\n if (request) return request.firstPage;\n const controller = new AbortController();\n const created: DocumentsOfTypeRequest = {\n type,\n limit,\n firstPage: fulfilledPromise(undefined),\n controller,\n nextCursor: undefined,\n };\n this.typeRequests.set(key, created);\n created.firstPage = addPromiseState(\n this.loadTypePage(key, \"\", limit, controller, []),\n );\n return created.firstPage;\n }\n\n loadMoreDocumentsOfType(type: string, limit: number): void {\n const key = typeKey(type, limit);\n const entry = this.getDocumentsOfTypeState(type, limit);\n const request = this.typeRequests.get(key);\n if (entry.status !== \"success\" || !request?.nextCursor) return;\n void this.loadTypePage(\n key,\n request.nextCursor,\n limit,\n request.controller,\n entry.ids,\n );\n }\n\n subscribeDocumentsOfType(\n type: string,\n limit: number,\n callback: () => void,\n ): () => void {\n const key = typeKey(type, limit);\n this.typeListeners.set(key, [\n ...(this.typeListeners.get(key) ?? []),\n callback,\n ]);\n return () => {\n const current = this.typeListeners.get(key) ?? [];\n this.typeListeners.set(\n key,\n current.filter((listener) => listener !== callback),\n );\n };\n }\n\n /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */\n private async loadTypePage(\n key: string,\n cursor: string,\n limit: number,\n controller: AbortController,\n before: readonly string[],\n ): Promise<void> {\n const type = this.typeRequests.get(key)?.type ?? \"\";\n this.setTypeEntry(key, {\n ...this.getTypeEntry(key),\n status: \"pending\",\n });\n try {\n const page = await this.client.find(\n { type },\n undefined,\n { cursor, limit },\n controller.signal,\n );\n if (controller.signal.aborted) return;\n for (const document of page.results) {\n this.primeDocument(document);\n }\n const request = this.typeRequests.get(key);\n if (request) request.nextCursor = page.nextCursor;\n this.setTypeEntry(key, {\n status: \"success\",\n ids: [...before, ...page.results.map((d) => d.header.id)],\n error: undefined,\n hasNextPage: !!page.nextCursor,\n });\n } catch (error) {\n if (controller.signal.aborted) return;\n this.setTypeEntry(key, {\n ...this.getTypeEntry(key),\n status: \"error\",\n error,\n });\n }\n }\n\n /** Reloads every loaded page of a type a created or deleted document belongs to. */\n private reloadTypesChangedBy(event: DocumentChangeEvent): void {\n if (this.typeRequests.size === 0) return;\n let changed: (key: string, type: string) => boolean;\n if (event.type === DOCUMENT_CHANGE_TYPE.Created) {\n const types = new Set(event.documents.map((d) => d.header.documentType));\n changed = (_key, type) => types.has(type);\n } else if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {\n const id = event.context?.childId;\n if (!id) return;\n changed = (key) => this.getTypeEntry(key).ids.includes(id);\n } else {\n return;\n }\n for (const [key, request] of this.typeRequests) {\n if (!changed(key, request.type)) continue;\n request.controller.abort();\n const controller = new AbortController();\n // One page as long as everything loaded, plus what was created, so no row drops.\n const created =\n event.type === DOCUMENT_CHANGE_TYPE.Created\n ? event.documents.filter(\n (d) => d.header.documentType === request.type,\n ).length\n : 0;\n const loaded = this.getTypeEntry(key).ids.length;\n const limit = Math.max(request.limit, loaded + created);\n request.controller = controller;\n void this.loadTypePage(key, \"\", limit, controller, []);\n }\n }\n\n private primeDocument(document: PHDocument): void {\n const current = this.documents.get(document.header.id);\n if (current && current.status !== \"rejected\") return;\n this.documents.set(document.header.id, fulfilledPromise(document));\n }\n\n private getTypeEntry(key: string): DocumentsOfTypeEntry {\n return this.typeEntries.get(key) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;\n }\n\n private setTypeEntry(key: string, entry: DocumentsOfTypeEntry): void {\n this.typeEntries.set(key, entry);\n for (const listener of this.typeListeners.get(key) ?? []) {\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 for (const request of this.typeRequests.values()) {\n request.controller.abort();\n }\n this.typeRequests.clear();\n this.typeEntries.clear();\n this.typeListeners.clear();\n this.refetcher.clear();\n this.operationListeners.clear();\n }\n}\n\nexport { IDLE_REFETCH_STATE } from \"./document-refetcher.js\";\n\n/** The read half of a browser client, or the reader itself. */\nfunction readerOf(\n client: IReactorBrowserClient | IDocumentCacheReader,\n): IDocumentCacheReader {\n const read = (client as Partial<IReactorBrowserClient>).read;\n return read ?? client;\n}\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 getDocument = () => (id ? documentCache?.get(id) : undefined);\n const document = useSyncExternalStore(\n (cb) => (id && documentCache ? documentCache.subscribe(id, cb) : () => {}),\n getDocument,\n getDocument,\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 getPromise = () => (id ? documentCache?.get(id) : undefined);\n const getRefetch = () => readRefetchState(documentCache, id);\n const promise = useSyncExternalStore(subscribe, getPromise, getPromise);\n const refetch = useSyncExternalStore(subscribe, getRefetch, getRefetch);\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 const getBatch = () =>\n ids?.length && documentCache ? documentCache.getBatch(ids) : undefined;\n\n const documents = useSyncExternalStore(\n (cb) =>\n ids?.length && documentCache\n ? documentCache.subscribe(ids, cb)\n : () => {},\n getBatch,\n getBatch,\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 { useMemo, useRef } from \"react\";\nimport {\n dispatchActions,\n type DispatchSuccessCallback,\n} from \"../actions/dispatch.js\";\n\n/** Dispatches actions.\n *\n * Once the write lands, `onErrors` runs first, with an `OperationRejectedError` per action\n * the document did not apply; it is skipped when every action applied. Then `onSuccess`\n * runs with the document and an outcome, whether or not any action was rejected:\n * `outcome.rejected` holds the same errors, and is empty only when every action applied.\n * If `onErrors` throws, `onSuccess` does not run.\n *\n * When nothing lands (no document, no reactor, a failed write), only `onErrors` runs, with why. */\nexport type DispatchFn<TAction> = (\n actionOrActions: TAction[] | TAction | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: DispatchSuccessCallback,\n) => void;\n\nexport type UseDispatchResult<TDocument, TAction> = readonly [\n TDocument | undefined,\n DispatchFn<TAction>,\n];\n\n/** A dispatch to the document `getDocument` returns when it runs. */\nexport function createDispatch<TDocument = PHDocument, TAction = Action>(\n getDocument: () => TDocument | undefined,\n): DispatchFn<TAction> {\n /**\n * Dispatches actions to the document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the\n * document did not apply, or with the failure when the dispatch itself did not complete.\n * Runs before `onSuccess`.\n * @param onSuccess - Callback invoked with the document once the write lands, after\n * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.\n */\n return function dispatch(actionOrActions, onErrors, onSuccess) {\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: DispatchSuccessCallback | undefined =\n onSuccess &&\n ((result, outcome) => {\n answered = true;\n onSuccess(result, outcome);\n });\n dispatchActions(\n actionOrActions,\n getDocument(),\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}\n\n/** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */\nexport function useDispatch<TDocument = PHDocument, TAction = Action>(\n document: TDocument | undefined,\n): UseDispatchResult<TDocument, TAction> {\n // Stable per document id; it always dispatches against the latest document.\n const latest = useRef(document);\n latest.current = document;\n const id = (document as PHDocument | undefined)?.header.id;\n const dispatch = useMemo(\n () => createDispatch<TDocument, TAction>(() => latest.current),\n [id],\n );\n return [document, dispatch] as const;\n}\n"],"mappings":";;;;;AAQA,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,IAAa,0BAAb,cAA6C,MAAM;CACjD,cAAc;EACZ,MACE,wFACF;CACF;AACF;;;AAIA,IAAa,yBAAb,MAAa,+BAA+B,MAAM;CAQrC;CACA;CARX,OAAgB;CAChB;CACA;CACA;CACA;CAEA,YACE,YACA,OACA,WACA,SACA;EACA,MAAM,QAAQ,SAAS,WAAW,QAAQ,SAAS,QAAQ,OAAO;EALzD,KAAA,aAAA;EACA,KAAA,QAAA;EAKT,KAAK,WAAW,UAAU,OAAO;EACjC,KAAK,aAAa,UAAU,OAAO;EACnC,KAAK,QAAQ,UAAU;EACvB,KAAK,OAAO,QAAQ;CACtB;;CAGA,OAAO,cACL,YACA,OACA,WACoC;EACpC,MAAM,UAAU,iBAAiB,SAAS;EAC1C,OAAO,QAAQ,SAAS,YACpB,KAAA,IACA,IAAI,uBAAuB,YAAY,OAAO,WAAW,OAAO;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,cAAc,QAAQ;CACxB;AACF;;;;ACzOA,SAAgB,eACd,aACqB;;;;;;;;;;CAUrB,OAAO,SAAS,SAAS,iBAAiB,UAAU,WAAW;EAE7D,IAAI,WAAW;EACf,MAAM,eACJ,cACE,WAAoB;GACpB,WAAW;GACX,SAAS,MAAM;EACjB;EACF,MAAM,gBACJ,eACE,QAAQ,YAAY;GACpB,WAAW;GACX,UAAU,QAAQ,OAAO;EAC3B;EACF,gBACE,iBACA,YAAY,GACZ,cACA,aACF,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;AACF;;AAGA,SAAgB,YACd,UACuC;CAEvC,MAAM,SAAS,OAAO,QAAQ;CAC9B,OAAO,UAAU;CACjB,MAAM,KAAM,UAAqC,OAAO;CAKxD,OAAO,CAAC,UAJS,cACT,qBAAyC,OAAO,OAAO,GAC7D,CAAC,EAAE,CAEoB,CAAC;AAC5B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as useDocument, c as useDocuments, n as useDispatch } from "./dispatch-
|
|
1
|
+
import { a as useDocument, c as useDocuments, n as useDispatch } from "./dispatch-C8J9jQ-o.js";
|
|
2
2
|
//#region src/hooks/document-by-id.ts
|
|
3
3
|
/** Returns a document by id. */
|
|
4
4
|
function useDocumentById(id) {
|
|
@@ -13,4 +13,4 @@ function useDocumentsByIds(ids) {
|
|
|
13
13
|
//#endregion
|
|
14
14
|
export { useDocumentsByIds as n, useDocumentById as t };
|
|
15
15
|
|
|
16
|
-
//# sourceMappingURL=document-by-id-
|
|
16
|
+
//# sourceMappingURL=document-by-id-Dpp76ZNE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-by-id-
|
|
1
|
+
{"version":3,"file":"document-by-id-Dpp76ZNE.js","names":[],"sources":["../src/hooks/document-by-id.ts"],"sourcesContent":["import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useDispatch, type UseDispatchResult } from \"./dispatch.js\";\nimport { useDocument, useDocuments } from \"./document-cache.js\";\n\n/** Returns a document by id. */\nexport function useDocumentById(\n id: string | null | undefined,\n): UseDispatchResult<PHDocument, Action> {\n const document = useDocument(id);\n const [, dispatch] = useDispatch<PHDocument, Action>(document);\n return [document, dispatch] as const;\n}\n\n/** Returns documents by ids. */\nexport function useDocumentsByIds(ids: string[] | null | undefined) {\n return useDocuments(ids);\n}\n"],"mappings":";;;AAKA,SAAgB,gBACd,IACuC;CACvC,MAAM,WAAW,YAAY,EAAE;CAC/B,MAAM,GAAG,YAAY,YAAgC,QAAQ;CAC7D,OAAO,CAAC,UAAU,QAAQ;AAC5B;;AAGA,SAAgB,kBAAkB,KAAkC;CAClE,OAAO,aAAa,GAAG;AACzB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { c as getPHStore, f as usePHStore, n as subscribeToPHValue, s as getActivePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
|
|
2
|
-
import { S as isDuplicateModuleError, n as useDispatch, x as isDuplicateManifestError } from "./dispatch-
|
|
2
|
+
import { S as isDuplicateModuleError, n as useDispatch, x as isDuplicateManifestError } from "./dispatch-C8J9jQ-o.js";
|
|
3
3
|
import { A as extractNodeIdFromSlug, I as makeDriveSlug, N as findDriveBySlug, O as extractDriveSlugFromPath, R as makeNodeSlug, _ as preloadTarget, c as getCurrentPathname, d as hasHostNavigation, j as extractNodeSlugFromPath, m as openTarget } from "./navigation-BqphkrOB.js";
|
|
4
4
|
import { createContext, useCallback, useContext, useEffect, useSyncExternalStore } from "react";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -641,4 +641,4 @@ function useDocumentModelModuleById(id, version) {
|
|
|
641
641
|
//#endregion
|
|
642
642
|
export { makeAuthMiddleware as $, addDrivesEventHandler as A, invalidateDriveNodes as B, setSelectedNode as C, usePreloadNode as D, useOpenNode as E, isInitialSyncInFlight as F, useDriveNode as G, markLocalDriveWrite as H, listSyncRemotes as I, isFileNodeKind as J, useDriveNodes as K, addDriveNodesEventHandler as L, useDrives as M, DriveProvider as N, useSelectedNodeId as O, useDriveContext as P, ambientRenownTokenProvider as Q, dropDriveNode as R, selectNode as S, useNodeTarget as T, peekDriveNode as U, loadDriveNodes as V, takeLocalDriveWrite as W, listAllDriveNodes as X, isFolderNodeKind as Y, sortNodesByName as Z, useSetSelectedDrive as _, setVetraPackageManager as a, getNodeTarget as b, addSelectedDriveIdEventHandler as c, setSelectedDrive as d, setSelectedDriveId as f, useSelectedDriveSafe as g, useSelectedDriveId as h, onVetraPackageManager as i, setDrives as j, useSetSelectedNode as k, preloadDrive as l, useSelectedDrive as m, useDocumentModelModules as n, useVetraPackageManager as o, usePreloadDrive as p, useDriveNodesCache as q, addVetraPackageManagerEventHandler as r, useVetraPackages as s, useDocumentModelModuleById as t, selectDrive as u, addResetSelectedNodeEventHandler as v, setSelectedNodeId as w, preloadNode as x, addSelectedNodeIdEventHandler as y, getDriveNode as z };
|
|
643
643
|
|
|
644
|
-
//# sourceMappingURL=document-model-modules-
|
|
644
|
+
//# sourceMappingURL=document-model-modules-XrYfGXt8.js.map
|
package/dist/{document-model-modules-D_kT09sv.js.map → document-model-modules-XrYfGXt8.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-model-modules-D_kT09sv.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/utils/nodes.ts","../src/hooks/drive-nodes.ts","../src/routing/initial-sync.ts","../src/hooks/drive-context.tsx","../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 { getPHStore } from \"../hooks/ph-store.js\";\nimport 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 = getPHStore()?.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","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n\nconst NODE_PAGE_SIZE = 1000;\n\n/** Every node of a drive from `read.drives`, paged until the last page;\n * `parentFolder` narrows it as `listNodes` does (null: the root level). */\nexport async function listAllDriveNodes(\n reader: IDriveReadClient,\n driveId: string,\n options: { parentFolder?: string | null; signal?: AbortSignal } = {},\n): Promise<Node[]> {\n const nodes: Node[] = [];\n let cursor = \"\";\n for (;;) {\n const page = await reader.listNodes(\n driveId,\n options.parentFolder,\n { limit: NODE_PAGE_SIZE, cursor },\n options.signal,\n );\n nodes.push(...page.results);\n if (!page.nextCursor || page.results.length === 0) return nodes;\n cursor = page.nextCursor;\n }\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { listAllDriveNodes } from \"../utils/nodes.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getActivePHStore, getPHStore, usePHStore } from \"./ph-store.js\";\n\n/** One drive's cached nodes, read through `read.drives`. */\nexport type DriveNodesEntry = {\n readonly byId: ReadonlyMap<string, Node>;\n /** \"all\" once a full listing landed; \"partial\" holds single fetches or a\n * listing being refreshed. */\n readonly loaded: \"none\" | \"partial\" | \"all\";\n /** The drive's nodes from the last full listing, kept while it refreshes. */\n readonly nodes?: Node[];\n readonly loading?: Promise<Node[]>;\n /** The drive changed while `loading` was in flight: that listing may miss\n * the change, so another one follows as soon as it lands. */\n readonly stale?: true;\n /** The last full listing failed; hooks do not retry until invalidated. */\n readonly error?: unknown;\n};\n\n/** Node caches by drive id; replaced, never mutated, so hooks see changes. */\nexport type DriveNodesCache = ReadonlyMap<string, DriveNodesEntry>;\n\nexport type DriveNodesOptions = {\n /** Skip the cache and read through `read.drives`. */\n refresh?: boolean;\n store?: PHStore;\n};\n\nconst driveNodesEventFunctions = makePHEventFunctions(\"driveNodes\");\n/** Returns the per-drive node caches */\nexport const useDriveNodesCache = driveNodesEventFunctions.useValue;\n\n/** Adds an event handler for the drive node cache */\nexport const addDriveNodesEventHandler =\n driveNodesEventFunctions.addEventHandler;\n\nconst mounted = new Map<string, number>();\n\nfunction retain(driveId: string) {\n mounted.set(driveId, (mounted.get(driveId) ?? 0) + 1);\n return () => {\n const count = (mounted.get(driveId) ?? 1) - 1;\n if (count > 0) mounted.set(driveId, count);\n else mounted.delete(driveId);\n };\n}\n\nfunction driveReader(store: PHStore | undefined): IDriveReadClient {\n const read = store?.reactorClient?.read;\n if (read) return read.drives;\n throw new Error(\"The reactor client is not initialized\");\n}\n\nfunction entryOf(store: PHStore | undefined, driveId: string) {\n return store?.driveNodes?.get(driveId);\n}\n\nfunction setEntry(\n store: PHStore | undefined,\n driveId: string,\n entry: DriveNodesEntry | undefined,\n) {\n if (!store) return;\n const next = new Map(store.driveNodes);\n if (entry) next.set(driveId, entry);\n else next.delete(driveId);\n store.driveNodes = next;\n // A plain `window.ph` does not notify on assignment.\n if (\n !getActivePHStore() &&\n typeof window !== \"undefined\" &&\n store === window.ph\n ) {\n window.dispatchEvent(new CustomEvent(\"ph:driveNodesUpdated\"));\n }\n}\n\n/** Loads every node of a drive into the cache, paging through\n * `read.drives.listNodes`; served from the cache once loaded. */\nexport function loadDriveNodes(\n driveId: string,\n options: DriveNodesOptions = {},\n): Promise<Node[]> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (current?.loading) {\n // A refresh asked for during a listing lists again once it lands: the\n // one in flight may predate the change that asked for it.\n if (options.refresh && !current.stale) {\n setEntry(store, driveId, { ...current, stale: true });\n }\n return current.loading;\n }\n if (!options.refresh && current?.loaded === \"all\" && current.nodes) {\n return Promise.resolve(current.nodes);\n }\n const read = store?.reactorClient?.read;\n if (!read) {\n return Promise.reject(new Error(\"The reactor client is not initialized\"));\n }\n const reader: IDriveReadClient = read.drives;\n const loading = listAllDriveNodes(reader, driveId);\n setEntry(store, driveId, {\n byId: current?.byId ?? new Map(),\n nodes: current?.nodes,\n loaded: current?.byId.size ? \"partial\" : \"none\",\n loading,\n });\n loading.then(\n (nodes) => {\n const settled = entryOf(store, driveId);\n if (settled?.loading !== loading) return;\n setEntry(store, driveId, {\n byId: new Map(nodes.map((n) => [n.id, n])),\n nodes,\n loaded: \"all\",\n });\n if (settled.stale) {\n if (mounted.has(driveId)) {\n loadDriveNodes(driveId, { store, refresh: true }).catch(\n (error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n } else {\n setEntry(store, driveId, undefined);\n }\n }\n },\n (error: unknown) => {\n const entry = entryOf(store, driveId);\n if (entry?.loading !== loading) return;\n setEntry(store, driveId, { ...entry, loading: undefined, error });\n },\n );\n return loading;\n}\n\n/** A node from the cache, else read through `read.drives.getNode`;\n * undefined when the drive does not hold it. */\nexport async function getDriveNode(\n driveId: string,\n nodeId: string,\n options: DriveNodesOptions = {},\n): Promise<Node | undefined> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (!options.refresh && current) {\n const cached = current.byId.get(nodeId);\n if (cached || current.loaded === \"all\") return cached;\n }\n const reader = driveReader(store);\n let node: Node;\n try {\n node = await reader.getNode(driveId, nodeId);\n } catch {\n return undefined;\n }\n const entry = entryOf(store, driveId);\n const byId = new Map(entry?.byId);\n byId.set(node.id, node);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry?.nodes && replaceNode(entry.nodes, node),\n loaded: entry?.loaded === \"all\" ? \"all\" : \"partial\",\n });\n return node;\n}\n\nfunction replaceNode(nodes: Node[], node: Node) {\n const at = nodes.findIndex((n) => n.id === node.id);\n if (at < 0) return [...nodes, node];\n return nodes.map((n, i) => (i === at ? node : n));\n}\n\n/** A node from the cache only, without reading; for synchronous callers. */\nexport function peekDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n): Node | undefined {\n return entryOf(store, driveId)?.byId.get(nodeId);\n}\n\n/** Drops a drive's cached nodes; while a hook shows them, they reload and\n * the old nodes stay visible until the new listing lands. */\nexport function invalidateDriveNodes(\n driveId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const current = entryOf(store, driveId);\n if (!current) return;\n if (current.loading) {\n // The listing in flight may predate this change; another follows it.\n if (!current.stale) setEntry(store, driveId, { ...current, stale: true });\n return;\n }\n if (!mounted.has(driveId)) {\n setEntry(store, driveId, undefined);\n return;\n }\n setEntry(store, driveId, {\n byId: current.byId,\n nodes: current.nodes,\n loaded: \"partial\",\n });\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n}\n\n/** Drives this tab has just written to; their next change is read at once. */\nconst localDriveWrites = new Set<string>();\n\n/**\n * Notes that this tab wrote to a drive, so the drive change handler re-reads\n * it on the change that follows instead of waiting out its interval: the\n * person who added, renamed or removed a node expects to see it, while a\n * drive being filled by someone else can wait.\n */\nexport function markLocalDriveWrite(driveId: string): void {\n localDriveWrites.add(driveId);\n}\n\n/** Spends a drive's local-write mark; true when one was set. */\nexport function takeLocalDriveWrite(driveId: string): boolean {\n return localDriveWrites.delete(driveId);\n}\n\n/** Takes a node out of a drive's cache after this tab removed it, so the\n * listing drops it at once instead of after the next drive refresh. */\nexport function dropDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const entry = entryOf(store, driveId);\n if (!entry?.byId.has(nodeId)) return;\n const byId = new Map(entry.byId);\n byId.delete(nodeId);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry.nodes?.filter((n) => n.id !== nodeId),\n });\n}\n\nfunction useDriveNodesEntry(driveId: string | null | undefined) {\n const store = usePHStore() ?? getPHStore();\n const cache = useDriveNodesCache();\n return [store, driveId ? cache?.get(driveId) : undefined] as const;\n}\n\n/** Every node of a drive, loaded on first use; undefined until loaded. */\nexport function useDriveNodes(\n driveId: string | null | undefined,\n): Node[] | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const needsLoad =\n !!driveId && !entry?.loading && !entry?.error && entry?.loaded !== \"all\";\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !needsLoad) return;\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive nodes failed: @error\", error),\n );\n }, [driveId, needsLoad, store]);\n\n return entry?.nodes;\n}\n\n/** One node of a drive, from the cache or read on its own. */\nexport function useDriveNode(\n driveId: string | null | undefined,\n nodeId: string | null | undefined,\n): Node | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const node = nodeId ? entry?.byId.get(nodeId) : undefined;\n const needsFetch =\n !!driveId &&\n !!nodeId &&\n !node &&\n entry?.loaded !== \"all\" &&\n !entry?.loading;\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !nodeId || !needsFetch) return;\n getDriveNode(driveId, nodeId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive node failed: @error\", error),\n );\n }, [driveId, nodeId, needsFetch, store]);\n\n return node;\n}\n","import type { Remote } from \"@powerhousedao/reactor\";\nimport type { PHStore } from \"../hooks/ph-store.js\";\n\n/** The store's sync remotes; none before the reactor is ready. */\nexport function listSyncRemotes(store: PHStore | undefined): Remote[] {\n try {\n return (\n store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ??\n []\n );\n } catch {\n return [];\n }\n}\n\n// Only a first pull in flight may still bring drives. A connected remote that\n// never polled is paused or answer-only; one failed or failing to reconnect won't soon.\nfunction isFirstPullInFlight(remote: Remote) {\n try {\n const { state, receivingPages, lastSuccessUtcMs, failureCount } =\n remote.channel.getConnectionState();\n if (state === \"connected\") return receivingPages;\n if (state === \"reconnecting\") return !lastSuccessUtcMs && !failureCount;\n return state === \"connecting\" && (receivingPages || !lastSuccessUtcMs);\n } catch {\n return false;\n }\n}\n\n/** Whether a remote, or one syncing `driveId` when given, is in its first pull. */\nexport function isInitialSyncInFlight(\n store: PHStore | undefined,\n driveId?: string,\n) {\n return listSyncRemotes(store).some(\n (remote) =>\n (driveId === undefined || remote.meta.collectionId.driveId === driveId) &&\n isFirstPullInFlight(remote),\n );\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { PHNavigateOptions } from \"../types/global.js\";\n\n/** The drive a drive app shows. `open`/`preload` replace the app's navigation,\n * e.g. for a host that keeps the open node in local state. */\nexport type DriveContextValue = {\n drive: DocumentDriveDocument;\n dispatch: DocumentDispatch<DocumentDriveAction>;\n /** The open folder; undefined at the drive's root or on a document. */\n folder?: FolderNode;\n /** The open node, a folder or a document. */\n nodeId?: string;\n open?: (node: Node | undefined, options?: PHNavigateOptions) => void;\n preload?: (node: Node | undefined) => void;\n};\n\nconst DriveContext = createContext<DriveContextValue | undefined>(undefined);\n\n/** Hosts render a drive app inside this; `useSelectedDrive`, `useSelectedNode`\n * and `useSelectedFolder` below read it, and opening nodes calls its `open`. */\nexport function DriveProvider(props: {\n value: DriveContextValue;\n children: ReactNode;\n}) {\n return (\n <DriveContext.Provider value={props.value}>\n {props.children}\n </DriveContext.Provider>\n );\n}\n\n/** The nearest drive app's drive, or undefined outside one. */\nexport function useDriveContext() {\n return useContext(DriveContext);\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 {\n PHNavigateOptions,\n PHNavigationTarget,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n makeDriveSlug,\n makeNodeSlug,\n} from \"../utils/url.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport { useCallback } from \"react\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { peekDriveNode } from \"./drive-nodes.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, usePHStore } from \"./ph-store.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useStoreSelectedNodeId = selectedNodeIdEventFunctions.useValue;\n\n/** The selected node id: the drive app's open node, else the app's selection. */\nexport function useSelectedNodeId() {\n const context = useDriveContext();\n const selectedNodeId = useStoreSelectedNodeId();\n return context ? context.nodeId : selectedNodeId;\n}\n/** Sets the selected node id without touching the URL. */\nexport const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\n/** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\nfunction decodeSlug(slug: string) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n}\n\n// The selected drive's slug, else the path's: a pending navigation's path\n// already names its destination, not the drive still shown.\nfunction openDriveSlug(store: PHStore | undefined, pathname: string) {\n const selected = store?.drives?.find(\n (d) => d.header.id === store.selectedDriveId,\n );\n if (selected) return makeDriveSlug(selected);\n const driveSlug = extractDriveSlugFromPath(pathname);\n return driveSlug ? decodeSlug(driveSlug) : undefined;\n}\n\n// The node in `drive`, else in the app's open drive.\nfunction nodeTarget(\n nodeSlug: string,\n drive?: DocumentDriveDocument,\n): PHNavigationTarget | undefined {\n const driveSlug = drive\n ? makeDriveSlug(drive)\n : openDriveSlug(getPHStore(), getCurrentPathname());\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\ntype NodeRef = Node | string | undefined;\n\nconst toSlug = (node: NodeRef) =>\n typeof node === \"string\" ? node : makeNodeSlug(node);\n\n/** Selects a node in `drive`, else in the app's open drive. */\nexport function selectNode(\n node: NodeRef,\n options?: PHNavigateOptions,\n drive?: DocumentDriveDocument,\n) {\n const nodeSlug = toSlug(node);\n // A host router resolves the node and writes the selection itself.\n if (!hasHostNavigation()) {\n setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n }\n const target = nodeTarget(nodeSlug, drive);\n if (target) openTarget(target, options);\n}\n\n/** Sets the selected node (file or folder) of the app's store; `search` sets\n * the params it opens with. Inside a drive app, use `useSetSelectedNode`. */\nexport function setSelectedNode(node: NodeRef, options?: PHNavigateOptions) {\n selectNode(node, options);\n}\n\nfunction findNode(\n drive: DocumentDriveDocument,\n node: NodeRef,\n store: PHStore | undefined,\n) {\n if (typeof node !== \"string\") return node;\n const id = extractNodeIdFromSlug(node);\n return id ? peekDriveNode(drive.header.id, id, store) : undefined;\n}\n\n/** Opens a node: through the drive app's `open` when it has one, else the\n * app's navigation in the drive app's drive. */\nexport function useSetSelectedNode() {\n const context = useDriveContext();\n const store = usePHStore() ?? getPHStore();\n return useCallback(\n (node: NodeRef, options?: PHNavigateOptions) => {\n if (context?.open) {\n context.open(findNode(context.drive, node, store), options);\n return;\n }\n selectNode(node, options, context?.drive);\n },\n [context, store],\n );\n}\n\n/** Opens a node, or with `undefined` its drive. */\nexport const useOpenNode: () => (\n node: Node | undefined,\n options?: PHNavigateOptions,\n) => void = useSetSelectedNode;\n\n/** Where a node of `drive`, else of the open drive, navigates to. */\nexport function getNodeTarget(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n return nodeTarget(makeNodeSlug(node), drive);\n}\n\n/** Where a node navigates to: in the drive app's drive, else the open drive. */\nexport function useNodeTarget(node: Node | undefined) {\n const context = useDriveContext();\n return getNodeTarget(node, context?.drive);\n}\n\n/** Warms a node's view before it is opened, e.g. on hover. */\nexport function preloadNode(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n if (!node) return;\n const target = nodeTarget(makeNodeSlug(node), drive);\n if (target) preloadTarget(target);\n}\n\n/** `preloadNode` through the drive app's `preload`, if it has one. */\nexport function usePreloadNode() {\n const context = useDriveContext();\n return useCallback(\n (node: Node | undefined) => {\n if (context?.preload) context.preload(node);\n else if (!context?.open) preloadNode(node, context?.drive);\n },\n [context],\n );\n}\n\nexport function addResetSelectedNodeEventHandler() {\n subscribeToPHValue(\"selectedDriveId\", () => {\n setSelectedNodeId(undefined);\n });\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport { useCallback } from \"react\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n findDriveBySlug,\n makeDriveSlug,\n} from \"../utils/url.js\";\nimport { isInitialSyncInFlight } from \"../routing/initial-sync.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useDrives } from \"./drives.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport { selectNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\nconst useStoreSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Returns the selected drive id: the drive app's drive, else the app's selection. */\nexport function useSelectedDriveId() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n return context ? context.drive.header.id : selectedDriveId;\n}\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id\n * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */\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 context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = context\n ? undefined\n : drives?.find((drive) => drive.header.id === selectedDriveId);\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (context) {\n return [context.drive, context.dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n }\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\ntype DriveRef = string | DocumentDriveDocument | undefined;\n\n/** Selects a drive in the app's store. */\nexport function setSelectedDrive(driveOrDriveSlug: DriveRef) {\n selectDrive(driveOrDriveSlug);\n}\n\n/** `setSelectedDrive`, as a hook. */\nexport function useSetSelectedDrive() {\n return useCallback((drive: DriveRef) => selectDrive(drive), []);\n}\n\n/** Selects a drive in the app's store. */\nexport function selectDrive(driveOrDriveSlug: DriveRef) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n\n // A host router resolves the drive and writes the selection itself.\n if (hasHostNavigation()) {\n cancelPendingDriveSelection();\n openTarget(driveSlug ? { driveSlug } : undefined);\n return;\n }\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 = getPHStore()?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : findDriveBySlug(drives, driveSlug);\n const driveId = drive?.header.id;\n\n // Deprecated: hosts without a navigation only; route loaders wait for drives.\n // A deep link may predate remote drive registration, so defer the lookup.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(getCurrentPathname()) === 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 (getPHStore()?.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 openTarget(driveId && driveSlug ? { driveSlug } : undefined);\n}\n\n/** Warms a drive's view before it is opened, e.g. on hover. */\nexport function preloadDrive(drive: DocumentDriveDocument | undefined) {\n if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });\n}\n\n/** `preloadDrive`, as a hook. */\nexport function usePreloadDrive() {\n return useCallback(\n (drive: DocumentDriveDocument | undefined) => preloadDrive(drive),\n [],\n );\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\nlet unsubscribePending: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (unsubscribePending) {\n unsubscribePending();\n unsubscribePending = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Deprecated with the no-navigation path: re-runs the slug lookup on drives\n// updates, restores the pinned node, and redirects home 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(getCurrentPathname());\n const handler = () => {\n const drive = findDriveBySlug(getPHStore()?.drives, driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n selectDrive(driveSlug);\n selectNode(nodeSlug);\n };\n unsubscribePending = subscribeToPHValue(\"drives\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n openTarget(undefined);\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport 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 const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n getPackages,\n getPackages,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/**\n * Non-react access to the Vetra package manager: calls `callback` once a\n * manager is available - immediately when already set, otherwise when\n * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker\n * wiring uses this to forward package updates from plain boot code.\n */\nexport function onVetraPackageManager(\n callback: (packageManager: IPackageManager) => void,\n): () => void {\n let delivered: IPackageManager | undefined;\n const deliver = () => {\n const packageManager = vetraPackageManagerFunctions.getSnapshot();\n if (!packageManager || packageManager === delivered) return;\n delivered = packageManager;\n callback(packageManager);\n };\n const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);\n deliver();\n return unsubscribe;\n}\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 getPHStore()?.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 getPHStore()?.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":";;;;;;;;AAYA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,WAAW,CAAC,EAAE;CAC7B,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;;;;ACjDA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC9D;;AAGA,SAAgB,eACd,MACkB;CAClB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;AAGA,SAAgB,iBACd,MACoB;CACpB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;AAEA,MAAM,iBAAiB;;;AAIvB,eAAsB,kBACpB,QACA,SACA,UAAkE,CAAC,GAClD;CACjB,MAAM,QAAgB,CAAC;CACvB,IAAI,SAAS;CACb,SAAS;EACP,MAAM,OAAO,MAAM,OAAO,UACxB,SACA,QAAQ,cACR;GAAE,OAAO;GAAgB;EAAO,GAChC,QAAQ,MACV;EACA,MAAM,KAAK,GAAG,KAAK,OAAO;EAC1B,IAAI,CAAC,KAAK,cAAc,KAAK,QAAQ,WAAW,GAAG,OAAO;EAC1D,SAAS,KAAK;CA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tC;EACF;EACA,IAAI,gBAAgB,eAAe;GACjC,gBAAgB;GAChB,eAAe;EACjB;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"document-model-modules-XrYfGXt8.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/utils/nodes.ts","../src/hooks/drive-nodes.ts","../src/routing/initial-sync.ts","../src/hooks/drive-context.tsx","../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 { getPHStore } from \"../hooks/ph-store.js\";\nimport 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 = getPHStore()?.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","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n\nconst NODE_PAGE_SIZE = 1000;\n\n/** Every node of a drive from `read.drives`, paged until the last page;\n * `parentFolder` narrows it as `listNodes` does (null: the root level). */\nexport async function listAllDriveNodes(\n reader: IDriveReadClient,\n driveId: string,\n options: { parentFolder?: string | null; signal?: AbortSignal } = {},\n): Promise<Node[]> {\n const nodes: Node[] = [];\n let cursor = \"\";\n for (;;) {\n const page = await reader.listNodes(\n driveId,\n options.parentFolder,\n { limit: NODE_PAGE_SIZE, cursor },\n options.signal,\n );\n nodes.push(...page.results);\n if (!page.nextCursor || page.results.length === 0) return nodes;\n cursor = page.nextCursor;\n }\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { listAllDriveNodes } from \"../utils/nodes.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getActivePHStore, getPHStore, usePHStore } from \"./ph-store.js\";\n\n/** One drive's cached nodes, read through `read.drives`. */\nexport type DriveNodesEntry = {\n readonly byId: ReadonlyMap<string, Node>;\n /** \"all\" once a full listing landed; \"partial\" holds single fetches or a\n * listing being refreshed. */\n readonly loaded: \"none\" | \"partial\" | \"all\";\n /** The drive's nodes from the last full listing, kept while it refreshes. */\n readonly nodes?: Node[];\n readonly loading?: Promise<Node[]>;\n /** The drive changed while `loading` was in flight: that listing may miss\n * the change, so another one follows as soon as it lands. */\n readonly stale?: true;\n /** The last full listing failed; hooks do not retry until invalidated. */\n readonly error?: unknown;\n};\n\n/** Node caches by drive id; replaced, never mutated, so hooks see changes. */\nexport type DriveNodesCache = ReadonlyMap<string, DriveNodesEntry>;\n\nexport type DriveNodesOptions = {\n /** Skip the cache and read through `read.drives`. */\n refresh?: boolean;\n store?: PHStore;\n};\n\nconst driveNodesEventFunctions = makePHEventFunctions(\"driveNodes\");\n/** Returns the per-drive node caches */\nexport const useDriveNodesCache = driveNodesEventFunctions.useValue;\n\n/** Adds an event handler for the drive node cache */\nexport const addDriveNodesEventHandler =\n driveNodesEventFunctions.addEventHandler;\n\nconst mounted = new Map<string, number>();\n\nfunction retain(driveId: string) {\n mounted.set(driveId, (mounted.get(driveId) ?? 0) + 1);\n return () => {\n const count = (mounted.get(driveId) ?? 1) - 1;\n if (count > 0) mounted.set(driveId, count);\n else mounted.delete(driveId);\n };\n}\n\nfunction driveReader(store: PHStore | undefined): IDriveReadClient {\n const read = store?.reactorClient?.read;\n if (read) return read.drives;\n throw new Error(\"The reactor client is not initialized\");\n}\n\nfunction entryOf(store: PHStore | undefined, driveId: string) {\n return store?.driveNodes?.get(driveId);\n}\n\nfunction setEntry(\n store: PHStore | undefined,\n driveId: string,\n entry: DriveNodesEntry | undefined,\n) {\n if (!store) return;\n const next = new Map(store.driveNodes);\n if (entry) next.set(driveId, entry);\n else next.delete(driveId);\n store.driveNodes = next;\n // A plain `window.ph` does not notify on assignment.\n if (\n !getActivePHStore() &&\n typeof window !== \"undefined\" &&\n store === window.ph\n ) {\n window.dispatchEvent(new CustomEvent(\"ph:driveNodesUpdated\"));\n }\n}\n\n/** Loads every node of a drive into the cache, paging through\n * `read.drives.listNodes`; served from the cache once loaded. */\nexport function loadDriveNodes(\n driveId: string,\n options: DriveNodesOptions = {},\n): Promise<Node[]> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (current?.loading) {\n // A refresh asked for during a listing lists again once it lands: the\n // one in flight may predate the change that asked for it.\n if (options.refresh && !current.stale) {\n setEntry(store, driveId, { ...current, stale: true });\n }\n return current.loading;\n }\n if (!options.refresh && current?.loaded === \"all\" && current.nodes) {\n return Promise.resolve(current.nodes);\n }\n const read = store?.reactorClient?.read;\n if (!read) {\n return Promise.reject(new Error(\"The reactor client is not initialized\"));\n }\n const reader: IDriveReadClient = read.drives;\n const loading = listAllDriveNodes(reader, driveId);\n setEntry(store, driveId, {\n byId: current?.byId ?? new Map(),\n nodes: current?.nodes,\n loaded: current?.byId.size ? \"partial\" : \"none\",\n loading,\n });\n loading.then(\n (nodes) => {\n const settled = entryOf(store, driveId);\n if (settled?.loading !== loading) return;\n setEntry(store, driveId, {\n byId: new Map(nodes.map((n) => [n.id, n])),\n nodes,\n loaded: \"all\",\n });\n if (settled.stale) {\n if (mounted.has(driveId)) {\n loadDriveNodes(driveId, { store, refresh: true }).catch(\n (error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n } else {\n setEntry(store, driveId, undefined);\n }\n }\n },\n (error: unknown) => {\n const entry = entryOf(store, driveId);\n if (entry?.loading !== loading) return;\n setEntry(store, driveId, { ...entry, loading: undefined, error });\n },\n );\n return loading;\n}\n\n/** A node from the cache, else read through `read.drives.getNode`;\n * undefined when the drive does not hold it. */\nexport async function getDriveNode(\n driveId: string,\n nodeId: string,\n options: DriveNodesOptions = {},\n): Promise<Node | undefined> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (!options.refresh && current) {\n const cached = current.byId.get(nodeId);\n if (cached || current.loaded === \"all\") return cached;\n }\n const reader = driveReader(store);\n let node: Node;\n try {\n node = await reader.getNode(driveId, nodeId);\n } catch {\n return undefined;\n }\n const entry = entryOf(store, driveId);\n const byId = new Map(entry?.byId);\n byId.set(node.id, node);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry?.nodes && replaceNode(entry.nodes, node),\n loaded: entry?.loaded === \"all\" ? \"all\" : \"partial\",\n });\n return node;\n}\n\nfunction replaceNode(nodes: Node[], node: Node) {\n const at = nodes.findIndex((n) => n.id === node.id);\n if (at < 0) return [...nodes, node];\n return nodes.map((n, i) => (i === at ? node : n));\n}\n\n/** A node from the cache only, without reading; for synchronous callers. */\nexport function peekDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n): Node | undefined {\n return entryOf(store, driveId)?.byId.get(nodeId);\n}\n\n/** Drops a drive's cached nodes; while a hook shows them, they reload and\n * the old nodes stay visible until the new listing lands. */\nexport function invalidateDriveNodes(\n driveId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const current = entryOf(store, driveId);\n if (!current) return;\n if (current.loading) {\n // The listing in flight may predate this change; another follows it.\n if (!current.stale) setEntry(store, driveId, { ...current, stale: true });\n return;\n }\n if (!mounted.has(driveId)) {\n setEntry(store, driveId, undefined);\n return;\n }\n setEntry(store, driveId, {\n byId: current.byId,\n nodes: current.nodes,\n loaded: \"partial\",\n });\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n}\n\n/** Drives this tab has just written to; their next change is read at once. */\nconst localDriveWrites = new Set<string>();\n\n/**\n * Notes that this tab wrote to a drive, so the drive change handler re-reads\n * it on the change that follows instead of waiting out its interval: the\n * person who added, renamed or removed a node expects to see it, while a\n * drive being filled by someone else can wait.\n */\nexport function markLocalDriveWrite(driveId: string): void {\n localDriveWrites.add(driveId);\n}\n\n/** Spends a drive's local-write mark; true when one was set. */\nexport function takeLocalDriveWrite(driveId: string): boolean {\n return localDriveWrites.delete(driveId);\n}\n\n/** Takes a node out of a drive's cache after this tab removed it, so the\n * listing drops it at once instead of after the next drive refresh. */\nexport function dropDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const entry = entryOf(store, driveId);\n if (!entry?.byId.has(nodeId)) return;\n const byId = new Map(entry.byId);\n byId.delete(nodeId);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry.nodes?.filter((n) => n.id !== nodeId),\n });\n}\n\nfunction useDriveNodesEntry(driveId: string | null | undefined) {\n const store = usePHStore() ?? getPHStore();\n const cache = useDriveNodesCache();\n return [store, driveId ? cache?.get(driveId) : undefined] as const;\n}\n\n/** Every node of a drive, loaded on first use; undefined until loaded. */\nexport function useDriveNodes(\n driveId: string | null | undefined,\n): Node[] | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const needsLoad =\n !!driveId && !entry?.loading && !entry?.error && entry?.loaded !== \"all\";\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !needsLoad) return;\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive nodes failed: @error\", error),\n );\n }, [driveId, needsLoad, store]);\n\n return entry?.nodes;\n}\n\n/** One node of a drive, from the cache or read on its own. */\nexport function useDriveNode(\n driveId: string | null | undefined,\n nodeId: string | null | undefined,\n): Node | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const node = nodeId ? entry?.byId.get(nodeId) : undefined;\n const needsFetch =\n !!driveId &&\n !!nodeId &&\n !node &&\n entry?.loaded !== \"all\" &&\n !entry?.loading;\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !nodeId || !needsFetch) return;\n getDriveNode(driveId, nodeId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive node failed: @error\", error),\n );\n }, [driveId, nodeId, needsFetch, store]);\n\n return node;\n}\n","import type { Remote } from \"@powerhousedao/reactor\";\nimport type { PHStore } from \"../hooks/ph-store.js\";\n\n/** The store's sync remotes; none before the reactor is ready. */\nexport function listSyncRemotes(store: PHStore | undefined): Remote[] {\n try {\n return (\n store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ??\n []\n );\n } catch {\n return [];\n }\n}\n\n// Only a first pull in flight may still bring drives. A connected remote that\n// never polled is paused or answer-only; one failed or failing to reconnect won't soon.\nfunction isFirstPullInFlight(remote: Remote) {\n try {\n const { state, receivingPages, lastSuccessUtcMs, failureCount } =\n remote.channel.getConnectionState();\n if (state === \"connected\") return receivingPages;\n if (state === \"reconnecting\") return !lastSuccessUtcMs && !failureCount;\n return state === \"connecting\" && (receivingPages || !lastSuccessUtcMs);\n } catch {\n return false;\n }\n}\n\n/** Whether a remote, or one syncing `driveId` when given, is in its first pull. */\nexport function isInitialSyncInFlight(\n store: PHStore | undefined,\n driveId?: string,\n) {\n return listSyncRemotes(store).some(\n (remote) =>\n (driveId === undefined || remote.meta.collectionId.driveId === driveId) &&\n isFirstPullInFlight(remote),\n );\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { PHNavigateOptions } from \"../types/global.js\";\n\n/** The drive a drive app shows. `open`/`preload` replace the app's navigation,\n * e.g. for a host that keeps the open node in local state. */\nexport type DriveContextValue = {\n drive: DocumentDriveDocument;\n dispatch: DocumentDispatch<DocumentDriveAction>;\n /** The open folder; undefined at the drive's root or on a document. */\n folder?: FolderNode;\n /** The open node, a folder or a document. */\n nodeId?: string;\n open?: (node: Node | undefined, options?: PHNavigateOptions) => void;\n preload?: (node: Node | undefined) => void;\n};\n\nconst DriveContext = createContext<DriveContextValue | undefined>(undefined);\n\n/** Hosts render a drive app inside this; `useSelectedDrive`, `useSelectedNode`\n * and `useSelectedFolder` below read it, and opening nodes calls its `open`. */\nexport function DriveProvider(props: {\n value: DriveContextValue;\n children: ReactNode;\n}) {\n return (\n <DriveContext.Provider value={props.value}>\n {props.children}\n </DriveContext.Provider>\n );\n}\n\n/** The nearest drive app's drive, or undefined outside one. */\nexport function useDriveContext() {\n return useContext(DriveContext);\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 {\n PHNavigateOptions,\n PHNavigationTarget,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n makeDriveSlug,\n makeNodeSlug,\n} from \"../utils/url.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport { useCallback } from \"react\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { peekDriveNode } from \"./drive-nodes.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, usePHStore } from \"./ph-store.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useStoreSelectedNodeId = selectedNodeIdEventFunctions.useValue;\n\n/** The selected node id: the drive app's open node, else the app's selection. */\nexport function useSelectedNodeId() {\n const context = useDriveContext();\n const selectedNodeId = useStoreSelectedNodeId();\n return context ? context.nodeId : selectedNodeId;\n}\n/** Sets the selected node id without touching the URL. */\nexport const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\n/** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\nfunction decodeSlug(slug: string) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n}\n\n// The selected drive's slug, else the path's: a pending navigation's path\n// already names its destination, not the drive still shown.\nfunction openDriveSlug(store: PHStore | undefined, pathname: string) {\n const selected = store?.drives?.find(\n (d) => d.header.id === store.selectedDriveId,\n );\n if (selected) return makeDriveSlug(selected);\n const driveSlug = extractDriveSlugFromPath(pathname);\n return driveSlug ? decodeSlug(driveSlug) : undefined;\n}\n\n// The node in `drive`, else in the app's open drive.\nfunction nodeTarget(\n nodeSlug: string,\n drive?: DocumentDriveDocument,\n): PHNavigationTarget | undefined {\n const driveSlug = drive\n ? makeDriveSlug(drive)\n : openDriveSlug(getPHStore(), getCurrentPathname());\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\ntype NodeRef = Node | string | undefined;\n\nconst toSlug = (node: NodeRef) =>\n typeof node === \"string\" ? node : makeNodeSlug(node);\n\n/** Selects a node in `drive`, else in the app's open drive. */\nexport function selectNode(\n node: NodeRef,\n options?: PHNavigateOptions,\n drive?: DocumentDriveDocument,\n) {\n const nodeSlug = toSlug(node);\n // A host router resolves the node and writes the selection itself.\n if (!hasHostNavigation()) {\n setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n }\n const target = nodeTarget(nodeSlug, drive);\n if (target) openTarget(target, options);\n}\n\n/** Sets the selected node (file or folder) of the app's store; `search` sets\n * the params it opens with. Inside a drive app, use `useSetSelectedNode`. */\nexport function setSelectedNode(node: NodeRef, options?: PHNavigateOptions) {\n selectNode(node, options);\n}\n\nfunction findNode(\n drive: DocumentDriveDocument,\n node: NodeRef,\n store: PHStore | undefined,\n) {\n if (typeof node !== \"string\") return node;\n const id = extractNodeIdFromSlug(node);\n return id ? peekDriveNode(drive.header.id, id, store) : undefined;\n}\n\n/** Opens a node: through the drive app's `open` when it has one, else the\n * app's navigation in the drive app's drive. */\nexport function useSetSelectedNode() {\n const context = useDriveContext();\n const store = usePHStore() ?? getPHStore();\n return useCallback(\n (node: NodeRef, options?: PHNavigateOptions) => {\n if (context?.open) {\n context.open(findNode(context.drive, node, store), options);\n return;\n }\n selectNode(node, options, context?.drive);\n },\n [context, store],\n );\n}\n\n/** Opens a node, or with `undefined` its drive. */\nexport const useOpenNode: () => (\n node: Node | undefined,\n options?: PHNavigateOptions,\n) => void = useSetSelectedNode;\n\n/** Where a node of `drive`, else of the open drive, navigates to. */\nexport function getNodeTarget(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n return nodeTarget(makeNodeSlug(node), drive);\n}\n\n/** Where a node navigates to: in the drive app's drive, else the open drive. */\nexport function useNodeTarget(node: Node | undefined) {\n const context = useDriveContext();\n return getNodeTarget(node, context?.drive);\n}\n\n/** Warms a node's view before it is opened, e.g. on hover. */\nexport function preloadNode(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n if (!node) return;\n const target = nodeTarget(makeNodeSlug(node), drive);\n if (target) preloadTarget(target);\n}\n\n/** `preloadNode` through the drive app's `preload`, if it has one. */\nexport function usePreloadNode() {\n const context = useDriveContext();\n return useCallback(\n (node: Node | undefined) => {\n if (context?.preload) context.preload(node);\n else if (!context?.open) preloadNode(node, context?.drive);\n },\n [context],\n );\n}\n\nexport function addResetSelectedNodeEventHandler() {\n subscribeToPHValue(\"selectedDriveId\", () => {\n setSelectedNodeId(undefined);\n });\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport { useCallback } from \"react\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n findDriveBySlug,\n makeDriveSlug,\n} from \"../utils/url.js\";\nimport { isInitialSyncInFlight } from \"../routing/initial-sync.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useDrives } from \"./drives.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport { selectNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\nconst useStoreSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Returns the selected drive id: the drive app's drive, else the app's selection. */\nexport function useSelectedDriveId() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n return context ? context.drive.header.id : selectedDriveId;\n}\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id\n * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */\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 context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = context\n ? undefined\n : drives?.find((drive) => drive.header.id === selectedDriveId);\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (context) {\n return [context.drive, context.dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n }\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\ntype DriveRef = string | DocumentDriveDocument | undefined;\n\n/** Selects a drive in the app's store. */\nexport function setSelectedDrive(driveOrDriveSlug: DriveRef) {\n selectDrive(driveOrDriveSlug);\n}\n\n/** `setSelectedDrive`, as a hook. */\nexport function useSetSelectedDrive() {\n return useCallback((drive: DriveRef) => selectDrive(drive), []);\n}\n\n/** Selects a drive in the app's store. */\nexport function selectDrive(driveOrDriveSlug: DriveRef) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n\n // A host router resolves the drive and writes the selection itself.\n if (hasHostNavigation()) {\n cancelPendingDriveSelection();\n openTarget(driveSlug ? { driveSlug } : undefined);\n return;\n }\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 = getPHStore()?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : findDriveBySlug(drives, driveSlug);\n const driveId = drive?.header.id;\n\n // Deprecated: hosts without a navigation only; route loaders wait for drives.\n // A deep link may predate remote drive registration, so defer the lookup.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(getCurrentPathname()) === 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 (getPHStore()?.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 openTarget(driveId && driveSlug ? { driveSlug } : undefined);\n}\n\n/** Warms a drive's view before it is opened, e.g. on hover. */\nexport function preloadDrive(drive: DocumentDriveDocument | undefined) {\n if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });\n}\n\n/** `preloadDrive`, as a hook. */\nexport function usePreloadDrive() {\n return useCallback(\n (drive: DocumentDriveDocument | undefined) => preloadDrive(drive),\n [],\n );\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\nlet unsubscribePending: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (unsubscribePending) {\n unsubscribePending();\n unsubscribePending = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Deprecated with the no-navigation path: re-runs the slug lookup on drives\n// updates, restores the pinned node, and redirects home 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(getCurrentPathname());\n const handler = () => {\n const drive = findDriveBySlug(getPHStore()?.drives, driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n selectDrive(driveSlug);\n selectNode(nodeSlug);\n };\n unsubscribePending = subscribeToPHValue(\"drives\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n openTarget(undefined);\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport 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 const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n getPackages,\n getPackages,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/**\n * Non-react access to the Vetra package manager: calls `callback` once a\n * manager is available - immediately when already set, otherwise when\n * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker\n * wiring uses this to forward package updates from plain boot code.\n */\nexport function onVetraPackageManager(\n callback: (packageManager: IPackageManager) => void,\n): () => void {\n let delivered: IPackageManager | undefined;\n const deliver = () => {\n const packageManager = vetraPackageManagerFunctions.getSnapshot();\n if (!packageManager || packageManager === delivered) return;\n delivered = packageManager;\n callback(packageManager);\n };\n const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);\n deliver();\n return unsubscribe;\n}\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 getPHStore()?.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 getPHStore()?.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":";;;;;;;;AAYA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,WAAW,CAAC,EAAE;CAC7B,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;;;;ACjDA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC9D;;AAGA,SAAgB,eACd,MACkB;CAClB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;AAGA,SAAgB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