@powerhousedao/reactor-browser 6.4.0-next.2 → 6.4.0-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-0E5S0hZ6.d.ts → attachment-service-DdLM0Yf5.d.ts} +40 -9
- package/dist/attachment-service-DdLM0Yf5.d.ts.map +1 -0
- package/dist/auth-Ryem1MiX.d.ts +53 -0
- package/dist/auth-Ryem1MiX.d.ts.map +1 -0
- package/dist/{client-BFnMV-EO.js → client-DMCO2IaR.js} +3 -2
- package/dist/client-DMCO2IaR.js.map +1 -0
- package/dist/{document-model-modules-DCC6DjOP.js → document-model-modules-CHo9NZhj.js} +37 -5
- package/dist/document-model-modules-CHo9NZhj.js.map +1 -0
- package/dist/{document-operations-BUbpyfSf.js → document-operations-Dj0fTOHE.js} +113 -14
- package/dist/document-operations-Dj0fTOHE.js.map +1 -0
- package/dist/{global-DfeQC3Fg.d.ts → global-DMTXzdRf.d.ts} +28 -2
- package/dist/{global-DfeQC3Fg.d.ts.map → global-DMTXzdRf.d.ts.map} +1 -1
- package/dist/{index-BlCYgfht.d.ts → index-C5bsy9EC.d.ts} +127 -4
- package/dist/index-C5bsy9EC.d.ts.map +1 -0
- package/dist/index.d.ts +13 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/local-sign-in-D2zVzXgm.js +12 -0
- package/dist/local-sign-in-D2zVzXgm.js.map +1 -0
- package/dist/{renown-BlvHEYjM.js → renown-BwJ9oWxt.js} +414 -64
- package/dist/renown-BwJ9oWxt.js.map +1 -0
- package/dist/src/ai/index.d.ts +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/graphql-client/entry.d.ts +4 -4
- package/dist/src/graphql-client/entry.js +3 -3
- package/dist/src/renown/index.d.ts +2 -2
- package/dist/src/renown/index.js +2 -2
- package/dist/src/rpc/index.d.ts +17 -11
- package/dist/src/rpc/index.d.ts.map +1 -1
- package/dist/src/rpc/index.js +4 -3
- package/dist/src/rpc/index.js.map +1 -1
- package/dist/{switchboard-directory-CwT34q4g.js → switchboard-directory-7KPHB5Tz.js} +2 -2
- package/dist/{switchboard-directory-CwT34q4g.js.map → switchboard-directory-7KPHB5Tz.js.map} +1 -1
- package/package.json +11 -11
- package/dist/attachment-service-0E5S0hZ6.d.ts.map +0 -1
- package/dist/auth-DRbzRdeC.d.ts +0 -32
- package/dist/auth-DRbzRdeC.d.ts.map +0 -1
- package/dist/client-BFnMV-EO.js.map +0 -1
- package/dist/document-model-modules-DCC6DjOP.js.map +0 -1
- package/dist/document-operations-BUbpyfSf.js.map +0 -1
- package/dist/index-BlCYgfht.d.ts.map +0 -1
- package/dist/renown-BlvHEYjM.js.map +0 -1
package/dist/{switchboard-directory-CwT34q4g.js.map → switchboard-directory-7KPHB5Tz.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard-directory-CwT34q4g.js","names":[],"sources":["../src/hooks/node-by-id.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/editor-context.tsx","../src/hooks/selected-document.ts","../src/utils/gql-channel.ts","../src/utils/switchboard.ts","../src/utils/switchboard-directory.ts"],"sourcesContent":["import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useDriveNode } from \"./drive-nodes.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\n\n/** Returns a node in the selected drive by id. */\nexport function useNodeById(id: string | null | undefined): Node | undefined {\n return useDriveNode(useSelectedDriveId(), id);\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodeById } from \"./node-by-id.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n getNodeTarget,\n useNodeTarget,\n preloadNode,\n setSelectedNode,\n useOpenNode,\n usePreloadNode,\n useSetSelectedNode,\n} from \"./set-selected-node.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n return useNodeById(useSelectedNodeId());\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type {\n DocumentDispatch,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext, useMemo } from \"react\";\n\n/** The document an editor is rendered with, and a dispatch bound to it. */\nexport type EditorDocumentContextValue = readonly [\n PHDocument,\n DocumentDispatch,\n];\n\nconst EditorDocumentContext = createContext<\n EditorDocumentContextValue | undefined\n>(undefined);\n\n/** Hosts render an editor inside this, with the same `document` and `dispatch`\n * as its props; `useSelected*Document` hooks below read them. */\nexport function EditorDocumentProvider(props: {\n document: PHDocument;\n dispatch: DocumentDispatch;\n children: ReactNode;\n}) {\n const { document, dispatch } = props;\n const value = useMemo(\n () => [document, dispatch] as const,\n [document, dispatch],\n );\n return (\n <EditorDocumentContext.Provider value={value}>\n {props.children}\n </EditorDocumentContext.Provider>\n );\n}\n\n/** The nearest editor's document and dispatch, or undefined outside one. */\nexport function useEditorDocumentContext() {\n return useContext(EditorDocumentContext);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n DocumentTypeMismatchError,\n NoSelectedDocumentError,\n} from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useEditorDocumentContext } from \"./editor-context.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id: the editor's document, else the drive\n * app's open document, else the app's selection. */\nexport function useSelectedDocumentId(): string | undefined {\n const editor = useEditorDocumentContext();\n const drive = useDriveContext();\n const selectedNode = useSelectedNode();\n if (editor) return editor[0].header.id;\n // The drive may not list a document the route opened yet.\n if (drive?.nodeId && !drive.folder) {\n return selectedNode && !isFileNode(selectedNode) ? undefined : drive.nodeId;\n }\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const [document, dispatch] = useSelectedDocumentSafe();\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document: the editor's, else the app's selection. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const editor = useEditorDocumentContext();\n const selectedDocumentId = useSelectedDocumentId();\n const selected = useDocumentById(editor ? null : selectedDocumentId);\n return editor ?? selected;\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const editor = useEditorDocumentContext();\n const documentId = useSelectedDocumentId();\n // Called on every render; without a type, or in an editor, it reads no document.\n const result = useDocumentOfType<TDocument, TAction>(\n documentType && !editor ? documentId : null,\n documentType,\n );\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentType) {\n return [];\n }\n if (editor) {\n const [document, dispatch] = editor;\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n document.header.id,\n documentType,\n document.header.documentType,\n );\n }\n return [document as TDocument, dispatch];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return result;\n}\n","/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n","import { pascalCase } from \"change-case\";\nimport type { DocumentModelModule } from \"document-model\";\nimport {\n Kind,\n parse,\n type DefinitionNode,\n type InterfaceTypeDefinitionNode,\n type ObjectTypeDefinitionNode,\n type TypeNode,\n type UnionTypeDefinitionNode,\n} from \"graphql\";\nimport lzString from \"lz-string\";\nimport { GQL_CHANNEL_SUFFIX } from \"./gql-channel.js\";\nimport { GetDocumentWithOperationsDocument } from \"../graphql/gen/schema.js\";\n\nexport async function getDriveIdBySlug(driveUrl: string, slug: string) {\n if (!driveUrl) {\n return;\n }\n\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"drives\"); // add /drives\n const drivesUrl = urlParts.join(\"/\");\n const result = await fetch(drivesUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n query: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n variables: {\n slug,\n },\n }),\n });\n\n const data = (await result.json()) as {\n data: { driveIdBySlug: string };\n };\n\n return data.data.driveIdBySlug;\n}\n\nexport function getSlugFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n return urlParts.pop();\n}\n\nexport function getSwitchboardGatewayUrlFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"graphql\"); // add /graphql\n return urlParts.join(\"/\");\n}\n\nexport function getDocumentGraphqlQuery() {\n const loc = GetDocumentWithOperationsDocument.loc;\n if (!loc) {\n throw new Error(\n \"GetDocumentWithOperationsDocument is misconfigured, loc is missing.\",\n );\n }\n return loc.source.body;\n}\n\n/**\n * The base URL of the switchboard that serves a drive's GraphQL channel.\n *\n * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the\n * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does\n * not end with the suffix is unexpected — fall back to its origin.\n */\nexport function getSwitchboardBaseFromChannelUrl(channelUrl: string): string {\n if (channelUrl.endsWith(GQL_CHANNEL_SUFFIX)) {\n return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);\n }\n return new URL(channelUrl).origin;\n}\n\n/**\n * The GraphQL name the switchboard exposes a document model under. Mirrors\n * `getDocumentModelSchemaName` on the server (`model-schema-templates.ts`): the root\n * query field and the state type names are all derived from the model's\n * `global.name`.\n */\nfunction getDocumentModelSchemaName(model: DocumentModelModule): string {\n return pascalCase(model.documentModel.global.name.replaceAll(\"/\", \" \"));\n}\n\ntype StateType =\n | ObjectTypeDefinitionNode\n | InterfaceTypeDefinitionNode\n | UnionTypeDefinitionNode;\n\nfunction buildStateTypeMap(definitions: ReadonlyArray<DefinitionNode>) {\n const typeMap = new Map<string, StateType>();\n for (const def of definitions) {\n if (\n def.kind === Kind.OBJECT_TYPE_DEFINITION ||\n def.kind === Kind.INTERFACE_TYPE_DEFINITION ||\n def.kind === Kind.UNION_TYPE_DEFINITION\n ) {\n typeMap.set(def.name.value, def);\n }\n }\n return typeMap;\n}\n\n/**\n * Recursively expands the fields of a state object type into a GraphQL\n * selection. Objects expand their sub-selection (lists expand their item\n * type); enums, scalars, and built-ins are leaves.\n */\nfunction expandStateFields(\n typeDef: StateType,\n typeMap: Map<string, StateType>,\n): string {\n if (typeDef.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n throw new Error(\n `Abstract state type requires the generic document query: ${typeDef.name.value}`,\n );\n }\n return (typeDef.fields ?? [])\n .map((field) => {\n const fieldName = field.name.value;\n let typeNode: TypeNode = field.type;\n if (typeNode.kind === Kind.NON_NULL_TYPE) {\n typeNode = typeNode.type;\n }\n\n if (typeNode.kind === Kind.LIST_TYPE) {\n let itemType: TypeNode = typeNode.type;\n if (itemType.kind === Kind.NON_NULL_TYPE) {\n itemType = itemType.type;\n }\n if (itemType.kind === Kind.LIST_TYPE) {\n throw new Error(\n `Nested lists are not supported in state selections: ${fieldName}`,\n );\n }\n if (itemType.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const itemTypeDef = typeMap.get(itemType.name.value);\n if (!itemTypeDef) {\n // Scalar, enum, or built-in item — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;\n }\n\n if (typeNode.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const typeDef = typeMap.get(typeNode.name.value);\n if (!typeDef) {\n // Scalar, enum, or a type from another schema — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;\n })\n .join(\" \");\n}\n\n/**\n * Finds the root state object type in a state SDL. Root state types follow\n * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last\n * by convention — the same resolution order the server uses\n * (`extractRootTypeName` in `create-schema.ts`).\n */\nfunction findRootStateType(\n definitions: ReadonlyArray<DefinitionNode>,\n candidates: string[],\n): ObjectTypeDefinitionNode {\n let lastObjectType: ObjectTypeDefinitionNode | null = null;\n for (const def of definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n continue;\n }\n if (candidates.includes(def.name.value)) {\n return def;\n }\n lastObjectType = def;\n }\n if (!lastObjectType) {\n throw new Error(\"No root state type found in the document model schema\");\n }\n return lastObjectType;\n}\n\n/**\n * Derives the subselection for the document's `global` state scope from the\n * model's state SDL (e.g. `name total`), expanding object fields\n * recursively. Throws when the schema is missing, unparseable, or has no\n * root object type — the caller falls back to the generic document query.\n */\nexport function getDocumentStateSelection(model: DocumentModelModule): string {\n const spec = model.documentModel.global.specifications.at(-1);\n const schema = spec?.state.global.schema;\n if (!schema || !schema.trim()) {\n throw new Error(\"Document model has no global state schema\");\n }\n const ast = parse(schema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const documentName = getDocumentModelSchemaName(model);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}State`,\n `${documentName}GlobalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\nfunction getLocalStateSelection(\n localSchema: string,\n documentName: string,\n): string {\n const ast = parse(localSchema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}LocalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\n/**\n * Builds a query scoped to a document type's own subgraph root field,\n * selecting the document and its full typed state. The shape mirrors what\n * the switchboard generates per model (`generateNewApiSchema` in\n * `model-schema-templates.ts`): `<Name> { document(idOrSlug:) { document { ...\n * state { auth document global local } } } childIds }`.\n */\nfunction buildModelScopedQuery(model: DocumentModelModule): string {\n const globalState = model.documentModel.global;\n const documentName = getDocumentModelSchemaName(model);\n const globalSelection = getDocumentStateSelection(model);\n\n const spec = globalState.specifications.at(-1);\n const localSchema = spec?.state.local.schema ?? \"\";\n const hasLocalStateType = localSchema.includes(\n `type ${documentName}LocalState`,\n );\n const localSelection = hasLocalStateType\n ? getLocalStateSelection(localSchema, documentName)\n : null;\n\n return [\n \"query GetDocument($idOrSlug: String!) {\",\n ` ${documentName} {`,\n \" document(idOrSlug: $idOrSlug) {\",\n \" document {\",\n \" id\",\n \" name\",\n \" documentType\",\n \" state {\",\n \" auth\",\n \" document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }\",\n ` global { ${globalSelection} }`,\n ` ${localSelection ? `local { ${localSelection} }` : \"local\"}`,\n \" }\",\n \" }\",\n \" childIds\",\n \" }\",\n \" }\",\n \"}\",\n ].join(\"\\n\");\n}\n\nexport function buildDocumentSubgraphQuery(\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n let query: string;\n // Only trust a model that actually matches the document's type; a model\n // with a different root field would produce a query the supergraph cannot\n // resolve.\n if (model && model.documentModel.global.id === documentType) {\n try {\n query = buildModelScopedQuery(model);\n } catch (error) {\n console.warn(\n \"Could not derive a document-scoped query from the document model, \" +\n \"falling back to the generic document query:\",\n error,\n );\n query = getDocumentGraphqlQuery();\n }\n } else {\n query = getDocumentGraphqlQuery();\n }\n const variables = { idOrSlug: identifier };\n const headers = authToken\n ? {\n Authorization: `Bearer ${authToken}`,\n }\n : undefined;\n\n const payload: Record<string, string> = {\n document: query.trim(),\n variables: JSON.stringify(variables, null, 2),\n };\n if (headers) {\n payload.headers = JSON.stringify(headers);\n }\n return lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\n\nexport function buildDocumentSubgraphUrl(\n channelUrl: string,\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n const encodedQuery = buildDocumentSubgraphQuery(\n documentType,\n identifier,\n model,\n authToken,\n );\n const base = getSwitchboardBaseFromChannelUrl(channelUrl);\n return `${base}/explorer?explorerURLState=${encodedQuery}`;\n}\n","// The switchboards an app reaches, and the one a call should go to. Hosts\n// build the directory once at boot (createSwitchboardDirectory) and set it on\n// their store; callers ask resolveSwitchboard, which never guesses a URL.\nimport { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { ORIGIN_PLACEHOLDER } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport type {\n SwitchboardDirectory,\n SwitchboardEntry,\n SwitchboardWorkflows,\n} from \"../types/switchboards.js\";\nimport { getSwitchboardBaseFromChannelUrl } from \"./switchboard.js\";\n\n/** What a router says about its backends; structural, so hosts pass their own. */\nexport interface SwitchboardRouter {\n readonly backends: readonly {\n readonly name: string;\n readonly facts: {\n readonly known: boolean;\n readonly reactor: { readonly workflows: boolean };\n };\n }[];\n /** The name of the backend that serves `identifier`. */\n locate(identifier: string, signal?: AbortSignal): Promise<string>;\n}\n\nexport interface SwitchboardDirectoryOptions {\n /**\n * The host's remote backends, as the served config lists them\n * (`instance.remoteBackends`): a name and one of the switchboard's drive\n * addresses, `<base>/d/<slug>`.\n */\n remoteBackends?: readonly { readonly name: string; readonly url: string }[];\n /** The router over those backends, for their facts and for `locate`. */\n router?: SwitchboardRouter;\n /** The tab's sync manager, read on each call: every gql remote's switchboard. */\n syncManager?: () => Pick<ISyncManager, \"list\"> | undefined;\n /** What `${origin}` stands for; defaults to the page's origin. */\n origin?: string;\n}\n\n/** `${origin}` resolved against the page; a base stays as it is otherwise. */\nfunction resolveOrigin(base: string, origin: string | undefined): string {\n if (!base.startsWith(ORIGIN_PLACEHOLDER)) return base;\n const page =\n origin ?? (typeof location === \"undefined\" ? undefined : location.origin);\n return page ? page + base.slice(ORIGIN_PLACEHOLDER.length) : base;\n}\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/** A synced drive's switchboard, named by its host and path. */\nfunction syncName(base: string): string {\n return base.replace(/^[a-z]+:\\/\\//i, \"\");\n}\n\n/**\n * Builds the directory from the host's remote backends and the tab's synced\n * drives. A backend's facts are read on each `list`, so a refresh shows.\n */\nexport function createSwitchboardDirectory(\n options: SwitchboardDirectoryOptions,\n): SwitchboardDirectory {\n const backends = (options.remoteBackends ?? []).flatMap(({ name, url }) => {\n const drive = switchboardOfDrive(url);\n if (!drive) return [];\n const base = trimSlash(resolveOrigin(drive.base, options.origin));\n return [{ name, base }];\n });\n\n const workflowsOf = (name: string): SwitchboardWorkflows => {\n const backend = options.router?.backends.find((b) => b.name === name);\n if (!backend?.facts.known) return \"unknown\";\n return backend.facts.reactor.workflows;\n };\n\n const remotes = () => {\n try {\n return options.syncManager?.()?.list() ?? [];\n } catch {\n return [];\n }\n };\n\n const syncBase = (remote: ReturnType<typeof remotes>[number]) => {\n const { channelConfig } = remote.meta;\n const url =\n channelConfig.type === \"gql\" ? channelConfig.parameters.url : \"\";\n if (typeof url !== \"string\" || !url) return undefined;\n try {\n return trimSlash(getSwitchboardBaseFromChannelUrl(url));\n } catch {\n return undefined;\n }\n };\n\n const list = (): SwitchboardEntry[] => {\n const entries: SwitchboardEntry[] = backends.map(({ name, base }) => ({\n name,\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"backend\",\n workflows: workflowsOf(name),\n }));\n const seen = new Set(entries.map((entry) => entry.base));\n for (const remote of remotes()) {\n const base = syncBase(remote);\n if (!base || seen.has(base)) continue;\n seen.add(base);\n entries.push({\n name: syncName(base),\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"sync\",\n workflows: \"unknown\",\n });\n }\n return entries;\n };\n\n const locate = async (\n documentId: string,\n signal?: AbortSignal,\n ): Promise<SwitchboardEntry | undefined> => {\n const entries = list();\n const collectionId = DriveCollectionId.forDrive(documentId);\n const remote = remotes().find((r) =>\n r.meta.collectionId.equals(collectionId),\n );\n const synced = remote && syncBase(remote);\n if (synced) return entries.find((entry) => entry.base === synced);\n if (!options.router || backends.length === 0) return undefined;\n let name: string;\n try {\n name = await options.router.locate(documentId, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n return undefined;\n }\n return entries.find(\n (entry) => entry.via === \"backend\" && entry.name === name,\n );\n };\n\n return { list, locate };\n}\n\nexport type SwitchboardLookupErrorCode =\n | \"NO_DIRECTORY\"\n | \"NO_SWITCHBOARD\"\n | \"UNKNOWN_SWITCHBOARD\"\n | \"AMBIGUOUS_SWITCHBOARD\"\n | \"NO_WORKFLOW_RUNTIME\";\n\n/** Why no switchboard could be picked, with the ones there are. */\nexport class SwitchboardLookupError extends Error {\n constructor(\n message: string,\n readonly code: SwitchboardLookupErrorCode,\n readonly switchboards: readonly SwitchboardEntry[] = [],\n ) {\n super(message);\n this.name = \"SwitchboardLookupError\";\n }\n}\n\nexport interface SwitchboardRequest {\n /** A name from the directory, or a URL on the switchboard (its base, GraphQL or any path under it). */\n switchboard?: string;\n /** The document or drive the call is about: its switchboard, when the directory can place it. */\n documentId?: string;\n /** What the switchboard must run. */\n need?: \"workflows\";\n signal?: AbortSignal;\n}\n\nfunction describe(entry: SwitchboardEntry): string {\n const workflows =\n entry.workflows === \"unknown\"\n ? \"workflows unknown\"\n : entry.workflows\n ? \"runs workflows\"\n : \"no workflows\";\n return `${entry.name} (${entry.base}, ${workflows})`;\n}\n\nfunction describeAll(entries: readonly SwitchboardEntry[]): string {\n return entries.map(describe).join(\"; \");\n}\n\n/** The entry `switchboard` names: by name, then by the longest base it lies under. */\nfunction byNameOrUrl(\n entries: readonly SwitchboardEntry[],\n switchboard: string,\n): SwitchboardEntry | undefined {\n const named = entries.find((entry) => entry.name === switchboard);\n if (named) return named;\n const url = trimSlash(switchboard);\n return entries\n .filter((entry) => url === entry.base || url.startsWith(`${entry.base}/`))\n .sort((a, b) => b.base.length - a.base.length)[0];\n}\n\nfunction checkNeed(\n entry: SwitchboardEntry,\n need: SwitchboardRequest[\"need\"],\n entries: readonly SwitchboardEntry[],\n): SwitchboardEntry {\n if (need === \"workflows\" && entry.workflows === false) {\n throw new SwitchboardLookupError(\n `Switchboard ${entry.name} (${entry.base}) runs no workflow runtime.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n return entry;\n}\n\n/**\n * The switchboard a call goes to: the one named, else the one serving the\n * document, else the only one there is (or the only one running what `need`\n * asks for). Throws a {@link SwitchboardLookupError} that lists the\n * switchboards whenever it can't pick one; there is no default URL.\n */\nexport async function resolveSwitchboard(\n directory: SwitchboardDirectory | undefined,\n request: SwitchboardRequest = {},\n): Promise<SwitchboardEntry> {\n if (!directory) {\n throw new SwitchboardLookupError(\n \"This app provides no switchboard directory, so no switchboard can be picked.\",\n \"NO_DIRECTORY\",\n );\n }\n const entries = directory.list();\n const { need } = request;\n\n if (request.switchboard) {\n const named = byNameOrUrl(entries, request.switchboard);\n if (!named) {\n throw new SwitchboardLookupError(\n entries.length > 0\n ? `No switchboard \"${request.switchboard}\". This app reaches: ${describeAll(entries)}.`\n : `No switchboard \"${request.switchboard}\": this app reaches no switchboard.`,\n \"UNKNOWN_SWITCHBOARD\",\n entries,\n );\n }\n return checkNeed(named, need, entries);\n }\n\n // With one switchboard, placing the document could only name that one.\n if (request.documentId && entries.length > 1) {\n const located = await directory.locate(request.documentId, request.signal);\n if (located) return checkNeed(located, need, entries);\n }\n\n if (entries.length === 0) {\n throw new SwitchboardLookupError(\n \"This app reaches no switchboard; it is connected to none.\",\n \"NO_SWITCHBOARD\",\n );\n }\n if (entries.length === 1) return checkNeed(entries[0], need, entries);\n\n if (need === \"workflows\") {\n const running = entries.filter((entry) => entry.workflows === true);\n if (running.length === 1) return running[0];\n if (running.length === 0) {\n const maybe = entries.filter((entry) => entry.workflows === \"unknown\");\n if (maybe.length === 1) return maybe[0];\n if (maybe.length === 0) {\n throw new SwitchboardLookupError(\n `None of the switchboards runs a workflow runtime: ${describeAll(entries)}.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n }\n }\n throw new SwitchboardLookupError(\n `This app reaches several switchboards (${describeAll(entries)}); name one with \"switchboard\".`,\n \"AMBIGUOUS_SWITCHBOARD\",\n entries,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAgB,YAAY,IAAiD;CAC3E,OAAO,aAAa,mBAAmB,GAAG,EAAE;AAC9C;;;;ACSA,SAAgB,kB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UAAU,QAAQ,IAAI,MAAM,OAAO;CAEpE,IAAI,SAAS,aAAa;EACxB,MAAM,UAAU,QAAQ,QAAQ,UAAU,MAAM,cAAc,IAAI;EAClE,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;EACzC,IAAI,QAAQ,WAAW,GAAG;GACxB,MAAM,QAAQ,QAAQ,QAAQ,UAAU,MAAM,cAAc,SAAS;GACrE,IAAI,MAAM,WAAW,GAAG,OAAO,MAAM;GACrC,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,uBACR,qDAAqD,YAAY,OAAO,EAAE,IAC1E,uBACA,OACF;EAEJ;CACF;CACA,MAAM,IAAI,uBACR,0CAA0C,YAAY,OAAO,EAAE,kCAC/D,yBACA,OACF;AACF"}
|
|
1
|
+
{"version":3,"file":"switchboard-directory-7KPHB5Tz.js","names":[],"sources":["../src/hooks/node-by-id.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/editor-context.tsx","../src/hooks/selected-document.ts","../src/utils/gql-channel.ts","../src/utils/switchboard.ts","../src/utils/switchboard-directory.ts"],"sourcesContent":["import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useDriveNode } from \"./drive-nodes.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\n\n/** Returns a node in the selected drive by id. */\nexport function useNodeById(id: string | null | undefined): Node | undefined {\n return useDriveNode(useSelectedDriveId(), id);\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodeById } from \"./node-by-id.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n getNodeTarget,\n useNodeTarget,\n preloadNode,\n setSelectedNode,\n useOpenNode,\n usePreloadNode,\n useSetSelectedNode,\n} from \"./set-selected-node.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n return useNodeById(useSelectedNodeId());\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type {\n DocumentDispatch,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext, useMemo } from \"react\";\n\n/** The document an editor is rendered with, and a dispatch bound to it. */\nexport type EditorDocumentContextValue = readonly [\n PHDocument,\n DocumentDispatch,\n];\n\nconst EditorDocumentContext = createContext<\n EditorDocumentContextValue | undefined\n>(undefined);\n\n/** Hosts render an editor inside this, with the same `document` and `dispatch`\n * as its props; `useSelected*Document` hooks below read them. */\nexport function EditorDocumentProvider(props: {\n document: PHDocument;\n dispatch: DocumentDispatch;\n children: ReactNode;\n}) {\n const { document, dispatch } = props;\n const value = useMemo(\n () => [document, dispatch] as const,\n [document, dispatch],\n );\n return (\n <EditorDocumentContext.Provider value={value}>\n {props.children}\n </EditorDocumentContext.Provider>\n );\n}\n\n/** The nearest editor's document and dispatch, or undefined outside one. */\nexport function useEditorDocumentContext() {\n return useContext(EditorDocumentContext);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n DocumentTypeMismatchError,\n NoSelectedDocumentError,\n} from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useEditorDocumentContext } from \"./editor-context.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id: the editor's document, else the drive\n * app's open document, else the app's selection. */\nexport function useSelectedDocumentId(): string | undefined {\n const editor = useEditorDocumentContext();\n const drive = useDriveContext();\n const selectedNode = useSelectedNode();\n if (editor) return editor[0].header.id;\n // The drive may not list a document the route opened yet.\n if (drive?.nodeId && !drive.folder) {\n return selectedNode && !isFileNode(selectedNode) ? undefined : drive.nodeId;\n }\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const [document, dispatch] = useSelectedDocumentSafe();\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document: the editor's, else the app's selection. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const editor = useEditorDocumentContext();\n const selectedDocumentId = useSelectedDocumentId();\n const selected = useDocumentById(editor ? null : selectedDocumentId);\n return editor ?? selected;\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const editor = useEditorDocumentContext();\n const documentId = useSelectedDocumentId();\n // Called on every render; without a type, or in an editor, it reads no document.\n const result = useDocumentOfType<TDocument, TAction>(\n documentType && !editor ? documentId : null,\n documentType,\n );\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentType) {\n return [];\n }\n if (editor) {\n const [document, dispatch] = editor;\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n document.header.id,\n documentType,\n document.header.documentType,\n );\n }\n return [document as TDocument, dispatch];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return result;\n}\n","/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n","import { pascalCase } from \"change-case\";\nimport type { DocumentModelModule } from \"document-model\";\nimport {\n Kind,\n parse,\n type DefinitionNode,\n type InterfaceTypeDefinitionNode,\n type ObjectTypeDefinitionNode,\n type TypeNode,\n type UnionTypeDefinitionNode,\n} from \"graphql\";\nimport lzString from \"lz-string\";\nimport { GQL_CHANNEL_SUFFIX } from \"./gql-channel.js\";\nimport { GetDocumentWithOperationsDocument } from \"../graphql/gen/schema.js\";\n\nexport async function getDriveIdBySlug(driveUrl: string, slug: string) {\n if (!driveUrl) {\n return;\n }\n\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"drives\"); // add /drives\n const drivesUrl = urlParts.join(\"/\");\n const result = await fetch(drivesUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n query: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n variables: {\n slug,\n },\n }),\n });\n\n const data = (await result.json()) as {\n data: { driveIdBySlug: string };\n };\n\n return data.data.driveIdBySlug;\n}\n\nexport function getSlugFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n return urlParts.pop();\n}\n\nexport function getSwitchboardGatewayUrlFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"graphql\"); // add /graphql\n return urlParts.join(\"/\");\n}\n\nexport function getDocumentGraphqlQuery() {\n const loc = GetDocumentWithOperationsDocument.loc;\n if (!loc) {\n throw new Error(\n \"GetDocumentWithOperationsDocument is misconfigured, loc is missing.\",\n );\n }\n return loc.source.body;\n}\n\n/**\n * The base URL of the switchboard that serves a drive's GraphQL channel.\n *\n * The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the\n * suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does\n * not end with the suffix is unexpected — fall back to its origin.\n */\nexport function getSwitchboardBaseFromChannelUrl(channelUrl: string): string {\n if (channelUrl.endsWith(GQL_CHANNEL_SUFFIX)) {\n return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);\n }\n return new URL(channelUrl).origin;\n}\n\n/**\n * The GraphQL name the switchboard exposes a document model under. Mirrors\n * `getDocumentModelSchemaName` on the server (`model-schema-templates.ts`): the root\n * query field and the state type names are all derived from the model's\n * `global.name`.\n */\nfunction getDocumentModelSchemaName(model: DocumentModelModule): string {\n return pascalCase(model.documentModel.global.name.replaceAll(\"/\", \" \"));\n}\n\ntype StateType =\n | ObjectTypeDefinitionNode\n | InterfaceTypeDefinitionNode\n | UnionTypeDefinitionNode;\n\nfunction buildStateTypeMap(definitions: ReadonlyArray<DefinitionNode>) {\n const typeMap = new Map<string, StateType>();\n for (const def of definitions) {\n if (\n def.kind === Kind.OBJECT_TYPE_DEFINITION ||\n def.kind === Kind.INTERFACE_TYPE_DEFINITION ||\n def.kind === Kind.UNION_TYPE_DEFINITION\n ) {\n typeMap.set(def.name.value, def);\n }\n }\n return typeMap;\n}\n\n/**\n * Recursively expands the fields of a state object type into a GraphQL\n * selection. Objects expand their sub-selection (lists expand their item\n * type); enums, scalars, and built-ins are leaves.\n */\nfunction expandStateFields(\n typeDef: StateType,\n typeMap: Map<string, StateType>,\n): string {\n if (typeDef.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n throw new Error(\n `Abstract state type requires the generic document query: ${typeDef.name.value}`,\n );\n }\n return (typeDef.fields ?? [])\n .map((field) => {\n const fieldName = field.name.value;\n let typeNode: TypeNode = field.type;\n if (typeNode.kind === Kind.NON_NULL_TYPE) {\n typeNode = typeNode.type;\n }\n\n if (typeNode.kind === Kind.LIST_TYPE) {\n let itemType: TypeNode = typeNode.type;\n if (itemType.kind === Kind.NON_NULL_TYPE) {\n itemType = itemType.type;\n }\n if (itemType.kind === Kind.LIST_TYPE) {\n throw new Error(\n `Nested lists are not supported in state selections: ${fieldName}`,\n );\n }\n if (itemType.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const itemTypeDef = typeMap.get(itemType.name.value);\n if (!itemTypeDef) {\n // Scalar, enum, or built-in item — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;\n }\n\n if (typeNode.kind !== Kind.NAMED_TYPE) {\n return fieldName;\n }\n const typeDef = typeMap.get(typeNode.name.value);\n if (!typeDef) {\n // Scalar, enum, or a type from another schema — a leaf.\n return fieldName;\n }\n return `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;\n })\n .join(\" \");\n}\n\n/**\n * Finds the root state object type in a state SDL. Root state types follow\n * the `<Name>State` / `<Name>GlobalState` conventions, and are defined last\n * by convention — the same resolution order the server uses\n * (`extractRootTypeName` in `create-schema.ts`).\n */\nfunction findRootStateType(\n definitions: ReadonlyArray<DefinitionNode>,\n candidates: string[],\n): ObjectTypeDefinitionNode {\n let lastObjectType: ObjectTypeDefinitionNode | null = null;\n for (const def of definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n continue;\n }\n if (candidates.includes(def.name.value)) {\n return def;\n }\n lastObjectType = def;\n }\n if (!lastObjectType) {\n throw new Error(\"No root state type found in the document model schema\");\n }\n return lastObjectType;\n}\n\n/**\n * Derives the subselection for the document's `global` state scope from the\n * model's state SDL (e.g. `name total`), expanding object fields\n * recursively. Throws when the schema is missing, unparseable, or has no\n * root object type — the caller falls back to the generic document query.\n */\nexport function getDocumentStateSelection(model: DocumentModelModule): string {\n const spec = model.documentModel.global.specifications.at(-1);\n const schema = spec?.state.global.schema;\n if (!schema || !schema.trim()) {\n throw new Error(\"Document model has no global state schema\");\n }\n const ast = parse(schema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const documentName = getDocumentModelSchemaName(model);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}State`,\n `${documentName}GlobalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\nfunction getLocalStateSelection(\n localSchema: string,\n documentName: string,\n): string {\n const ast = parse(localSchema);\n const typeMap = buildStateTypeMap(ast.definitions);\n const rootType = findRootStateType(ast.definitions, [\n `${documentName}LocalState`,\n ]);\n return expandStateFields(rootType, typeMap);\n}\n\n/**\n * Builds a query scoped to a document type's own subgraph root field,\n * selecting the document and its full typed state. The shape mirrors what\n * the switchboard generates per model (`generateNewApiSchema` in\n * `model-schema-templates.ts`): `<Name> { document(idOrSlug:) { document { ...\n * state { auth document global local } } } childIds }`.\n */\nfunction buildModelScopedQuery(model: DocumentModelModule): string {\n const globalState = model.documentModel.global;\n const documentName = getDocumentModelSchemaName(model);\n const globalSelection = getDocumentStateSelection(model);\n\n const spec = globalState.specifications.at(-1);\n const localSchema = spec?.state.local.schema ?? \"\";\n const hasLocalStateType = localSchema.includes(\n `type ${documentName}LocalState`,\n );\n const localSelection = hasLocalStateType\n ? getLocalStateSelection(localSchema, documentName)\n : null;\n\n return [\n \"query GetDocument($idOrSlug: String!) {\",\n ` ${documentName} {`,\n \" document(idOrSlug: $idOrSlug) {\",\n \" document {\",\n \" id\",\n \" name\",\n \" documentType\",\n \" state {\",\n \" auth\",\n \" document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }\",\n ` global { ${globalSelection} }`,\n ` ${localSelection ? `local { ${localSelection} }` : \"local\"}`,\n \" }\",\n \" }\",\n \" childIds\",\n \" }\",\n \" }\",\n \"}\",\n ].join(\"\\n\");\n}\n\nexport function buildDocumentSubgraphQuery(\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n let query: string;\n // Only trust a model that actually matches the document's type; a model\n // with a different root field would produce a query the supergraph cannot\n // resolve.\n if (model && model.documentModel.global.id === documentType) {\n try {\n query = buildModelScopedQuery(model);\n } catch (error) {\n console.warn(\n \"Could not derive a document-scoped query from the document model, \" +\n \"falling back to the generic document query:\",\n error,\n );\n query = getDocumentGraphqlQuery();\n }\n } else {\n query = getDocumentGraphqlQuery();\n }\n const variables = { idOrSlug: identifier };\n const headers = authToken\n ? {\n Authorization: `Bearer ${authToken}`,\n }\n : undefined;\n\n const payload: Record<string, string> = {\n document: query.trim(),\n variables: JSON.stringify(variables, null, 2),\n };\n if (headers) {\n payload.headers = JSON.stringify(headers);\n }\n return lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\n\nexport function buildDocumentSubgraphUrl(\n channelUrl: string,\n documentType: string,\n identifier: string,\n model?: DocumentModelModule,\n authToken?: string,\n): string {\n const encodedQuery = buildDocumentSubgraphQuery(\n documentType,\n identifier,\n model,\n authToken,\n );\n const base = getSwitchboardBaseFromChannelUrl(channelUrl);\n return `${base}/explorer?explorerURLState=${encodedQuery}`;\n}\n","// The switchboards an app reaches, and the one a call should go to. Hosts\n// build the directory once at boot (createSwitchboardDirectory) and set it on\n// their store; callers ask resolveSwitchboard, which never guesses a URL.\nimport { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { ORIGIN_PLACEHOLDER } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport type {\n SwitchboardDirectory,\n SwitchboardEntry,\n SwitchboardWorkflows,\n} from \"../types/switchboards.js\";\nimport { getSwitchboardBaseFromChannelUrl } from \"./switchboard.js\";\n\n/** What a router says about its backends; structural, so hosts pass their own. */\nexport interface SwitchboardRouter {\n readonly backends: readonly {\n readonly name: string;\n readonly facts: {\n readonly known: boolean;\n readonly reactor: { readonly workflows: boolean };\n };\n }[];\n /** The name of the backend that serves `identifier`. */\n locate(identifier: string, signal?: AbortSignal): Promise<string>;\n}\n\nexport interface SwitchboardDirectoryOptions {\n /**\n * The host's remote backends, as the served config lists them\n * (`instance.remoteBackends`): a name and one of the switchboard's drive\n * addresses, `<base>/d/<slug>`.\n */\n remoteBackends?: readonly { readonly name: string; readonly url: string }[];\n /** The router over those backends, for their facts and for `locate`. */\n router?: SwitchboardRouter;\n /** The tab's sync manager, read on each call: every gql remote's switchboard. */\n syncManager?: () => Pick<ISyncManager, \"list\"> | undefined;\n /** What `${origin}` stands for; defaults to the page's origin. */\n origin?: string;\n}\n\n/** `${origin}` resolved against the page; a base stays as it is otherwise. */\nfunction resolveOrigin(base: string, origin: string | undefined): string {\n if (!base.startsWith(ORIGIN_PLACEHOLDER)) return base;\n const page =\n origin ?? (typeof location === \"undefined\" ? undefined : location.origin);\n return page ? page + base.slice(ORIGIN_PLACEHOLDER.length) : base;\n}\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/** A synced drive's switchboard, named by its host and path. */\nfunction syncName(base: string): string {\n return base.replace(/^[a-z]+:\\/\\//i, \"\");\n}\n\n/**\n * Builds the directory from the host's remote backends and the tab's synced\n * drives. A backend's facts are read on each `list`, so a refresh shows.\n */\nexport function createSwitchboardDirectory(\n options: SwitchboardDirectoryOptions,\n): SwitchboardDirectory {\n const backends = (options.remoteBackends ?? []).flatMap(({ name, url }) => {\n const drive = switchboardOfDrive(url);\n if (!drive) return [];\n const base = trimSlash(resolveOrigin(drive.base, options.origin));\n return [{ name, base }];\n });\n\n const workflowsOf = (name: string): SwitchboardWorkflows => {\n const backend = options.router?.backends.find((b) => b.name === name);\n if (!backend?.facts.known) return \"unknown\";\n return backend.facts.reactor.workflows;\n };\n\n const remotes = () => {\n try {\n return options.syncManager?.()?.list() ?? [];\n } catch {\n return [];\n }\n };\n\n const syncBase = (remote: ReturnType<typeof remotes>[number]) => {\n const { channelConfig } = remote.meta;\n const url =\n channelConfig.type === \"gql\" ? channelConfig.parameters.url : \"\";\n if (typeof url !== \"string\" || !url) return undefined;\n try {\n return trimSlash(getSwitchboardBaseFromChannelUrl(url));\n } catch {\n return undefined;\n }\n };\n\n const list = (): SwitchboardEntry[] => {\n const entries: SwitchboardEntry[] = backends.map(({ name, base }) => ({\n name,\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"backend\",\n workflows: workflowsOf(name),\n }));\n const seen = new Set(entries.map((entry) => entry.base));\n for (const remote of remotes()) {\n const base = syncBase(remote);\n if (!base || seen.has(base)) continue;\n seen.add(base);\n entries.push({\n name: syncName(base),\n base,\n graphqlUrl: `${base}/graphql`,\n via: \"sync\",\n workflows: \"unknown\",\n });\n }\n return entries;\n };\n\n const locate = async (\n documentId: string,\n signal?: AbortSignal,\n ): Promise<SwitchboardEntry | undefined> => {\n const entries = list();\n const collectionId = DriveCollectionId.forDrive(documentId);\n const remote = remotes().find((r) =>\n r.meta.collectionId.equals(collectionId),\n );\n const synced = remote && syncBase(remote);\n if (synced) return entries.find((entry) => entry.base === synced);\n if (!options.router || backends.length === 0) return undefined;\n let name: string;\n try {\n name = await options.router.locate(documentId, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n return undefined;\n }\n return entries.find(\n (entry) => entry.via === \"backend\" && entry.name === name,\n );\n };\n\n return { list, locate };\n}\n\nexport type SwitchboardLookupErrorCode =\n | \"NO_DIRECTORY\"\n | \"NO_SWITCHBOARD\"\n | \"UNKNOWN_SWITCHBOARD\"\n | \"AMBIGUOUS_SWITCHBOARD\"\n | \"NO_WORKFLOW_RUNTIME\";\n\n/** Why no switchboard could be picked, with the ones there are. */\nexport class SwitchboardLookupError extends Error {\n constructor(\n message: string,\n readonly code: SwitchboardLookupErrorCode,\n readonly switchboards: readonly SwitchboardEntry[] = [],\n ) {\n super(message);\n this.name = \"SwitchboardLookupError\";\n }\n}\n\nexport interface SwitchboardRequest {\n /** A name from the directory, or a URL on the switchboard (its base, GraphQL or any path under it). */\n switchboard?: string;\n /** The document or drive the call is about: its switchboard, when the directory can place it. */\n documentId?: string;\n /** What the switchboard must run. */\n need?: \"workflows\";\n signal?: AbortSignal;\n}\n\nfunction describe(entry: SwitchboardEntry): string {\n const workflows =\n entry.workflows === \"unknown\"\n ? \"workflows unknown\"\n : entry.workflows\n ? \"runs workflows\"\n : \"no workflows\";\n return `${entry.name} (${entry.base}, ${workflows})`;\n}\n\nfunction describeAll(entries: readonly SwitchboardEntry[]): string {\n return entries.map(describe).join(\"; \");\n}\n\n/** The entry `switchboard` names: by name, then by the longest base it lies under. */\nfunction byNameOrUrl(\n entries: readonly SwitchboardEntry[],\n switchboard: string,\n): SwitchboardEntry | undefined {\n const named = entries.find((entry) => entry.name === switchboard);\n if (named) return named;\n const url = trimSlash(switchboard);\n return entries\n .filter((entry) => url === entry.base || url.startsWith(`${entry.base}/`))\n .sort((a, b) => b.base.length - a.base.length)[0];\n}\n\nfunction checkNeed(\n entry: SwitchboardEntry,\n need: SwitchboardRequest[\"need\"],\n entries: readonly SwitchboardEntry[],\n): SwitchboardEntry {\n if (need === \"workflows\" && entry.workflows === false) {\n throw new SwitchboardLookupError(\n `Switchboard ${entry.name} (${entry.base}) runs no workflow runtime.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n return entry;\n}\n\n/**\n * The switchboard a call goes to: the one named, else the one serving the\n * document, else the only one there is (or the only one running what `need`\n * asks for). Throws a {@link SwitchboardLookupError} that lists the\n * switchboards whenever it can't pick one; there is no default URL.\n */\nexport async function resolveSwitchboard(\n directory: SwitchboardDirectory | undefined,\n request: SwitchboardRequest = {},\n): Promise<SwitchboardEntry> {\n if (!directory) {\n throw new SwitchboardLookupError(\n \"This app provides no switchboard directory, so no switchboard can be picked.\",\n \"NO_DIRECTORY\",\n );\n }\n const entries = directory.list();\n const { need } = request;\n\n if (request.switchboard) {\n const named = byNameOrUrl(entries, request.switchboard);\n if (!named) {\n throw new SwitchboardLookupError(\n entries.length > 0\n ? `No switchboard \"${request.switchboard}\". This app reaches: ${describeAll(entries)}.`\n : `No switchboard \"${request.switchboard}\": this app reaches no switchboard.`,\n \"UNKNOWN_SWITCHBOARD\",\n entries,\n );\n }\n return checkNeed(named, need, entries);\n }\n\n // With one switchboard, placing the document could only name that one.\n if (request.documentId && entries.length > 1) {\n const located = await directory.locate(request.documentId, request.signal);\n if (located) return checkNeed(located, need, entries);\n }\n\n if (entries.length === 0) {\n throw new SwitchboardLookupError(\n \"This app reaches no switchboard; it is connected to none.\",\n \"NO_SWITCHBOARD\",\n );\n }\n if (entries.length === 1) return checkNeed(entries[0], need, entries);\n\n if (need === \"workflows\") {\n const running = entries.filter((entry) => entry.workflows === true);\n if (running.length === 1) return running[0];\n if (running.length === 0) {\n const maybe = entries.filter((entry) => entry.workflows === \"unknown\");\n if (maybe.length === 1) return maybe[0];\n if (maybe.length === 0) {\n throw new SwitchboardLookupError(\n `None of the switchboards runs a workflow runtime: ${describeAll(entries)}.`,\n \"NO_WORKFLOW_RUNTIME\",\n entries,\n );\n }\n }\n }\n throw new SwitchboardLookupError(\n `This app reaches several switchboards (${describeAll(entries)}); name one with \"switchboard\".`,\n \"AMBIGUOUS_SWITCHBOARD\",\n entries,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAgB,YAAY,IAAiD;CAC3E,OAAO,aAAa,mBAAmB,GAAG,EAAE;AAC9C;;;;ACSA,SAAgB,kBAAoC;CAClD,OAAO,YAAY,kBAAkB,CAAC;AACxC;;;;ACVA,SAAgB,kBAId,YACA,cACA;CACA,MAAM,CAAC,UA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AAM,cAAc,IAAI;EAClE,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;EACzC,IAAI,QAAQ,WAAW,GAAG;GACxB,MAAM,QAAQ,QAAQ,QAAQ,UAAU,MAAM,cAAc,SAAS;GACrE,IAAI,MAAM,WAAW,GAAG,OAAO,MAAM;GACrC,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,uBACR,qDAAqD,YAAY,OAAO,EAAE,IAC1E,uBACA,OACF;EAEJ;CACF;CACA,MAAM,IAAI,uBACR,0CAA0C,YAAY,OAAO,EAAE,kCAC/D,yBACA,OACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/reactor-browser",
|
|
3
|
-
"version": "6.4.0-next.
|
|
3
|
+
"version": "6.4.0-next.4",
|
|
4
4
|
"license": "AGPL-3.0-only",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -64,18 +64,18 @@
|
|
|
64
64
|
"sideEffects": false,
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@ai-sdk/openai-compatible": "3.0.65",
|
|
67
|
-
"@powerhousedao/analytics-engine-browser": "6.4.0-next.
|
|
68
|
-
"@powerhousedao/analytics-engine-core": "6.4.0-next.
|
|
69
|
-
"@powerhousedao/reactor": "6.4.0-next.
|
|
70
|
-
"@powerhousedao/reactor-attachments": "6.4.0-next.
|
|
71
|
-
"@powerhousedao/reactor-drive": "6.4.0-next.
|
|
72
|
-
"@powerhousedao/reactor-router": "6.4.0-next.
|
|
73
|
-
"@powerhousedao/shared": "6.4.0-next.
|
|
74
|
-
"@renown/sdk": "6.4.0-next.
|
|
67
|
+
"@powerhousedao/analytics-engine-browser": "6.4.0-next.4",
|
|
68
|
+
"@powerhousedao/analytics-engine-core": "6.4.0-next.4",
|
|
69
|
+
"@powerhousedao/reactor": "6.4.0-next.4",
|
|
70
|
+
"@powerhousedao/reactor-attachments": "6.4.0-next.4",
|
|
71
|
+
"@powerhousedao/reactor-drive": "6.4.0-next.4",
|
|
72
|
+
"@powerhousedao/reactor-router": "6.4.0-next.4",
|
|
73
|
+
"@powerhousedao/shared": "6.4.0-next.4",
|
|
74
|
+
"@renown/sdk": "6.4.0-next.4",
|
|
75
75
|
"@tanstack/react-query": "^5.49.2",
|
|
76
76
|
"ai": "7.0.130",
|
|
77
77
|
"change-case": "5.4.4",
|
|
78
|
-
"document-model": "6.4.0-next.
|
|
78
|
+
"document-model": "6.4.0-next.4",
|
|
79
79
|
"es-module-lexer": "^2.0.0",
|
|
80
80
|
"graphql-request": "7.4.0",
|
|
81
81
|
"graphql-ws": "6.0.7",
|
|
@@ -111,7 +111,7 @@
|
|
|
111
111
|
"fflate": "^0.8.2",
|
|
112
112
|
"graphql": "^16",
|
|
113
113
|
"graphql-tag": "^2",
|
|
114
|
-
"playwright": "1.
|
|
114
|
+
"playwright": "1.64.1",
|
|
115
115
|
"react": "19.2.6",
|
|
116
116
|
"react-dom": "19.2.6",
|
|
117
117
|
"tsdown": "0.23.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"attachment-service-0E5S0hZ6.d.ts","names":[],"sources":["../src/actions/dispatch.ts","../src/document-refetcher.ts","../src/document-cache.ts","../src/remote-controller/types.ts","../src/graphql-client/adapter.ts","../src/graphql-client/drive-nodes.ts","../src/graphql-client/errors.ts","../src/graphql-client/transport.ts","../src/graphql-client/subgraph.ts","../src/graphql-client/graphql-reactor-client.ts","../src/graphql-client/graphql-reactor-provider.tsx","../src/graphql-client/operations.ts","../src/graphql-client/signing.ts","../src/graphql-client/static-package-manager.ts","../src/graphql-client/subscriptions.ts","../src/graphql-client/switchboard-backend.ts","../src/hooks/document-cache.ts","../src/hooks/reactor.ts","../src/hooks/dispatch.ts","../src/hooks/document-model-modules.ts","../src/hooks/document-operations.ts","../src/hooks/attachment-service.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;KAoHY,2BACV,QAAQ,cACR,SAAS;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uB;cAGvB,mBAAkB,OAAO;cAOzB,iBAAgB;;;;;;;;;;;;KC/FjB,WAAW,YACrB,iBAAiB,YAAY,qBAC7B,YAAY,QAAQ,kBACpB,YAAY;KAGF,kBAAkB,WAAW,qBACvC,uBACA,WAAW;;iBAIG,eAAe,YAAY,cAAY,UAAU,UAC/D,mBAAmB,wBAClB,WAAW;;iBAwCE,YAAY,YAAY,cAAY,UAAU,UAC5D,UAAU,wBACT,kBAAkB,WAAW;;;iBCtEhB,2BAA2B;;;;;;;;;iBAuB3B,2BACd,+BACA,mBACC;;;KCvBS;;;;;;EAMV;;EAEA;;;KAIU;;EAEV,qBAAqB;;EAErB;;EAEA,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;iBAyBc,sBACd,uCACA,eACA,UAAS,+BACR;;;;cC/CU,sBAAsB,iBAAiB;;cAIvC,sBAAsB,iBAAiB;;cAIvC,kCAAkC"}
|
package/dist/auth-DRbzRdeC.d.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { v as SdkFunctionWrapper } from "./schema-C6ECceaN.js";
|
|
2
|
-
//#region src/graphql-client/auth.d.ts
|
|
3
|
-
/**
|
|
4
|
-
* Resolves the bearer token to send with a request.
|
|
5
|
-
*
|
|
6
|
-
* Returning `undefined` (or an empty string) means "send this request
|
|
7
|
-
* anonymously": open Switchboards must keep serving reads to logged-out users.
|
|
8
|
-
*/
|
|
9
|
-
type BearerTokenProvider = () => Promise<string | undefined>;
|
|
10
|
-
/**
|
|
11
|
-
* The default token provider: the token of the currently logged-in Renown user.
|
|
12
|
-
*
|
|
13
|
-
* It is deliberately resolved from `window.ph` on every call rather than
|
|
14
|
-
* captured at construction time, so a client built before login starts sending
|
|
15
|
-
* the token as soon as there is one.
|
|
16
|
-
*
|
|
17
|
-
* The token is requested WITHOUT an `aud` claim - the Switchboard verifier
|
|
18
|
-
* rejects tokens that carry an audience.
|
|
19
|
-
*/
|
|
20
|
-
declare function ambientRenownTokenProvider(): Promise<string | undefined>;
|
|
21
|
-
/**
|
|
22
|
-
* Builds the SDK middleware that authenticates every request.
|
|
23
|
-
*
|
|
24
|
-
* The token is resolved per request and never cached, so a login, a logout or
|
|
25
|
-
* an expiry between two calls is picked up by the next one. When no token is
|
|
26
|
-
* available the request goes out unauthenticated.
|
|
27
|
-
*/
|
|
28
|
-
declare function makeAuthMiddleware(tokenProvider: BearerTokenProvider): SdkFunctionWrapper;
|
|
29
|
-
//#endregion
|
|
30
|
-
export { ambientRenownTokenProvider as n, makeAuthMiddleware as r, BearerTokenProvider as t };
|
|
31
|
-
export {};
|
|
32
|
-
//# sourceMappingURL=auth-DRbzRdeC.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"auth-DRbzRdeC.d.ts","names":[],"sources":["../src/graphql-client/auth.ts"],"mappings":";;;;;;;;KASY,4BAA4B;;;;;;;;;;;iBAelB,8BAA8B;;;;;;;;iBAsBpC,mBACd,eAAe,sBACd"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-BFnMV-EO.js","names":[],"sources":["../src/rpc/bus-event-ids.ts","../src/registry/fetchers.ts","../src/registry/client.ts"],"sourcesContent":["// Dependency-free, so the root entry can listen without the RPC graph.\n\n// Synthetic bus channel id for sync-status deltas (not a reactor IEventBus type).\nexport const SYNC_STATUS_CHANGED_EVENT = 90001;\n// Carries the worker's remotes after a local peer is adopted or removed.\nexport const SYNC_REMOTES_CHANGED_EVENT = 90002;\n","import type { PackageInfo, PackagePage } from \"@powerhousedao/shared/registry\";\n\n// Strip a trailing \"/\" so we don't emit `http://host//packages` when a user\n// writes `packageRegistryUrl: \"http://host/\"`. Verdaccio's own web backend\n// 404s on the doubled slash, which cascades into an empty registry list and\n// masks the real install flow.\nexport function trimTrailingSlash(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n// The registry's largest page; the cap bounds a registry that never ends\nconst PAGE_SIZE = 50;\nconst MAX_PAGES = 200;\n\nasync function getJson(url: string): Promise<unknown> {\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n return res.json();\n}\n\n// Every package matching `query`, in full detail, paged `PAGE_SIZE` at a time.\nasync function queryAllPackages(\n registryUrl: string,\n query: Record<string, string>,\n): Promise<PackageInfo[]> {\n const packages: PackageInfo[] = [];\n for (let n = 0; n < MAX_PAGES; n++) {\n const params = new URLSearchParams({\n ...query,\n detail: \"full\",\n limit: String(PAGE_SIZE),\n offset: String(packages.length),\n });\n const page = (await getJson(\n `${trimTrailingSlash(registryUrl)}/packages?${params.toString()}`,\n )) as PackagePage<PackageInfo>;\n packages.push(...page.items);\n if (!page.hasMore || page.items.length === 0) break;\n }\n return packages;\n}\n\nexport async function getPackages(registryUrl: string) {\n return queryAllPackages(registryUrl, {});\n}\n\n// Packages whose name, description, publisher or module names match `search`.\nexport async function searchPackages(\n registryUrl: string,\n search: string,\n): Promise<PackageInfo[]> {\n return queryAllPackages(registryUrl, { search });\n}\n\n/**\n * One page of the registry listing (trimmed items). Used by the Package\n * Manager's Available tab for infinite scroll + server-side search.\n */\nexport async function getPackagePage(\n registryUrl: string,\n params: { limit: number; offset: number; search?: string },\n): Promise<PackagePage> {\n const query = new URLSearchParams({\n limit: String(params.limit),\n offset: String(params.offset),\n });\n if (params.search) query.set(\"search\", params.search);\n return (await getJson(\n `${trimTrailingSlash(registryUrl)}/packages?${query.toString()}`,\n )) as PackagePage;\n}\n\n/**\n * Full package info for every package exposing a given document type, to offer\n * installs without loading the whole listing.\n */\nexport async function getPackagesForDocumentType(\n registryUrl: string,\n documentType: string,\n): Promise<PackageInfo[]> {\n return queryAllPackages(registryUrl, { documentType });\n}\n\nexport async function getPackagesByDocumentType(\n registryUrl: string,\n documentType: string,\n): Promise<string[]> {\n const encodedType = encodeURIComponent(documentType);\n const res = await fetch(\n `${trimTrailingSlash(registryUrl)}/packages/by-document-type?type=${encodedType}`,\n );\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n return (await res.json()) as string[];\n}\n\n/**\n * Fetch full metadata (versions + dist-tags) for one package from the\n * single-package endpoint. Returns null when the package no longer exists\n * upstream.\n */\nexport async function getPackageInfo(\n registryUrl: string,\n name: string,\n): Promise<PackageInfo | null> {\n const encodedName = encodeURIComponent(name);\n const res = await fetch(\n `${trimTrailingSlash(registryUrl)}/packages/${encodedName}`,\n );\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n return (await res.json()) as PackageInfo;\n}\n","import type { PackageInfo } from \"@powerhousedao/shared/registry\";\nimport {\n getPackages,\n getPackagesByDocumentType,\n searchPackages,\n} from \"./fetchers.js\";\nimport type { PublishEvent } from \"./types.js\";\n\nfunction cdnUrlToApiUrl(cdnUrl: string): string {\n return cdnUrl.replace(/\\/-\\/cdn\\/?$/, \"\");\n}\nexport class RegistryClient {\n readonly apiUrl: string;\n\n constructor(cdnUrl: string) {\n this.apiUrl = cdnUrlToApiUrl(cdnUrl);\n }\n\n async getPackages(): Promise<PackageInfo[]> {\n const data = await getPackages(this.apiUrl);\n return data;\n }\n\n async getPackagesByDocumentType(documentType: string): Promise<string[]> {\n return await getPackagesByDocumentType(this.apiUrl, documentType);\n }\n\n async searchPackages(query: string): Promise<PackageInfo[]> {\n if (!query) return this.getPackages();\n return await searchPackages(this.apiUrl, query);\n }\n\n onPublish(callback: (event: PublishEvent) => void): () => void {\n const eventSource = new EventSource(`${this.apiUrl}/-/events`);\n\n eventSource.addEventListener(\"publish\", (e: MessageEvent<string>) => {\n const data = JSON.parse(e.data) as PublishEvent;\n callback(data);\n });\n\n return () => {\n eventSource.close();\n };\n }\n}\n"],"mappings":";AAGA,MAAa,4BAA4B;AAEzC,MAAa,6BAA6B;;;ACC1C,SAAgB,kBAAkB,KAAqB;CACrD,OAAO,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AAChD;AAGA,MAAM,YAAY;AAClB,MAAM,Y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,aACtE;CACA,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,wBAAwB,IAAI,QAAQ;CACjE,OAAQ,MAAM,IAAI,KAAK;AACzB;;;;;;AAOA,eAAsB,eACpB,aACA,MAC6B;CAC7B,MAAM,cAAc,mBAAmB,IAAI;CAC3C,MAAM,MAAM,MAAM,MAChB,GAAG,kBAAkB,WAAW,EAAE,YAAY,aAChD;CACA,IAAI,IAAI,WAAW,KAAK,OAAO;CAC/B,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,wBAAwB,IAAI,QAAQ;CACjE,OAAQ,MAAM,IAAI,KAAK;AACzB;;;ACvGA,SAAS,eAAe,QAAwB;CAC9C,OAAO,OAAO,QAAQ,gBAAgB,EAAE;AAC1C;AACA,IAAa,iBAAb,MAA4B;CAC1B;CAEA,YAAY,QAAgB;EAC1B,KAAK,SAAS,eAAe,MAAM;CACrC;CAEA,MAAM,cAAsC;EAE1C,OAAO,MADY,YAAY,KAAK,MAAM;CAE5C;CAEA,MAAM,0BAA0B,cAAyC;EACvE,OAAO,MAAM,0BAA0B,KAAK,QAAQ,YAAY;CAClE;CAEA,MAAM,eAAe,OAAuC;EAC1D,IAAI,CAAC,OAAO,OAAO,KAAK,YAAY;EACpC,OAAO,MAAM,eAAe,KAAK,QAAQ,KAAK;CAChD;CAEA,UAAU,UAAqD;EAC7D,MAAM,cAAc,IAAI,YAAY,GAAG,KAAK,OAAO,UAAU;EAE7D,YAAY,iBAAiB,YAAY,MAA4B;GAEnE,SADa,KAAK,MAAM,EAAE,IACd,CAAC;EACf,CAAC;EAED,aAAa;GACX,YAAY,MAAM;EACpB;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"document-model-modules-DCC6DjOP.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/utils/nodes.ts","../src/hooks/drive-nodes.ts","../src/hooks/reactor.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/switchboards.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 { getPHStore } from \"./ph-store.js\";\nimport type { PGlite } from \"@electric-sql/pglite\";\nimport type {\n Database,\n IDocumentModelRegistry,\n IReactorClient,\n ISyncManager,\n} from \"@powerhousedao/reactor\";\nimport type {\n AddPHGlobalEventHandler,\n BrowserReactorClientModule,\n IReactorBrowserClient,\n ReactorBrowserHalves,\n SetPHGlobalValue,\n UsePHGlobalValue,\n WorkerReactorClientModule,\n} from \"@powerhousedao/reactor-browser\";\nimport type { Kysely } from \"kysely\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst reactorClientModuleEventFunctions = makePHEventFunctions(\n \"reactorClientModule\",\n);\nconst reactorClientEventFunctions = makePHEventFunctions(\"reactorClient\");\nconst reactorHalvesEventFunctions = makePHEventFunctions(\"reactor\");\nconst fullReactorClientEventFunctions =\n makePHEventFunctions(\"fullReactorClient\");\n\n/** Returns the reactor client module (in-process or worker-backed) */\nexport const useReactorClientModule: UsePHGlobalValue<\n BrowserReactorClientModule | WorkerReactorClientModule\n> = reactorClientModuleEventFunctions.useValue;\n\n/** Sets the reactor client module */\nexport const setReactorClientModule: SetPHGlobalValue<\n BrowserReactorClientModule | WorkerReactorClientModule\n> = reactorClientModuleEventFunctions.setValue;\n\n/** Adds an event handler for the reactor client module */\nexport const addReactorClientModuleEventHandler: AddPHGlobalEventHandler =\n reactorClientModuleEventFunctions.addEventHandler;\n\n/** Returns the reactor client */\nexport const useReactorClient: UsePHGlobalValue<IReactorBrowserClient> =\n reactorClientEventFunctions.useValue;\n\n/**\n * Sets the reactor client, and `window.ph.reactor` to its read and write\n * halves. A client without halves leaves `reactor` unset.\n */\nexport const setReactorClient: SetPHGlobalValue<IReactorBrowserClient> = (\n client,\n) => {\n reactorClientEventFunctions.setValue(client);\n reactorHalvesEventFunctions.setValue(halvesOf(client));\n};\n\n/** Returns the reactor client's read and write halves */\nexport const useReactorHalves: UsePHGlobalValue<ReactorBrowserHalves> =\n reactorHalvesEventFunctions.useValue;\n\n/** Adds an event handler for the reactor client's halves */\nexport const addReactorHalvesEventHandler: AddPHGlobalEventHandler =\n reactorHalvesEventFunctions.addEventHandler;\n\nfunction halvesOf(\n client: IReactorBrowserClient | undefined,\n): ReactorBrowserHalves | undefined {\n const read = client?.read as ReactorBrowserHalves[\"read\"] | undefined;\n const write = client?.write as ReactorBrowserHalves[\"write\"] | undefined;\n return read && write ? { read, write } : undefined;\n}\n\n/** Adds an event handler for the reactor client */\nexport const addReactorClientEventHandler: AddPHGlobalEventHandler =\n reactorClientEventFunctions.addEventHandler;\n\n/** Sets the client full-client actions use instead of the module's */\nexport const setFullReactorClient: SetPHGlobalValue<IReactorClient> =\n fullReactorClientEventFunctions.setValue;\n\n/** Adds an event handler for the full reactor client */\nexport const addFullReactorClientEventHandler: AddPHGlobalEventHandler =\n fullReactorClientEventFunctions.addEventHandler;\n\n/** The client full-client actions use: the one set, else the module's. */\nexport function getFullReactorClient(): IReactorClient | undefined {\n return (\n getPHStore()?.fullReactorClient ?? getPHStore()?.reactorClientModule?.client\n );\n}\n\n// The following are derived from the reactor client module:\n\nexport const useSync = (): ISyncManager | undefined =>\n useReactorClientModule()?.reactorModule?.syncModule?.syncManager;\n\nexport const useSyncList = () => {\n const sync = useSync();\n return sync?.list() ?? [];\n};\n\nexport const useModelRegistry = (): IDocumentModelRegistry | undefined =>\n useReactorClientModule()?.reactorModule?.documentModelRegistry;\n\nexport const useDatabase = (): Kysely<Database> | undefined => {\n const module = useReactorClientModule();\n return module?.kind === \"browser\"\n ? module.reactorModule?.database\n : undefined;\n};\n\nexport const usePGlite = (): PGlite | undefined => {\n const module = useReactorClientModule();\n return module?.kind === \"browser\" ? module.reactorModule?.pg : undefined;\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 type {\n AddPHGlobalEventHandler,\n SetPHGlobalValue,\n SwitchboardDirectory,\n UsePHGlobalValue,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst switchboardsEventFunctions = makePHEventFunctions(\"switchboards\");\n\n/** The switchboards the app reaches, from the provided store. */\nexport const useSwitchboards: UsePHGlobalValue<SwitchboardDirectory> =\n switchboardsEventFunctions.useValue;\n\n/** Sets the app's switchboard directory; the host does this at boot. */\nexport const setSwitchboards: SetPHGlobalValue<SwitchboardDirectory> =\n switchboardsEventFunctions.setValue;\n\n/** Registers the switchboards window event handler */\nexport const addSwitchboardsEventHandler: AddPHGlobalEventHandler =\n switchboardsEventFunctions.addEventHandler;\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,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