@powerhousedao/reactor-browser 6.2.3-dev.85 → 6.2.3-dev.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/{attachment-service-BuPjCTlF.d.ts → attachment-service-BZVL5UJ1.d.ts} +36 -38
  2. package/dist/attachment-service-BZVL5UJ1.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/{client-BUpynoY6.js → client-BNMyQ_Z2.js} +28 -1
  6. package/dist/client-BNMyQ_Z2.js.map +1 -0
  7. package/dist/{client-XPGQrO4a.d.ts → client-C-NgSjoc.d.ts} +3 -2
  8. package/dist/client-C-NgSjoc.d.ts.map +1 -0
  9. package/dist/{document-model-modules-D-VXC3ET.js → document-model-modules-ChmfyIxT.js} +2 -2
  10. package/dist/{document-model-modules-D-VXC3ET.js.map → document-model-modules-ChmfyIxT.js.map} +1 -1
  11. package/dist/{document-operations-CsiIPsx9.js → document-operations-DCwmgcLe.js} +103 -13
  12. package/dist/document-operations-DCwmgcLe.js.map +1 -0
  13. package/dist/{global-DY6FeQYj.d.ts → global-bbfp3_1x.d.ts} +6 -4
  14. package/dist/{global-DY6FeQYj.d.ts.map → global-bbfp3_1x.d.ts.map} +1 -1
  15. package/dist/{index-C5yCJAVE.d.ts → index-31WV0-fD.d.ts} +2 -2
  16. package/dist/{index-C5yCJAVE.d.ts.map → index-31WV0-fD.d.ts.map} +1 -1
  17. package/dist/index.d.ts +27 -7
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +85 -15
  20. package/dist/index.js.map +1 -1
  21. package/dist/{navigation-BqphkrOB.js → renown-CBoTdGrg.js} +96 -4
  22. package/dist/renown-CBoTdGrg.js.map +1 -0
  23. package/dist/{renown-BtjgHBjH.js → renown-a_8pPr10.js} +2 -3
  24. package/dist/{renown-BtjgHBjH.js.map → renown-a_8pPr10.js.map} +1 -1
  25. package/dist/{types-BNVqRNli.d.ts → schema-Bn6L3QR1.d.ts} +15 -57
  26. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  27. package/dist/src/ai/index.d.ts +198 -7
  28. package/dist/src/ai/index.d.ts.map +1 -1
  29. package/dist/src/ai/index.js +657 -138
  30. package/dist/src/ai/index.js.map +1 -1
  31. package/dist/src/graphql/client.d.ts +2 -2
  32. package/dist/src/graphql/client.js +1 -1
  33. package/dist/src/graphql-client/entry.d.ts +5 -4
  34. package/dist/src/graphql-client/entry.js +2 -2
  35. package/dist/src/renown/index.d.ts +1 -1
  36. package/dist/src/renown/index.js +2 -2
  37. package/dist/{switchboard-DnvOmOx5.js → switchboard-B640iT1L.js} +2 -2
  38. package/dist/{switchboard-DnvOmOx5.js.map → switchboard-B640iT1L.js.map} +1 -1
  39. package/dist/types-CT44EMmw.d.ts +59 -0
  40. package/dist/types-CT44EMmw.d.ts.map +1 -0
  41. package/package.json +10 -10
  42. package/dist/attachment-service-BuPjCTlF.d.ts.map +0 -1
  43. package/dist/client-BUpynoY6.js.map +0 -1
  44. package/dist/client-XPGQrO4a.d.ts.map +0 -1
  45. package/dist/document-operations-CsiIPsx9.js.map +0 -1
  46. package/dist/navigation-BqphkrOB.js.map +0 -1
  47. package/dist/renown-BxkZYzbQ.js +0 -97
  48. package/dist/renown-BxkZYzbQ.js.map +0 -1
  49. package/dist/types-BNVqRNli.d.ts.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { c as getPHStore, f as usePHStore, n as subscribeToPHValue, s as getActivePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
2
  import { C as isDuplicateModuleError, S as isDuplicateManifestError, n as useDispatch } from "./dispatch-Cylwl2Dk.js";
3
- import { A as extractNodeIdFromSlug, I as makeDriveSlug, N as findDriveBySlug, O as extractDriveSlugFromPath, R as makeNodeSlug, _ as preloadTarget, c as getCurrentPathname, d as hasHostNavigation, j as extractNodeSlugFromPath, m as openTarget } from "./navigation-BqphkrOB.js";
3
+ import { $ as makeNodeSlug, C as getCurrentPathname, E as hasHostNavigation, G as extractNodeIdFromSlug, J as findDriveBySlug, K as extractNodeSlugFromPath, M as preloadTarget, U as extractDriveSlugFromPath, Z as makeDriveSlug, k as openTarget } from "./renown-CBoTdGrg.js";
4
4
  import { createContext, useCallback, useContext, useEffect, useSyncExternalStore } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { logger } from "document-model";
@@ -641,4 +641,4 @@ function useDocumentModelModuleById(id, version) {
641
641
  //#endregion
642
642
  export { makeAuthMiddleware as $, addDrivesEventHandler as A, invalidateDriveNodes as B, setSelectedNode as C, usePreloadNode as D, useOpenNode as E, isInitialSyncInFlight as F, useDriveNode as G, markLocalDriveWrite as H, listSyncRemotes as I, isFileNodeKind as J, useDriveNodes as K, addDriveNodesEventHandler as L, useDrives as M, DriveProvider as N, useSelectedNodeId as O, useDriveContext as P, ambientRenownTokenProvider as Q, dropDriveNode as R, selectNode as S, useNodeTarget as T, peekDriveNode as U, loadDriveNodes as V, takeLocalDriveWrite as W, listAllDriveNodes as X, isFolderNodeKind as Y, sortNodesByName as Z, useSetSelectedDrive as _, setVetraPackageManager as a, getNodeTarget as b, addSelectedDriveIdEventHandler as c, setSelectedDrive as d, setSelectedDriveId as f, useSelectedDriveSafe as g, useSelectedDriveId as h, onVetraPackageManager as i, setDrives as j, useSetSelectedNode as k, preloadDrive as l, useSelectedDrive as m, useDocumentModelModules as n, useVetraPackageManager as o, usePreloadDrive as p, useDriveNodesCache as q, addVetraPackageManagerEventHandler as r, useVetraPackages as s, useDocumentModelModuleById as t, selectDrive as u, addResetSelectedNodeEventHandler as v, setSelectedNodeId as w, preloadNode as x, addSelectedNodeIdEventHandler as y, getDriveNode as z };
643
643
 
644
- //# sourceMappingURL=document-model-modules-D-VXC3ET.js.map
644
+ //# sourceMappingURL=document-model-modules-ChmfyIxT.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"document-model-modules-D-VXC3ET.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/utils/nodes.ts","../src/hooks/drive-nodes.ts","../src/routing/initial-sync.ts","../src/hooks/drive-context.tsx","../src/hooks/drives.ts","../src/hooks/set-selected-node.ts","../src/hooks/selected-drive.ts","../src/hooks/vetra-packages.ts","../src/hooks/document-model-modules.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\n\n/**\n * Resolves the bearer token to send with a request.\n *\n * Returning `undefined` (or an empty string) means \"send this request\n * anonymously\": open Switchboards must keep serving reads to logged-out users.\n */\nexport type BearerTokenProvider = () => Promise<string | undefined>;\n\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n\n/**\n * The default token provider: the token of the currently logged-in Renown user.\n *\n * It is deliberately resolved from `window.ph` on every call rather than\n * captured at construction time, so a client built before login starts sending\n * the token as soon as there is one.\n *\n * The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n * rejects tokens that carry an audience.\n */\nexport async function ambientRenownTokenProvider(): Promise<\n string | undefined\n> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const renown = getPHStore()?.renown;\n if (!renown?.user) {\n return undefined;\n }\n\n return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n\n/**\n * Builds the SDK middleware that authenticates every request.\n *\n * The token is resolved per request and never cached, so a login, a logout or\n * an expiry between two calls is picked up by the next one. When no token is\n * available the request goes out unauthenticated.\n */\nexport function makeAuthMiddleware(\n tokenProvider: BearerTokenProvider,\n): SdkFunctionWrapper {\n return async (action) => {\n const token = await tokenProvider();\n if (!token) {\n return action();\n }\n\n return action({ authorization: `Bearer ${token}` });\n };\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n\nconst NODE_PAGE_SIZE = 1000;\n\n/** Every node of a drive from `read.drives`, paged until the last page;\n * `parentFolder` narrows it as `listNodes` does (null: the root level). */\nexport async function listAllDriveNodes(\n reader: IDriveReadClient,\n driveId: string,\n options: { parentFolder?: string | null; signal?: AbortSignal } = {},\n): Promise<Node[]> {\n const nodes: Node[] = [];\n let cursor = \"\";\n for (;;) {\n const page = await reader.listNodes(\n driveId,\n options.parentFolder,\n { limit: NODE_PAGE_SIZE, cursor },\n options.signal,\n );\n nodes.push(...page.results);\n if (!page.nextCursor || page.results.length === 0) return nodes;\n cursor = page.nextCursor;\n }\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { listAllDriveNodes } from \"../utils/nodes.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getActivePHStore, getPHStore, usePHStore } from \"./ph-store.js\";\n\n/** One drive's cached nodes, read through `read.drives`. */\nexport type DriveNodesEntry = {\n readonly byId: ReadonlyMap<string, Node>;\n /** \"all\" once a full listing landed; \"partial\" holds single fetches or a\n * listing being refreshed. */\n readonly loaded: \"none\" | \"partial\" | \"all\";\n /** The drive's nodes from the last full listing, kept while it refreshes. */\n readonly nodes?: Node[];\n readonly loading?: Promise<Node[]>;\n /** The drive changed while `loading` was in flight: that listing may miss\n * the change, so another one follows as soon as it lands. */\n readonly stale?: true;\n /** The last full listing failed; hooks do not retry until invalidated. */\n readonly error?: unknown;\n};\n\n/** Node caches by drive id; replaced, never mutated, so hooks see changes. */\nexport type DriveNodesCache = ReadonlyMap<string, DriveNodesEntry>;\n\nexport type DriveNodesOptions = {\n /** Skip the cache and read through `read.drives`. */\n refresh?: boolean;\n store?: PHStore;\n};\n\nconst driveNodesEventFunctions = makePHEventFunctions(\"driveNodes\");\n/** Returns the per-drive node caches */\nexport const useDriveNodesCache = driveNodesEventFunctions.useValue;\n\n/** Adds an event handler for the drive node cache */\nexport const addDriveNodesEventHandler =\n driveNodesEventFunctions.addEventHandler;\n\nconst mounted = new Map<string, number>();\n\nfunction retain(driveId: string) {\n mounted.set(driveId, (mounted.get(driveId) ?? 0) + 1);\n return () => {\n const count = (mounted.get(driveId) ?? 1) - 1;\n if (count > 0) mounted.set(driveId, count);\n else mounted.delete(driveId);\n };\n}\n\nfunction driveReader(store: PHStore | undefined): IDriveReadClient {\n const read = store?.reactorClient?.read;\n if (read) return read.drives;\n throw new Error(\"The reactor client is not initialized\");\n}\n\nfunction entryOf(store: PHStore | undefined, driveId: string) {\n return store?.driveNodes?.get(driveId);\n}\n\nfunction setEntry(\n store: PHStore | undefined,\n driveId: string,\n entry: DriveNodesEntry | undefined,\n) {\n if (!store) return;\n const next = new Map(store.driveNodes);\n if (entry) next.set(driveId, entry);\n else next.delete(driveId);\n store.driveNodes = next;\n // A plain `window.ph` does not notify on assignment.\n if (\n !getActivePHStore() &&\n typeof window !== \"undefined\" &&\n store === window.ph\n ) {\n window.dispatchEvent(new CustomEvent(\"ph:driveNodesUpdated\"));\n }\n}\n\n/** Loads every node of a drive into the cache, paging through\n * `read.drives.listNodes`; served from the cache once loaded. */\nexport function loadDriveNodes(\n driveId: string,\n options: DriveNodesOptions = {},\n): Promise<Node[]> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (current?.loading) {\n // A refresh asked for during a listing lists again once it lands: the\n // one in flight may predate the change that asked for it.\n if (options.refresh && !current.stale) {\n setEntry(store, driveId, { ...current, stale: true });\n }\n return current.loading;\n }\n if (!options.refresh && current?.loaded === \"all\" && current.nodes) {\n return Promise.resolve(current.nodes);\n }\n const read = store?.reactorClient?.read;\n if (!read) {\n return Promise.reject(new Error(\"The reactor client is not initialized\"));\n }\n const reader: IDriveReadClient = read.drives;\n const loading = listAllDriveNodes(reader, driveId);\n setEntry(store, driveId, {\n byId: current?.byId ?? new Map(),\n nodes: current?.nodes,\n loaded: current?.byId.size ? \"partial\" : \"none\",\n loading,\n });\n loading.then(\n (nodes) => {\n const settled = entryOf(store, driveId);\n if (settled?.loading !== loading) return;\n setEntry(store, driveId, {\n byId: new Map(nodes.map((n) => [n.id, n])),\n nodes,\n loaded: \"all\",\n });\n if (settled.stale) {\n if (mounted.has(driveId)) {\n loadDriveNodes(driveId, { store, refresh: true }).catch(\n (error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n } else {\n setEntry(store, driveId, undefined);\n }\n }\n },\n (error: unknown) => {\n const entry = entryOf(store, driveId);\n if (entry?.loading !== loading) return;\n setEntry(store, driveId, { ...entry, loading: undefined, error });\n },\n );\n return loading;\n}\n\n/** A node from the cache, else read through `read.drives.getNode`;\n * undefined when the drive does not hold it. */\nexport async function getDriveNode(\n driveId: string,\n nodeId: string,\n options: DriveNodesOptions = {},\n): Promise<Node | undefined> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (!options.refresh && current) {\n const cached = current.byId.get(nodeId);\n if (cached || current.loaded === \"all\") return cached;\n }\n const reader = driveReader(store);\n let node: Node;\n try {\n node = await reader.getNode(driveId, nodeId);\n } catch {\n return undefined;\n }\n const entry = entryOf(store, driveId);\n const byId = new Map(entry?.byId);\n byId.set(node.id, node);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry?.nodes && replaceNode(entry.nodes, node),\n loaded: entry?.loaded === \"all\" ? \"all\" : \"partial\",\n });\n return node;\n}\n\nfunction replaceNode(nodes: Node[], node: Node) {\n const at = nodes.findIndex((n) => n.id === node.id);\n if (at < 0) return [...nodes, node];\n return nodes.map((n, i) => (i === at ? node : n));\n}\n\n/** A node from the cache only, without reading; for synchronous callers. */\nexport function peekDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n): Node | undefined {\n return entryOf(store, driveId)?.byId.get(nodeId);\n}\n\n/** Drops a drive's cached nodes; while a hook shows them, they reload and\n * the old nodes stay visible until the new listing lands. */\nexport function invalidateDriveNodes(\n driveId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const current = entryOf(store, driveId);\n if (!current) return;\n if (current.loading) {\n // The listing in flight may predate this change; another follows it.\n if (!current.stale) setEntry(store, driveId, { ...current, stale: true });\n return;\n }\n if (!mounted.has(driveId)) {\n setEntry(store, driveId, undefined);\n return;\n }\n setEntry(store, driveId, {\n byId: current.byId,\n nodes: current.nodes,\n loaded: \"partial\",\n });\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n}\n\n/** Drives this tab has just written to; their next change is read at once. */\nconst localDriveWrites = new Set<string>();\n\n/**\n * Notes that this tab wrote to a drive, so the drive change handler re-reads\n * it on the change that follows instead of waiting out its interval: the\n * person who added, renamed or removed a node expects to see it, while a\n * drive being filled by someone else can wait.\n */\nexport function markLocalDriveWrite(driveId: string): void {\n localDriveWrites.add(driveId);\n}\n\n/** Spends a drive's local-write mark; true when one was set. */\nexport function takeLocalDriveWrite(driveId: string): boolean {\n return localDriveWrites.delete(driveId);\n}\n\n/** Takes a node out of a drive's cache after this tab removed it, so the\n * listing drops it at once instead of after the next drive refresh. */\nexport function dropDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const entry = entryOf(store, driveId);\n if (!entry?.byId.has(nodeId)) return;\n const byId = new Map(entry.byId);\n byId.delete(nodeId);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry.nodes?.filter((n) => n.id !== nodeId),\n });\n}\n\nfunction useDriveNodesEntry(driveId: string | null | undefined) {\n const store = usePHStore() ?? getPHStore();\n const cache = useDriveNodesCache();\n return [store, driveId ? cache?.get(driveId) : undefined] as const;\n}\n\n/** Every node of a drive, loaded on first use; undefined until loaded. */\nexport function useDriveNodes(\n driveId: string | null | undefined,\n): Node[] | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const needsLoad =\n !!driveId && !entry?.loading && !entry?.error && entry?.loaded !== \"all\";\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !needsLoad) return;\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive nodes failed: @error\", error),\n );\n }, [driveId, needsLoad, store]);\n\n return entry?.nodes;\n}\n\n/** One node of a drive, from the cache or read on its own. */\nexport function useDriveNode(\n driveId: string | null | undefined,\n nodeId: string | null | undefined,\n): Node | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const node = nodeId ? entry?.byId.get(nodeId) : undefined;\n const needsFetch =\n !!driveId &&\n !!nodeId &&\n !node &&\n entry?.loaded !== \"all\" &&\n !entry?.loading;\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !nodeId || !needsFetch) return;\n getDriveNode(driveId, nodeId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive node failed: @error\", error),\n );\n }, [driveId, nodeId, needsFetch, store]);\n\n return node;\n}\n","import type { Remote } from \"@powerhousedao/reactor\";\nimport type { PHStore } from \"../hooks/ph-store.js\";\n\n/** The store's sync remotes; none before the reactor is ready. */\nexport function listSyncRemotes(store: PHStore | undefined): Remote[] {\n try {\n return (\n store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ??\n []\n );\n } catch {\n return [];\n }\n}\n\n// Only a first pull in flight may still bring drives. A connected remote that\n// never polled is paused or answer-only; one failed or failing to reconnect won't soon.\nfunction isFirstPullInFlight(remote: Remote) {\n try {\n const { state, receivingPages, lastSuccessUtcMs, failureCount } =\n remote.channel.getConnectionState();\n if (state === \"connected\") return receivingPages;\n if (state === \"reconnecting\") return !lastSuccessUtcMs && !failureCount;\n return state === \"connecting\" && (receivingPages || !lastSuccessUtcMs);\n } catch {\n return false;\n }\n}\n\n/** Whether a remote, or one syncing `driveId` when given, is in its first pull. */\nexport function isInitialSyncInFlight(\n store: PHStore | undefined,\n driveId?: string,\n) {\n return listSyncRemotes(store).some(\n (remote) =>\n (driveId === undefined || remote.meta.collectionId.driveId === driveId) &&\n isFirstPullInFlight(remote),\n );\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { PHNavigateOptions } from \"../types/global.js\";\n\n/** The drive a drive app shows. `open`/`preload` replace the app's navigation,\n * e.g. for a host that keeps the open node in local state. */\nexport type DriveContextValue = {\n drive: DocumentDriveDocument;\n dispatch: DocumentDispatch<DocumentDriveAction>;\n /** The open folder; undefined at the drive's root or on a document. */\n folder?: FolderNode;\n /** The open node, a folder or a document. */\n nodeId?: string;\n open?: (node: Node | undefined, options?: PHNavigateOptions) => void;\n preload?: (node: Node | undefined) => void;\n};\n\nconst DriveContext = createContext<DriveContextValue | undefined>(undefined);\n\n/** Hosts render a drive app inside this; `useSelectedDrive`, `useSelectedNode`\n * and `useSelectedFolder` below read it, and opening nodes calls its `open`. */\nexport function DriveProvider(props: {\n value: DriveContextValue;\n children: ReactNode;\n}) {\n return (\n <DriveContext.Provider value={props.value}>\n {props.children}\n </DriveContext.Provider>\n );\n}\n\n/** The nearest drive app's drive, or undefined outside one. */\nexport function useDriveContext() {\n return useContext(DriveContext);\n}\n","import type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n\n/** Returns all of the drives in the reactor */\nexport const useDrives: UsePHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.useValue;\n\n/** Sets the drives in the reactor */\nexport const setDrives: SetPHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.setValue;\n\n/** Adds an event handler for the drives */\nexport const addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n","import type {\n PHNavigateOptions,\n PHNavigationTarget,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n makeDriveSlug,\n makeNodeSlug,\n} from \"../utils/url.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport { useCallback } from \"react\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { peekDriveNode } from \"./drive-nodes.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, usePHStore } from \"./ph-store.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useStoreSelectedNodeId = selectedNodeIdEventFunctions.useValue;\n\n/** The selected node id: the drive app's open node, else the app's selection. */\nexport function useSelectedNodeId() {\n const context = useDriveContext();\n const selectedNodeId = useStoreSelectedNodeId();\n return context ? context.nodeId : selectedNodeId;\n}\n/** Sets the selected node id without touching the URL. */\nexport const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\n/** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\nfunction decodeSlug(slug: string) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n}\n\n// The selected drive's slug, else the path's: a pending navigation's path\n// already names its destination, not the drive still shown.\nfunction openDriveSlug(store: PHStore | undefined, pathname: string) {\n const selected = store?.drives?.find(\n (d) => d.header.id === store.selectedDriveId,\n );\n if (selected) return makeDriveSlug(selected);\n const driveSlug = extractDriveSlugFromPath(pathname);\n return driveSlug ? decodeSlug(driveSlug) : undefined;\n}\n\n// The node in `drive`, else in the app's open drive.\nfunction nodeTarget(\n nodeSlug: string,\n drive?: DocumentDriveDocument,\n): PHNavigationTarget | undefined {\n const driveSlug = drive\n ? makeDriveSlug(drive)\n : openDriveSlug(getPHStore(), getCurrentPathname());\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\ntype NodeRef = Node | string | undefined;\n\nconst toSlug = (node: NodeRef) =>\n typeof node === \"string\" ? node : makeNodeSlug(node);\n\n/** Selects a node in `drive`, else in the app's open drive. */\nexport function selectNode(\n node: NodeRef,\n options?: PHNavigateOptions,\n drive?: DocumentDriveDocument,\n) {\n const nodeSlug = toSlug(node);\n // A host router resolves the node and writes the selection itself.\n if (!hasHostNavigation()) {\n setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n }\n const target = nodeTarget(nodeSlug, drive);\n if (target) openTarget(target, options);\n}\n\n/** Sets the selected node (file or folder) of the app's store; `search` sets\n * the params it opens with. Inside a drive app, use `useSetSelectedNode`. */\nexport function setSelectedNode(node: NodeRef, options?: PHNavigateOptions) {\n selectNode(node, options);\n}\n\nfunction findNode(\n drive: DocumentDriveDocument,\n node: NodeRef,\n store: PHStore | undefined,\n) {\n if (typeof node !== \"string\") return node;\n const id = extractNodeIdFromSlug(node);\n return id ? peekDriveNode(drive.header.id, id, store) : undefined;\n}\n\n/** Opens a node: through the drive app's `open` when it has one, else the\n * app's navigation in the drive app's drive. */\nexport function useSetSelectedNode() {\n const context = useDriveContext();\n const store = usePHStore() ?? getPHStore();\n return useCallback(\n (node: NodeRef, options?: PHNavigateOptions) => {\n if (context?.open) {\n context.open(findNode(context.drive, node, store), options);\n return;\n }\n selectNode(node, options, context?.drive);\n },\n [context, store],\n );\n}\n\n/** Opens a node, or with `undefined` its drive. */\nexport const useOpenNode: () => (\n node: Node | undefined,\n options?: PHNavigateOptions,\n) => void = useSetSelectedNode;\n\n/** Where a node of `drive`, else of the open drive, navigates to. */\nexport function getNodeTarget(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n return nodeTarget(makeNodeSlug(node), drive);\n}\n\n/** Where a node navigates to: in the drive app's drive, else the open drive. */\nexport function useNodeTarget(node: Node | undefined) {\n const context = useDriveContext();\n return getNodeTarget(node, context?.drive);\n}\n\n/** Warms a node's view before it is opened, e.g. on hover. */\nexport function preloadNode(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n if (!node) return;\n const target = nodeTarget(makeNodeSlug(node), drive);\n if (target) preloadTarget(target);\n}\n\n/** `preloadNode` through the drive app's `preload`, if it has one. */\nexport function usePreloadNode() {\n const context = useDriveContext();\n return useCallback(\n (node: Node | undefined) => {\n if (context?.preload) context.preload(node);\n else if (!context?.open) preloadNode(node, context?.drive);\n },\n [context],\n );\n}\n\nexport function addResetSelectedNodeEventHandler() {\n subscribeToPHValue(\"selectedDriveId\", () => {\n setSelectedNodeId(undefined);\n });\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport { useCallback } from \"react\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n findDriveBySlug,\n makeDriveSlug,\n} from \"../utils/url.js\";\nimport { isInitialSyncInFlight } from \"../routing/initial-sync.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useDrives } from \"./drives.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport { selectNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\nconst useStoreSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Returns the selected drive id: the drive app's drive, else the app's selection. */\nexport function useSelectedDriveId() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n return context ? context.drive.header.id : selectedDriveId;\n}\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id\n * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */\nexport const addSelectedDriveIdEventHandler =\n selectedDriveIdEventFunctions.addEventHandler;\n\n/** Returns the selected drive */\nexport function useSelectedDrive() {\n const drive = useSelectedDriveSafe();\n if (!drive[0]) {\n throw new Error(\n \"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\",\n );\n }\n\n return drive;\n}\n\n/** Returns the selected drive, or undefined if no drive is selected */\nexport function useSelectedDriveSafe() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = context\n ? undefined\n : drives?.find((drive) => drive.header.id === selectedDriveId);\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (context) {\n return [context.drive, context.dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n }\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\ntype DriveRef = string | DocumentDriveDocument | undefined;\n\n/** Selects a drive in the app's store. */\nexport function setSelectedDrive(driveOrDriveSlug: DriveRef) {\n selectDrive(driveOrDriveSlug);\n}\n\n/** `setSelectedDrive`, as a hook. */\nexport function useSetSelectedDrive() {\n return useCallback((drive: DriveRef) => selectDrive(drive), []);\n}\n\n/** Selects a drive in the app's store. */\nexport function selectDrive(driveOrDriveSlug: DriveRef) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n\n // A host router resolves the drive and writes the selection itself.\n if (hasHostNavigation()) {\n cancelPendingDriveSelection();\n openTarget(driveSlug ? { driveSlug } : undefined);\n return;\n }\n\n // A full drive document is selected directly — a just-created drive\n // navigates before the collection refresh. Slugs go through the lookup.\n const drives = getPHStore()?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : findDriveBySlug(drives, driveSlug);\n const driveId = drive?.header.id;\n\n // Deprecated: hosts without a navigation only; route loaders wait for drives.\n // A deep link may predate remote drive registration, so defer the lookup.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(getCurrentPathname()) === driveSlug\n ) {\n // Clear the previous selection so a stale drive doesn't render against\n // the new URL; the selected node resets with it, the URL is untouched.\n if (getPHStore()?.selectedDriveId) {\n setSelectedDriveId(undefined);\n }\n deferDriveSelection(driveSlug);\n return;\n }\n\n // Any resolved selection supersedes a pending deferred lookup.\n cancelPendingDriveSelection();\n\n setSelectedDriveId(driveId);\n openTarget(driveId && driveSlug ? { driveSlug } : undefined);\n}\n\n/** Warms a drive's view before it is opened, e.g. on hover. */\nexport function preloadDrive(drive: DocumentDriveDocument | undefined) {\n if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });\n}\n\n/** `preloadDrive`, as a hook. */\nexport function usePreloadDrive() {\n return useCallback(\n (drive: DocumentDriveDocument | undefined) => preloadDrive(drive),\n [],\n );\n}\n\n// Tick between unresolved-slug checks; re-armed while a sync is in flight.\nconst DEFERRED_DRIVE_TICK_MS = 2_000;\n// Hard cap so a wedged remote can't pin the deep link forever.\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15_000;\n\nlet unsubscribePending: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (unsubscribePending) {\n unsubscribePending();\n unsubscribePending = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Deprecated with the no-navigation path: re-runs the slug lookup on drives\n// updates, restores the pinned node, and redirects home once syncs settle.\nfunction deferDriveSelection(driveSlug: string) {\n cancelPendingDriveSelection();\n\n // Capture the node pinned in the deep link before setSelectedDrive\n // rewrites the URL to /d/<driveSlug>, dropping the node segment.\n const nodeSlug = extractNodeSlugFromPath(getCurrentPathname());\n const handler = () => {\n const drive = findDriveBySlug(getPHStore()?.drives, driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n selectDrive(driveSlug);\n selectNode(nodeSlug);\n };\n unsubscribePending = subscribeToPHValue(\"drives\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n openTarget(undefined);\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n isDuplicateManifestError,\n isDuplicateModuleError,\n} from \"../reactor-interop.js\";\nimport type { IPackageManager } from \"../types/vetra.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst vetraPackageManagerFunctions = makePHEventFunctions(\n \"vetraPackageManager\",\n);\n\nexport const useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n\nconst EMPTY_VETRA_PACKAGES: DocumentModelLib[] = [];\nconst noPackageManagerUnsubscribe = () => {};\n\n/**\n * Returns all of the Vetra packages loaded by the Connect instance.\n *\n * The snapshot and subscription must keep stable identity while no package\n * manager is registered: `useSyncExternalStore` loops when the snapshot\n * changes on every read, which a fresh `[]` does.\n */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n getPackages,\n getPackages,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/**\n * Non-react access to the Vetra package manager: calls `callback` once a\n * manager is available - immediately when already set, otherwise when\n * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker\n * wiring uses this to forward package updates from plain boot code.\n */\nexport function onVetraPackageManager(\n callback: (packageManager: IPackageManager) => void,\n): () => void {\n let delivered: IPackageManager | undefined;\n const deliver = () => {\n const packageManager = vetraPackageManagerFunctions.getSnapshot();\n if (!packageManager || packageManager === delivered) return;\n delivered = packageManager;\n callback(packageManager);\n };\n const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);\n deliver();\n return unsubscribe;\n}\n\n/** Sets the Vetra package manager and registers its packages */\nexport function setVetraPackageManager(packageManager: IPackageManager) {\n vetraPackageManagerFunctions.setValue(packageManager);\n updateReactorClientDocumentModels(packageManager.packages);\n updateReactorClientUpgradeManifests(packageManager.packages);\n packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n updateReactorClientUpgradeManifests(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // dedupe by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n (m.version ?? 1) === (module.version ?? 1),\n ) === index,\n );\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n const results = registry.registerModules(...documentModelModules);\n const duplicateTypes = new Set<string>();\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateModuleError(result.error)) {\n duplicateTypes.add(result.item.documentModel.global.id);\n } else {\n console.error(\n \"Failed to register document model module:\",\n result.error,\n );\n }\n }\n }\n if (duplicateTypes.size > 0) {\n // unregisterModules is type-scoped, so replace the whole version family\n // with the incoming package's modules: re-registering only the duplicated\n // items would purge any new version that registered successfully above.\n registry.unregisterModules(...duplicateTypes);\n registry.registerModules(\n ...documentModelModules.filter((module) =>\n duplicateTypes.has(module.documentModel.global.id),\n ),\n );\n }\n}\n\nfunction updateReactorClientUpgradeManifests(packages: DocumentModelLib[]) {\n const upgradeManifests = packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter((u) => u !== undefined);\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || upgradeManifests.length === 0) return;\n\n const results = registry.registerUpgradeManifests(...upgradeManifests);\n const duplicates = [];\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateManifestError(result.error)) {\n duplicates.push(result);\n } else {\n console.error(\"Failed to register upgrade manifest:\", result.error);\n }\n }\n }\n if (duplicates.length > 0) {\n const duplicateTypes = duplicates\n .map((r) => r.item.documentType)\n .filter((t): t is string => !!t);\n registry.unregisterUpgradeManifests(...duplicateTypes);\n registry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n }\n}\n","import type { DocumentModelModule } from \"document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useDocumentModelModules(): DocumentModelModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n}\n\n/**\n * Resolves a document model module by document type, mirroring the registry's\n * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n * LATEST version of the type wins (`version ?? 1` as each module's default),\n * with `version` given only an exact match is returned. The reactor resolves\n * modules the same way when a document is created, so metadata read through\n * this hook and the version a creation actually uses cannot disagree.\n */\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n version?: number,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n if (!id || !documentModelModules) return undefined;\n\n let latestModule: DocumentModelModule | undefined;\n let latestVersion = -1;\n for (const module of documentModelModules) {\n if (module.documentModel.global.id !== id) continue;\n const moduleVersion = module.version ?? 1;\n if (version !== undefined) {\n if (moduleVersion === version) return module;\n continue;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n return latestModule;\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,WAAW,CAAC,EAAE;CAC7B,IAAI,CAAC,QAAQ,MACX;CAGF,OAAO,OAAO,eAAe,EAAE,WAAW,6BAA6B,CAAC;AAC1E;;;;;;;;AASA,SAAgB,mBACd,eACoB;CACpB,OAAO,OAAO,WAAW;EACvB,MAAM,QAAQ,MAAM,cAAc;EAClC,IAAI,CAAC,OACH,OAAO,OAAO;EAGhB,OAAO,OAAO,EAAE,eAAe,UAAU,QAAQ,CAAC;CACpD;AACF;;;;ACjDA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC9D;;AAGA,SAAgB,eACd,MACkB;CAClB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;AAGA,SAAgB,iBACd,MACoB;CACpB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;AAEA,MAAM,iBAAiB;;;AAIv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UA,SAAgB,2BACd,IACA,SACiC;CACjC,MAAM,uBAAuB,wBAAwB;CACrD,IAAI,CAAC,MAAM,CAAC,sBAAsB,OAAO,KAAA;CAEzC,IAAI;CACJ,IAAI,gBAAgB;CACpB,KAAK,MAAM,UAAU,sBAAsB;EACzC,IAAI,OAAO,cAAc,OAAO,OAAO,IAAI;EAC3C,MAAM,gBAAgB,OAAO,WAAW;EACxC,IAAI,YAAY,KAAA,GAAW;GACzB,IAAI,kBAAkB,SAAS,OAAO;GACtC;EACF;EACA,IAAI,gBAAgB,eAAe;GACjC,gBAAgB;GAChB,eAAe;EACjB;CACF;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"document-model-modules-ChmfyIxT.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/utils/nodes.ts","../src/hooks/drive-nodes.ts","../src/routing/initial-sync.ts","../src/hooks/drive-context.tsx","../src/hooks/drives.ts","../src/hooks/set-selected-node.ts","../src/hooks/selected-drive.ts","../src/hooks/vetra-packages.ts","../src/hooks/document-model-modules.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\n\n/**\n * Resolves the bearer token to send with a request.\n *\n * Returning `undefined` (or an empty string) means \"send this request\n * anonymously\": open Switchboards must keep serving reads to logged-out users.\n */\nexport type BearerTokenProvider = () => Promise<string | undefined>;\n\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n\n/**\n * The default token provider: the token of the currently logged-in Renown user.\n *\n * It is deliberately resolved from `window.ph` on every call rather than\n * captured at construction time, so a client built before login starts sending\n * the token as soon as there is one.\n *\n * The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n * rejects tokens that carry an audience.\n */\nexport async function ambientRenownTokenProvider(): Promise<\n string | undefined\n> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const renown = getPHStore()?.renown;\n if (!renown?.user) {\n return undefined;\n }\n\n return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n\n/**\n * Builds the SDK middleware that authenticates every request.\n *\n * The token is resolved per request and never cached, so a login, a logout or\n * an expiry between two calls is picked up by the next one. When no token is\n * available the request goes out unauthenticated.\n */\nexport function makeAuthMiddleware(\n tokenProvider: BearerTokenProvider,\n): SdkFunctionWrapper {\n return async (action) => {\n const token = await tokenProvider();\n if (!token) {\n return action();\n }\n\n return action({ authorization: `Bearer ${token}` });\n };\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n\nconst NODE_PAGE_SIZE = 1000;\n\n/** Every node of a drive from `read.drives`, paged until the last page;\n * `parentFolder` narrows it as `listNodes` does (null: the root level). */\nexport async function listAllDriveNodes(\n reader: IDriveReadClient,\n driveId: string,\n options: { parentFolder?: string | null; signal?: AbortSignal } = {},\n): Promise<Node[]> {\n const nodes: Node[] = [];\n let cursor = \"\";\n for (;;) {\n const page = await reader.listNodes(\n driveId,\n options.parentFolder,\n { limit: NODE_PAGE_SIZE, cursor },\n options.signal,\n );\n nodes.push(...page.results);\n if (!page.nextCursor || page.results.length === 0) return nodes;\n cursor = page.nextCursor;\n }\n}\n","import type { IDriveReadClient } from \"@powerhousedao/reactor\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport { useEffect } from \"react\";\nimport { listAllDriveNodes } from \"../utils/nodes.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getActivePHStore, getPHStore, usePHStore } from \"./ph-store.js\";\n\n/** One drive's cached nodes, read through `read.drives`. */\nexport type DriveNodesEntry = {\n readonly byId: ReadonlyMap<string, Node>;\n /** \"all\" once a full listing landed; \"partial\" holds single fetches or a\n * listing being refreshed. */\n readonly loaded: \"none\" | \"partial\" | \"all\";\n /** The drive's nodes from the last full listing, kept while it refreshes. */\n readonly nodes?: Node[];\n readonly loading?: Promise<Node[]>;\n /** The drive changed while `loading` was in flight: that listing may miss\n * the change, so another one follows as soon as it lands. */\n readonly stale?: true;\n /** The last full listing failed; hooks do not retry until invalidated. */\n readonly error?: unknown;\n};\n\n/** Node caches by drive id; replaced, never mutated, so hooks see changes. */\nexport type DriveNodesCache = ReadonlyMap<string, DriveNodesEntry>;\n\nexport type DriveNodesOptions = {\n /** Skip the cache and read through `read.drives`. */\n refresh?: boolean;\n store?: PHStore;\n};\n\nconst driveNodesEventFunctions = makePHEventFunctions(\"driveNodes\");\n/** Returns the per-drive node caches */\nexport const useDriveNodesCache = driveNodesEventFunctions.useValue;\n\n/** Adds an event handler for the drive node cache */\nexport const addDriveNodesEventHandler =\n driveNodesEventFunctions.addEventHandler;\n\nconst mounted = new Map<string, number>();\n\nfunction retain(driveId: string) {\n mounted.set(driveId, (mounted.get(driveId) ?? 0) + 1);\n return () => {\n const count = (mounted.get(driveId) ?? 1) - 1;\n if (count > 0) mounted.set(driveId, count);\n else mounted.delete(driveId);\n };\n}\n\nfunction driveReader(store: PHStore | undefined): IDriveReadClient {\n const read = store?.reactorClient?.read;\n if (read) return read.drives;\n throw new Error(\"The reactor client is not initialized\");\n}\n\nfunction entryOf(store: PHStore | undefined, driveId: string) {\n return store?.driveNodes?.get(driveId);\n}\n\nfunction setEntry(\n store: PHStore | undefined,\n driveId: string,\n entry: DriveNodesEntry | undefined,\n) {\n if (!store) return;\n const next = new Map(store.driveNodes);\n if (entry) next.set(driveId, entry);\n else next.delete(driveId);\n store.driveNodes = next;\n // A plain `window.ph` does not notify on assignment.\n if (\n !getActivePHStore() &&\n typeof window !== \"undefined\" &&\n store === window.ph\n ) {\n window.dispatchEvent(new CustomEvent(\"ph:driveNodesUpdated\"));\n }\n}\n\n/** Loads every node of a drive into the cache, paging through\n * `read.drives.listNodes`; served from the cache once loaded. */\nexport function loadDriveNodes(\n driveId: string,\n options: DriveNodesOptions = {},\n): Promise<Node[]> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (current?.loading) {\n // A refresh asked for during a listing lists again once it lands: the\n // one in flight may predate the change that asked for it.\n if (options.refresh && !current.stale) {\n setEntry(store, driveId, { ...current, stale: true });\n }\n return current.loading;\n }\n if (!options.refresh && current?.loaded === \"all\" && current.nodes) {\n return Promise.resolve(current.nodes);\n }\n const read = store?.reactorClient?.read;\n if (!read) {\n return Promise.reject(new Error(\"The reactor client is not initialized\"));\n }\n const reader: IDriveReadClient = read.drives;\n const loading = listAllDriveNodes(reader, driveId);\n setEntry(store, driveId, {\n byId: current?.byId ?? new Map(),\n nodes: current?.nodes,\n loaded: current?.byId.size ? \"partial\" : \"none\",\n loading,\n });\n loading.then(\n (nodes) => {\n const settled = entryOf(store, driveId);\n if (settled?.loading !== loading) return;\n setEntry(store, driveId, {\n byId: new Map(nodes.map((n) => [n.id, n])),\n nodes,\n loaded: \"all\",\n });\n if (settled.stale) {\n if (mounted.has(driveId)) {\n loadDriveNodes(driveId, { store, refresh: true }).catch(\n (error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n } else {\n setEntry(store, driveId, undefined);\n }\n }\n },\n (error: unknown) => {\n const entry = entryOf(store, driveId);\n if (entry?.loading !== loading) return;\n setEntry(store, driveId, { ...entry, loading: undefined, error });\n },\n );\n return loading;\n}\n\n/** A node from the cache, else read through `read.drives.getNode`;\n * undefined when the drive does not hold it. */\nexport async function getDriveNode(\n driveId: string,\n nodeId: string,\n options: DriveNodesOptions = {},\n): Promise<Node | undefined> {\n const store = options.store ?? getPHStore();\n const current = entryOf(store, driveId);\n if (!options.refresh && current) {\n const cached = current.byId.get(nodeId);\n if (cached || current.loaded === \"all\") return cached;\n }\n const reader = driveReader(store);\n let node: Node;\n try {\n node = await reader.getNode(driveId, nodeId);\n } catch {\n return undefined;\n }\n const entry = entryOf(store, driveId);\n const byId = new Map(entry?.byId);\n byId.set(node.id, node);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry?.nodes && replaceNode(entry.nodes, node),\n loaded: entry?.loaded === \"all\" ? \"all\" : \"partial\",\n });\n return node;\n}\n\nfunction replaceNode(nodes: Node[], node: Node) {\n const at = nodes.findIndex((n) => n.id === node.id);\n if (at < 0) return [...nodes, node];\n return nodes.map((n, i) => (i === at ? node : n));\n}\n\n/** A node from the cache only, without reading; for synchronous callers. */\nexport function peekDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n): Node | undefined {\n return entryOf(store, driveId)?.byId.get(nodeId);\n}\n\n/** Drops a drive's cached nodes; while a hook shows them, they reload and\n * the old nodes stay visible until the new listing lands. */\nexport function invalidateDriveNodes(\n driveId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const current = entryOf(store, driveId);\n if (!current) return;\n if (current.loading) {\n // The listing in flight may predate this change; another follows it.\n if (!current.stale) setEntry(store, driveId, { ...current, stale: true });\n return;\n }\n if (!mounted.has(driveId)) {\n setEntry(store, driveId, undefined);\n return;\n }\n setEntry(store, driveId, {\n byId: current.byId,\n nodes: current.nodes,\n loaded: \"partial\",\n });\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Reloading drive nodes failed: @error\", error),\n );\n}\n\n/** Drives this tab has just written to; their next change is read at once. */\nconst localDriveWrites = new Set<string>();\n\n/**\n * Notes that this tab wrote to a drive, so the drive change handler re-reads\n * it on the change that follows instead of waiting out its interval: the\n * person who added, renamed or removed a node expects to see it, while a\n * drive being filled by someone else can wait.\n */\nexport function markLocalDriveWrite(driveId: string): void {\n localDriveWrites.add(driveId);\n}\n\n/** Spends a drive's local-write mark; true when one was set. */\nexport function takeLocalDriveWrite(driveId: string): boolean {\n return localDriveWrites.delete(driveId);\n}\n\n/** Takes a node out of a drive's cache after this tab removed it, so the\n * listing drops it at once instead of after the next drive refresh. */\nexport function dropDriveNode(\n driveId: string,\n nodeId: string,\n store: PHStore | undefined = getPHStore(),\n) {\n const entry = entryOf(store, driveId);\n if (!entry?.byId.has(nodeId)) return;\n const byId = new Map(entry.byId);\n byId.delete(nodeId);\n setEntry(store, driveId, {\n ...entry,\n byId,\n nodes: entry.nodes?.filter((n) => n.id !== nodeId),\n });\n}\n\nfunction useDriveNodesEntry(driveId: string | null | undefined) {\n const store = usePHStore() ?? getPHStore();\n const cache = useDriveNodesCache();\n return [store, driveId ? cache?.get(driveId) : undefined] as const;\n}\n\n/** Every node of a drive, loaded on first use; undefined until loaded. */\nexport function useDriveNodes(\n driveId: string | null | undefined,\n): Node[] | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const needsLoad =\n !!driveId && !entry?.loading && !entry?.error && entry?.loaded !== \"all\";\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !needsLoad) return;\n loadDriveNodes(driveId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive nodes failed: @error\", error),\n );\n }, [driveId, needsLoad, store]);\n\n return entry?.nodes;\n}\n\n/** One node of a drive, from the cache or read on its own. */\nexport function useDriveNode(\n driveId: string | null | undefined,\n nodeId: string | null | undefined,\n): Node | undefined {\n const [store, entry] = useDriveNodesEntry(driveId);\n const node = nodeId ? entry?.byId.get(nodeId) : undefined;\n const needsFetch =\n !!driveId &&\n !!nodeId &&\n !node &&\n entry?.loaded !== \"all\" &&\n !entry?.loading;\n\n useEffect(() => {\n if (!driveId) return;\n return retain(driveId);\n }, [driveId]);\n\n useEffect(() => {\n if (!driveId || !nodeId || !needsFetch) return;\n getDriveNode(driveId, nodeId, { store }).catch((error: unknown) =>\n logger.error(\"Loading drive node failed: @error\", error),\n );\n }, [driveId, nodeId, needsFetch, store]);\n\n return node;\n}\n","import type { Remote } from \"@powerhousedao/reactor\";\nimport type { PHStore } from \"../hooks/ph-store.js\";\n\n/** The store's sync remotes; none before the reactor is ready. */\nexport function listSyncRemotes(store: PHStore | undefined): Remote[] {\n try {\n return (\n store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ??\n []\n );\n } catch {\n return [];\n }\n}\n\n// Only a first pull in flight may still bring drives. A connected remote that\n// never polled is paused or answer-only; one failed or failing to reconnect won't soon.\nfunction isFirstPullInFlight(remote: Remote) {\n try {\n const { state, receivingPages, lastSuccessUtcMs, failureCount } =\n remote.channel.getConnectionState();\n if (state === \"connected\") return receivingPages;\n if (state === \"reconnecting\") return !lastSuccessUtcMs && !failureCount;\n return state === \"connecting\" && (receivingPages || !lastSuccessUtcMs);\n } catch {\n return false;\n }\n}\n\n/** Whether a remote, or one syncing `driveId` when given, is in its first pull. */\nexport function isInitialSyncInFlight(\n store: PHStore | undefined,\n driveId?: string,\n) {\n return listSyncRemotes(store).some(\n (remote) =>\n (driveId === undefined || remote.meta.collectionId.driveId === driveId) &&\n isFirstPullInFlight(remote),\n );\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"@powerhousedao/shared/document-model\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { PHNavigateOptions } from \"../types/global.js\";\n\n/** The drive a drive app shows. `open`/`preload` replace the app's navigation,\n * e.g. for a host that keeps the open node in local state. */\nexport type DriveContextValue = {\n drive: DocumentDriveDocument;\n dispatch: DocumentDispatch<DocumentDriveAction>;\n /** The open folder; undefined at the drive's root or on a document. */\n folder?: FolderNode;\n /** The open node, a folder or a document. */\n nodeId?: string;\n open?: (node: Node | undefined, options?: PHNavigateOptions) => void;\n preload?: (node: Node | undefined) => void;\n};\n\nconst DriveContext = createContext<DriveContextValue | undefined>(undefined);\n\n/** Hosts render a drive app inside this; `useSelectedDrive`, `useSelectedNode`\n * and `useSelectedFolder` below read it, and opening nodes calls its `open`. */\nexport function DriveProvider(props: {\n value: DriveContextValue;\n children: ReactNode;\n}) {\n return (\n <DriveContext.Provider value={props.value}>\n {props.children}\n </DriveContext.Provider>\n );\n}\n\n/** The nearest drive app's drive, or undefined outside one. */\nexport function useDriveContext() {\n return useContext(DriveContext);\n}\n","import type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n\n/** Returns all of the drives in the reactor */\nexport const useDrives: UsePHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.useValue;\n\n/** Sets the drives in the reactor */\nexport const setDrives: SetPHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.setValue;\n\n/** Adds an event handler for the drives */\nexport const addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n","import type {\n PHNavigateOptions,\n PHNavigationTarget,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n makeDriveSlug,\n makeNodeSlug,\n} from \"../utils/url.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport { useCallback } from \"react\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { peekDriveNode } from \"./drive-nodes.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport type { PHStore } from \"./ph-store.js\";\nimport { getPHStore, usePHStore } from \"./ph-store.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useStoreSelectedNodeId = selectedNodeIdEventFunctions.useValue;\n\n/** The selected node id: the drive app's open node, else the app's selection. */\nexport function useSelectedNodeId() {\n const context = useDriveContext();\n const selectedNodeId = useStoreSelectedNodeId();\n return context ? context.nodeId : selectedNodeId;\n}\n/** Sets the selected node id without touching the URL. */\nexport const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\n/** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\nfunction decodeSlug(slug: string) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n}\n\n// The selected drive's slug, else the path's: a pending navigation's path\n// already names its destination, not the drive still shown.\nfunction openDriveSlug(store: PHStore | undefined, pathname: string) {\n const selected = store?.drives?.find(\n (d) => d.header.id === store.selectedDriveId,\n );\n if (selected) return makeDriveSlug(selected);\n const driveSlug = extractDriveSlugFromPath(pathname);\n return driveSlug ? decodeSlug(driveSlug) : undefined;\n}\n\n// The node in `drive`, else in the app's open drive.\nfunction nodeTarget(\n nodeSlug: string,\n drive?: DocumentDriveDocument,\n): PHNavigationTarget | undefined {\n const driveSlug = drive\n ? makeDriveSlug(drive)\n : openDriveSlug(getPHStore(), getCurrentPathname());\n if (!driveSlug) return undefined;\n return { driveSlug, nodeSlug: nodeSlug || undefined };\n}\n\ntype NodeRef = Node | string | undefined;\n\nconst toSlug = (node: NodeRef) =>\n typeof node === \"string\" ? node : makeNodeSlug(node);\n\n/** Selects a node in `drive`, else in the app's open drive. */\nexport function selectNode(\n node: NodeRef,\n options?: PHNavigateOptions,\n drive?: DocumentDriveDocument,\n) {\n const nodeSlug = toSlug(node);\n // A host router resolves the node and writes the selection itself.\n if (!hasHostNavigation()) {\n setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n }\n const target = nodeTarget(nodeSlug, drive);\n if (target) openTarget(target, options);\n}\n\n/** Sets the selected node (file or folder) of the app's store; `search` sets\n * the params it opens with. Inside a drive app, use `useSetSelectedNode`. */\nexport function setSelectedNode(node: NodeRef, options?: PHNavigateOptions) {\n selectNode(node, options);\n}\n\nfunction findNode(\n drive: DocumentDriveDocument,\n node: NodeRef,\n store: PHStore | undefined,\n) {\n if (typeof node !== \"string\") return node;\n const id = extractNodeIdFromSlug(node);\n return id ? peekDriveNode(drive.header.id, id, store) : undefined;\n}\n\n/** Opens a node: through the drive app's `open` when it has one, else the\n * app's navigation in the drive app's drive. */\nexport function useSetSelectedNode() {\n const context = useDriveContext();\n const store = usePHStore() ?? getPHStore();\n return useCallback(\n (node: NodeRef, options?: PHNavigateOptions) => {\n if (context?.open) {\n context.open(findNode(context.drive, node, store), options);\n return;\n }\n selectNode(node, options, context?.drive);\n },\n [context, store],\n );\n}\n\n/** Opens a node, or with `undefined` its drive. */\nexport const useOpenNode: () => (\n node: Node | undefined,\n options?: PHNavigateOptions,\n) => void = useSetSelectedNode;\n\n/** Where a node of `drive`, else of the open drive, navigates to. */\nexport function getNodeTarget(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n return nodeTarget(makeNodeSlug(node), drive);\n}\n\n/** Where a node navigates to: in the drive app's drive, else the open drive. */\nexport function useNodeTarget(node: Node | undefined) {\n const context = useDriveContext();\n return getNodeTarget(node, context?.drive);\n}\n\n/** Warms a node's view before it is opened, e.g. on hover. */\nexport function preloadNode(\n node: Node | undefined,\n drive?: DocumentDriveDocument,\n) {\n if (!node) return;\n const target = nodeTarget(makeNodeSlug(node), drive);\n if (target) preloadTarget(target);\n}\n\n/** `preloadNode` through the drive app's `preload`, if it has one. */\nexport function usePreloadNode() {\n const context = useDriveContext();\n return useCallback(\n (node: Node | undefined) => {\n if (context?.preload) context.preload(node);\n else if (!context?.open) preloadNode(node, context?.drive);\n },\n [context],\n );\n}\n\nexport function addResetSelectedNodeEventHandler() {\n subscribeToPHValue(\"selectedDriveId\", () => {\n setSelectedNodeId(undefined);\n });\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport { useCallback } from \"react\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n findDriveBySlug,\n makeDriveSlug,\n} from \"../utils/url.js\";\nimport { isInitialSyncInFlight } from \"../routing/initial-sync.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDriveContext } from \"./drive-context.js\";\nimport { useDrives } from \"./drives.js\";\nimport {\n makePHEventFunctions,\n subscribeToPHValue,\n} from \"./make-ph-event-functions.js\";\nimport {\n getCurrentPathname,\n hasHostNavigation,\n openTarget,\n preloadTarget,\n} from \"./navigation.js\";\nimport { selectNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\nconst useStoreSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Returns the selected drive id: the drive app's drive, else the app's selection. */\nexport function useSelectedDriveId() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n return context ? context.drive.header.id : selectedDriveId;\n}\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id\n * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */\nexport const addSelectedDriveIdEventHandler =\n selectedDriveIdEventFunctions.addEventHandler;\n\n/** Returns the selected drive */\nexport function useSelectedDrive() {\n const drive = useSelectedDriveSafe();\n if (!drive[0]) {\n throw new Error(\n \"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\",\n );\n }\n\n return drive;\n}\n\n/** Returns the selected drive, or undefined if no drive is selected */\nexport function useSelectedDriveSafe() {\n const context = useDriveContext();\n const selectedDriveId = useStoreSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = context\n ? undefined\n : drives?.find((drive) => drive.header.id === selectedDriveId);\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (context) {\n return [context.drive, context.dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n }\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\ntype DriveRef = string | DocumentDriveDocument | undefined;\n\n/** Selects a drive in the app's store. */\nexport function setSelectedDrive(driveOrDriveSlug: DriveRef) {\n selectDrive(driveOrDriveSlug);\n}\n\n/** `setSelectedDrive`, as a hook. */\nexport function useSetSelectedDrive() {\n return useCallback((drive: DriveRef) => selectDrive(drive), []);\n}\n\n/** Selects a drive in the app's store. */\nexport function selectDrive(driveOrDriveSlug: DriveRef) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);\n\n // A host router resolves the drive and writes the selection itself.\n if (hasHostNavigation()) {\n cancelPendingDriveSelection();\n openTarget(driveSlug ? { driveSlug } : undefined);\n return;\n }\n\n // A full drive document is selected directly — a just-created drive\n // navigates before the collection refresh. Slugs go through the lookup.\n const drives = getPHStore()?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : findDriveBySlug(drives, driveSlug);\n const driveId = drive?.header.id;\n\n // Deprecated: hosts without a navigation only; route loaders wait for drives.\n // A deep link may predate remote drive registration, so defer the lookup.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(getCurrentPathname()) === driveSlug\n ) {\n // Clear the previous selection so a stale drive doesn't render against\n // the new URL; the selected node resets with it, the URL is untouched.\n if (getPHStore()?.selectedDriveId) {\n setSelectedDriveId(undefined);\n }\n deferDriveSelection(driveSlug);\n return;\n }\n\n // Any resolved selection supersedes a pending deferred lookup.\n cancelPendingDriveSelection();\n\n setSelectedDriveId(driveId);\n openTarget(driveId && driveSlug ? { driveSlug } : undefined);\n}\n\n/** Warms a drive's view before it is opened, e.g. on hover. */\nexport function preloadDrive(drive: DocumentDriveDocument | undefined) {\n if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });\n}\n\n/** `preloadDrive`, as a hook. */\nexport function usePreloadDrive() {\n return useCallback(\n (drive: DocumentDriveDocument | undefined) => preloadDrive(drive),\n [],\n );\n}\n\n// Tick between unresolved-slug checks; re-armed while a sync is in flight.\nconst DEFERRED_DRIVE_TICK_MS = 2_000;\n// Hard cap so a wedged remote can't pin the deep link forever.\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15_000;\n\nlet unsubscribePending: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (unsubscribePending) {\n unsubscribePending();\n unsubscribePending = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Deprecated with the no-navigation path: re-runs the slug lookup on drives\n// updates, restores the pinned node, and redirects home once syncs settle.\nfunction deferDriveSelection(driveSlug: string) {\n cancelPendingDriveSelection();\n\n // Capture the node pinned in the deep link before setSelectedDrive\n // rewrites the URL to /d/<driveSlug>, dropping the node segment.\n const nodeSlug = extractNodeSlugFromPath(getCurrentPathname());\n const handler = () => {\n const drive = findDriveBySlug(getPHStore()?.drives, driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n selectDrive(driveSlug);\n selectNode(nodeSlug);\n };\n unsubscribePending = subscribeToPHValue(\"drives\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n openTarget(undefined);\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n","import { getPHStore } from \"./ph-store.js\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n isDuplicateManifestError,\n isDuplicateModuleError,\n} from \"../reactor-interop.js\";\nimport type { IPackageManager } from \"../types/vetra.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst vetraPackageManagerFunctions = makePHEventFunctions(\n \"vetraPackageManager\",\n);\n\nexport const useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n\nconst EMPTY_VETRA_PACKAGES: DocumentModelLib[] = [];\nconst noPackageManagerUnsubscribe = () => {};\n\n/**\n * Returns all of the Vetra packages loaded by the Connect instance.\n *\n * The snapshot and subscription must keep stable identity while no package\n * manager is registered: `useSyncExternalStore` loops when the snapshot\n * changes on every read, which a fresh `[]` does.\n */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n getPackages,\n getPackages,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/**\n * Non-react access to the Vetra package manager: calls `callback` once a\n * manager is available - immediately when already set, otherwise when\n * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker\n * wiring uses this to forward package updates from plain boot code.\n */\nexport function onVetraPackageManager(\n callback: (packageManager: IPackageManager) => void,\n): () => void {\n let delivered: IPackageManager | undefined;\n const deliver = () => {\n const packageManager = vetraPackageManagerFunctions.getSnapshot();\n if (!packageManager || packageManager === delivered) return;\n delivered = packageManager;\n callback(packageManager);\n };\n const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);\n deliver();\n return unsubscribe;\n}\n\n/** Sets the Vetra package manager and registers its packages */\nexport function setVetraPackageManager(packageManager: IPackageManager) {\n vetraPackageManagerFunctions.setValue(packageManager);\n updateReactorClientDocumentModels(packageManager.packages);\n updateReactorClientUpgradeManifests(packageManager.packages);\n packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n updateReactorClientUpgradeManifests(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // dedupe by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n (m.version ?? 1) === (module.version ?? 1),\n ) === index,\n );\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n const results = registry.registerModules(...documentModelModules);\n const duplicateTypes = new Set<string>();\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateModuleError(result.error)) {\n duplicateTypes.add(result.item.documentModel.global.id);\n } else {\n console.error(\n \"Failed to register document model module:\",\n result.error,\n );\n }\n }\n }\n if (duplicateTypes.size > 0) {\n // unregisterModules is type-scoped, so replace the whole version family\n // with the incoming package's modules: re-registering only the duplicated\n // items would purge any new version that registered successfully above.\n registry.unregisterModules(...duplicateTypes);\n registry.registerModules(\n ...documentModelModules.filter((module) =>\n duplicateTypes.has(module.documentModel.global.id),\n ),\n );\n }\n}\n\nfunction updateReactorClientUpgradeManifests(packages: DocumentModelLib[]) {\n const upgradeManifests = packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter((u) => u !== undefined);\n\n const registry =\n getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || upgradeManifests.length === 0) return;\n\n const results = registry.registerUpgradeManifests(...upgradeManifests);\n const duplicates = [];\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateManifestError(result.error)) {\n duplicates.push(result);\n } else {\n console.error(\"Failed to register upgrade manifest:\", result.error);\n }\n }\n }\n if (duplicates.length > 0) {\n const duplicateTypes = duplicates\n .map((r) => r.item.documentType)\n .filter((t): t is string => !!t);\n registry.unregisterUpgradeManifests(...duplicateTypes);\n registry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n }\n}\n","import type { DocumentModelModule } from \"document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useDocumentModelModules(): DocumentModelModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n}\n\n/**\n * Resolves a document model module by document type, mirroring the registry's\n * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n * LATEST version of the type wins (`version ?? 1` as each module's default),\n * with `version` given only an exact match is returned. The reactor resolves\n * modules the same way when a document is created, so metadata read through\n * this hook and the version a creation actually uses cannot disagree.\n */\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n version?: number,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n if (!id || !documentModelModules) return undefined;\n\n let latestModule: DocumentModelModule | undefined;\n let latestVersion = -1;\n for (const module of documentModelModules) {\n if (module.documentModel.global.id !== id) continue;\n const moduleVersion = module.version ?? 1;\n if (version !== undefined) {\n if (moduleVersion === version) return module;\n continue;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n return latestModule;\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;CACA,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,SAAS,WAAW,CAAC,EAAE;CAC7B,IAAI,CAAC,QAAQ,MACX;CAGF,OAAO,OAAO,eAAe,EAAE,WAAW,6BAA6B,CAAC;AAC1E;;;;;;;;AASA,SAAgB,mBACd,eACoB;CACpB,OAAO,OAAO,WAAW;EACvB,MAAM,QAAQ,MAAM,cAAc;EAClC,IAAI,C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B,KAAK,MAAM,EAAE,KAAK,YAAY,CAAC,CAC/B,QAAQ,MAAmB,CAAC,CAAC,CAAC;EACjC,SAAS,2BAA2B,GAAG,cAAc;EACrD,SAAS,yBAAyB,GAAG,WAAW,KAAK,MAAM,EAAE,IAAI,CAAC;CACpE;AACF;;;AChJA,SAAgB,0BAA6D;CAE3E,OADsB,iBACH,CAAC,CACjB,SAAS,QAAQ,IAAI,cAAc,CAAC,CACpC,QACE,QAAQ,OAAO,YAEd,QAAQ,WACL,MACC,EAAE,cAAc,OAAO,OAAO,OAAO,cAAc,OAAO,MAC1D,EAAE,YAAY,OAAO,OACzB,MAAM,KACV;AACJ;;;;;;;;;AAUA,SAAgB,2BACd,IACA,SACiC;CACjC,MAAM,uBAAuB,wBAAwB;CACrD,IAAI,CAAC,MAAM,CAAC,sBAAsB,OAAO,KAAA;CAEzC,IAAI;CACJ,IAAI,gBAAgB;CACpB,KAAK,MAAM,UAAU,sBAAsB;EACzC,IAAI,OAAO,cAAc,OAAO,OAAO,IAAI;EAC3C,MAAM,gBAAgB,OAAO,WAAW;EACxC,IAAI,YAAY,KAAA,GAAW;GACzB,IAAI,kBAAkB,SAAS,OAAO;GACtC;EACF;EACA,IAAI,gBAAgB,eAAe;GACjC,gBAAgB;GAChB,eAAe;EACjB;CACF;CACA,OAAO;AACT"}
@@ -1,13 +1,12 @@
1
1
  import { c as getPHStore, f as usePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
2
  import { A as DocumentModelNotFoundError, D as queueActions, O as queueOperations, P as UnsupportedDocumentTypeError, b as DOCUMENT_CHANGE_TYPE, f as DocumentCache, h as IDLE_OPERATIONS_ENTRY, i as setDocumentCache, k as uploadOperations, o as useDocumentCache, r as addDocumentCacheEventHandler, v as isOperationCache } from "./dispatch-Cylwl2Dk.js";
3
- import { $ as makeAuthMiddleware, A as addDrivesEventHandler, B as invalidateDriveNodes, H as markLocalDriveWrite, L as addDriveNodesEventHandler, Q as ambientRenownTokenProvider, R as dropDriveNode, X as listAllDriveNodes, a as setVetraPackageManager, c as addSelectedDriveIdEventHandler, f as setSelectedDriveId, h as useSelectedDriveId, r as addVetraPackageManagerEventHandler, u as selectDrive, v as addResetSelectedNodeEventHandler, w as setSelectedNodeId, y as addSelectedNodeIdEventHandler, z as getDriveNode } from "./document-model-modules-D-VXC3ET.js";
4
- import { A as extractNodeIdFromSlug, N as findDriveBySlug, O as extractDriveSlugFromPath, S as setBrowserOpenSync, c as getCurrentPathname, d as hasHostNavigation, h as openTargetWith, j as extractNodeSlugFromPath, l as getPHNavigation, m as openTarget, v as recordToSearch, w as targetPathname, x as searchToRecord } from "./navigation-BqphkrOB.js";
5
- import { a as PhDocumentFieldsFragmentDoc, i as JobChangesDocument, n as DocumentChangesDocument, t as createClient$1 } from "./client-BUpynoY6.js";
6
- import { f as addLoadingEventHandler, t as addRenownEventHandler } from "./renown-BxkZYzbQ.js";
3
+ import { $ as makeAuthMiddleware, A as addDrivesEventHandler, B as invalidateDriveNodes, H as markLocalDriveWrite, L as addDriveNodesEventHandler, Q as ambientRenownTokenProvider, R as dropDriveNode, X as listAllDriveNodes, a as setVetraPackageManager, c as addSelectedDriveIdEventHandler, f as setSelectedDriveId, h as useSelectedDriveId, r as addVetraPackageManagerEventHandler, u as selectDrive, v as addResetSelectedNodeEventHandler, w as setSelectedNodeId, y as addSelectedNodeIdEventHandler, z as getDriveNode } from "./document-model-modules-ChmfyIxT.js";
4
+ import { A as openTargetWith, C as getCurrentPathname, E as hasHostNavigation, G as extractNodeIdFromSlug, I as searchToRecord, J as findDriveBySlug, K as extractNodeSlugFromPath, L as setBrowserOpenSync, N as recordToSearch, U as extractDriveSlugFromPath, f as addLoadingEventHandler, k as openTarget, t as addRenownEventHandler, w as getPHNavigation, z as targetPathname } from "./renown-CBoTdGrg.js";
5
+ import { a as PhDocumentFieldsFragmentDoc, i as JobChangesDocument, n as DocumentChangesDocument, t as createClient$1 } from "./client-BNMyQ_Z2.js";
7
6
  import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
8
7
  import { Fragment, jsx } from "react/jsx-runtime";
9
8
  import { logger } from "document-model";
10
- import { PEER_CAPABILITIES, UnsupportedDocumentModelVersionError, actionSignerIdentity, actionSigningTarget, actions, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, capSelection, createCopyHeader, createPresignedHeader, createZip, creationState, deserializeSignature, documentModelDocumentType, generateId, hasDerivedDocumentId, hashDocumentStateForScope, headNewDocument, isSignaturePolicy, localSupports, normalizeDocumentModelVersion, replayDocumentVersioned, selectDocumentModelModule, setName, setPreferredEditor, signaturePolicyOf, toTransportAction, withSignaturePolicy } from "@powerhousedao/shared/document-model";
9
+ import { PEER_CAPABILITIES, UnsupportedDocumentModelVersionError, actionSignerIdentity, actionSigningTarget, actions, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, capSelection, capabilitiesOf, createCopyHeader, createPresignedHeader, createZip, creationState, deserializeSignature, documentModelDocumentType, generateId, hasDerivedDocumentId, hashDocumentStateForScope, headNewDocument, isSignaturePolicy, localSupports, normalizeDocumentModelVersion, optionalBaseReducerCapabilities, replayDocumentVersioned, selectDocumentModelModule, serializeByKey, setName, setPreferredEditor, signaturePolicyOf, toTransportAction, undoCapabilitiesOf, undoNeedsTargets, undoRedoActions, undoRedoAvailabilityOf, withSignaturePolicy } from "@powerhousedao/shared/document-model";
11
10
  import { addFolder, copyNode, driveDocumentModelModule, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
12
11
  import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
13
12
  import { gql } from "graphql-tag";
@@ -1599,7 +1598,8 @@ function snapshotTarget(action, snapshot) {
1599
1598
  *
1600
1599
  * `UNDO` and `REDO` rewrite history the light read path never fetched (and
1601
1600
  * the reducer appends no operation for them); `NOOP` is only ever produced
1602
- * by an undo chain; the document-scope actions run through the reactor's
1601
+ * by an undo chain; a `RETRACT` names a target in that unfetched history; the
1602
+ * document-scope actions run through the reactor's
1603
1603
  * document-action handler rather than a document-model reducer
1604
1604
  * (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
1605
1605
  * `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.
@@ -1608,6 +1608,7 @@ const unsupportedBatchActions = /* @__PURE__ */ new Set([
1608
1608
  "UNDO",
1609
1609
  "REDO",
1610
1610
  "NOOP",
1611
+ "RETRACT",
1611
1612
  "CREATE_DOCUMENT",
1612
1613
  "DELETE_DOCUMENT",
1613
1614
  "UPGRADE_DOCUMENT",
@@ -1622,8 +1623,8 @@ const unsupportedBatchActions = /* @__PURE__ */ new Set([
1622
1623
  * `baseReducer` reads `baseReducerVersion(document.header)` for every action and
1623
1624
  * throws when the header has no `protocolVersions`, which a header built by
1624
1625
  * {@link phDocumentFromGetDocument} lacks when the server sends none. The
1625
- * version only selects between the v1
1626
- * and v2 UNDO/NOOP branches, and every action reaching the prediction loop is an
1626
+ * version only selects how UNDO, REDO and RETRACT apply, and every action
1627
+ * reaching the prediction loop is an
1627
1628
  * ordinary append-only one, so it cannot change the predicted state here; it is
1628
1629
  * passed purely so the lookup does not throw.
1629
1630
  */
@@ -1670,7 +1671,7 @@ async function prepareSignedActions(actions, snapshot, signer, module, signal) {
1670
1671
  const before = scopeOperationCount(working, scope);
1671
1672
  let next;
1672
1673
  try {
1673
- next = module.reducer(working, signedAction, void 0, { protocolVersion: working.header.protocolVersions?.["base-reducer"] ?? predictionProtocolVersion });
1674
+ next = module.reducer(working, signedAction, void 0, { protocolVersion: optionalBaseReducerCapabilities(working.header)?.version ?? predictionProtocolVersion });
1674
1675
  } catch (error) {
1675
1676
  throw new Error(`cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`, { cause: error });
1676
1677
  }
@@ -2218,6 +2219,7 @@ var GraphQLReactorClient = class {
2218
2219
  documentModels;
2219
2220
  resolveSigner;
2220
2221
  driveIdFor;
2222
+ undoRedoChains = /* @__PURE__ */ new Map();
2221
2223
  stopRealtime;
2222
2224
  realtimeStarted = false;
2223
2225
  realtimeGeneration = 0;
@@ -2537,6 +2539,79 @@ var GraphQLReactorClient = class {
2537
2539
  return updated;
2538
2540
  }
2539
2541
  /**
2542
+ * Undoes the last applied operation of `scope` under this client's own
2543
+ * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
2544
+ * Switchboard resolves with {@link undoRedoTargets}. One at a time per
2545
+ * document, scope and branch. A stale target is refused, not re-resolved.
2546
+ */
2547
+ undo(documentIdentifier, scope = "global", branch = "main", signal) {
2548
+ return this.undoOrRedo("UNDO", documentIdentifier, scope, branch, signal);
2549
+ }
2550
+ /** Redoes the last undo of `scope`; see {@link undo}. */
2551
+ redo(documentIdentifier, scope = "global", branch = "main", signal) {
2552
+ return this.undoOrRedo("REDO", documentIdentifier, scope, branch, signal);
2553
+ }
2554
+ /** Exact on base-reducer 3, from the targets the Switchboard resolves. */
2555
+ async undoRedoAvailability(documentIdentifier, scope = "global", branch = "main", signal) {
2556
+ const { caps, header } = await this.undoCapabilities(documentIdentifier, branch, signal);
2557
+ const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
2558
+ return undoRedoAvailabilityOf(caps, targets, header.revision[scope] ?? 0, true);
2559
+ }
2560
+ /**
2561
+ * The rows a base-reducer 3 undo and redo would retract, resolved by the
2562
+ * Switchboard as the caller. A Switchboard without the query is refused
2563
+ * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
2564
+ * sent: the Switchboard reads the caller from the bearer.
2565
+ */
2566
+ async undoRedoTargets(documentIdentifier, scope = "global", view, signal) {
2567
+ try {
2568
+ const { undoRedoTargets } = await this.sdk.GetUndoRedoTargets({
2569
+ documentIdOrSlug: documentIdentifier,
2570
+ scope,
2571
+ branch: view?.branch
2572
+ }, void 0, signal);
2573
+ return {
2574
+ ...undoRedoTargets.undoTarget ? { undoTarget: undoRedoTargets.undoTarget } : {},
2575
+ ...undoRedoTargets.redoTarget ? { redoTarget: undoRedoTargets.redoTarget } : {}
2576
+ };
2577
+ } catch (error) {
2578
+ if (queriesUnknownField(error, "undoRedoTargets")) throw new GraphQLOperationNotSupportedError("undoRedoTargets", "the Switchboard predates the undoRedoTargets query");
2579
+ throw error;
2580
+ }
2581
+ }
2582
+ undoOrRedo(type, documentIdentifier, scope, branch, signal) {
2583
+ return serializeByKey(this.undoRedoChains, JSON.stringify([
2584
+ documentIdentifier,
2585
+ scope,
2586
+ branch
2587
+ ]), async () => {
2588
+ const { caps } = await this.undoCapabilities(documentIdentifier, branch, signal);
2589
+ const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
2590
+ return this.execute(documentIdentifier, branch, undoRedoActions(caps, type, scope, targets), signal);
2591
+ });
2592
+ }
2593
+ /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
2594
+ async undoCapabilities(documentIdentifier, branch, signal) {
2595
+ const { header } = await this.get(documentIdentifier, { branch }, signal);
2596
+ const fromHeader = optionalBaseReducerCapabilities(header);
2597
+ if (fromHeader) return {
2598
+ caps: fromHeader,
2599
+ header
2600
+ };
2601
+ const create = (await this.getOperations(documentIdentifier, {
2602
+ branch,
2603
+ scopes: ["document"]
2604
+ }, void 0, {
2605
+ cursor: "0",
2606
+ limit: 1
2607
+ }, signal)).results.at(0)?.action;
2608
+ const input = create?.type === "CREATE_DOCUMENT" ? create.input : void 0;
2609
+ return {
2610
+ caps: undoCapabilitiesOf(header, input) ?? capabilitiesOf(1),
2611
+ header
2612
+ };
2613
+ }
2614
+ /**
2540
2615
  * Runs multiple mutation jobs in dependency order over the Switchboard's
2541
2616
  * `executeBatch` mutation and waits for all to settle, returning the result
2542
2617
  * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
@@ -4113,7 +4188,8 @@ const phGlobalEventHandlerRegisterFunctions = {
4113
4188
  isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
4114
4189
  isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
4115
4190
  toast: addToastEventHandler,
4116
- navigation: () => {}
4191
+ navigation: () => {},
4192
+ aiTools: () => {}
4117
4193
  };
4118
4194
  function addPHEventHandlers() {
4119
4195
  callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
@@ -4214,6 +4290,16 @@ const DEFAULT_BREAKER = Object.freeze({
4214
4290
  failures: 3,
4215
4291
  openMs: 3e4
4216
4292
  });
4293
+ function breakerSettings(breaker) {
4294
+ if (breaker === false) return {
4295
+ failures: Infinity,
4296
+ openMs: 0
4297
+ };
4298
+ return {
4299
+ ...DEFAULT_BREAKER,
4300
+ ...breaker
4301
+ };
4302
+ }
4217
4303
  const FACTS_QUERY = `
4218
4304
  query SwitchboardFacts {
4219
4305
  inspection {
@@ -4376,7 +4462,7 @@ function isUnknownJob(job) {
4376
4462
  /** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
4377
4463
  function createSwitchboardBackend(descriptor) {
4378
4464
  const drives = new KnownDrives();
4379
- const breaker = new Breaker(descriptor.name, descriptor.breaker ?? DEFAULT_BREAKER);
4465
+ const breaker = new Breaker(descriptor.name, breakerSettings(descriptor.breaker));
4380
4466
  const signer = descriptor.signer;
4381
4467
  const gql = new GraphQLReactorClient({
4382
4468
  url: descriptor.url,
@@ -4416,7 +4502,11 @@ function createSwitchboardBackend(descriptor) {
4416
4502
  const job = await gql.getJob(jobId, signal);
4417
4503
  return job && isUnknownJob(job) ? void 0 : job;
4418
4504
  },
4419
- waitForJob: (job, signal) => gql.waitForJob(job, signal)
4505
+ waitForJob: (job, signal) => gql.waitForJob(job, signal),
4506
+ undo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.undo(identifier, scope, branch, signal))),
4507
+ redo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.redo(identifier, scope, branch, signal))),
4508
+ undoRedoTargets: (identifier, scope, view, signal) => gql.undoRedoTargets(identifier, scope, view, signal),
4509
+ undoRedoAvailability: (identifier, scope, branch, signal) => gql.undoRedoAvailability(identifier, scope, branch, signal)
4420
4510
  };
4421
4511
  let reading;
4422
4512
  const read = () => reading ??= readFacts(gql, descriptor.url).finally(() => {
@@ -4546,4 +4636,4 @@ function useDocumentOperations(documentId, scope, options = {}) {
4546
4636
  //#endregion
4547
4637
  export { addIsAddLocalDrivesEnabledEventHandler as $, deleteNode as $i, useIsDeletePublicDrivesEnabled as $n, viewFilterInputFromViewFilter as $r, setIsAnalyticsEnabled as $t, useGraphQLReactorClient as A, closePHModal as Aa, phDocumentFromMutation as Ai, setVersion as An, addIsExternalControlsEnabledEventHandler as Ar, addSentryReleaseEventHandler as At, useAttachmentService as B, usePHModal as Ba, COMMON_PACKAGE_ID as Bi, useEnabledEditors as Bn, useIsDragAndDropEnabled as Br, setBasePath as Bt, addSyncSelectionOnPopStateEventHandler as C, useReactorClient as Ca, withRequestDeadline as Ci, setRequiresHardRefresh as Cn, useStudioMode as Cr, addRenownChainIdEventHandler as Ct, usePackageDiscoveryService as D, useSyncList as Da, toLegacyNode as Di, setSentryRelease as Dn, useWarnOutdatedApp as Dr, addRouterBasenameEventHandler as Dt, setPackageDiscoveryService as E, useSync as Ea, GraphQLDriveReadClient as Ei, setSentryEnv as En, useVersionCheckInterval as Er, addRequiresHardRefreshEventHandler as Et, addFeaturesEventHandler as F, setPHModal as Fa, extractRevisionMap as Fi, useBasePath as Fn, phDocumentEditorConfigSetters as Fr, addWarnOutdatedAppEventHandler as Ft, addDefaultDrivesUrlEventHandler as G, useSearchParams as Ga, GraphQLWrongBackendError as Gi, useIsAddLocalDrivesEnabled as Gn, recordBackendAuthError as Gr, setEnabledEditors as Gt, addAnalyticsDatabaseNameEventHandler as H, isPlainClick as Ha, DRIVE_DOCUMENT_TYPES as Hi, useGaTrackingId as Hn, addBackendAuthEventHandler as Hr, setDefaultDrivesUrl as Ht, setFeatures as I, showCreateDocumentModal as Ia, hasRevisionConflict as Ii, useCliVersion as In, setAllowedDocumentTypes as Ir, phGlobalConfigHooks as It, addEnabledEditorsEventHandler as J, queriesUnknownField as Ji, useIsAnalyticsEnabled as Jn, GraphQLReactorClient as Jr, setIsAddCloudDrivesEnabled as Jt, addDisabledEditorsEventHandler as K, useSetSearchParams as Ka, JobFailedError as Ki, useIsAddPublicDrivesEnabled as Kn, setBackendAuth as Kr, setFileUploadOperationsChunkSize as Kt, useFeatures as L, showDeleteNodeModal as La, screamingSnakeToCamel as Li, useDefaultDrivesUrl as Ln, setIsDragAndDropEnabled as Lr, phGlobalConfigSetters as Lt, useDragNode as M, modalFromSearch as Ma, ConflictError as Mi, setWarnOutdatedApp as Mn, phAppConfigHooks as Mr, addSwitchboardUrlEventHandler as Mt, useDropNode as N, modalHref as Na, buildPulledDocument as Ni, useAllowList as Nn, phAppConfigSetters as Nr, addVersionCheckIntervalEventHandler as Nt, addGraphQLReactorClientEventHandler as O, MODAL_SEARCH_PARAM as Oa, isoStringFromDateTime as Oi, setStudioMode as On, addAllowedDocumentTypesEventHandler as Or, addSentryDsnEventHandler as Ot, useDropTarget as P, modalSearch as Pa, convertRemoteOperations as Pi, useAnalyticsDatabaseName as Pn, phDocumentEditorConfigHooks as Pr, addVersionEventHandler as Pt, addIsAddDriveEnabledEventHandler as Q, copyNode$1 as Qi, useIsDeleteLocalDrivesEnabled as Qn, isGraphQLReactorClient as Qr, setIsAnalyticsDatabaseWorkerEnabled as Qt, addAttachmentServiceEventHandler as R, showPHModal as Ra, uncreatedDocument as Ri, useDisabledEditors as Rn, setIsExternalControlsEnabled as Rr, setAllowList as Rt, addSetSelectedNodeOnPopStateEventHandler as S, usePGlite as Sa, switchboardFetch as Si, setRenownUrl as Sn, useSentryRelease as Sr, addRenownAdaptersEventHandler as St, addPackageDiscoveryServiceEventHandler as T, useReactorHalves as Ta, GraphQLDriveNodeSource as Ti, setSentryDsn as Tn, useVersion as Tr, addRenownUrlEventHandler as Tt, addBasePathEventHandler as U, useLinkProps as Ua, BatchJobFailedError as Ui, useIsAddCloudDrivesEnabled as Un, backendAuthStatusOf as Ur, setDisabledEditors as Ut, addAllowListEventHandler as V, withoutModalSearch as Va, DEFAULT_DRIVE_EDITOR_ID as Vi, useFileUploadOperationsChunkSize as Vn, useIsExternalControlsEnabled as Vr, setCliVersion as Vt, addCliVersionEventHandler as W, usePHNavigation as Wa, GraphQLOperationNotSupportedError as Wi, useIsAddDriveEnabled as Wn, isBackendAuthError as Wr, setDrivesPreserveStrategy as Wt, addGaTrackingIdEventHandler as X, addFileWithProgress as Xi, useIsCloudDrivesEnabled as Xn, createGraphQLDriveNodeSource as Xr, setIsAddLocalDrivesEnabled as Xt, addFileUploadOperationsChunkSizeEventHandler as Y, addDocument as Yi, useIsAnalyticsExternalProcessorsEnabled as Yn, ambientRenownSigner as Yr, setIsAddDriveEnabled as Yt, addIsAddCloudDrivesEnabledEventHandler as Z, addFolder$1 as Zi, useIsDeleteCloudDrivesEnabled as Zn, findIsServableOverGraphQL as Zr, setIsAddPublicDrivesEnabled as Zt, useSelectedTimelineRevision as _, setFullReactorClient as _a, readCreateProtocolVersions as _i, setLocalDrivesEnabled as _n, useRenownUrl as _r, addIsPublicDrivesEnabledEventHandler as _t, createSwitchboardBackend as a, moveNode$1 as aa, SubgraphSdkRegistry as ai, setIsDiffAnalyticsEnabled as an, useIsExternalPackagesEnabled as ar, addIsDeleteCloudDrivesEnabledEventHandler as at, useSelectedTimelineItem as b, useDatabase as ba, isDeadlineError as bi, setRenownChainId as bn, useSentryDsn as br, addLocalDrivesEnabledEventHandler as bt, useSwitchboardClient as c, setPreferredEditorOnNode as ca, StaticPackageManager as ci, setIsEditorDebugModeEnabled as cn, useIsLocalDrivesEnabled as cr, addIsDiffAnalyticsEnabledEventHandler as ct, commonGlobalEventHandlerFunctions as d, isDocumentTypeSupported as da, prepareSignedActions as di, setIsExternalProcessorsEnabled as dn, useIsSentryTracingEnabled as dr, addIsEditorDebugModeEnabledEventHandler as dt, exportFile as ea, createJobChangesSocket as ei, setIsAnalyticsExternalProcessorsEnabled as en, useIsDiffAnalyticsEnabled as er, addIsAddPublicDrivesEnabledEventHandler as et, addToastEventHandler as f, addFullReactorClientEventHandler as fa, signStampedAction as fi, setIsExternalRelationalProcessorsEnabled as fn, useLocalDrivesEnabled as fr, addIsEditorReadModeEnabledEventHandler as ft, setSelectedTimelineRevision as g, getFullReactorClient as ga, ReactorOperationFieldsFragmentDoc as gi, setIsSentryTracingEnabled as gn, useRenownNetworkId as gr, addIsLocalDrivesEnabledEventHandler as gt, addSelectedTimelineRevisionEventHandler as h, addReactorHalvesEventHandler as ha, MutateDocumentWithOperationsDocument as hi, setIsRelationalProcessorsEnabled as hn, useRenownChainId as hr, addIsExternalRelationalProcessorsEnabledEventHandler as ht, SwitchboardUnreachableError as i, loadFile as ia, subscriptionsUrlFromGraphqlUrl as ii, setIsDeletePublicDrivesEnabled as in, useIsEditorReadModeEnabled as ir, addIsCloudDrivesEnabledEventHandler as it, addDraggingNodeEventHandler as j, isRoutedModal as ja, revisionMapFromRevisionsList as ji, setVersionCheckInterval as jn, isExternalControlsEnabledEventFunctions as jr, addStudioModeEventHandler as jt, setGraphQLReactorClient as k, addModalEventHandler as ka, phDocumentFromGetDocument as ki, setSwitchboardUrl as kn, addIsDragAndDropEnabledEventHandler as kr, addSentryEnvEventHandler as kt, addPHEventHandlers as l, upgradeDocument as la, packageFromDocumentModels as li, setIsEditorReadModeEnabled as ln, useIsPublicDrivesEnabled as lr, addIsDocumentModelSelectionSettingsEnabledEventHandler as lt, usePHToast as m, addReactorClientModuleEventHandler as ma, GetDocumentAtConsistencyDocument as mi, setIsPublicDrivesEnabled as mn, useRenownAdapters as mr, addIsExternalProcessorsEnabledEventHandler as mt, DEFAULT_BREAKER as n, fetchDocumentOperations as na, makeAuthConnectionParams as ni, setIsDeleteCloudDrivesEnabled as nn, useIsDriveAnalyticsEnabled as nr, addIsAnalyticsEnabledEventHandler as nt, GraphQLReactorProvider as o, renameDriveNode as oa, describeGraphQLDocument as oi, setIsDocumentModelSelectionSettingsEnabled as on, useIsExternalProcessorsEnabled as or, addIsDeleteLocalDrivesEnabledEventHandler as ot, setPHToast as p, addReactorClientEventHandler as pa, stampAction as pi, setIsLocalDrivesEnabled as pn, useLogLevel as pr, addIsExternalPackagesEnabledEventHandler as pt, addDrivesPreserveStrategyEventHandler as q, queriesUnknownArgument as qi, useIsAnalyticsDatabaseWorkerEnabled as qn, useBackendAuth as qr, setGaTrackingId as qt, DEFAULT_REQUEST_TIMEOUT_MS as r, getDocumentExtension as ra, startDocumentChangesSubscription as ri, setIsDeleteLocalDrivesEnabled as rn, useIsEditorDebugModeEnabled as rr, addIsAnalyticsExternalProcessorsEnabledEventHandler as rt, ensurePHEventHandlers as s, renameNode as sa, subgraphUrlFromGraphqlUrl as si, setIsDriveAnalyticsEnabled as sn, useIsExternalRelationalProcessorsEnabled as sr, addIsDeletePublicDrivesEnabledEventHandler as st, useDocumentOperations as t, extractInitialState as ta, isAuthRefusalClose as ti, setIsCloudDrivesEnabled as tn, useIsDocumentModelSelectionSettingsEnabled as tr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as tt, callEventHandlerRegisterFunctions as u, getUserPermissions as ua, resolveDocumentModelModule as ui, setIsExternalPackagesEnabled as un, useIsRelationalProcessorsEnabled as ur, addIsDriveAnalyticsEnabledEventHandler as ut, addSelectedTimelineItemEventHandler as v, setReactorClient as va, readCreateSignaturePolicy as vi, setLogLevel as vn, useRequiresHardRefresh as vr, addIsRelationalProcessorsEnabledEventHandler as vt, syncSelectionFromPath as w, useReactorClientModule as wa, withStreamedBodies as wi, setRouterBasename as wn, useSwitchboardUrl as wr, addRenownNetworkIdEventHandler as wt, addSetSelectedDriveOnPopStateEventHandler as x, useModelRegistry as xa, isNodeFetch as xi, setRenownNetworkId as xn, useSentryEnv as xr, addLogLevelEventHandler as xt, setSelectedTimelineItem as y, setReactorClientModule as ya, globalFetch as yi, setRenownAdapters as yn, useRouterBasename as yr, addIsSentryTracingEnabledEventHandler as yt, setAttachmentService as z, useModalLinkProps as za, underSignaturePolicy as zi, useDrivesPreserveStrategy as zn, useAllowedDocumentTypes as zr, setAnalyticsDatabaseName as zt };
4548
4638
 
4549
- //# sourceMappingURL=document-operations-CsiIPsx9.js.map
4639
+ //# sourceMappingURL=document-operations-DCwmgcLe.js.map