@powerhousedao/connect-core 6.4.0-next.2 → 6.4.0-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{backend-auth-gate-DNKg_v4Y.js → backend-auth-gate-CZgrKCSF.js} +4 -2
- package/dist/backend-auth-gate-CZgrKCSF.js.map +1 -0
- package/dist/{backend-auth-gate-DiFpY5rt.d.ts → backend-auth-gate-DZJTO3Sb.d.ts} +6 -3
- package/dist/backend-auth-gate-DZJTO3Sb.d.ts.map +1 -0
- package/dist/{connect-router-P44ov38H.d.ts → connect-router-BzqhC9kH.d.ts} +8 -2
- package/dist/{connect-router-P44ov38H.d.ts.map → connect-router-BzqhC9kH.d.ts.map} +1 -1
- package/dist/{index-12S96gPF.d.ts → index-BOGt2DKP.d.ts} +2 -2
- package/dist/{index-12S96gPF.d.ts.map → index-BOGt2DKP.d.ts.map} +1 -1
- package/dist/{index-CXPPPM8r.d.ts → index-CFPU-wyN.d.ts} +2 -2
- package/dist/{index-CXPPPM8r.d.ts.map → index-CFPU-wyN.d.ts.map} +1 -1
- package/dist/{index-Beqvfchq.d.ts → index-COMeKF-S.d.ts} +6 -3
- package/dist/index-COMeKF-S.d.ts.map +1 -0
- package/dist/{index-NmWuyjQT.d.ts → index-CSSK3luV.d.ts} +2 -2
- package/dist/{index-NmWuyjQT.d.ts.map → index-CSSK3luV.d.ts.map} +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +9 -9
- package/dist/{multi-reactor-D5r70cL2.js → multi-reactor-BLu7TBTr.js} +2 -2
- package/dist/{multi-reactor-D5r70cL2.js.map → multi-reactor-BLu7TBTr.js.map} +1 -1
- package/dist/{plugin-host-CaTO1tq-.js → plugin-host-D6GSDZsy.js} +2 -2
- package/dist/{plugin-host-CaTO1tq-.js.map → plugin-host-D6GSDZsy.js.map} +1 -1
- package/dist/{plugin-ui-Cvd3Kpgb.js → plugin-ui-BPhSLN0f.js} +4 -4
- package/dist/{plugin-ui-Cvd3Kpgb.js.map → plugin-ui-BPhSLN0f.js.map} +1 -1
- package/dist/plugins.d.ts +2 -2
- package/dist/plugins.js +2 -2
- package/dist/{route-tree-D0aszMrk.js → route-tree-Cth194sC.js} +12 -3
- package/dist/route-tree-Cth194sC.js.map +1 -0
- package/dist/route-tree.d.ts +1 -1
- package/dist/{router-R54qCm4H.js → router-B3Rus6QT.js} +4 -4
- package/dist/{router-R54qCm4H.js.map → router-B3Rus6QT.js.map} +1 -1
- package/dist/router.d.ts +3 -3
- package/dist/router.js +5 -5
- package/dist/{runtime-DV6oRJYU.js → runtime-BhFI4kFP.js} +3 -3
- package/dist/{runtime-DV6oRJYU.js.map → runtime-BhFI4kFP.js.map} +1 -1
- package/dist/{runtime-config-BdPf1LSz.d.ts → runtime-config-bFOaAulk.d.ts} +2 -2
- package/dist/{runtime-config-BdPf1LSz.d.ts.map → runtime-config-bFOaAulk.d.ts.map} +1 -1
- package/dist/runtime-config.d.ts +1 -1
- package/dist/runtime-config.js +3 -3
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +2 -2
- package/dist/{sidebar-C2y4mZnX.js → sidebar-CbMDUc8H.js} +2 -2
- package/dist/{sidebar-C2y4mZnX.js.map → sidebar-CbMDUc8H.js.map} +1 -1
- package/dist/{views-LyRJcSKu.js → views-DnC_AzYO.js} +154 -9
- package/dist/views-DnC_AzYO.js.map +1 -0
- package/dist/views.d.ts +2 -2
- package/dist/views.js +2 -2
- package/package.json +9 -9
- package/src/router/index.ts +1 -0
- package/src/router/route-tree.ts +17 -2
- package/src/runtime/backend-auth-gate.ts +13 -2
- package/src/views/backend-auth-gate.tsx +151 -4
- package/dist/backend-auth-gate-DNKg_v4Y.js.map +0 -1
- package/dist/backend-auth-gate-DiFpY5rt.d.ts.map +0 -1
- package/dist/index-Beqvfchq.d.ts.map +0 -1
- package/dist/route-tree-D0aszMrk.js.map +0 -1
- package/dist/views-LyRJcSKu.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-DV6oRJYU.js","names":[],"sources":["../src/runtime/runtime-flag.ts","../src/runtime/multi-reactor-flag.ts","../src/runtime/reactor-worker-flag.ts","../src/runtime/reactor-client-mode.ts","../src/runtime/app-reactor-client.ts","../src/runtime/new-drive.ts","../src/runtime/drive-placement.ts","../src/runtime/drive-placements.ts","../src/runtime/ph-store.ts","../src/runtime/local-package.ts"],"sourcesContent":["export type RuntimeFlagInput = {\n configFlag: boolean;\n queryParam?: string | null;\n storedValue?: string | null;\n};\n\n// A query-param override wins, then a stored dev override, then the config flag.\nexport function resolveRuntimeFlag(input: RuntimeFlagInput): boolean {\n const fromQuery = parseFlag(input.queryParam);\n if (fromQuery !== undefined) {\n return fromQuery;\n }\n const fromStore = parseFlag(input.storedValue);\n if (fromStore !== undefined) {\n return fromStore;\n }\n return input.configFlag;\n}\n\nexport type RuntimeFlagKeys = {\n queryKey: string;\n storageKey: string;\n readConfigFlag: () => boolean;\n};\n\n// Effective flag from config + dev override; a query-param override is persisted\n// to localStorage so it survives a refresh. Blocked storage reads as no override.\nexport function isRuntimeFlagEnabled(keys: RuntimeFlagKeys): boolean {\n const configFlag = keys.readConfigFlag();\n if (typeof window === \"undefined\") {\n return configFlag;\n }\n const queryParam = new URLSearchParams(window.location.search).get(\n keys.queryKey,\n );\n const storedValue = readStoredValue(keys.storageKey);\n const enabled = resolveRuntimeFlag({ configFlag, queryParam, storedValue });\n // Persist only an explicit override, not an unrecognized value.\n if (parseFlag(queryParam) !== undefined) {\n persistStoredValue(keys.storageKey, enabled);\n }\n return enabled;\n}\n\nfunction readStoredValue(storageKey: string): string | null {\n try {\n return window.localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\nfunction persistStoredValue(storageKey: string, enabled: boolean): void {\n try {\n window.localStorage.setItem(storageKey, enabled ? \"true\" : \"false\");\n } catch {\n // The override still applies for this page load.\n }\n}\n\nfunction parseFlag(value: string | null | undefined): boolean | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"true\" || normalized === \"1\") {\n return true;\n }\n if (normalized === \"false\" || normalized === \"0\") {\n return false;\n }\n // Unrecognized value (e.g. a typo): no override, fall through to store/config.\n return undefined;\n}\n","import { getRuntimeConfig } from \"./runtime-config.js\";\n\n// Config only: the flag is in the worker fingerprint, so a per-tab value would split tabs.\nexport function isMultiReactorEnabled(): boolean {\n return getRuntimeConfig().connect.instance?.multiReactor ?? false;\n}\n","import { getRuntimeConfig } from \"./runtime-config.js\";\nimport {\n isRuntimeFlagEnabled,\n resolveRuntimeFlag,\n type RuntimeFlagInput,\n} from \"./runtime-flag.js\";\n\nexport const REACTOR_WORKER_QUERY_KEY = \"reactorWorker\";\nexport const REACTOR_WORKER_STORAGE_KEY = \"ph:reactorWorker\";\n\nexport type ReactorWorkerFlagInput = RuntimeFlagInput;\n\nexport function resolveReactorWorkerEnabled(\n input: ReactorWorkerFlagInput,\n): boolean {\n return resolveRuntimeFlag(input);\n}\n\nexport function isReactorWorkerEnabled(): boolean {\n return isRuntimeFlagEnabled({\n queryKey: REACTOR_WORKER_QUERY_KEY,\n storageKey: REACTOR_WORKER_STORAGE_KEY,\n readConfigFlag: () =>\n getRuntimeConfig().connect.instance?.reactorWorker ?? false,\n });\n}\n","import type { PHReactorClientMode } from \"@powerhousedao/shared/clis\";\nimport { getRuntimeConfig } from \"./runtime-config.js\";\nimport { isMultiReactorEnabled } from \"./multi-reactor-flag.js\";\nimport { isReactorWorkerEnabled } from \"./reactor-worker-flag.js\";\nimport { logger } from \"document-model\";\n\n/**\n * Which of the four reactor clients Connect boots. Standardized by the\n * multi-reactor work; this resolves the single selector Connect acts on:\n *\n * in-process | worker | remote | router\n *\n * Precedence: an explicit `?reactorClient=` query override (kept in\n * localStorage so it survives a reload), then a stored override, then the\n * served `connect.instance.reactorClient` (projected from the host's reactor\n * backends), then `in-process`. The `reactorWorker`/`multiReactor` booleans\n * no longer select a client.\n *\n * `remote` is the only mode that builds NO local reactor (no PGlite): it is a\n * pure client to a remote Switchboard. `router` keeps the local reactor and\n * adds remote backends; `worker`/`in-process` are the local reactor alone.\n */\nexport type ReactorClientMode = PHReactorClientMode;\n\nconst MODES: ReadonlySet<string> = new Set([\n \"in-process\",\n \"worker\",\n \"remote\",\n \"router\",\n]);\n\nexport const REACTOR_CLIENT_QUERY_KEY = \"reactorClient\";\nexport const REACTOR_CLIENT_STORAGE_KEY = \"ph:reactorClient\";\n\nconst asMode = (value: string | null | undefined) =>\n value && MODES.has(value) ? (value as ReactorClientMode) : undefined;\n\nconst LOCAL_ONLY: ReadonlySet<ReactorClientMode> = new Set([\n \"in-process\",\n \"worker\",\n]);\n\n/** Set while this page load keeps its reactor to itself against the host's `newDrives`. */\nlet blockedNewDrives: Error | undefined;\n\n/** While new drives go to a switchboard, a local-only override applies only from the URL, never from storage. */\nfunction fromTab(newDrives: string | undefined): ReactorClientMode | undefined {\n if (typeof window === \"undefined\") return undefined;\n let query: ReactorClientMode | undefined;\n try {\n query = asMode(\n new URLSearchParams(window.location.search).get(REACTOR_CLIENT_QUERY_KEY),\n );\n } catch {\n return undefined;\n }\n const localOnly = (mode: ReactorClientMode | undefined) =>\n newDrives !== undefined && mode !== undefined && LOCAL_ONLY.has(mode);\n try {\n if (query) {\n if (localOnly(query)) {\n window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);\n } else {\n window.localStorage.setItem(REACTOR_CLIENT_STORAGE_KEY, query);\n }\n return query;\n }\n const stored = asMode(\n window.localStorage.getItem(REACTOR_CLIENT_STORAGE_KEY),\n );\n if (!localOnly(stored)) return stored;\n window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);\n logger.warn(\n \"Ignoring the stored ?reactorClient=@mode: new drives go to @switchboard\",\n stored,\n newDrives,\n );\n return undefined;\n } catch {\n // Blocked storage: the query still applies for this page load.\n return query;\n }\n}\n\nexport function resolveReactorClientMode(): ReactorClientMode {\n const instance = getRuntimeConfig().connect.instance;\n const newDrives = instance?.router?.newDrives;\n const override = fromTab(newDrives);\n blockedNewDrives =\n override && newDrives !== undefined && LOCAL_ONLY.has(override)\n ? new Error(\n `New drives go to ${newDrives}, but this browser is set to keep its reactor to itself (?reactorClient=${override}).`,\n )\n : undefined;\n if (override) return override;\n const configured = instance?.reactorClient;\n if (configured && MODES.has(configured)) return configured;\n // The booleans that selected a client before `reactorClient`: said aloud,\n // since the reactor this boots is not the one they ask for.\n const legacy = isMultiReactorEnabled()\n ? \"multiReactor\"\n : isReactorWorkerEnabled()\n ? \"reactorWorker\"\n : undefined;\n if (legacy) {\n logger.warn(\n \"@flag no longer selects the reactor client: this Connect runs its reactor in-process. Declare reactor.backends in hosts/connect/host.js, or open with ?reactorClient=\",\n legacy,\n );\n }\n return \"in-process\";\n}\n\n/** Why this page load can't create a drive where the host says, or undefined when it can. */\nexport function newDrivesBlocked(): Error | undefined {\n return blockedNewDrives;\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n getDrives,\n getFullReactorClient,\n getPHStore,\n recordBackendAuthError,\n setBackendAuth,\n setDrives,\n setFullReactorClient,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n PHConnectRemoteBackend,\n PHConnectRouterSettings,\n} from \"@powerhousedao/shared/clis\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { ISigner } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport type * as MultiReactor from \"./multi-reactor.js\";\nimport type {\n LoadedDocumentModels,\n LocalReactorModule,\n} from \"./multi-reactor.js\";\nimport type { ReactorClientMode } from \"./reactor-client-mode.js\";\nimport { resolveReactorClientMode } from \"./reactor-client-mode.js\";\nimport { isReactorWorkerEnabled } from \"./reactor-worker-flag.js\";\nimport { setDriveRelister } from \"./drive-relist.js\";\n\n// Kept here: multi-reactor.ts is loaded lazily.\nconst REMOTE_BACKEND_NAME = \"switchboard-remote\";\n\ntype MultiReactorModule = typeof MultiReactor;\n\nexport type AppReactorClientParams = {\n mode: ReactorClientMode;\n /** Built, and ready (the worker has started up). Undefined in `remote`\n * mode, where no local reactor is built. */\n module: LocalReactorModule | undefined;\n /** The fallback switchboard when `remoteBackends` is empty. */\n remoteDriveUrl: string | undefined;\n /** One per switchboard, by host key; `url` is a drive address on it. */\n remoteBackends?: readonly PHConnectRemoteBackend[];\n /** Where new drives go and the router's timeouts, from the host config. */\n router?: PHConnectRouterSettings;\n /** Config placements known at build time; later ones go through `setConfiguredPlacement`. */\n collections?: Readonly<Record<string, string>>;\n /** Signs routed writes; unsigned (anonymous) without one. */\n signer?: ISigner;\n documentModelModules: LoadedDocumentModels;\n loadRouter?: () => Promise<MultiReactorModule>;\n};\n\nconst loadMultiReactor = (): Promise<MultiReactorModule> =>\n import(\"./multi-reactor.js\");\n\n/** What a mode builds in the tab; `remote` builds no local reactor (no PGlite). */\nexport type ReactorClientPlan = {\n mode: ReactorClientMode;\n /** `router`: the local reactor plus remote backends. */\n multiReactor: boolean;\n needsLocalReactor: boolean;\n /** The local reactor runs in the shared worker. */\n localAsWorker: boolean;\n};\n\nexport function planReactorClient(\n mode: ReactorClientMode = resolveReactorClientMode(),\n): ReactorClientPlan {\n const needsLocalReactor = mode !== \"remote\";\n return {\n mode,\n multiReactor: mode === \"router\",\n needsLocalReactor,\n localAsWorker:\n needsLocalReactor &&\n (mode === \"worker\" || (mode === \"router\" && isReactorWorkerEnabled())),\n };\n}\n\n/** Builds the tab's reactor, e.g. Connect's PGlite or worker reactor. */\nexport type LocalReactorFactory = (\n plan: ReactorClientPlan,\n) => Promise<LocalReactorModule>;\n\nexport type CreateAppReactorClientOptions = Omit<\n AppReactorClientParams,\n \"mode\" | \"module\"\n> & {\n plan?: ReactorClientPlan;\n /** Called only when the plan needs a local reactor. */\n localReactor?: LocalReactorFactory;\n};\n\n/** Builds the local reactor the plan needs, then selects the app's client. */\nexport async function createAppReactorClient(\n options: CreateAppReactorClientOptions,\n) {\n const { localReactor, ...params } = options;\n const plan = options.plan ?? planReactorClient();\n let module: LocalReactorModule | undefined;\n if (plan.needsLocalReactor) {\n if (!localReactor) {\n throw new Error(\n `reactorClient mode \"${plan.mode}\" needs a local reactor; pass localReactor`,\n );\n }\n module = await localReactor(plan);\n }\n const { client, router } = await selectClient({\n ...params,\n mode: plan.mode,\n module,\n });\n return { plan, module, client, router };\n}\n\n/**\n * Pick the client for the resolved mode:\n * - `in-process` / `worker`: the local client, router module never loaded.\n * - `router`: the local reactor plus remote backends.\n * - `remote`: a remote-only router — a full IReactorClient that proxies to\n * the Switchboard over GraphQL with NO local reactor (no PGlite).\n */\nexport async function selectAppReactorClient(\n params: AppReactorClientParams,\n): Promise<IReactorClient> {\n return (await selectClient(params)).client;\n}\n\n/** The app's client, and the router when it is one. */\nasync function selectClient(params: AppReactorClientParams): Promise<{\n client: IReactorClient;\n router?: MultiReactor.ConnectRoutingClient;\n}> {\n if (params.mode === \"remote\") {\n setFullReactorClient(undefined);\n const remote = await buildRemoteOnly(params);\n setFullReactorClient(remote);\n return { client: remote, router: remote };\n }\n if (params.mode !== \"router\") {\n if (getPHStore()?.fullReactorClient) {\n setFullReactorClient(undefined);\n }\n return { client: requireModule(params).client };\n }\n setFullReactorClient(undefined);\n const routed = await buildRouter(params);\n setFullReactorClient(routed);\n return routed\n ? { client: routed, router: routed }\n : { client: requireModule(params).client };\n}\n\nfunction requireModule(params: AppReactorClientParams): LocalReactorModule {\n if (!params.module) {\n throw new Error(\n `reactorClient mode \"${params.mode}\" needs a local reactor, but none was built`,\n );\n }\n return params.module;\n}\n\n/**\n * A Switchboard that cannot answer must not fail boot: list the tab's drives.\n *\n * A Switchboard that REFUSES the caller (401/403) must not fail boot either:\n * the refusal is recorded (`backendAuth`) so the root view shows the sign-in\n * gate, and the drive list is empty until the user is someone the backend\n * accepts. A remote-only client has no local drives to fall back on.\n */\nexport async function getAppDrives(\n client: IReactorClient,\n local: IReactorClient,\n): Promise<DocumentDriveDocument[]> {\n if (client === local) {\n try {\n const drives = await getDrives(local);\n setBackendAuth(undefined);\n return drives;\n } catch (error) {\n if (recordBackendAuthError(error, \"switchboard\")) {\n logger.warn(\n \"The Switchboard refused this caller; showing the sign-in gate: @error\",\n error,\n );\n return [];\n }\n throw error;\n }\n }\n try {\n const drives = await getDrives(client);\n setBackendAuth(undefined);\n return drives;\n } catch (error) {\n if (recordBackendAuthError(error, \"switchboard\")) {\n logger.warn(\n \"A remote backend refused this caller; listing the local reactor's drives: @error\",\n error,\n );\n } else {\n logger.warn(\n \"Could not list drives through the router; listing the local reactor's: @error\",\n error,\n );\n }\n return getDrives(local);\n }\n}\n\n/**\n * The boot refresh of the drives store. It lists through `getAppDrives`\n * whichever client is in use, so a Switchboard that refuses the caller is\n * recorded for the sign-in gate here too: the remote-only client is its own\n * `local`, and a bare `refreshReactorDataClient` would let the 401 escape\n * and fail the boot before the gate can render.\n */\nexport async function refreshAppDrives(\n client: IReactorClient,\n local: IReactorClient,\n): Promise<void> {\n setDrives(await getAppDrives(client, local));\n}\n\n/**\n * Lists the drives again as the caller the tab now is, through the clients\n * boot left in the store: after a sign-in landing or a sign-out that followed\n * a backend's refusal. Nothing to do before boot has set a client.\n */\nexport async function relistAppDrives(): Promise<void> {\n const client = getFullReactorClient();\n if (!client) return;\n const local = getPHStore()?.reactorClientModule?.client ?? client;\n await refreshAppDrives(client, local);\n}\n\n// The backend auth gate relists through drive-relist (see there)\nsetDriveRelister(relistAppDrives);\n\n/** The switchboards to route to: the host's remote backends, else the default drive's. */\nfunction switchboardRemotes(params: AppReactorClientParams): {\n remotes: MultiReactor.SwitchboardRemote[];\n unparsed: string[];\n} {\n const listed: readonly PHConnectRemoteBackend[] = params.remoteBackends\n ?.length\n ? params.remoteBackends\n : params.remoteDriveUrl\n ? [{ name: REMOTE_BACKEND_NAME, url: params.remoteDriveUrl }]\n : [];\n const remotes: MultiReactor.SwitchboardRemote[] = [];\n const unparsed: string[] = [];\n for (const { url, ...remote } of listed) {\n const graphqlUrl = switchboardOfDrive(url)?.graphql;\n if (graphqlUrl) remotes.push({ ...remote, graphqlUrl });\n else unparsed.push(url);\n }\n return { remotes, unparsed };\n}\n\nasync function buildRouter(\n params: AppReactorClientParams,\n): Promise<MultiReactor.ConnectRoutingClient | undefined> {\n const { remotes, unparsed } = switchboardRemotes(params);\n for (const url of unparsed) {\n logger.warn(\n \"multiReactor is on but the remote drive URL @url does not parse; skipping it\",\n url,\n );\n }\n // New drives belong on a switchboard: without the router they would be\n // created in this browser, so it is required.\n const newDrives = params.router?.newDrives;\n if (remotes.length === 0) {\n if (newDrives !== undefined) {\n throw new Error(\n `New drives go to ${newDrives}, but this Connect has no address for it, so it can't start.`,\n );\n }\n logger.warn(\n \"multiReactor is on but no remote drive URL is configured; using the local reactor only\",\n );\n return undefined;\n }\n let multiReactor: MultiReactorModule;\n try {\n multiReactor = await (params.loadRouter ?? loadMultiReactor)();\n } catch (error) {\n if (newDrives !== undefined) {\n throw new Error(\n `New drives go to ${newDrives}, but the router that reaches it didn't load, so Connect can't start.`,\n { cause: error },\n );\n }\n logger.error(\"Could not load the multi-reactor router: @error\", error);\n return undefined;\n }\n logger.info(\n \"Multi-reactor routing to @urls\",\n remotes.map((remote) => remote.graphqlUrl).join(\", \"),\n );\n return multiReactor.buildMultiReactorClient({\n module: requireModule(params),\n remotes,\n collections: params.collections,\n ...params.router,\n signer: params.signer,\n documentModelModules: params.documentModelModules,\n });\n}\n\n/**\n * The `remote` mode: a remote-only router — a full IReactorClient that proxies\n * to the Switchboard over GraphQL with NO local backend, so no local reactor\n * and no PGlite are ever built. A missing/unparseable remote URL is a hard\n * config error here (unlike `router`, there is no local reactor to fall back\n * to).\n */\nasync function buildRemoteOnly(\n params: AppReactorClientParams,\n): Promise<MultiReactor.ConnectRoutingClient> {\n const { remotes, unparsed } = switchboardRemotes(params);\n if (unparsed.length > 0) {\n throw new Error(\n `reactorClient \"remote\": the remote drive URL \"${unparsed[0]}\" does not resolve to a Switchboard GraphQL endpoint`,\n );\n }\n if (remotes.length === 0) {\n throw new Error(\n 'reactorClient \"remote\" needs a remote drive URL — declare a remote backend / default drive the client can proxy to',\n );\n }\n const multiReactor = await (params.loadRouter ?? loadMultiReactor)();\n logger.info(\n \"Remote reactor client → @urls\",\n remotes.map((remote) => remote.graphqlUrl).join(\", \"),\n );\n return multiReactor.buildMultiReactorClient({\n module: undefined,\n remotes,\n collections: params.collections,\n ...params.router,\n signer: params.signer,\n documentModelModules: params.documentModelModules,\n });\n}\n","import { isDriveAuthError } from \"@powerhousedao/reactor\";\n\n/** A drive create the switchboard new drives go to did not answer. */\nexport class NewDriveUnansweredError extends Error {\n override readonly name = \"NewDriveUnansweredError\";\n\n constructor(\n readonly backend: string,\n options?: ErrorOptions,\n ) {\n super(`${backend} isn't answering, so the drive wasn't created.`, options);\n }\n}\n\n/** `auth`: the switchboard refused the caller, so signing in may help. */\nexport class NewDriveRefusedError extends Error {\n override readonly name = \"NewDriveRefusedError\";\n\n constructor(\n readonly backend: string,\n readonly auth: boolean,\n reason: string | undefined,\n options?: ErrorOptions,\n ) {\n super(\n reason\n ? `${backend} refused the new drive: ${reason}`\n : `${backend} refused the new drive.`,\n options,\n );\n }\n}\n\n// fetch's network failure: Node, Chrome, Firefox, Safari.\nconst NETWORK_FAILURE =\n /fetch failed|failed to fetch|networkerror|load failed/i;\n\ntype Failure = {\n name?: unknown;\n message?: unknown;\n cause?: unknown;\n statusCode?: unknown;\n category?: unknown;\n response?: { status?: unknown; errors?: { message?: unknown }[] };\n};\n\n/** Each error in the cause chain, outermost first. */\nfunction* chain(error: unknown): Generator<Failure> {\n for (let at = error; at; at = (at as Failure).cause) yield at as Failure;\n}\n\nfunction statusOf(at: Failure): number | undefined {\n const status = at.response?.status ?? at.statusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/** A failure to reach a switchboard, not an answer from it. */\nfunction isUnanswered(error: unknown): boolean {\n for (const at of chain(error)) {\n if (\n at.name === \"SwitchboardUnreachableError\" ||\n at.name === \"TimeoutError\" ||\n at.name === \"ProbeTimeoutError\" ||\n at.category === \"network\" ||\n (at instanceof TypeError && NETWORK_FAILURE.test(at.message))\n ) {\n return true;\n }\n const status = statusOf(at);\n if (status !== undefined && status >= 500) return true;\n }\n return false;\n}\n\nfunction isAuthRefusal(error: unknown): boolean {\n for (const at of chain(error)) {\n if (isDriveAuthError(at)) return true;\n const status = statusOf(at);\n if (status === 401 || status === 403) return true;\n }\n return false;\n}\n\n/** An answer from a server, not a failure in this browser. */\nfunction isServerAnswer(error: unknown): boolean {\n for (const at of chain(error)) {\n if (\n at.response !== undefined ||\n statusOf(at) !== undefined ||\n at.name === \"GraphQLRequestError\" ||\n at.name === \"MisrouteUnresolvedError\"\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The first reason the switchboard gave, if it gave one. */\nfunction reasonOf(error: unknown): string | undefined {\n for (const at of chain(error)) {\n const message = at.response?.errors?.[0]?.message;\n if (typeof message === \"string\" && message !== \"\") return message;\n if (at.name === \"GraphQLRequestError\" && typeof at.message === \"string\") {\n return at.message;\n }\n }\n return undefined;\n}\n\n/** A failed drive create, named for the switchboard `client` creates new drives on; else `error` itself. */\nexport function newDriveError(client: unknown, error: unknown): unknown {\n const backend = (client as { newDrives?: unknown } | null | undefined)\n ?.newDrives;\n if (typeof backend !== \"string\") return error;\n if (isUnanswered(error)) {\n return new NewDriveUnansweredError(backend, { cause: error });\n }\n if (!isServerAnswer(error)) return error;\n return new NewDriveRefusedError(\n backend,\n isAuthRefusal(error),\n reasonOf(error),\n { cause: error },\n );\n}\n","import { DriveCollectionId } from \"@powerhousedao/reactor\";\nimport type {\n PHConnectCollection,\n PHConnectRemoteBackend,\n PHConnectRuntimeDefaultDrive,\n} from \"@powerhousedao/shared/clis\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { logger } from \"document-model\";\n\n/** The router backend of the reactor in this browser. */\nexport const LOCAL_BACKEND_NAME = \"connect-local\";\n\n/** A drive the host keeps on a switchboard, and where its config opens it. */\nexport type SwitchboardDrive = {\n /** The host's name for it: its address's slug, or a collection's key. */\n slug: string;\n url: string;\n /** The switchboard's backend. */\n remote: string;\n /** `remote` (no copy here) or `LOCAL_BACKEND_NAME` (a synced copy). */\n configured: string;\n /** Not a default drive: its address may not be the one it is served at. */\n collection: boolean;\n};\n\n/** A switchboard drive with the names callers reach it by. */\nexport type ResolvedSwitchboardDrive = SwitchboardDrive & {\n id?: string;\n servedSlug?: string;\n};\n\n/** A drive this browser moved away from its host config. */\nexport type PlacementEntry = {\n slug: string;\n backend: string;\n configWas: string;\n};\n\ntype PlacementConfig = {\n drives?: { defaultDrives?: readonly PHConnectRuntimeDefaultDrive[] };\n instance?: {\n remoteBackends?: readonly PHConnectRemoteBackend[];\n collections?: Record<string, PHConnectCollection>;\n };\n};\n\n/** The config's local default drives, placed on this browser so a\n * switchboard `newDrives` doesn't take them. */\nexport function localDrivePlacements(\n defaultDrives: readonly PHConnectRuntimeDefaultDrive[],\n): Record<string, string> {\n return Object.fromEntries(\n defaultDrives.flatMap((drive) =>\n !(\"url\" in drive) && drive.id ? [[drive.id, LOCAL_BACKEND_NAME]] : [],\n ),\n );\n}\n\nexport function keepsLocalCopy(drive: PHConnectRuntimeDefaultDrive): boolean {\n return !(\"url\" in drive) || drive.sync !== false;\n}\n\n/** Remote default drives with a backend, then collections. */\nexport function switchboardDrives(config: PlacementConfig): SwitchboardDrive[] {\n const drives: SwitchboardDrive[] = [];\n for (const drive of config.drives?.defaultDrives ?? []) {\n if (!(\"url\" in drive) || !drive.backend) continue;\n const slug = switchboardOfDrive(drive.url)?.slug;\n if (slug === undefined) continue;\n drives.push({\n slug,\n url: drive.url,\n remote: drive.backend,\n configured: drive.sync === false ? drive.backend : LOCAL_BACKEND_NAME,\n collection: false,\n });\n }\n const remotes = config.instance?.remoteBackends ?? [];\n for (const [slug, entry] of Object.entries(\n config.instance?.collections ?? {},\n )) {\n const remote = remotes.find((r) => r.name === entry.backend);\n const base = remote && switchboardOfDrive(remote.url)?.base;\n if (!base || drives.some((drive) => drive.slug === slug)) continue;\n drives.push({\n slug,\n url: `${base}/d/${encodeURIComponent(slug)}`,\n remote: entry.backend,\n configured: entry.sync === false ? entry.backend : LOCAL_BACKEND_NAME,\n collection: true,\n });\n }\n return drives;\n}\n\n/** Stale: no such drive, a backend it can't open on, back to config, or a changed config value. */\nexport function applyPlacementEntries(\n drives: readonly SwitchboardDrive[],\n entries: readonly PlacementEntry[],\n): { applied: PlacementEntry[]; stale: PlacementEntry[] } {\n const applied: PlacementEntry[] = [];\n const stale: PlacementEntry[] = [];\n for (const entry of entries) {\n const drive = drives.find((d) => d.slug === entry.slug);\n const holds =\n drive !== undefined &&\n entry.configWas === drive.configured &&\n entry.backend !== drive.configured &&\n (entry.backend === drive.remote || entry.backend === LOCAL_BACKEND_NAME);\n (holds ? applied : stale).push(entry);\n }\n return { applied, stale };\n}\n\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nexport function servesSlug(declared: string, served: string): boolean {\n return (\n served === declared ||\n (served.startsWith(`${declared}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1)))\n );\n}\n\ntype DriveNames = { id: string; slug: string };\n\nfunction withinDeadline<T>(work: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`no answer in ${timeoutMs} ms`)),\n timeoutMs,\n );\n });\n return Promise.race([work, deadline]).finally(() => clearTimeout(timer));\n}\n\nexport type ResolveSwitchboardDrivesOptions = {\n timeoutMs?: number;\n /** A collection whose address does not answer: find it among its switchboard's drives. */\n findServed?: (drive: SwitchboardDrive) => Promise<DriveNames | undefined>;\n};\n\n/** An unreachable drive keeps only the slug in its address. */\nexport async function resolveSwitchboardDrives(\n drives: readonly SwitchboardDrive[],\n fetchInfo: (url: string) => Promise<DriveNames>,\n { timeoutMs = 5_000, findServed }: ResolveSwitchboardDrivesOptions = {},\n): Promise<ResolvedSwitchboardDrive[]> {\n return Promise.all(\n drives.map(async (drive): Promise<ResolvedSwitchboardDrive> => {\n try {\n const { id, slug } = await withinDeadline(\n fetchInfo(drive.url),\n timeoutMs,\n );\n return { ...drive, id, servedSlug: slug };\n } catch (error) {\n if (drive.collection && findServed) {\n try {\n const served = await withinDeadline(findServed(drive), timeoutMs);\n if (served) {\n return { ...drive, id: served.id, servedSlug: served.slug };\n }\n } catch (findError) {\n logger.warn(\n \"Could not find drive @slug on @remote: @error\",\n drive.slug,\n drive.remote,\n findError,\n );\n }\n }\n logger.warn(\n \"Could not read drive @url; routing it by its address only: @error\",\n drive.url,\n error,\n );\n const slug = switchboardOfDrive(drive.url)?.slug;\n return slug === undefined ? drive : { ...drive, servedSlug: slug };\n }\n }),\n );\n}\n\n/** The address the drive is served at. */\nexport function servedUrl(drive: ResolvedSwitchboardDrive): string {\n const at = switchboardOfDrive(drive.url);\n return at && drive.servedSlug && drive.servedSlug !== at.slug\n ? `${at.base}/d/${encodeURIComponent(drive.servedSlug)}`\n : drive.url;\n}\n\n/** The keys a placement is installed under: the id and the served slug. */\nexport function placementKeys(drive: ResolvedSwitchboardDrive): string[] {\n return [drive.id, drive.servedSlug].filter(\n (key): key is string => key !== undefined && key !== \"\",\n );\n}\n\nexport type SyncRemotes = {\n list(): readonly {\n meta: { name: string; collectionId: DriveCollectionId };\n }[];\n remove(name: string): Promise<void>;\n};\n\n/** Drops the sync remote of every given drive; its local data is left unread. */\nexport async function removeLocalCopies(\n sync: SyncRemotes,\n resolved: readonly { id?: string }[],\n): Promise<void> {\n for (const drive of resolved) {\n if (!drive.id) continue;\n const collectionId = DriveCollectionId.forDrive(drive.id);\n const remotes = sync\n .list()\n .filter((remote) => remote.meta.collectionId.equals(collectionId));\n for (const remote of remotes) {\n await sync.remove(remote.meta.name);\n }\n }\n}\n","import type {\n IRoutableBackend,\n RoutingReactorClient,\n} from \"@powerhousedao/reactor-router\";\nimport { driveDocumentType } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport {\n applyPlacementEntries,\n servesSlug,\n LOCAL_BACKEND_NAME,\n placementKeys,\n removeLocalCopies,\n servedUrl,\n type PlacementEntry,\n type ResolvedSwitchboardDrive,\n type SwitchboardDrive,\n type SyncRemotes,\n} from \"./drive-placement.js\";\n\n/** A collection by its declared slug among its switchboard's drives, e.g. one served hashed. */\nexport async function findServedDrive(\n router: Pick<RoutingReactorClient, \"backends\">,\n drive: SwitchboardDrive,\n): Promise<{ id: string; slug: string } | undefined> {\n const backend = router.backends.find((b) => b.name === drive.remote);\n if (!backend) return undefined;\n const { results } = await backend.api.find({ type: driveDocumentType });\n const served = results.find(\n (doc) => doc.header.slug && servesSlug(drive.slug, doc.header.slug),\n );\n return served && { id: served.header.id, slug: served.header.slug };\n}\n\n/** Where a drive opens given its stored move, if any: the move, else the host config. */\nexport function effectiveBackend(\n drive: SwitchboardDrive,\n entry: PlacementEntry | undefined,\n): string {\n return entry?.backend ?? drive.configured;\n}\n\n/** A drive opening on `backend` reads its copy here, which must arrive first. */\nexport function needsCopy(backend: string): boolean {\n return backend === LOCAL_BACKEND_NAME;\n}\n\n/** A switchboard, or the copy here, read for the operations it stores. */\nexport type OperationReader = Pick<IRoutableBackend, \"getOperations\">;\n\n/** Action ids in `scope` from index `from`, and the next index to read. */\nexport async function actionIdsFrom(\n reader: OperationReader,\n documentId: string,\n scope: string,\n from: number,\n): Promise<{ ids: string[]; next: number }> {\n const ids: string[] = [];\n let next = from;\n let paging: Parameters<OperationReader[\"getOperations\"]>[3];\n do {\n const page = await reader.getOperations(\n documentId,\n { branch: \"main\", scopes: [scope] },\n { sinceRevision: from },\n paging,\n );\n for (const operation of page.results) {\n ids.push(operation.action.id);\n next = Math.max(next, operation.index + 1);\n }\n paging =\n page.nextCursor && page.results.length > 0\n ? { cursor: page.nextCursor, limit: page.options.limit }\n : undefined;\n } while (paging);\n return { ids, next };\n}\n\n/** Holds every action the source holds; each replica numbers its own revisions. */\nexport function caughtUp(\n local: Readonly<Record<string, ReadonlySet<string>>>,\n source: Readonly<Record<string, readonly string[]>>,\n): boolean {\n return Object.entries(source).every(([scope, ids]) =>\n ids.every((id) => local[scope]?.has(id) ?? false),\n );\n}\n\n/** Where this browser keeps its moves; per origin, so every tab shares it. */\nexport interface PlacementStore {\n list(): Promise<PlacementEntry[]>;\n put(entry: PlacementEntry): Promise<void>;\n delete(slug: string): Promise<void>;\n}\n\n/** The router's two placement layers. */\nexport type PlacementRouter = {\n setPlacement(key: string, backend: string | undefined): void;\n setConfiguredPlacement(key: string, backend: string | undefined): void;\n};\n\nexport type PlacementSync = SyncRemotes & {\n /** Adds a sync remote for the drive. */\n add(url: string, driveId: string): Promise<void>;\n /** Bounded wait until the local copy holds what `remote` holds; rejects when it does not. */\n untilCopied(driveId: string, remote: string): Promise<void>;\n};\n\nexport type DrivePlacement = {\n drive: ResolvedSwitchboardDrive;\n /** Where the drive opens in this browser now. */\n backend: string;\n /** This browser moved it away from the host config. */\n moved: boolean;\n /** A move is running. */\n busy: boolean;\n /** Where a running move takes the drive. */\n movingTo?: string;\n};\n\n/** Config placement plus this browser's moves: store, then sync remote, then router. */\nexport class DrivePlacements {\n private applied = new Map<string, PlacementEntry>();\n private resolved: ResolvedSwitchboardDrive[] = [];\n private router: PlacementRouter | undefined;\n private readonly busy = new Map<string, string>();\n private attached = false;\n private readonly listeners = new Set<() => void>();\n private snapshot = new Map<string, DrivePlacement>();\n\n constructor(\n readonly drives: readonly SwitchboardDrive[],\n applied: readonly PlacementEntry[],\n private readonly store: PlacementStore,\n private readonly sync: PlacementSync,\n ) {\n for (const entry of applied) this.applied.set(entry.slug, entry);\n }\n\n /** Reads the store and drops the entries the config has overtaken (O2). */\n static async load(\n drives: readonly SwitchboardDrive[],\n store: PlacementStore,\n sync: PlacementSync,\n ): Promise<DrivePlacements> {\n let entries: PlacementEntry[] = [];\n try {\n entries = await store.list();\n } catch (error) {\n logger.warn(\"Could not read this browser's drive moves: @error\", error);\n }\n const { applied, stale } = applyPlacementEntries(drives, entries);\n for (const entry of stale) {\n store.delete(entry.slug).catch((error: unknown) => {\n logger.warn(\n \"Could not drop drive move @slug: @error\",\n entry.slug,\n error,\n );\n });\n }\n return new DrivePlacements(drives, applied, store, sync);\n }\n\n /** Where `drive` opens in this browser: a move, else the config. */\n backendOf(drive: SwitchboardDrive): string {\n return effectiveBackend(drive, this.applied.get(drive.slug));\n }\n\n /** Whether a remote default drive at `url` keeps a copy here. */\n keepsCopy(url: string): boolean {\n const drive = this.drives.find((d) => d.url === url);\n return !drive || this.backendOf(drive) === LOCAL_BACKEND_NAME;\n }\n\n /** Drives that open on their switchboard with no copy here. */\n placed(): SwitchboardDrive[] {\n return this.drives.filter(\n (drive) => this.backendOf(drive) !== LOCAL_BACKEND_NAME,\n );\n }\n\n /** Collections this browser keeps a copy of; default drives are added with the others. */\n keptCollections(): ResolvedSwitchboardDrive[] {\n return this.resolved.filter(\n (drive) =>\n drive.collection &&\n drive.id !== undefined &&\n this.backendOf(drive) === LOCAL_BACKEND_NAME,\n );\n }\n\n /** Installs both layers for every drive the router can be told about. */\n attach(\n router: PlacementRouter | undefined,\n resolved: readonly ResolvedSwitchboardDrive[],\n ): void {\n this.router = router;\n this.resolved = [...resolved];\n this.attached = true;\n for (const drive of this.resolved) this.install(drive);\n this.notify();\n }\n\n /**\n * Attaches, follows the moves other tabs made since `load`, then brings\n * the sync remotes in line; returns the collections to keep a copy of.\n */\n async start(\n router: PlacementRouter | undefined,\n resolved: readonly ResolvedSwitchboardDrive[],\n syncsDrives: boolean,\n ): Promise<ResolvedSwitchboardDrive[]> {\n this.attach(router, resolved);\n await this.reload();\n if (!syncsDrives) return [];\n const placed = new Set(this.placed().map((drive) => drive.slug));\n await removeLocalCopies(\n this.sync,\n this.resolved.filter(\n (drive) => placed.has(drive.slug) && !this.busy.has(drive.slug),\n ),\n );\n return this.keptCollections();\n }\n\n /** The drive's placement in this browser; undefined for a drive the host does not place on a switchboard. */\n placementOf(driveId: string): DrivePlacement | undefined {\n return this.snapshot.get(driveId);\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Opens the drive on `backend` in this browser: its switchboard, or a copy here. */\n async move(driveId: string, backend: string): Promise<void> {\n const drive = this.resolved.find((d) => d.id === driveId);\n if (!drive?.id) {\n throw new Error(\n `Drive ${driveId} is not on a switchboard this app links`,\n );\n }\n if (backend !== drive.remote && backend !== LOCAL_BACKEND_NAME) {\n throw new Error(`Drive ${drive.slug} can't open on ${backend}`);\n }\n if (this.busy.has(drive.slug) || this.backendOf(drive) === backend) return;\n const previous = this.applied.get(drive.slug);\n const entry: PlacementEntry | undefined =\n backend === drive.configured\n ? undefined\n : { slug: drive.slug, backend, configWas: drive.configured };\n const id = drive.id;\n this.busy.set(drive.slug, backend);\n this.notify();\n try {\n await this.record(drive.slug, entry);\n if (needsCopy(backend)) {\n try {\n await this.sync.add(servedUrl(drive), id);\n await this.sync.untilCopied(id, drive.remote);\n } catch (error) {\n // Store first: the removal's broadcast makes other tabs re-read it.\n await this.record(drive.slug, previous);\n await removeLocalCopies(this.sync, [drive]);\n throw error;\n }\n } else {\n try {\n await removeLocalCopies(this.sync, [drive]);\n } catch (error) {\n await this.record(drive.slug, previous);\n throw error;\n }\n }\n this.install(drive);\n } finally {\n this.busy.delete(drive.slug);\n this.notify();\n }\n }\n\n /** Back to where the host config opens the drive. */\n reset(driveId: string): Promise<void> {\n const drive = this.resolved.find((d) => d.id === driveId);\n return drive ? this.move(driveId, drive.configured) : Promise.resolve();\n }\n\n /** Re-reads the store after another tab moved a drive; true when something changed. */\n async reload(): Promise<boolean> {\n if (!this.attached) return false;\n const next = await this.readMoves();\n if (!next) return false;\n const changed = this.drives.filter(\n (drive) =>\n !this.busy.has(drive.slug) &&\n effectiveBackend(drive, next.get(drive.slug)) !== this.backendOf(drive),\n );\n if (changed.length === 0) return false;\n await Promise.all(\n changed.map((drive) => this.follow(drive, next.get(drive.slug))),\n );\n this.notify();\n return true;\n }\n\n /** A copy kept by another tab is routed here only once it has arrived. */\n private async follow(\n drive: SwitchboardDrive,\n entry: PlacementEntry | undefined,\n ): Promise<void> {\n const resolved = this.resolved.find((d) => d.slug === drive.slug);\n if (needsCopy(effectiveBackend(drive, entry)) && resolved?.id) {\n this.busy.set(drive.slug, LOCAL_BACKEND_NAME);\n this.notify();\n try {\n await this.sync.untilCopied(resolved.id, resolved.remote);\n } catch (error) {\n logger.warn(\n \"Drive @slug was not copied into this browser; leaving it where it opens: @error\",\n drive.slug,\n error,\n );\n return;\n } finally {\n this.busy.delete(drive.slug);\n }\n // The mover may have rolled back while this tab waited.\n const latest = await this.readMoves();\n if (!latest) return;\n entry = latest.get(drive.slug);\n }\n if (entry) this.applied.set(drive.slug, entry);\n else this.applied.delete(drive.slug);\n if (resolved) this.install(resolved);\n }\n\n private async readMoves(): Promise<Map<string, PlacementEntry> | undefined> {\n let entries: PlacementEntry[];\n try {\n entries = await this.store.list();\n } catch (error) {\n logger.warn(\"Could not read this browser's drive moves: @error\", error);\n return undefined;\n }\n const { applied } = applyPlacementEntries(this.drives, entries);\n return new Map(applied.map((entry) => [entry.slug, entry]));\n }\n\n private async record(\n slug: string,\n entry: PlacementEntry | undefined,\n ): Promise<void> {\n if (entry) {\n await this.store.put(entry);\n this.applied.set(slug, entry);\n } else {\n await this.store.delete(slug);\n this.applied.delete(slug);\n }\n }\n\n private install(drive: ResolvedSwitchboardDrive): void {\n const router = this.router;\n if (!router) return;\n const configured =\n drive.configured === drive.remote ? drive.remote : undefined;\n const runtime = this.applied.get(drive.slug)?.backend;\n for (const key of placementKeys(drive)) {\n router.setConfiguredPlacement(key, configured);\n router.setPlacement(key, runtime);\n }\n }\n\n private notify(): void {\n const snapshot = new Map<string, DrivePlacement>();\n for (const drive of this.resolved) {\n if (!drive.id) continue;\n const backend = this.backendOf(drive);\n snapshot.set(drive.id, {\n drive,\n backend,\n moved: backend !== drive.configured,\n busy: this.busy.has(drive.slug),\n ...(this.busy.has(drive.slug)\n ? { movingTo: this.busy.get(drive.slug) }\n : {}),\n });\n }\n this.snapshot = snapshot;\n for (const listener of [...this.listeners]) listener();\n }\n}\n","import type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport {\n bindPHStoreToWindow,\n createPHStore,\n getActivePHStore,\n} from \"@powerhousedao/reactor-browser\";\n\n/** The app's PH store: the active one, else a new one bound to `window.ph`.\n * Values set on `window.ph` before carry over. */\nexport function getConnectPHStore(): PHStore {\n const active = getActivePHStore();\n if (active) return active;\n const store = createPHStore();\n bindPHStoreToWindow(store);\n return store;\n}\n","import type { DocumentModelLib } from \"document-model\";\n\n/** A module namespace, as `import * as pkg` or Vite HMR hands it over. */\nexport type ModuleNamespace = Record<string, any> & {\n [Symbol.toStringTag]: \"Module\";\n};\n\nexport type LocalPackage = DocumentModelLib<any> | ModuleNamespace;\n\n/** The package itself, or a loader (`() => import(\"./index.js\")`) that keeps it off the boot path. */\nexport type LocalPackageSource = LocalPackage | (() => Promise<LocalPackage>);\n\n/** Starts loading the project's package; a loader runs once, here. */\nexport function loadLocalPackage(\n source: LocalPackageSource | undefined,\n): DocumentModelLib | Promise<DocumentModelLib> | undefined {\n const pkg = (typeof source === \"function\" ? source() : source) as\n | DocumentModelLib\n | Promise<DocumentModelLib>\n | undefined;\n // Consumers await it; this only stops an early rejection being reported as unhandled.\n if (pkg instanceof Promise) pkg.catch(() => undefined);\n return pkg;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,mBAAmB,OAAkC;CACnE,MAAM,YAAY,UAAU,MAAM,UAAU;CAC5C,IAAI,cAAc,KAAA,GAChB,OAAO;CAET,MAAM,YAAY,UAAU,MAAM,WAAW;CAC7C,IAAI,cAAc,KAAA,GAChB,OAAO;CAET,OAAO,MAAM;AACf;AAUA,SAAgB,qBAAqB,MAAgC;CACnE,MAAM,aAAa,KAAK,eAAe;CACvC,IAAI,O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AAI,CAAC,QAAQ;EACb,MAAM,aACJ,MAAM,eAAe,MAAM,SAAS,MAAM,SAAS,KAAA;EACrD,MAAM,UAAU,KAAK,QAAQ,IAAI,MAAM,IAAI,CAAC,EAAE;EAC9C,KAAK,MAAM,OAAO,cAAc,KAAK,GAAG;GACtC,OAAO,uBAAuB,KAAK,UAAU;GAC7C,OAAO,aAAa,KAAK,OAAO;EAClC;CACF;CAEA,SAAuB;EACrB,MAAM,2BAAW,IAAI,IAA4B;EACjD,KAAK,MAAM,SAAS,KAAK,UAAU;GACjC,IAAI,CAAC,MAAM,IAAI;GACf,MAAM,UAAU,KAAK,UAAU,KAAK;GACpC,SAAS,IAAI,MAAM,IAAI;IACrB;IACA;IACA,OAAO,YAAY,MAAM;IACzB,MAAM,KAAK,KAAK,IAAI,MAAM,IAAI;IAC9B,GAAI,KAAK,KAAK,IAAI,MAAM,IAAI,IACxB,EAAE,UAAU,KAAK,KAAK,IAAI,MAAM,IAAI,EAAE,IACtC,CAAC;GACP,CAAC;EACH;EACA,KAAK,WAAW;EAChB,KAAK,MAAM,YAAY,CAAC,GAAG,KAAK,SAAS,GAAG,SAAS;CACvD;AACF;;;;;AClYA,SAAgB,oBAA6B;CAC3C,MAAM,SAAS,iBAAiB;CAChC,IAAI,QAAQ,OAAO;CACnB,MAAM,QAAQ,cAAc;CAC5B,oBAAoB,KAAK;CACzB,OAAO;AACT;;;;ACFA,SAAgB,iBACd,QAC0D;CAC1D,MAAM,MAAO,OAAO,WAAW,aAAa,OAAO,IAAI;CAKvD,IAAI,eAAe,SAAS,IAAI,YAAY,KAAA,CAAS;CACrD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"runtime-BhFI4kFP.js","names":[],"sources":["../src/runtime/runtime-flag.ts","../src/runtime/multi-reactor-flag.ts","../src/runtime/reactor-worker-flag.ts","../src/runtime/reactor-client-mode.ts","../src/runtime/app-reactor-client.ts","../src/runtime/new-drive.ts","../src/runtime/drive-placement.ts","../src/runtime/drive-placements.ts","../src/runtime/ph-store.ts","../src/runtime/local-package.ts"],"sourcesContent":["export type RuntimeFlagInput = {\n configFlag: boolean;\n queryParam?: string | null;\n storedValue?: string | null;\n};\n\n// A query-param override wins, then a stored dev override, then the config flag.\nexport function resolveRuntimeFlag(input: RuntimeFlagInput): boolean {\n const fromQuery = parseFlag(input.queryParam);\n if (fromQuery !== undefined) {\n return fromQuery;\n }\n const fromStore = parseFlag(input.storedValue);\n if (fromStore !== undefined) {\n return fromStore;\n }\n return input.configFlag;\n}\n\nexport type RuntimeFlagKeys = {\n queryKey: string;\n storageKey: string;\n readConfigFlag: () => boolean;\n};\n\n// Effective flag from config + dev override; a query-param override is persisted\n// to localStorage so it survives a refresh. Blocked storage reads as no override.\nexport function isRuntimeFlagEnabled(keys: RuntimeFlagKeys): boolean {\n const configFlag = keys.readConfigFlag();\n if (typeof window === \"undefined\") {\n return configFlag;\n }\n const queryParam = new URLSearchParams(window.location.search).get(\n keys.queryKey,\n );\n const storedValue = readStoredValue(keys.storageKey);\n const enabled = resolveRuntimeFlag({ configFlag, queryParam, storedValue });\n // Persist only an explicit override, not an unrecognized value.\n if (parseFlag(queryParam) !== undefined) {\n persistStoredValue(keys.storageKey, enabled);\n }\n return enabled;\n}\n\nfunction readStoredValue(storageKey: string): string | null {\n try {\n return window.localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\nfunction persistStoredValue(storageKey: string, enabled: boolean): void {\n try {\n window.localStorage.setItem(storageKey, enabled ? \"true\" : \"false\");\n } catch {\n // The override still applies for this page load.\n }\n}\n\nfunction parseFlag(value: string | null | undefined): boolean | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"true\" || normalized === \"1\") {\n return true;\n }\n if (normalized === \"false\" || normalized === \"0\") {\n return false;\n }\n // Unrecognized value (e.g. a typo): no override, fall through to store/config.\n return undefined;\n}\n","import { getRuntimeConfig } from \"./runtime-config.js\";\n\n// Config only: the flag is in the worker fingerprint, so a per-tab value would split tabs.\nexport function isMultiReactorEnabled(): boolean {\n return getRuntimeConfig().connect.instance?.multiReactor ?? false;\n}\n","import { getRuntimeConfig } from \"./runtime-config.js\";\nimport {\n isRuntimeFlagEnabled,\n resolveRuntimeFlag,\n type RuntimeFlagInput,\n} from \"./runtime-flag.js\";\n\nexport const REACTOR_WORKER_QUERY_KEY = \"reactorWorker\";\nexport const REACTOR_WORKER_STORAGE_KEY = \"ph:reactorWorker\";\n\nexport type ReactorWorkerFlagInput = RuntimeFlagInput;\n\nexport function resolveReactorWorkerEnabled(\n input: ReactorWorkerFlagInput,\n): boolean {\n return resolveRuntimeFlag(input);\n}\n\nexport function isReactorWorkerEnabled(): boolean {\n return isRuntimeFlagEnabled({\n queryKey: REACTOR_WORKER_QUERY_KEY,\n storageKey: REACTOR_WORKER_STORAGE_KEY,\n readConfigFlag: () =>\n getRuntimeConfig().connect.instance?.reactorWorker ?? false,\n });\n}\n","import type { PHReactorClientMode } from \"@powerhousedao/shared/clis\";\nimport { getRuntimeConfig } from \"./runtime-config.js\";\nimport { isMultiReactorEnabled } from \"./multi-reactor-flag.js\";\nimport { isReactorWorkerEnabled } from \"./reactor-worker-flag.js\";\nimport { logger } from \"document-model\";\n\n/**\n * Which of the four reactor clients Connect boots. Standardized by the\n * multi-reactor work; this resolves the single selector Connect acts on:\n *\n * in-process | worker | remote | router\n *\n * Precedence: an explicit `?reactorClient=` query override (kept in\n * localStorage so it survives a reload), then a stored override, then the\n * served `connect.instance.reactorClient` (projected from the host's reactor\n * backends), then `in-process`. The `reactorWorker`/`multiReactor` booleans\n * no longer select a client.\n *\n * `remote` is the only mode that builds NO local reactor (no PGlite): it is a\n * pure client to a remote Switchboard. `router` keeps the local reactor and\n * adds remote backends; `worker`/`in-process` are the local reactor alone.\n */\nexport type ReactorClientMode = PHReactorClientMode;\n\nconst MODES: ReadonlySet<string> = new Set([\n \"in-process\",\n \"worker\",\n \"remote\",\n \"router\",\n]);\n\nexport const REACTOR_CLIENT_QUERY_KEY = \"reactorClient\";\nexport const REACTOR_CLIENT_STORAGE_KEY = \"ph:reactorClient\";\n\nconst asMode = (value: string | null | undefined) =>\n value && MODES.has(value) ? (value as ReactorClientMode) : undefined;\n\nconst LOCAL_ONLY: ReadonlySet<ReactorClientMode> = new Set([\n \"in-process\",\n \"worker\",\n]);\n\n/** Set while this page load keeps its reactor to itself against the host's `newDrives`. */\nlet blockedNewDrives: Error | undefined;\n\n/** While new drives go to a switchboard, a local-only override applies only from the URL, never from storage. */\nfunction fromTab(newDrives: string | undefined): ReactorClientMode | undefined {\n if (typeof window === \"undefined\") return undefined;\n let query: ReactorClientMode | undefined;\n try {\n query = asMode(\n new URLSearchParams(window.location.search).get(REACTOR_CLIENT_QUERY_KEY),\n );\n } catch {\n return undefined;\n }\n const localOnly = (mode: ReactorClientMode | undefined) =>\n newDrives !== undefined && mode !== undefined && LOCAL_ONLY.has(mode);\n try {\n if (query) {\n if (localOnly(query)) {\n window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);\n } else {\n window.localStorage.setItem(REACTOR_CLIENT_STORAGE_KEY, query);\n }\n return query;\n }\n const stored = asMode(\n window.localStorage.getItem(REACTOR_CLIENT_STORAGE_KEY),\n );\n if (!localOnly(stored)) return stored;\n window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);\n logger.warn(\n \"Ignoring the stored ?reactorClient=@mode: new drives go to @switchboard\",\n stored,\n newDrives,\n );\n return undefined;\n } catch {\n // Blocked storage: the query still applies for this page load.\n return query;\n }\n}\n\nexport function resolveReactorClientMode(): ReactorClientMode {\n const instance = getRuntimeConfig().connect.instance;\n const newDrives = instance?.router?.newDrives;\n const override = fromTab(newDrives);\n blockedNewDrives =\n override && newDrives !== undefined && LOCAL_ONLY.has(override)\n ? new Error(\n `New drives go to ${newDrives}, but this browser is set to keep its reactor to itself (?reactorClient=${override}).`,\n )\n : undefined;\n if (override) return override;\n const configured = instance?.reactorClient;\n if (configured && MODES.has(configured)) return configured;\n // The booleans that selected a client before `reactorClient`: said aloud,\n // since the reactor this boots is not the one they ask for.\n const legacy = isMultiReactorEnabled()\n ? \"multiReactor\"\n : isReactorWorkerEnabled()\n ? \"reactorWorker\"\n : undefined;\n if (legacy) {\n logger.warn(\n \"@flag no longer selects the reactor client: this Connect runs its reactor in-process. Declare reactor.backends in hosts/connect/host.js, or open with ?reactorClient=\",\n legacy,\n );\n }\n return \"in-process\";\n}\n\n/** Why this page load can't create a drive where the host says, or undefined when it can. */\nexport function newDrivesBlocked(): Error | undefined {\n return blockedNewDrives;\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n getDrives,\n getFullReactorClient,\n getPHStore,\n recordBackendAuthError,\n setBackendAuth,\n setDrives,\n setFullReactorClient,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n PHConnectRemoteBackend,\n PHConnectRouterSettings,\n} from \"@powerhousedao/shared/clis\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { ISigner } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport type * as MultiReactor from \"./multi-reactor.js\";\nimport type {\n LoadedDocumentModels,\n LocalReactorModule,\n} from \"./multi-reactor.js\";\nimport type { ReactorClientMode } from \"./reactor-client-mode.js\";\nimport { resolveReactorClientMode } from \"./reactor-client-mode.js\";\nimport { isReactorWorkerEnabled } from \"./reactor-worker-flag.js\";\nimport { setDriveRelister } from \"./drive-relist.js\";\n\n// Kept here: multi-reactor.ts is loaded lazily.\nconst REMOTE_BACKEND_NAME = \"switchboard-remote\";\n\ntype MultiReactorModule = typeof MultiReactor;\n\nexport type AppReactorClientParams = {\n mode: ReactorClientMode;\n /** Built, and ready (the worker has started up). Undefined in `remote`\n * mode, where no local reactor is built. */\n module: LocalReactorModule | undefined;\n /** The fallback switchboard when `remoteBackends` is empty. */\n remoteDriveUrl: string | undefined;\n /** One per switchboard, by host key; `url` is a drive address on it. */\n remoteBackends?: readonly PHConnectRemoteBackend[];\n /** Where new drives go and the router's timeouts, from the host config. */\n router?: PHConnectRouterSettings;\n /** Config placements known at build time; later ones go through `setConfiguredPlacement`. */\n collections?: Readonly<Record<string, string>>;\n /** Signs routed writes; unsigned (anonymous) without one. */\n signer?: ISigner;\n documentModelModules: LoadedDocumentModels;\n loadRouter?: () => Promise<MultiReactorModule>;\n};\n\nconst loadMultiReactor = (): Promise<MultiReactorModule> =>\n import(\"./multi-reactor.js\");\n\n/** What a mode builds in the tab; `remote` builds no local reactor (no PGlite). */\nexport type ReactorClientPlan = {\n mode: ReactorClientMode;\n /** `router`: the local reactor plus remote backends. */\n multiReactor: boolean;\n needsLocalReactor: boolean;\n /** The local reactor runs in the shared worker. */\n localAsWorker: boolean;\n};\n\nexport function planReactorClient(\n mode: ReactorClientMode = resolveReactorClientMode(),\n): ReactorClientPlan {\n const needsLocalReactor = mode !== \"remote\";\n return {\n mode,\n multiReactor: mode === \"router\",\n needsLocalReactor,\n localAsWorker:\n needsLocalReactor &&\n (mode === \"worker\" || (mode === \"router\" && isReactorWorkerEnabled())),\n };\n}\n\n/** Builds the tab's reactor, e.g. Connect's PGlite or worker reactor. */\nexport type LocalReactorFactory = (\n plan: ReactorClientPlan,\n) => Promise<LocalReactorModule>;\n\nexport type CreateAppReactorClientOptions = Omit<\n AppReactorClientParams,\n \"mode\" | \"module\"\n> & {\n plan?: ReactorClientPlan;\n /** Called only when the plan needs a local reactor. */\n localReactor?: LocalReactorFactory;\n};\n\n/** Builds the local reactor the plan needs, then selects the app's client. */\nexport async function createAppReactorClient(\n options: CreateAppReactorClientOptions,\n) {\n const { localReactor, ...params } = options;\n const plan = options.plan ?? planReactorClient();\n let module: LocalReactorModule | undefined;\n if (plan.needsLocalReactor) {\n if (!localReactor) {\n throw new Error(\n `reactorClient mode \"${plan.mode}\" needs a local reactor; pass localReactor`,\n );\n }\n module = await localReactor(plan);\n }\n const { client, router } = await selectClient({\n ...params,\n mode: plan.mode,\n module,\n });\n return { plan, module, client, router };\n}\n\n/**\n * Pick the client for the resolved mode:\n * - `in-process` / `worker`: the local client, router module never loaded.\n * - `router`: the local reactor plus remote backends.\n * - `remote`: a remote-only router — a full IReactorClient that proxies to\n * the Switchboard over GraphQL with NO local reactor (no PGlite).\n */\nexport async function selectAppReactorClient(\n params: AppReactorClientParams,\n): Promise<IReactorClient> {\n return (await selectClient(params)).client;\n}\n\n/** The app's client, and the router when it is one. */\nasync function selectClient(params: AppReactorClientParams): Promise<{\n client: IReactorClient;\n router?: MultiReactor.ConnectRoutingClient;\n}> {\n if (params.mode === \"remote\") {\n setFullReactorClient(undefined);\n const remote = await buildRemoteOnly(params);\n setFullReactorClient(remote);\n return { client: remote, router: remote };\n }\n if (params.mode !== \"router\") {\n if (getPHStore()?.fullReactorClient) {\n setFullReactorClient(undefined);\n }\n return { client: requireModule(params).client };\n }\n setFullReactorClient(undefined);\n const routed = await buildRouter(params);\n setFullReactorClient(routed);\n return routed\n ? { client: routed, router: routed }\n : { client: requireModule(params).client };\n}\n\nfunction requireModule(params: AppReactorClientParams): LocalReactorModule {\n if (!params.module) {\n throw new Error(\n `reactorClient mode \"${params.mode}\" needs a local reactor, but none was built`,\n );\n }\n return params.module;\n}\n\n/**\n * A Switchboard that cannot answer must not fail boot: list the tab's drives.\n *\n * A Switchboard that REFUSES the caller (401/403) must not fail boot either:\n * the refusal is recorded (`backendAuth`) so the root view shows the sign-in\n * gate, and the drive list is empty until the user is someone the backend\n * accepts. A remote-only client has no local drives to fall back on.\n */\nexport async function getAppDrives(\n client: IReactorClient,\n local: IReactorClient,\n): Promise<DocumentDriveDocument[]> {\n if (client === local) {\n try {\n const drives = await getDrives(local);\n setBackendAuth(undefined);\n return drives;\n } catch (error) {\n if (recordBackendAuthError(error, \"switchboard\")) {\n logger.warn(\n \"The Switchboard refused this caller; showing the sign-in gate: @error\",\n error,\n );\n return [];\n }\n throw error;\n }\n }\n try {\n const drives = await getDrives(client);\n setBackendAuth(undefined);\n return drives;\n } catch (error) {\n if (recordBackendAuthError(error, \"switchboard\")) {\n logger.warn(\n \"A remote backend refused this caller; listing the local reactor's drives: @error\",\n error,\n );\n } else {\n logger.warn(\n \"Could not list drives through the router; listing the local reactor's: @error\",\n error,\n );\n }\n return getDrives(local);\n }\n}\n\n/**\n * The boot refresh of the drives store. It lists through `getAppDrives`\n * whichever client is in use, so a Switchboard that refuses the caller is\n * recorded for the sign-in gate here too: the remote-only client is its own\n * `local`, and a bare `refreshReactorDataClient` would let the 401 escape\n * and fail the boot before the gate can render.\n */\nexport async function refreshAppDrives(\n client: IReactorClient,\n local: IReactorClient,\n): Promise<void> {\n setDrives(await getAppDrives(client, local));\n}\n\n/**\n * Lists the drives again as the caller the tab now is, through the clients\n * boot left in the store: after a sign-in landing or a sign-out that followed\n * a backend's refusal. Nothing to do before boot has set a client.\n */\nexport async function relistAppDrives(): Promise<void> {\n const client = getFullReactorClient();\n if (!client) return;\n const local = getPHStore()?.reactorClientModule?.client ?? client;\n await refreshAppDrives(client, local);\n}\n\n// The backend auth gate relists through drive-relist (see there)\nsetDriveRelister(relistAppDrives);\n\n/** The switchboards to route to: the host's remote backends, else the default drive's. */\nfunction switchboardRemotes(params: AppReactorClientParams): {\n remotes: MultiReactor.SwitchboardRemote[];\n unparsed: string[];\n} {\n const listed: readonly PHConnectRemoteBackend[] = params.remoteBackends\n ?.length\n ? params.remoteBackends\n : params.remoteDriveUrl\n ? [{ name: REMOTE_BACKEND_NAME, url: params.remoteDriveUrl }]\n : [];\n const remotes: MultiReactor.SwitchboardRemote[] = [];\n const unparsed: string[] = [];\n for (const { url, ...remote } of listed) {\n const graphqlUrl = switchboardOfDrive(url)?.graphql;\n if (graphqlUrl) remotes.push({ ...remote, graphqlUrl });\n else unparsed.push(url);\n }\n return { remotes, unparsed };\n}\n\nasync function buildRouter(\n params: AppReactorClientParams,\n): Promise<MultiReactor.ConnectRoutingClient | undefined> {\n const { remotes, unparsed } = switchboardRemotes(params);\n for (const url of unparsed) {\n logger.warn(\n \"multiReactor is on but the remote drive URL @url does not parse; skipping it\",\n url,\n );\n }\n // New drives belong on a switchboard: without the router they would be\n // created in this browser, so it is required.\n const newDrives = params.router?.newDrives;\n if (remotes.length === 0) {\n if (newDrives !== undefined) {\n throw new Error(\n `New drives go to ${newDrives}, but this Connect has no address for it, so it can't start.`,\n );\n }\n logger.warn(\n \"multiReactor is on but no remote drive URL is configured; using the local reactor only\",\n );\n return undefined;\n }\n let multiReactor: MultiReactorModule;\n try {\n multiReactor = await (params.loadRouter ?? loadMultiReactor)();\n } catch (error) {\n if (newDrives !== undefined) {\n throw new Error(\n `New drives go to ${newDrives}, but the router that reaches it didn't load, so Connect can't start.`,\n { cause: error },\n );\n }\n logger.error(\"Could not load the multi-reactor router: @error\", error);\n return undefined;\n }\n logger.info(\n \"Multi-reactor routing to @urls\",\n remotes.map((remote) => remote.graphqlUrl).join(\", \"),\n );\n return multiReactor.buildMultiReactorClient({\n module: requireModule(params),\n remotes,\n collections: params.collections,\n ...params.router,\n signer: params.signer,\n documentModelModules: params.documentModelModules,\n });\n}\n\n/**\n * The `remote` mode: a remote-only router — a full IReactorClient that proxies\n * to the Switchboard over GraphQL with NO local backend, so no local reactor\n * and no PGlite are ever built. A missing/unparseable remote URL is a hard\n * config error here (unlike `router`, there is no local reactor to fall back\n * to).\n */\nasync function buildRemoteOnly(\n params: AppReactorClientParams,\n): Promise<MultiReactor.ConnectRoutingClient> {\n const { remotes, unparsed } = switchboardRemotes(params);\n if (unparsed.length > 0) {\n throw new Error(\n `reactorClient \"remote\": the remote drive URL \"${unparsed[0]}\" does not resolve to a Switchboard GraphQL endpoint`,\n );\n }\n if (remotes.length === 0) {\n throw new Error(\n 'reactorClient \"remote\" needs a remote drive URL — declare a remote backend / default drive the client can proxy to',\n );\n }\n const multiReactor = await (params.loadRouter ?? loadMultiReactor)();\n logger.info(\n \"Remote reactor client → @urls\",\n remotes.map((remote) => remote.graphqlUrl).join(\", \"),\n );\n return multiReactor.buildMultiReactorClient({\n module: undefined,\n remotes,\n collections: params.collections,\n ...params.router,\n signer: params.signer,\n documentModelModules: params.documentModelModules,\n });\n}\n","import { isDriveAuthError } from \"@powerhousedao/reactor\";\n\n/** A drive create the switchboard new drives go to did not answer. */\nexport class NewDriveUnansweredError extends Error {\n override readonly name = \"NewDriveUnansweredError\";\n\n constructor(\n readonly backend: string,\n options?: ErrorOptions,\n ) {\n super(`${backend} isn't answering, so the drive wasn't created.`, options);\n }\n}\n\n/** `auth`: the switchboard refused the caller, so signing in may help. */\nexport class NewDriveRefusedError extends Error {\n override readonly name = \"NewDriveRefusedError\";\n\n constructor(\n readonly backend: string,\n readonly auth: boolean,\n reason: string | undefined,\n options?: ErrorOptions,\n ) {\n super(\n reason\n ? `${backend} refused the new drive: ${reason}`\n : `${backend} refused the new drive.`,\n options,\n );\n }\n}\n\n// fetch's network failure: Node, Chrome, Firefox, Safari.\nconst NETWORK_FAILURE =\n /fetch failed|failed to fetch|networkerror|load failed/i;\n\ntype Failure = {\n name?: unknown;\n message?: unknown;\n cause?: unknown;\n statusCode?: unknown;\n category?: unknown;\n response?: { status?: unknown; errors?: { message?: unknown }[] };\n};\n\n/** Each error in the cause chain, outermost first. */\nfunction* chain(error: unknown): Generator<Failure> {\n for (let at = error; at; at = (at as Failure).cause) yield at as Failure;\n}\n\nfunction statusOf(at: Failure): number | undefined {\n const status = at.response?.status ?? at.statusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/** A failure to reach a switchboard, not an answer from it. */\nfunction isUnanswered(error: unknown): boolean {\n for (const at of chain(error)) {\n if (\n at.name === \"SwitchboardUnreachableError\" ||\n at.name === \"TimeoutError\" ||\n at.name === \"ProbeTimeoutError\" ||\n at.category === \"network\" ||\n (at instanceof TypeError && NETWORK_FAILURE.test(at.message))\n ) {\n return true;\n }\n const status = statusOf(at);\n if (status !== undefined && status >= 500) return true;\n }\n return false;\n}\n\nfunction isAuthRefusal(error: unknown): boolean {\n for (const at of chain(error)) {\n if (isDriveAuthError(at)) return true;\n const status = statusOf(at);\n if (status === 401 || status === 403) return true;\n }\n return false;\n}\n\n/** An answer from a server, not a failure in this browser. */\nfunction isServerAnswer(error: unknown): boolean {\n for (const at of chain(error)) {\n if (\n at.response !== undefined ||\n statusOf(at) !== undefined ||\n at.name === \"GraphQLRequestError\" ||\n at.name === \"MisrouteUnresolvedError\"\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The first reason the switchboard gave, if it gave one. */\nfunction reasonOf(error: unknown): string | undefined {\n for (const at of chain(error)) {\n const message = at.response?.errors?.[0]?.message;\n if (typeof message === \"string\" && message !== \"\") return message;\n if (at.name === \"GraphQLRequestError\" && typeof at.message === \"string\") {\n return at.message;\n }\n }\n return undefined;\n}\n\n/** A failed drive create, named for the switchboard `client` creates new drives on; else `error` itself. */\nexport function newDriveError(client: unknown, error: unknown): unknown {\n const backend = (client as { newDrives?: unknown } | null | undefined)\n ?.newDrives;\n if (typeof backend !== \"string\") return error;\n if (isUnanswered(error)) {\n return new NewDriveUnansweredError(backend, { cause: error });\n }\n if (!isServerAnswer(error)) return error;\n return new NewDriveRefusedError(\n backend,\n isAuthRefusal(error),\n reasonOf(error),\n { cause: error },\n );\n}\n","import { DriveCollectionId } from \"@powerhousedao/reactor\";\nimport type {\n PHConnectCollection,\n PHConnectRemoteBackend,\n PHConnectRuntimeDefaultDrive,\n} from \"@powerhousedao/shared/clis\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { logger } from \"document-model\";\n\n/** The router backend of the reactor in this browser. */\nexport const LOCAL_BACKEND_NAME = \"connect-local\";\n\n/** A drive the host keeps on a switchboard, and where its config opens it. */\nexport type SwitchboardDrive = {\n /** The host's name for it: its address's slug, or a collection's key. */\n slug: string;\n url: string;\n /** The switchboard's backend. */\n remote: string;\n /** `remote` (no copy here) or `LOCAL_BACKEND_NAME` (a synced copy). */\n configured: string;\n /** Not a default drive: its address may not be the one it is served at. */\n collection: boolean;\n};\n\n/** A switchboard drive with the names callers reach it by. */\nexport type ResolvedSwitchboardDrive = SwitchboardDrive & {\n id?: string;\n servedSlug?: string;\n};\n\n/** A drive this browser moved away from its host config. */\nexport type PlacementEntry = {\n slug: string;\n backend: string;\n configWas: string;\n};\n\ntype PlacementConfig = {\n drives?: { defaultDrives?: readonly PHConnectRuntimeDefaultDrive[] };\n instance?: {\n remoteBackends?: readonly PHConnectRemoteBackend[];\n collections?: Record<string, PHConnectCollection>;\n };\n};\n\n/** The config's local default drives, placed on this browser so a\n * switchboard `newDrives` doesn't take them. */\nexport function localDrivePlacements(\n defaultDrives: readonly PHConnectRuntimeDefaultDrive[],\n): Record<string, string> {\n return Object.fromEntries(\n defaultDrives.flatMap((drive) =>\n !(\"url\" in drive) && drive.id ? [[drive.id, LOCAL_BACKEND_NAME]] : [],\n ),\n );\n}\n\nexport function keepsLocalCopy(drive: PHConnectRuntimeDefaultDrive): boolean {\n return !(\"url\" in drive) || drive.sync !== false;\n}\n\n/** Remote default drives with a backend, then collections. */\nexport function switchboardDrives(config: PlacementConfig): SwitchboardDrive[] {\n const drives: SwitchboardDrive[] = [];\n for (const drive of config.drives?.defaultDrives ?? []) {\n if (!(\"url\" in drive) || !drive.backend) continue;\n const slug = switchboardOfDrive(drive.url)?.slug;\n if (slug === undefined) continue;\n drives.push({\n slug,\n url: drive.url,\n remote: drive.backend,\n configured: drive.sync === false ? drive.backend : LOCAL_BACKEND_NAME,\n collection: false,\n });\n }\n const remotes = config.instance?.remoteBackends ?? [];\n for (const [slug, entry] of Object.entries(\n config.instance?.collections ?? {},\n )) {\n const remote = remotes.find((r) => r.name === entry.backend);\n const base = remote && switchboardOfDrive(remote.url)?.base;\n if (!base || drives.some((drive) => drive.slug === slug)) continue;\n drives.push({\n slug,\n url: `${base}/d/${encodeURIComponent(slug)}`,\n remote: entry.backend,\n configured: entry.sync === false ? entry.backend : LOCAL_BACKEND_NAME,\n collection: true,\n });\n }\n return drives;\n}\n\n/** Stale: no such drive, a backend it can't open on, back to config, or a changed config value. */\nexport function applyPlacementEntries(\n drives: readonly SwitchboardDrive[],\n entries: readonly PlacementEntry[],\n): { applied: PlacementEntry[]; stale: PlacementEntry[] } {\n const applied: PlacementEntry[] = [];\n const stale: PlacementEntry[] = [];\n for (const entry of entries) {\n const drive = drives.find((d) => d.slug === entry.slug);\n const holds =\n drive !== undefined &&\n entry.configWas === drive.configured &&\n entry.backend !== drive.configured &&\n (entry.backend === drive.remote || entry.backend === LOCAL_BACKEND_NAME);\n (holds ? applied : stale).push(entry);\n }\n return { applied, stale };\n}\n\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nexport function servesSlug(declared: string, served: string): boolean {\n return (\n served === declared ||\n (served.startsWith(`${declared}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1)))\n );\n}\n\ntype DriveNames = { id: string; slug: string };\n\nfunction withinDeadline<T>(work: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`no answer in ${timeoutMs} ms`)),\n timeoutMs,\n );\n });\n return Promise.race([work, deadline]).finally(() => clearTimeout(timer));\n}\n\nexport type ResolveSwitchboardDrivesOptions = {\n timeoutMs?: number;\n /** A collection whose address does not answer: find it among its switchboard's drives. */\n findServed?: (drive: SwitchboardDrive) => Promise<DriveNames | undefined>;\n};\n\n/** An unreachable drive keeps only the slug in its address. */\nexport async function resolveSwitchboardDrives(\n drives: readonly SwitchboardDrive[],\n fetchInfo: (url: string) => Promise<DriveNames>,\n { timeoutMs = 5_000, findServed }: ResolveSwitchboardDrivesOptions = {},\n): Promise<ResolvedSwitchboardDrive[]> {\n return Promise.all(\n drives.map(async (drive): Promise<ResolvedSwitchboardDrive> => {\n try {\n const { id, slug } = await withinDeadline(\n fetchInfo(drive.url),\n timeoutMs,\n );\n return { ...drive, id, servedSlug: slug };\n } catch (error) {\n if (drive.collection && findServed) {\n try {\n const served = await withinDeadline(findServed(drive), timeoutMs);\n if (served) {\n return { ...drive, id: served.id, servedSlug: served.slug };\n }\n } catch (findError) {\n logger.warn(\n \"Could not find drive @slug on @remote: @error\",\n drive.slug,\n drive.remote,\n findError,\n );\n }\n }\n logger.warn(\n \"Could not read drive @url; routing it by its address only: @error\",\n drive.url,\n error,\n );\n const slug = switchboardOfDrive(drive.url)?.slug;\n return slug === undefined ? drive : { ...drive, servedSlug: slug };\n }\n }),\n );\n}\n\n/** The address the drive is served at. */\nexport function servedUrl(drive: ResolvedSwitchboardDrive): string {\n const at = switchboardOfDrive(drive.url);\n return at && drive.servedSlug && drive.servedSlug !== at.slug\n ? `${at.base}/d/${encodeURIComponent(drive.servedSlug)}`\n : drive.url;\n}\n\n/** The keys a placement is installed under: the id and the served slug. */\nexport function placementKeys(drive: ResolvedSwitchboardDrive): string[] {\n return [drive.id, drive.servedSlug].filter(\n (key): key is string => key !== undefined && key !== \"\",\n );\n}\n\nexport type SyncRemotes = {\n list(): readonly {\n meta: { name: string; collectionId: DriveCollectionId };\n }[];\n remove(name: string): Promise<void>;\n};\n\n/** Drops the sync remote of every given drive; its local data is left unread. */\nexport async function removeLocalCopies(\n sync: SyncRemotes,\n resolved: readonly { id?: string }[],\n): Promise<void> {\n for (const drive of resolved) {\n if (!drive.id) continue;\n const collectionId = DriveCollectionId.forDrive(drive.id);\n const remotes = sync\n .list()\n .filter((remote) => remote.meta.collectionId.equals(collectionId));\n for (const remote of remotes) {\n await sync.remove(remote.meta.name);\n }\n }\n}\n","import type {\n IRoutableBackend,\n RoutingReactorClient,\n} from \"@powerhousedao/reactor-router\";\nimport { driveDocumentType } from \"@powerhousedao/shared/document-drive\";\nimport { logger } from \"document-model\";\nimport {\n applyPlacementEntries,\n servesSlug,\n LOCAL_BACKEND_NAME,\n placementKeys,\n removeLocalCopies,\n servedUrl,\n type PlacementEntry,\n type ResolvedSwitchboardDrive,\n type SwitchboardDrive,\n type SyncRemotes,\n} from \"./drive-placement.js\";\n\n/** A collection by its declared slug among its switchboard's drives, e.g. one served hashed. */\nexport async function findServedDrive(\n router: Pick<RoutingReactorClient, \"backends\">,\n drive: SwitchboardDrive,\n): Promise<{ id: string; slug: string } | undefined> {\n const backend = router.backends.find((b) => b.name === drive.remote);\n if (!backend) return undefined;\n const { results } = await backend.api.find({ type: driveDocumentType });\n const served = results.find(\n (doc) => doc.header.slug && servesSlug(drive.slug, doc.header.slug),\n );\n return served && { id: served.header.id, slug: served.header.slug };\n}\n\n/** Where a drive opens given its stored move, if any: the move, else the host config. */\nexport function effectiveBackend(\n drive: SwitchboardDrive,\n entry: PlacementEntry | undefined,\n): string {\n return entry?.backend ?? drive.configured;\n}\n\n/** A drive opening on `backend` reads its copy here, which must arrive first. */\nexport function needsCopy(backend: string): boolean {\n return backend === LOCAL_BACKEND_NAME;\n}\n\n/** A switchboard, or the copy here, read for the operations it stores. */\nexport type OperationReader = Pick<IRoutableBackend, \"getOperations\">;\n\n/** Action ids in `scope` from index `from`, and the next index to read. */\nexport async function actionIdsFrom(\n reader: OperationReader,\n documentId: string,\n scope: string,\n from: number,\n): Promise<{ ids: string[]; next: number }> {\n const ids: string[] = [];\n let next = from;\n let paging: Parameters<OperationReader[\"getOperations\"]>[3];\n do {\n const page = await reader.getOperations(\n documentId,\n { branch: \"main\", scopes: [scope] },\n { sinceRevision: from },\n paging,\n );\n for (const operation of page.results) {\n ids.push(operation.action.id);\n next = Math.max(next, operation.index + 1);\n }\n paging =\n page.nextCursor && page.results.length > 0\n ? { cursor: page.nextCursor, limit: page.options.limit }\n : undefined;\n } while (paging);\n return { ids, next };\n}\n\n/** Holds every action the source holds; each replica numbers its own revisions. */\nexport function caughtUp(\n local: Readonly<Record<string, ReadonlySet<string>>>,\n source: Readonly<Record<string, readonly string[]>>,\n): boolean {\n return Object.entries(source).every(([scope, ids]) =>\n ids.every((id) => local[scope]?.has(id) ?? false),\n );\n}\n\n/** Where this browser keeps its moves; per origin, so every tab shares it. */\nexport interface PlacementStore {\n list(): Promise<PlacementEntry[]>;\n put(entry: PlacementEntry): Promise<void>;\n delete(slug: string): Promise<void>;\n}\n\n/** The router's two placement layers. */\nexport type PlacementRouter = {\n setPlacement(key: string, backend: string | undefined): void;\n setConfiguredPlacement(key: string, backend: string | undefined): void;\n};\n\nexport type PlacementSync = SyncRemotes & {\n /** Adds a sync remote for the drive. */\n add(url: string, driveId: string): Promise<void>;\n /** Bounded wait until the local copy holds what `remote` holds; rejects when it does not. */\n untilCopied(driveId: string, remote: string): Promise<void>;\n};\n\nexport type DrivePlacement = {\n drive: ResolvedSwitchboardDrive;\n /** Where the drive opens in this browser now. */\n backend: string;\n /** This browser moved it away from the host config. */\n moved: boolean;\n /** A move is running. */\n busy: boolean;\n /** Where a running move takes the drive. */\n movingTo?: string;\n};\n\n/** Config placement plus this browser's moves: store, then sync remote, then router. */\nexport class DrivePlacements {\n private applied = new Map<string, PlacementEntry>();\n private resolved: ResolvedSwitchboardDrive[] = [];\n private router: PlacementRouter | undefined;\n private readonly busy = new Map<string, string>();\n private attached = false;\n private readonly listeners = new Set<() => void>();\n private snapshot = new Map<string, DrivePlacement>();\n\n constructor(\n readonly drives: readonly SwitchboardDrive[],\n applied: readonly PlacementEntry[],\n private readonly store: PlacementStore,\n private readonly sync: PlacementSync,\n ) {\n for (const entry of applied) this.applied.set(entry.slug, entry);\n }\n\n /** Reads the store and drops the entries the config has overtaken (O2). */\n static async load(\n drives: readonly SwitchboardDrive[],\n store: PlacementStore,\n sync: PlacementSync,\n ): Promise<DrivePlacements> {\n let entries: PlacementEntry[] = [];\n try {\n entries = await store.list();\n } catch (error) {\n logger.warn(\"Could not read this browser's drive moves: @error\", error);\n }\n const { applied, stale } = applyPlacementEntries(drives, entries);\n for (const entry of stale) {\n store.delete(entry.slug).catch((error: unknown) => {\n logger.warn(\n \"Could not drop drive move @slug: @error\",\n entry.slug,\n error,\n );\n });\n }\n return new DrivePlacements(drives, applied, store, sync);\n }\n\n /** Where `drive` opens in this browser: a move, else the config. */\n backendOf(drive: SwitchboardDrive): string {\n return effectiveBackend(drive, this.applied.get(drive.slug));\n }\n\n /** Whether a remote default drive at `url` keeps a copy here. */\n keepsCopy(url: string): boolean {\n const drive = this.drives.find((d) => d.url === url);\n return !drive || this.backendOf(drive) === LOCAL_BACKEND_NAME;\n }\n\n /** Drives that open on their switchboard with no copy here. */\n placed(): SwitchboardDrive[] {\n return this.drives.filter(\n (drive) => this.backendOf(drive) !== LOCAL_BACKEND_NAME,\n );\n }\n\n /** Collections this browser keeps a copy of; default drives are added with the others. */\n keptCollections(): ResolvedSwitchboardDrive[] {\n return this.resolved.filter(\n (drive) =>\n drive.collection &&\n drive.id !== undefined &&\n this.backendOf(drive) === LOCAL_BACKEND_NAME,\n );\n }\n\n /** Installs both layers for every drive the router can be told about. */\n attach(\n router: PlacementRouter | undefined,\n resolved: readonly ResolvedSwitchboardDrive[],\n ): void {\n this.router = router;\n this.resolved = [...resolved];\n this.attached = true;\n for (const drive of this.resolved) this.install(drive);\n this.notify();\n }\n\n /**\n * Attaches, follows the moves other tabs made since `load`, then brings\n * the sync remotes in line; returns the collections to keep a copy of.\n */\n async start(\n router: PlacementRouter | undefined,\n resolved: readonly ResolvedSwitchboardDrive[],\n syncsDrives: boolean,\n ): Promise<ResolvedSwitchboardDrive[]> {\n this.attach(router, resolved);\n await this.reload();\n if (!syncsDrives) return [];\n const placed = new Set(this.placed().map((drive) => drive.slug));\n await removeLocalCopies(\n this.sync,\n this.resolved.filter(\n (drive) => placed.has(drive.slug) && !this.busy.has(drive.slug),\n ),\n );\n return this.keptCollections();\n }\n\n /** The drive's placement in this browser; undefined for a drive the host does not place on a switchboard. */\n placementOf(driveId: string): DrivePlacement | undefined {\n return this.snapshot.get(driveId);\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Opens the drive on `backend` in this browser: its switchboard, or a copy here. */\n async move(driveId: string, backend: string): Promise<void> {\n const drive = this.resolved.find((d) => d.id === driveId);\n if (!drive?.id) {\n throw new Error(\n `Drive ${driveId} is not on a switchboard this app links`,\n );\n }\n if (backend !== drive.remote && backend !== LOCAL_BACKEND_NAME) {\n throw new Error(`Drive ${drive.slug} can't open on ${backend}`);\n }\n if (this.busy.has(drive.slug) || this.backendOf(drive) === backend) return;\n const previous = this.applied.get(drive.slug);\n const entry: PlacementEntry | undefined =\n backend === drive.configured\n ? undefined\n : { slug: drive.slug, backend, configWas: drive.configured };\n const id = drive.id;\n this.busy.set(drive.slug, backend);\n this.notify();\n try {\n await this.record(drive.slug, entry);\n if (needsCopy(backend)) {\n try {\n await this.sync.add(servedUrl(drive), id);\n await this.sync.untilCopied(id, drive.remote);\n } catch (error) {\n // Store first: the removal's broadcast makes other tabs re-read it.\n await this.record(drive.slug, previous);\n await removeLocalCopies(this.sync, [drive]);\n throw error;\n }\n } else {\n try {\n await removeLocalCopies(this.sync, [drive]);\n } catch (error) {\n await this.record(drive.slug, previous);\n throw error;\n }\n }\n this.install(drive);\n } finally {\n this.busy.delete(drive.slug);\n this.notify();\n }\n }\n\n /** Back to where the host config opens the drive. */\n reset(driveId: string): Promise<void> {\n const drive = this.resolved.find((d) => d.id === driveId);\n return drive ? this.move(driveId, drive.configured) : Promise.resolve();\n }\n\n /** Re-reads the store after another tab moved a drive; true when something changed. */\n async reload(): Promise<boolean> {\n if (!this.attached) return false;\n const next = await this.readMoves();\n if (!next) return false;\n const changed = this.drives.filter(\n (drive) =>\n !this.busy.has(drive.slug) &&\n effectiveBackend(drive, next.get(drive.slug)) !== this.backendOf(drive),\n );\n if (changed.length === 0) return false;\n await Promise.all(\n changed.map((drive) => this.follow(drive, next.get(drive.slug))),\n );\n this.notify();\n return true;\n }\n\n /** A copy kept by another tab is routed here only once it has arrived. */\n private async follow(\n drive: SwitchboardDrive,\n entry: PlacementEntry | undefined,\n ): Promise<void> {\n const resolved = this.resolved.find((d) => d.slug === drive.slug);\n if (needsCopy(effectiveBackend(drive, entry)) && resolved?.id) {\n this.busy.set(drive.slug, LOCAL_BACKEND_NAME);\n this.notify();\n try {\n await this.sync.untilCopied(resolved.id, resolved.remote);\n } catch (error) {\n logger.warn(\n \"Drive @slug was not copied into this browser; leaving it where it opens: @error\",\n drive.slug,\n error,\n );\n return;\n } finally {\n this.busy.delete(drive.slug);\n }\n // The mover may have rolled back while this tab waited.\n const latest = await this.readMoves();\n if (!latest) return;\n entry = latest.get(drive.slug);\n }\n if (entry) this.applied.set(drive.slug, entry);\n else this.applied.delete(drive.slug);\n if (resolved) this.install(resolved);\n }\n\n private async readMoves(): Promise<Map<string, PlacementEntry> | undefined> {\n let entries: PlacementEntry[];\n try {\n entries = await this.store.list();\n } catch (error) {\n logger.warn(\"Could not read this browser's drive moves: @error\", error);\n return undefined;\n }\n const { applied } = applyPlacementEntries(this.drives, entries);\n return new Map(applied.map((entry) => [entry.slug, entry]));\n }\n\n private async record(\n slug: string,\n entry: PlacementEntry | undefined,\n ): Promise<void> {\n if (entry) {\n await this.store.put(entry);\n this.applied.set(slug, entry);\n } else {\n await this.store.delete(slug);\n this.applied.delete(slug);\n }\n }\n\n private install(drive: ResolvedSwitchboardDrive): void {\n const router = this.router;\n if (!router) return;\n const configured =\n drive.configured === drive.remote ? drive.remote : undefined;\n const runtime = this.applied.get(drive.slug)?.backend;\n for (const key of placementKeys(drive)) {\n router.setConfiguredPlacement(key, configured);\n router.setPlacement(key, runtime);\n }\n }\n\n private notify(): void {\n const snapshot = new Map<string, DrivePlacement>();\n for (const drive of this.resolved) {\n if (!drive.id) continue;\n const backend = this.backendOf(drive);\n snapshot.set(drive.id, {\n drive,\n backend,\n moved: backend !== drive.configured,\n busy: this.busy.has(drive.slug),\n ...(this.busy.has(drive.slug)\n ? { movingTo: this.busy.get(drive.slug) }\n : {}),\n });\n }\n this.snapshot = snapshot;\n for (const listener of [...this.listeners]) listener();\n }\n}\n","import type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport {\n bindPHStoreToWindow,\n createPHStore,\n getActivePHStore,\n} from \"@powerhousedao/reactor-browser\";\n\n/** The app's PH store: the active one, else a new one bound to `window.ph`.\n * Values set on `window.ph` before carry over. */\nexport function getConnectPHStore(): PHStore {\n const active = getActivePHStore();\n if (active) return active;\n const store = createPHStore();\n bindPHStoreToWindow(store);\n return store;\n}\n","import type { DocumentModelLib } from \"document-model\";\n\n/** A module namespace, as `import * as pkg` or Vite HMR hands it over. */\nexport type ModuleNamespace = Record<string, any> & {\n [Symbol.toStringTag]: \"Module\";\n};\n\nexport type LocalPackage = DocumentModelLib<any> | ModuleNamespace;\n\n/** The package itself, or a loader (`() => import(\"./index.js\")`) that keeps it off the boot path. */\nexport type LocalPackageSource = LocalPackage | (() => Promise<LocalPackage>);\n\n/** Starts loading the project's package; a loader runs once, here. */\nexport function loadLocalPackage(\n source: LocalPackageSource | undefined,\n): DocumentModelLib | Promise<DocumentModelLib> | undefined {\n const pkg = (typeof source === \"function\" ? source() : source) as\n | DocumentModelLib\n | Promise<DocumentModelLib>\n | undefined;\n // Consumers await it; this only stops an early rejection being reported as unhandled.\n if (pkg instanceof Promise) pkg.catch(() => undefined);\n return pkg;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,mBAAmB,OAAkC;CACnE,MAAM,YAAY,UAAU,MAAM,UAAU;CAC5C,IAAI,cAAc,KAAA,GAChB,OAAO;CAET,MAAM,YAAY,UAAU,MAAM,WAAW;CAC7C,IAAI,cAAc,KAAA,GAChB,OAAO;CAET,OAAO,MAAM;AACf;AAUA,SAAgB,qBAAqB,MAAgC;CACnE,MAAM,aAAa,KAAK,eAAe;CACvC,IAAI,OAAO,WAAW,aACpB,OAAO;CAET,MAAM,aAAa,IAAI,gBAAgB,OAAO,SAAS,MAAM,CAAC,CAAC,IAC7D,KAAK,QACP;CAEA,MAAM,UAAU,mBAAmB;EAAE;EAAY;EAAY,aADzC,gBAAgB,KAAK,UAC8B;CAAE,CAAC;CAE1E,IAAI,UAAU,UAAU,MAAM,KAA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OAAO,aAAa,KAAK,OAAO;EAClC;CACF;CAEA,SAAuB;EACrB,MAAM,2BAAW,IAAI,IAA4B;EACjD,KAAK,MAAM,SAAS,KAAK,UAAU;GACjC,IAAI,CAAC,MAAM,IAAI;GACf,MAAM,UAAU,KAAK,UAAU,KAAK;GACpC,SAAS,IAAI,MAAM,IAAI;IACrB;IACA;IACA,OAAO,YAAY,MAAM;IACzB,MAAM,KAAK,KAAK,IAAI,MAAM,IAAI;IAC9B,GAAI,KAAK,KAAK,IAAI,MAAM,IAAI,IACxB,EAAE,UAAU,KAAK,KAAK,IAAI,MAAM,IAAI,EAAE,IACtC,CAAC;GACP,CAAC;EACH;EACA,KAAK,WAAW;EAChB,KAAK,MAAM,YAAY,CAAC,GAAG,KAAK,SAAS,GAAG,SAAS;CACvD;AACF;;;;;AClYA,SAAgB,oBAA6B;CAC3C,MAAM,SAAS,iBAAiB;CAChC,IAAI,QAAQ,OAAO;CACnB,MAAM,QAAQ,cAAc;CAC5B,oBAAoB,KAAK;CACzB,OAAO;AACT;;;;ACFA,SAAgB,iBACd,QAC0D;CAC1D,MAAM,MAAO,OAAO,WAAW,aAAa,OAAO,IAAI;CAKvD,IAAI,eAAe,SAAS,IAAI,YAAY,KAAA,CAAS;CACrD,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { W as ConnectPluginDefinition } from "./connect-router-BzqhC9kH.js";
|
|
2
2
|
import { RuntimePowerhouseConfig } from "@powerhousedao/shared/connect";
|
|
3
3
|
//#region src/runtime/runtime-config.d.ts
|
|
4
4
|
type LoadRuntimeConfigOptions = {
|
|
@@ -17,4 +17,4 @@ declare function primeRuntimeConfig(config: RuntimePowerhouseConfig): void;
|
|
|
17
17
|
//#endregion
|
|
18
18
|
export { primeRuntimeConfig as i, getRuntimeConfig as n, loadRuntimeConfig as r, LoadRuntimeConfigOptions as t };
|
|
19
19
|
export {};
|
|
20
|
-
//# sourceMappingURL=runtime-config-
|
|
20
|
+
//# sourceMappingURL=runtime-config-bFOaAulk.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-config-
|
|
1
|
+
{"version":3,"file":"runtime-config-bFOaAulk.d.ts","names":[],"sources":["../src/runtime/runtime-config.ts"],"mappings":";;;KAiBY;;;EAGV,gBAAgB,QAAQ,eAAe;;iBAGnB,kBACpB,UAAS,2BACR,QAAQ;;;;;iBAuDK,oBAAoB;;iBAKpB,mBAAmB,QAAQ"}
|
package/dist/runtime-config.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as primeRuntimeConfig, n as getRuntimeConfig, r as loadRuntimeConfig, t as LoadRuntimeConfigOptions } from "./runtime-config-
|
|
1
|
+
import { i as primeRuntimeConfig, n as getRuntimeConfig, r as loadRuntimeConfig, t as LoadRuntimeConfigOptions } from "./runtime-config-bFOaAulk.js";
|
|
2
2
|
export { LoadRuntimeConfigOptions, getRuntimeConfig, loadRuntimeConfig, primeRuntimeConfig };
|
|
3
3
|
export {};
|
package/dist/runtime-config.js
CHANGED
|
@@ -5,12 +5,12 @@ import { resolveOriginPlaceholders } from "@powerhousedao/shared/connect/origin-
|
|
|
5
5
|
//#region src/runtime/runtime-config.ts
|
|
6
6
|
const loader = () => getConnectRegistry().runtimeConfig ??= new ConfigLoader(new JsonConfigAdapter({ path: `${import.meta.env?.BASE_URL ?? "/"}powerhouse.config.json` }));
|
|
7
7
|
async function loadRuntimeConfig(options = {}) {
|
|
8
|
-
const pluginHost = options.plugins ? import("./plugin-host-
|
|
8
|
+
const pluginHost = options.plugins ? import("./plugin-host-D6GSDZsy.js").then((n) => n.r).then(async (host) => {
|
|
9
9
|
host.registerConnectPlugins(options.plugins);
|
|
10
10
|
await host.knownPlugins();
|
|
11
11
|
return host;
|
|
12
12
|
}) : void 0;
|
|
13
|
-
const pluginUi = options.plugins ? import("./plugin-ui-
|
|
13
|
+
const pluginUi = options.plugins ? import("./plugin-ui-BPhSLN0f.js").then((n) => n.a) : void 0;
|
|
14
14
|
pluginHost?.catch(() => void 0);
|
|
15
15
|
pluginUi?.catch(() => void 0);
|
|
16
16
|
let config = await loader().read();
|
|
@@ -28,7 +28,7 @@ async function loadRuntimeConfig(options = {}) {
|
|
|
28
28
|
composition
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
-
const { applyComposition } = await pluginHost ?? await import("./plugin-host-
|
|
31
|
+
const { applyComposition } = await pluginHost ?? await import("./plugin-host-D6GSDZsy.js").then((n) => n.r);
|
|
32
32
|
config.connect = await applyComposition(config.connect);
|
|
33
33
|
loader().prime(config);
|
|
34
34
|
if (pluginHost && pluginUi) {
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as ReactorWorkerFlagInput, A as LoadedDocumentModels, B as placementKeys, C as ReactorClientPlan, D as refreshAppDrives, E as planReactorClient, F as ResolvedSwitchboardDrive, G as switchboardDrives, H as resolveSwitchboardDrives, I as SwitchboardDrive, J as ReactorClientMode, K as REACTOR_CLIENT_QUERY_KEY, L as applyPlacementEntries, M as LOCAL_BACKEND_NAME, N as PlacementEntry, O as relistAppDrives, P as ResolveSwitchboardDrivesOptions, Q as REACTOR_WORKER_STORAGE_KEY, R as keepsLocalCopy, S as LocalReactorFactory, T as getAppDrives, U as servedUrl, V as removeLocalCopies, W as servesSlug, X as resolveReactorClientMode, Y as newDrivesBlocked, Z as REACTOR_WORKER_QUERY_KEY, _ as NewDriveRefusedError, a as getConnectPHStore, at as isRuntimeFlagEnabled, b as AppReactorClientParams, c as OperationReader, d as PlacementSync, et as isReactorWorkerEnabled, f as actionIdsFrom, g as needsCopy, h as findServedDrive, i as loadLocalPackage, it as RuntimeFlagKeys, j as LocalReactorModule, k as selectAppReactorClient, l as PlacementRouter, m as effectiveBackend, n as LocalPackageSource, nt as isMultiReactorEnabled, o as DrivePlacement, ot as resolveRuntimeFlag, p as caughtUp, q as REACTOR_CLIENT_STORAGE_KEY, r as ModuleNamespace, rt as RuntimeFlagInput, s as DrivePlacements, t as LocalPackage, tt as resolveReactorWorkerEnabled, u as PlacementStore, v as NewDriveUnansweredError, w as createAppReactorClient, x as CreateAppReactorClientOptions, y as newDriveError, z as localDrivePlacements } from "./index-
|
|
2
|
-
import { i as primeRuntimeConfig, n as getRuntimeConfig, r as loadRuntimeConfig } from "./runtime-config-
|
|
3
|
-
import { n as useBackendAuthGate, t as BackendAuthGateMode } from "./backend-auth-gate-
|
|
1
|
+
import { $ as ReactorWorkerFlagInput, A as LoadedDocumentModels, B as placementKeys, C as ReactorClientPlan, D as refreshAppDrives, E as planReactorClient, F as ResolvedSwitchboardDrive, G as switchboardDrives, H as resolveSwitchboardDrives, I as SwitchboardDrive, J as ReactorClientMode, K as REACTOR_CLIENT_QUERY_KEY, L as applyPlacementEntries, M as LOCAL_BACKEND_NAME, N as PlacementEntry, O as relistAppDrives, P as ResolveSwitchboardDrivesOptions, Q as REACTOR_WORKER_STORAGE_KEY, R as keepsLocalCopy, S as LocalReactorFactory, T as getAppDrives, U as servedUrl, V as removeLocalCopies, W as servesSlug, X as resolveReactorClientMode, Y as newDrivesBlocked, Z as REACTOR_WORKER_QUERY_KEY, _ as NewDriveRefusedError, a as getConnectPHStore, at as isRuntimeFlagEnabled, b as AppReactorClientParams, c as OperationReader, d as PlacementSync, et as isReactorWorkerEnabled, f as actionIdsFrom, g as needsCopy, h as findServedDrive, i as loadLocalPackage, it as RuntimeFlagKeys, j as LocalReactorModule, k as selectAppReactorClient, l as PlacementRouter, m as effectiveBackend, n as LocalPackageSource, nt as isMultiReactorEnabled, o as DrivePlacement, ot as resolveRuntimeFlag, p as caughtUp, q as REACTOR_CLIENT_STORAGE_KEY, r as ModuleNamespace, rt as RuntimeFlagInput, s as DrivePlacements, t as LocalPackage, tt as resolveReactorWorkerEnabled, u as PlacementStore, v as NewDriveUnansweredError, w as createAppReactorClient, x as CreateAppReactorClientOptions, y as newDriveError, z as localDrivePlacements } from "./index-CFPU-wyN.js";
|
|
2
|
+
import { i as primeRuntimeConfig, n as getRuntimeConfig, r as loadRuntimeConfig } from "./runtime-config-bFOaAulk.js";
|
|
3
|
+
import { n as useBackendAuthGate, t as BackendAuthGateMode } from "./backend-auth-gate-DZJTO3Sb.js";
|
|
4
4
|
import { n as useIsEmbedded, t as getIsEmbedded } from "./embedded-DT1C47F0.js";
|
|
5
5
|
export { type AppReactorClientParams, type BackendAuthGateMode, type CreateAppReactorClientOptions, type DrivePlacement, DrivePlacements, LOCAL_BACKEND_NAME, type LoadedDocumentModels, type LocalPackage, type LocalPackageSource, type LocalReactorFactory, type LocalReactorModule, type ModuleNamespace, NewDriveRefusedError, NewDriveUnansweredError, type OperationReader, type PlacementEntry, type PlacementRouter, type PlacementStore, type PlacementSync, REACTOR_CLIENT_QUERY_KEY, REACTOR_CLIENT_STORAGE_KEY, REACTOR_WORKER_QUERY_KEY, REACTOR_WORKER_STORAGE_KEY, type ReactorClientMode, type ReactorClientPlan, type ReactorWorkerFlagInput, type ResolveSwitchboardDrivesOptions, type ResolvedSwitchboardDrive, type RuntimeFlagInput, type RuntimeFlagKeys, type SwitchboardDrive, actionIdsFrom, applyPlacementEntries, caughtUp, createAppReactorClient, effectiveBackend, findServedDrive, getAppDrives, getConnectPHStore, getIsEmbedded, getRuntimeConfig, isMultiReactorEnabled, isReactorWorkerEnabled, isRuntimeFlagEnabled, keepsLocalCopy, loadLocalPackage, loadRuntimeConfig, localDrivePlacements, needsCopy, newDriveError, newDrivesBlocked, placementKeys, planReactorClient, primeRuntimeConfig, refreshAppDrives, relistAppDrives, removeLocalCopies, resolveReactorClientMode, resolveReactorWorkerEnabled, resolveRuntimeFlag, resolveSwitchboardDrives, selectAppReactorClient, servedUrl, servesSlug, switchboardDrives, useBackendAuthGate, useIsEmbedded };
|
|
6
6
|
export {};
|
package/dist/runtime.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getIsEmbedded, useIsEmbedded } from "./embedded.js";
|
|
2
2
|
import { getRuntimeConfig, loadRuntimeConfig, primeRuntimeConfig } from "./runtime-config.js";
|
|
3
|
-
import { A as newDrivesBlocked, C as getAppDrives, D as selectAppReactorClient, E as relistAppDrives, F as resolveReactorWorkerEnabled, I as isMultiReactorEnabled, L as isRuntimeFlagEnabled, M as REACTOR_WORKER_QUERY_KEY, N as REACTOR_WORKER_STORAGE_KEY, O as REACTOR_CLIENT_QUERY_KEY, P as isReactorWorkerEnabled, R as resolveRuntimeFlag, S as createAppReactorClient, T as refreshAppDrives, _ as servesSlug, a as caughtUp, b as NewDriveUnansweredError, c as needsCopy, d as keepsLocalCopy, f as localDrivePlacements, g as servedUrl, h as resolveSwitchboardDrives, i as actionIdsFrom, j as resolveReactorClientMode, k as REACTOR_CLIENT_STORAGE_KEY, l as LOCAL_BACKEND_NAME, m as removeLocalCopies, n as getConnectPHStore, o as effectiveBackend, p as placementKeys, r as DrivePlacements, s as findServedDrive, t as loadLocalPackage, u as applyPlacementEntries, v as switchboardDrives, w as planReactorClient, x as newDriveError, y as NewDriveRefusedError } from "./runtime-
|
|
4
|
-
import { t as useBackendAuthGate } from "./backend-auth-gate-
|
|
3
|
+
import { A as newDrivesBlocked, C as getAppDrives, D as selectAppReactorClient, E as relistAppDrives, F as resolveReactorWorkerEnabled, I as isMultiReactorEnabled, L as isRuntimeFlagEnabled, M as REACTOR_WORKER_QUERY_KEY, N as REACTOR_WORKER_STORAGE_KEY, O as REACTOR_CLIENT_QUERY_KEY, P as isReactorWorkerEnabled, R as resolveRuntimeFlag, S as createAppReactorClient, T as refreshAppDrives, _ as servesSlug, a as caughtUp, b as NewDriveUnansweredError, c as needsCopy, d as keepsLocalCopy, f as localDrivePlacements, g as servedUrl, h as resolveSwitchboardDrives, i as actionIdsFrom, j as resolveReactorClientMode, k as REACTOR_CLIENT_STORAGE_KEY, l as LOCAL_BACKEND_NAME, m as removeLocalCopies, n as getConnectPHStore, o as effectiveBackend, p as placementKeys, r as DrivePlacements, s as findServedDrive, t as loadLocalPackage, u as applyPlacementEntries, v as switchboardDrives, w as planReactorClient, x as newDriveError, y as NewDriveRefusedError } from "./runtime-BhFI4kFP.js";
|
|
4
|
+
import { t as useBackendAuthGate } from "./backend-auth-gate-CZgrKCSF.js";
|
|
5
5
|
export { DrivePlacements, LOCAL_BACKEND_NAME, NewDriveRefusedError, NewDriveUnansweredError, REACTOR_CLIENT_QUERY_KEY, REACTOR_CLIENT_STORAGE_KEY, REACTOR_WORKER_QUERY_KEY, REACTOR_WORKER_STORAGE_KEY, actionIdsFrom, applyPlacementEntries, caughtUp, createAppReactorClient, effectiveBackend, findServedDrive, getAppDrives, getConnectPHStore, getIsEmbedded, getRuntimeConfig, isMultiReactorEnabled, isReactorWorkerEnabled, isRuntimeFlagEnabled, keepsLocalCopy, loadLocalPackage, loadRuntimeConfig, localDrivePlacements, needsCopy, newDriveError, newDrivesBlocked, placementKeys, planReactorClient, primeRuntimeConfig, refreshAppDrives, relistAppDrives, removeLocalCopies, resolveReactorClientMode, resolveReactorWorkerEnabled, resolveRuntimeFlag, resolveSwitchboardDrives, selectAppReactorClient, servedUrl, servesSlug, switchboardDrives, useBackendAuthGate, useIsEmbedded };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as useRoutesById } from "./route-tree-Cth194sC.js";
|
|
2
2
|
import { useIsEmbedded } from "./embedded.js";
|
|
3
3
|
import { OPENED_FROM_STATE_KEY, SETTINGS_PATH, getDriveName, peekDriveNode, useDriveNode, useDrives } from "@powerhousedao/reactor-browser";
|
|
4
4
|
import { Outlet, notFound, redirect, useMatch, useMatches, useRouter, useRouterState } from "@tanstack/react-router";
|
|
@@ -220,4 +220,4 @@ function useConnectChrome() {
|
|
|
220
220
|
//#endregion
|
|
221
221
|
export { CONTENT_VIEW_ID as C, useIsColdStart as D, DrivePending as E, notFoundTitle as S, DRIVE_PENDING_MS as T, showsSettingsTab as _, useCreateDocumentTarget as a, appTitle as b, useDriveRouteData as c, keepOpenedFrom as d, redirectToSettingsTab as f, settingsTitle as g, settingsTabsOf as h, useSidebarMode as i, useDriveRouteIds as l, settingsTabs as m, useConnectChrome as n, DRIVE_ROUTE_ID as o, setSettingsRoute as p, useNavRoutes as r, NODE_ROUTE_ID as s, navRoutes as t, SETTINGS_ROUTE_ID as u, useForgetSettingsOpenedFrom as v, ContentOutlet as w, driveTitle as x, useSettingsTabs as y };
|
|
222
222
|
|
|
223
|
-
//# sourceMappingURL=sidebar-
|
|
223
|
+
//# sourceMappingURL=sidebar-CbMDUc8H.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sidebar-C2y4mZnX.js","names":[],"sources":["../src/router/cold-start.ts","../src/router/route-components.tsx","../src/router/titles.ts","../src/router/settings.ts","../src/router/route-data.ts","../src/router/create-target.ts","../src/router/sidebar.ts"],"sourcesContent":["import { useRouterState } from \"@tanstack/react-router\";\n\n/** True until the router has resolved its first location. */\nexport function useIsColdStart() {\n return useRouterState({ select: (state) => !state.resolvedLocation });\n}\n","import type {\n AnyRoute,\n AnyRouter,\n RouteComponent,\n} from \"@tanstack/react-router\";\nimport { Outlet, useMatch, useRouter } from \"@tanstack/react-router\";\nimport type { ReactNode } from \"react\";\nimport type {\n DocumentDriveDocument,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useIsColdStart } from \"./cold-start.js\";\n\n/** A drive view's props: drive apps and core's directory listing get the same. */\nexport type DriveViewProps = {\n drive: DocumentDriveDocument;\n /** The open folder; undefined at the drive's root. */\n folder?: FolderNode;\n /** The open document's view, when one is open. */\n children?: ReactNode;\n};\n\n/** A document view's props, e.g. core's JSON view or revision history. */\nexport type DocumentViewProps = { document: PHDocument };\n\n// Open views stay while a navigation loads; the pending view only after this.\nexport const DRIVE_PENDING_MS = 200;\n\n/** The scroll container of the content view. */\nexport const CONTENT_VIEW_ID = \"content-view\";\n\n/** A layout's content area: the matched route, in the container whose scroll\n * Connect resets on new views and restores on back and forward. */\nexport function ContentOutlet(props: { className?: string }) {\n return (\n <div\n className={props.className ?? \"flex h-full flex-col overflow-auto\"}\n id={CONTENT_VIEW_ID}\n data-scroll-restoration-id={CONTENT_VIEW_ID}\n >\n {useRouter().options.context.shell ? <LayoutPending /> : <Outlet />}\n </div>\n );\n}\n\n// The loading shell: the layout's own pendingComponent stands in for its page.\nfunction LayoutPending() {\n const router = useRouter<AnyRouter>();\n const routeId = useMatch({ strict: false, select: (match) => match.routeId });\n const routesById = router.routesById as Partial<Record<string, AnyRoute>>;\n const route = routeId ? routesById[routeId] : undefined;\n const Pending = route?.options.pendingComponent as RouteComponent | undefined;\n return Pending ? <Pending /> : null;\n}\n\n/** A note on a cold start; otherwise the open view stays while loading. */\nexport function DrivePending() {\n const isColdStart = useIsColdStart();\n if (!isColdStart) return null;\n return (\n <p role=\"status\" className=\"p-6 text-core-muted\">\n Loading drive…\n </p>\n );\n}\n","// Document titles for Connect's routes; route heads set them through <HeadContent />.\nimport type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport { getDriveName, peekDriveNode } from \"@powerhousedao/reactor-browser\";\nimport type { DriveRouteData } from \"./drive-route-loader.js\";\n\nconst DEFAULT_APP_NAME = \"Connect\";\n\n/** The configured app name, else \"Connect\". */\nexport function appTitle(appName?: string) {\n return appName || DEFAULT_APP_NAME;\n}\n\n/** `Not found · <app>`. */\nexport function notFoundTitle(appName?: string) {\n return `Not found · ${appTitle(appName)}`;\n}\n\n/** `<node> · <drive> · <app>`, from the store so renames show. */\nexport function driveTitle(\n store: PHStore,\n data: DriveRouteData | undefined,\n appName?: string,\n) {\n const drive = data && store.drives?.find((d) => d.header.id === data.driveId);\n if (!drive) return appTitle(appName);\n const node = data.nodeId\n ? peekDriveNode(drive.header.id, data.nodeId, store)\n : undefined;\n return [node?.name, getDriveName(drive)]\n .filter(Boolean)\n .concat(appTitle(appName))\n .join(\" · \");\n}\n","// The settings page: its tabs are the /settings route's children with `staticData.settings`.\nimport {\n OPENED_FROM_STATE_KEY,\n SETTINGS_PATH,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n AnyRoute,\n AnyRouter,\n HistoryState,\n StaticDataRouteOption,\n} from \"@tanstack/react-router\";\nimport { notFound, redirect, useRouter } from \"@tanstack/react-router\";\nimport type { ComponentType } from \"react\";\nimport { useMemo } from \"react\";\nimport { useRoutesById } from \"./route-tree.js\";\nimport type { ConnectRouterContext } from \"./drive-route-loader.js\";\nimport { appTitle } from \"./titles.js\";\n\n/** A settings tab, as a child route of /settings declares it in `staticData`. */\nexport type ConnectSettingsTab = {\n label: string;\n /** Ascending; Connect's own tabs use multiples of 10. */\n order: number;\n icon?: ComponentType<{ size?: number; className?: string }>;\n /** Marks the tab as destructive, e.g. the danger zone. */\n destructive?: boolean;\n /** Hidden, and redirected away from, when this returns false. */\n enabled?: (context: ConnectRouterContext) => boolean;\n};\n\ndeclare module \"@tanstack/react-router\" {\n interface StaticDataRouteOption {\n settings?: ConnectSettingsTab;\n }\n}\n\n/** The settings layout route's id. */\nexport const SETTINGS_ROUTE_ID = `/_app${SETTINGS_PATH}`;\n\n// Structural, not the router's match union: route options typed with it are circular.\ntype SettingsMatch = { routeId: string; staticData: StaticDataRouteOption };\n\n/** A listed tab: its id is its path below /settings. */\nexport type SettingsTabEntry = ConnectSettingsTab & {\n id: string;\n routeId: string;\n to: string;\n};\n\n/** The enabled tabs below `settingsRoute`, in order. */\nexport function settingsTabsOf(\n settingsRoute: AnyRoute,\n context: ConnectRouterContext,\n): SettingsTabEntry[] {\n const children = (settingsRoute.children ?? []) as AnyRoute[];\n const prefix = `${settingsRoute.fullPath}/`;\n return children\n .flatMap((route) => {\n const tab = (\n route.options as { staticData?: { settings?: ConnectSettingsTab } }\n ).staticData?.settings;\n if (!tab || tab.enabled?.(context) === false) return [];\n const { id: routeId, fullPath } = route as {\n id: string;\n fullPath: string;\n };\n const to = fullPath.replace(/\\/$/, \"\");\n return [{ ...tab, id: to.slice(prefix.length), routeId, to }];\n })\n .sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));\n}\n\n/** The settings tabs of `router`'s tree; empty without a settings route. */\nexport function settingsTabs(router: AnyRouter): SettingsTabEntry[] {\n const settingsRoute = router.routesById[SETTINGS_ROUTE_ID] as\n | AnyRoute\n | undefined;\n if (!settingsRoute) return [];\n return settingsTabsOf(\n settingsRoute,\n router.options.context as ConnectRouterContext,\n );\n}\n\nexport function useSettingsTabs() {\n const router = useRouter();\n const routesById = useRoutesById();\n return useMemo(() => settingsTabs(router), [router, routesById]);\n}\n\n/** Whether `matches` show a tab that may stay: not bare /settings, not a disabled tab. */\nexport function showsSettingsTab(\n matches: readonly SettingsMatch[],\n context: ConnectRouterContext,\n) {\n const leaf = matches.at(-1);\n if (!leaf || leaf.routeId === SETTINGS_ROUTE_ID) return false;\n return leaf.staticData.settings?.enabled?.(context) !== false;\n}\n\nlet routerSettingsRoute: AnyRoute | undefined;\n\n/** The router's settings route: core's, or a project's override of it. */\nexport function setSettingsRoute(route?: AnyRoute) {\n routerSettingsRoute = route;\n}\n\n/** Sends bare /settings and a disabled tab to the first tab. */\nexport function redirectToSettingsTab({\n matches,\n context,\n}: {\n matches: readonly SettingsMatch[];\n context: ConnectRouterContext;\n}): void {\n if (showsSettingsTab(matches, context)) return;\n const first =\n routerSettingsRoute && settingsTabsOf(routerSettingsRoute, context).at(0);\n // oxlint-disable-next-line typescript/only-throw-error -- router control flow\n if (!first) throw notFound();\n // oxlint-disable-next-line typescript/only-throw-error -- router control flow\n throw redirect<AnyRouter>({ to: first.to, replace: true, state: true });\n}\n\n/** `Settings · <tab> · <app>`. */\nexport function settingsTitle(tabLabel: string | undefined, appName?: string) {\n return [\"Settings\", tabLabel, appTitle(appName)].filter(Boolean).join(\" · \");\n}\n\n/** Makes closing settings go home, not back to an entry that may be gone,\n * e.g. a deleted drive. */\nexport function useForgetSettingsOpenedFrom() {\n const router = useRouter();\n return () =>\n router.navigate({\n to: \".\",\n search: true,\n replace: true,\n resetScroll: false,\n state: (prev) =>\n ({ ...prev, [OPENED_FROM_STATE_KEY]: undefined }) as HistoryState,\n });\n}\n\n/** History state that keeps where the settings page was opened from. */\nexport function keepOpenedFrom(state: object) {\n const from: unknown = Reflect.get(state, OPENED_FROM_STATE_KEY);\n return { [OPENED_FROM_STATE_KEY]: from } as unknown as HistoryState;\n}\n","import { useDriveNode, useDrives } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport { useRouterState } from \"@tanstack/react-router\";\nimport type { DriveRouteData } from \"./drive-route-loader.js\";\n\n/** The drive layout route's id. */\nexport const DRIVE_ROUTE_ID = \"/_app/d/$driveSlug\";\n/** The node route's id: below the drive layout, with an optional node. */\nexport const NODE_ROUTE_ID = \"/_app/d/$driveSlug/{-$nodeSlug}\";\n\n/** The open drive, folder and document, from the node route's loader data.\n * Live: a drive's edits re-render the caller. */\nexport type DriveRouteView = {\n drive: DocumentDriveDocument | undefined;\n /** The open folder; undefined at the drive's root or on a document. */\n folder: FolderNode | undefined;\n /** The open document's id; undefined on a folder or the drive's root. */\n documentId: string | undefined;\n};\n\n/** The ids the node route resolved, or undefined outside a drive. */\nexport function useDriveRouteIds(): DriveRouteData | undefined {\n return useRouterState({\n select: (state) =>\n state.matches.find((match) => match.routeId === NODE_ROUTE_ID)\n ?.loaderData as DriveRouteData | undefined,\n });\n}\n\n/** What the drive routes show: the drive, and the folder or document open in it. */\nexport function useDriveRouteData(): DriveRouteView {\n const ids = useDriveRouteIds();\n const drives = useDrives();\n const drive = ids && drives?.find((d) => d.header.id === ids.driveId);\n const node = useDriveNode(drive?.header.id, ids?.nodeId);\n const folder = node?.kind === \"folder\" ? node : undefined;\n // A node the listed drive doesn't have yet was a document the loader fetched.\n return { drive, folder, documentId: folder ? undefined : ids?.nodeId };\n}\n","import { useDrives } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { useState } from \"react\";\nimport { useDriveRouteData } from \"./route-data.js\";\n\nexport type CreateDocumentTarget = {\n /** The drive the document goes in; undefined until one is picked. */\n drive: DocumentDriveDocument | undefined;\n /** The drives to pick from, or undefined when the drive is given. */\n choices: DocumentDriveDocument[] | undefined;\n pick: (driveId: string) => void;\n /** Whether it is the open drive, whose open folder the document goes in. */\n isOpenDrive: boolean;\n};\n\n/** Where a new document goes: the modal's `driveId`, else the open drive, else\n * one the user picks, the only drive preselected. */\nexport function useCreateDocumentTarget(\n driveId: string | undefined,\n): CreateDocumentTarget {\n const { drive: openDrive } = useDriveRouteData();\n const drives = useDrives();\n const [picked, setPicked] = useState<string>();\n const given = driveId ?? openDrive?.header.id;\n const only = drives?.length === 1 ? drives[0].header.id : undefined;\n const id = given ?? picked ?? only;\n return {\n drive: drives?.find((d) => d.header.id === id),\n choices: given ? undefined : (drives ?? []),\n pick: setPicked,\n isOpenDrive: !!openDrive && openDrive.header.id === id,\n };\n}\n","// What routes tell the sidebar layout: nav items and whether to show the sidebar.\nimport type { AnyRoute, AnyRouter } from \"@tanstack/react-router\";\nimport { useMatches, useRouter } from \"@tanstack/react-router\";\nimport type { ComponentType } from \"react\";\nimport { useMemo } from \"react\";\nimport { useIsEmbedded } from \"../runtime/embedded.js\";\nimport { useRoutesById } from \"./route-tree.js\";\n\n/** A sidebar link to the route that declares it in `staticData.nav`. */\nexport type ConnectNavItem = {\n label: string;\n icon?: ComponentType<{ size?: number; className?: string }>;\n /** Ascending, after the drives. */\n order: number;\n};\n\n/** \"hidden\" drops the sidebar; \"collapsed\" keeps only its header and footer. */\nexport type SidebarMode = \"hidden\" | \"collapsed\";\n\ndeclare module \"@tanstack/react-router\" {\n interface StaticDataRouteOption {\n nav?: ConnectNavItem;\n sidebar?: SidebarMode;\n }\n}\n\nexport type NavRouteEntry = ConnectNavItem & { routeId: string; to: string };\n\n/** The routes with `staticData.nav`, in order; routes with params can't be listed. */\nexport function navRoutes(router: AnyRouter): NavRouteEntry[] {\n return Object.values(router.routesById as Record<string, AnyRoute>)\n .flatMap((route) => {\n const nav = (route.options as { staticData?: { nav?: ConnectNavItem } })\n .staticData?.nav;\n const { id: routeId, fullPath } = route as {\n id: string;\n fullPath: string;\n };\n if (!nav || fullPath.includes(\"$\")) return [];\n return [{ ...nav, routeId, to: fullPath.replace(/(.)\\/$/, \"$1\") }];\n })\n .sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));\n}\n\nexport function useNavRoutes() {\n const router = useRouter();\n const routesById = useRoutesById();\n return useMemo(() => navRoutes(router), [router, routesById]);\n}\n\n/** The deepest match's `staticData.sidebar`, if any declares one. */\nexport function useSidebarMode(): SidebarMode | undefined {\n return useMatches({\n select: (matches) =>\n matches.findLast((match) => match.staticData.sidebar !== undefined)\n ?.staticData.sidebar,\n });\n}\n\n/** What a layout shows of Connect's chrome on the matched route. */\nexport type ConnectChrome = {\n /** Connect runs inside another app (`?embed=1`): no sidebar, header or footer. */\n embedded: boolean;\n /** No sidebar: embedded, or the route's `staticData.sidebar` is \"hidden\". */\n sidebarHidden: boolean;\n /** The route's `staticData.sidebar` is \"collapsed\". */\n sidebarCollapsed: boolean;\n};\n\n/** The chrome Connect's `_app` layout shows, for a layout that replaces it. */\nexport function useConnectChrome(): ConnectChrome {\n const embedded = useIsEmbedded();\n const mode = useSidebarMode();\n return {\n embedded,\n sidebarHidden: embedded || mode === \"hidden\",\n sidebarCollapsed: !embedded && mode === \"collapsed\",\n };\n}\n"],"mappings":";;;;;;;;AAGA,SAAgB,iBAAiB;CAC/B,OAAO,eAAe,EAAE,SAAS,UAAU,CAAC,MAAM,iBAAiB,CAAC;AACtE;;;ACsBA,MAAa,mBAAmB;;AAGhC,MAAa,kBAAkB;;;AAI/B,SAAgB,cAAc,OAA+B;CAC3D,OACE,oBAAC,OAAD;EACE,WAAW,MAAM,aAAa;EAC9B,IAAI;EACJ,8BAA4B;EAE3B,UAAA,UAAU,CAAC,CAAC,QAAQ,QAAQ,QAAQ,oBA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U,OAAO,OAAO;CACtD;AACF;;;;ACHA,SAAgB,UAAU,QAAoC;CAC5D,OAAO,OAAO,OAAO,OAAO,UAAsC,CAAC,CAChE,SAAS,UAAU;EAClB,MAAM,MAAO,MAAM,QAChB,YAAY;EACf,MAAM,EAAE,IAAI,SAAS,aAAa;EAIlC,IAAI,CAAC,OAAO,SAAS,SAAS,GAAG,GAAG,OAAO,CAAC;EAC5C,OAAO,CAAC;GAAE,GAAG;GAAK;GAAS,IAAI,SAAS,QAAQ,UAAU,IAAI;EAAE,CAAC;CACnE,CAAC,CAAC,CACD,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC;AACvE;AAEA,SAAgB,eAAe;CAC7B,MAAM,SAAS,UAAU;CACzB,MAAM,aAAa,cAAc;CACjC,OAAO,cAAc,UAAU,MAAM,GAAG,CAAC,QAAQ,UAAU,CAAC;AAC9D;;AAGA,SAAgB,iBAA0C;CACxD,OAAO,WAAW,EAChB,SAAS,YACP,QAAQ,UAAU,UAAU,MAAM,WAAW,YAAY,KAAA,CAAS,CAAC,EAC/D,WAAW,QACnB,CAAC;AACH;;AAaA,SAAgB,mBAAkC;CAChD,MAAM,WAAW,cAAc;CAC/B,MAAM,OAAO,eAAe;CAC5B,OAAO;EACL;EACA,eAAe,YAAY,SAAS;EACpC,kBAAkB,CAAC,YAAY,SAAS;CAC1C;AACF"}
|
|
1
|
+
{"version":3,"file":"sidebar-CbMDUc8H.js","names":[],"sources":["../src/router/cold-start.ts","../src/router/route-components.tsx","../src/router/titles.ts","../src/router/settings.ts","../src/router/route-data.ts","../src/router/create-target.ts","../src/router/sidebar.ts"],"sourcesContent":["import { useRouterState } from \"@tanstack/react-router\";\n\n/** True until the router has resolved its first location. */\nexport function useIsColdStart() {\n return useRouterState({ select: (state) => !state.resolvedLocation });\n}\n","import type {\n AnyRoute,\n AnyRouter,\n RouteComponent,\n} from \"@tanstack/react-router\";\nimport { Outlet, useMatch, useRouter } from \"@tanstack/react-router\";\nimport type { ReactNode } from \"react\";\nimport type {\n DocumentDriveDocument,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useIsColdStart } from \"./cold-start.js\";\n\n/** A drive view's props: drive apps and core's directory listing get the same. */\nexport type DriveViewProps = {\n drive: DocumentDriveDocument;\n /** The open folder; undefined at the drive's root. */\n folder?: FolderNode;\n /** The open document's view, when one is open. */\n children?: ReactNode;\n};\n\n/** A document view's props, e.g. core's JSON view or revision history. */\nexport type DocumentViewProps = { document: PHDocument };\n\n// Open views stay while a navigation loads; the pending view only after this.\nexport const DRIVE_PENDING_MS = 200;\n\n/** The scroll container of the content view. */\nexport const CONTENT_VIEW_ID = \"content-view\";\n\n/** A layout's content area: the matched route, in the container whose scroll\n * Connect resets on new views and restores on back and forward. */\nexport function ContentOutlet(props: { className?: string }) {\n return (\n <div\n className={props.className ?? \"flex h-full flex-col overflow-auto\"}\n id={CONTENT_VIEW_ID}\n data-scroll-restoration-id={CONTENT_VIEW_ID}\n >\n {useRouter().options.context.shell ? <LayoutPending /> : <Outlet />}\n </div>\n );\n}\n\n// The loading shell: the layout's own pendingComponent stands in for its page.\nfunction LayoutPending() {\n const router = useRouter<AnyRouter>();\n const routeId = useMatch({ strict: false, select: (match) => match.routeId });\n const routesById = router.routesById as Partial<Record<string, AnyRoute>>;\n const route = routeId ? routesById[routeId] : undefined;\n const Pending = route?.options.pendingComponent as RouteComponent | undefined;\n return Pending ? <Pending /> : null;\n}\n\n/** A note on a cold start; otherwise the open view stays while loading. */\nexport function DrivePending() {\n const isColdStart = useIsColdStart();\n if (!isColdStart) return null;\n return (\n <p role=\"status\" className=\"p-6 text-core-muted\">\n Loading drive…\n </p>\n );\n}\n","// Document titles for Connect's routes; route heads set them through <HeadContent />.\nimport type { PHStore } from \"@powerhousedao/reactor-browser\";\nimport { getDriveName, peekDriveNode } from \"@powerhousedao/reactor-browser\";\nimport type { DriveRouteData } from \"./drive-route-loader.js\";\n\nconst DEFAULT_APP_NAME = \"Connect\";\n\n/** The configured app name, else \"Connect\". */\nexport function appTitle(appName?: string) {\n return appName || DEFAULT_APP_NAME;\n}\n\n/** `Not found · <app>`. */\nexport function notFoundTitle(appName?: string) {\n return `Not found · ${appTitle(appName)}`;\n}\n\n/** `<node> · <drive> · <app>`, from the store so renames show. */\nexport function driveTitle(\n store: PHStore,\n data: DriveRouteData | undefined,\n appName?: string,\n) {\n const drive = data && store.drives?.find((d) => d.header.id === data.driveId);\n if (!drive) return appTitle(appName);\n const node = data.nodeId\n ? peekDriveNode(drive.header.id, data.nodeId, store)\n : undefined;\n return [node?.name, getDriveName(drive)]\n .filter(Boolean)\n .concat(appTitle(appName))\n .join(\" · \");\n}\n","// The settings page: its tabs are the /settings route's children with `staticData.settings`.\nimport {\n OPENED_FROM_STATE_KEY,\n SETTINGS_PATH,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n AnyRoute,\n AnyRouter,\n HistoryState,\n StaticDataRouteOption,\n} from \"@tanstack/react-router\";\nimport { notFound, redirect, useRouter } from \"@tanstack/react-router\";\nimport type { ComponentType } from \"react\";\nimport { useMemo } from \"react\";\nimport { useRoutesById } from \"./route-tree.js\";\nimport type { ConnectRouterContext } from \"./drive-route-loader.js\";\nimport { appTitle } from \"./titles.js\";\n\n/** A settings tab, as a child route of /settings declares it in `staticData`. */\nexport type ConnectSettingsTab = {\n label: string;\n /** Ascending; Connect's own tabs use multiples of 10. */\n order: number;\n icon?: ComponentType<{ size?: number; className?: string }>;\n /** Marks the tab as destructive, e.g. the danger zone. */\n destructive?: boolean;\n /** Hidden, and redirected away from, when this returns false. */\n enabled?: (context: ConnectRouterContext) => boolean;\n};\n\ndeclare module \"@tanstack/react-router\" {\n interface StaticDataRouteOption {\n settings?: ConnectSettingsTab;\n }\n}\n\n/** The settings layout route's id. */\nexport const SETTINGS_ROUTE_ID = `/_app${SETTINGS_PATH}`;\n\n// Structural, not the router's match union: route options typed with it are circular.\ntype SettingsMatch = { routeId: string; staticData: StaticDataRouteOption };\n\n/** A listed tab: its id is its path below /settings. */\nexport type SettingsTabEntry = ConnectSettingsTab & {\n id: string;\n routeId: string;\n to: string;\n};\n\n/** The enabled tabs below `settingsRoute`, in order. */\nexport function settingsTabsOf(\n settingsRoute: AnyRoute,\n context: ConnectRouterContext,\n): SettingsTabEntry[] {\n const children = (settingsRoute.children ?? []) as AnyRoute[];\n const prefix = `${settingsRoute.fullPath}/`;\n return children\n .flatMap((route) => {\n const tab = (\n route.options as { staticData?: { settings?: ConnectSettingsTab } }\n ).staticData?.settings;\n if (!tab || tab.enabled?.(context) === false) return [];\n const { id: routeId, fullPath } = route as {\n id: string;\n fullPath: string;\n };\n const to = fullPath.replace(/\\/$/, \"\");\n return [{ ...tab, id: to.slice(prefix.length), routeId, to }];\n })\n .sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));\n}\n\n/** The settings tabs of `router`'s tree; empty without a settings route. */\nexport function settingsTabs(router: AnyRouter): SettingsTabEntry[] {\n const settingsRoute = router.routesById[SETTINGS_ROUTE_ID] as\n | AnyRoute\n | undefined;\n if (!settingsRoute) return [];\n return settingsTabsOf(\n settingsRoute,\n router.options.context as ConnectRouterContext,\n );\n}\n\nexport function useSettingsTabs() {\n const router = useRouter();\n const routesById = useRoutesById();\n return useMemo(() => settingsTabs(router), [router, routesById]);\n}\n\n/** Whether `matches` show a tab that may stay: not bare /settings, not a disabled tab. */\nexport function showsSettingsTab(\n matches: readonly SettingsMatch[],\n context: ConnectRouterContext,\n) {\n const leaf = matches.at(-1);\n if (!leaf || leaf.routeId === SETTINGS_ROUTE_ID) return false;\n return leaf.staticData.settings?.enabled?.(context) !== false;\n}\n\nlet routerSettingsRoute: AnyRoute | undefined;\n\n/** The router's settings route: core's, or a project's override of it. */\nexport function setSettingsRoute(route?: AnyRoute) {\n routerSettingsRoute = route;\n}\n\n/** Sends bare /settings and a disabled tab to the first tab. */\nexport function redirectToSettingsTab({\n matches,\n context,\n}: {\n matches: readonly SettingsMatch[];\n context: ConnectRouterContext;\n}): void {\n if (showsSettingsTab(matches, context)) return;\n const first =\n routerSettingsRoute && settingsTabsOf(routerSettingsRoute, context).at(0);\n // oxlint-disable-next-line typescript/only-throw-error -- router control flow\n if (!first) throw notFound();\n // oxlint-disable-next-line typescript/only-throw-error -- router control flow\n throw redirect<AnyRouter>({ to: first.to, replace: true, state: true });\n}\n\n/** `Settings · <tab> · <app>`. */\nexport function settingsTitle(tabLabel: string | undefined, appName?: string) {\n return [\"Settings\", tabLabel, appTitle(appName)].filter(Boolean).join(\" · \");\n}\n\n/** Makes closing settings go home, not back to an entry that may be gone,\n * e.g. a deleted drive. */\nexport function useForgetSettingsOpenedFrom() {\n const router = useRouter();\n return () =>\n router.navigate({\n to: \".\",\n search: true,\n replace: true,\n resetScroll: false,\n state: (prev) =>\n ({ ...prev, [OPENED_FROM_STATE_KEY]: undefined }) as HistoryState,\n });\n}\n\n/** History state that keeps where the settings page was opened from. */\nexport function keepOpenedFrom(state: object) {\n const from: unknown = Reflect.get(state, OPENED_FROM_STATE_KEY);\n return { [OPENED_FROM_STATE_KEY]: from } as unknown as HistoryState;\n}\n","import { useDriveNode, useDrives } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport { useRouterState } from \"@tanstack/react-router\";\nimport type { DriveRouteData } from \"./drive-route-loader.js\";\n\n/** The drive layout route's id. */\nexport const DRIVE_ROUTE_ID = \"/_app/d/$driveSlug\";\n/** The node route's id: below the drive layout, with an optional node. */\nexport const NODE_ROUTE_ID = \"/_app/d/$driveSlug/{-$nodeSlug}\";\n\n/** The open drive, folder and document, from the node route's loader data.\n * Live: a drive's edits re-render the caller. */\nexport type DriveRouteView = {\n drive: DocumentDriveDocument | undefined;\n /** The open folder; undefined at the drive's root or on a document. */\n folder: FolderNode | undefined;\n /** The open document's id; undefined on a folder or the drive's root. */\n documentId: string | undefined;\n};\n\n/** The ids the node route resolved, or undefined outside a drive. */\nexport function useDriveRouteIds(): DriveRouteData | undefined {\n return useRouterState({\n select: (state) =>\n state.matches.find((match) => match.routeId === NODE_ROUTE_ID)\n ?.loaderData as DriveRouteData | undefined,\n });\n}\n\n/** What the drive routes show: the drive, and the folder or document open in it. */\nexport function useDriveRouteData(): DriveRouteView {\n const ids = useDriveRouteIds();\n const drives = useDrives();\n const drive = ids && drives?.find((d) => d.header.id === ids.driveId);\n const node = useDriveNode(drive?.header.id, ids?.nodeId);\n const folder = node?.kind === \"folder\" ? node : undefined;\n // A node the listed drive doesn't have yet was a document the loader fetched.\n return { drive, folder, documentId: folder ? undefined : ids?.nodeId };\n}\n","import { useDrives } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { useState } from \"react\";\nimport { useDriveRouteData } from \"./route-data.js\";\n\nexport type CreateDocumentTarget = {\n /** The drive the document goes in; undefined until one is picked. */\n drive: DocumentDriveDocument | undefined;\n /** The drives to pick from, or undefined when the drive is given. */\n choices: DocumentDriveDocument[] | undefined;\n pick: (driveId: string) => void;\n /** Whether it is the open drive, whose open folder the document goes in. */\n isOpenDrive: boolean;\n};\n\n/** Where a new document goes: the modal's `driveId`, else the open drive, else\n * one the user picks, the only drive preselected. */\nexport function useCreateDocumentTarget(\n driveId: string | undefined,\n): CreateDocumentTarget {\n const { drive: openDrive } = useDriveRouteData();\n const drives = useDrives();\n const [picked, setPicked] = useState<string>();\n const given = driveId ?? openDrive?.header.id;\n const only = drives?.length === 1 ? drives[0].header.id : undefined;\n const id = given ?? picked ?? only;\n return {\n drive: drives?.find((d) => d.header.id === id),\n choices: given ? undefined : (drives ?? []),\n pick: setPicked,\n isOpenDrive: !!openDrive && openDrive.header.id === id,\n };\n}\n","// What routes tell the sidebar layout: nav items and whether to show the sidebar.\nimport type { AnyRoute, AnyRouter } from \"@tanstack/react-router\";\nimport { useMatches, useRouter } from \"@tanstack/react-router\";\nimport type { ComponentType } from \"react\";\nimport { useMemo } from \"react\";\nimport { useIsEmbedded } from \"../runtime/embedded.js\";\nimport { useRoutesById } from \"./route-tree.js\";\n\n/** A sidebar link to the route that declares it in `staticData.nav`. */\nexport type ConnectNavItem = {\n label: string;\n icon?: ComponentType<{ size?: number; className?: string }>;\n /** Ascending, after the drives. */\n order: number;\n};\n\n/** \"hidden\" drops the sidebar; \"collapsed\" keeps only its header and footer. */\nexport type SidebarMode = \"hidden\" | \"collapsed\";\n\ndeclare module \"@tanstack/react-router\" {\n interface StaticDataRouteOption {\n nav?: ConnectNavItem;\n sidebar?: SidebarMode;\n }\n}\n\nexport type NavRouteEntry = ConnectNavItem & { routeId: string; to: string };\n\n/** The routes with `staticData.nav`, in order; routes with params can't be listed. */\nexport function navRoutes(router: AnyRouter): NavRouteEntry[] {\n return Object.values(router.routesById as Record<string, AnyRoute>)\n .flatMap((route) => {\n const nav = (route.options as { staticData?: { nav?: ConnectNavItem } })\n .staticData?.nav;\n const { id: routeId, fullPath } = route as {\n id: string;\n fullPath: string;\n };\n if (!nav || fullPath.includes(\"$\")) return [];\n return [{ ...nav, routeId, to: fullPath.replace(/(.)\\/$/, \"$1\") }];\n })\n .sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));\n}\n\nexport function useNavRoutes() {\n const router = useRouter();\n const routesById = useRoutesById();\n return useMemo(() => navRoutes(router), [router, routesById]);\n}\n\n/** The deepest match's `staticData.sidebar`, if any declares one. */\nexport function useSidebarMode(): SidebarMode | undefined {\n return useMatches({\n select: (matches) =>\n matches.findLast((match) => match.staticData.sidebar !== undefined)\n ?.staticData.sidebar,\n });\n}\n\n/** What a layout shows of Connect's chrome on the matched route. */\nexport type ConnectChrome = {\n /** Connect runs inside another app (`?embed=1`): no sidebar, header or footer. */\n embedded: boolean;\n /** No sidebar: embedded, or the route's `staticData.sidebar` is \"hidden\". */\n sidebarHidden: boolean;\n /** The route's `staticData.sidebar` is \"collapsed\". */\n sidebarCollapsed: boolean;\n};\n\n/** The chrome Connect's `_app` layout shows, for a layout that replaces it. */\nexport function useConnectChrome(): ConnectChrome {\n const embedded = useIsEmbedded();\n const mode = useSidebarMode();\n return {\n embedded,\n sidebarHidden: embedded || mode === \"hidden\",\n sidebarCollapsed: !embedded && mode === \"collapsed\",\n };\n}\n"],"mappings":";;;;;;;;AAGA,SAAgB,iBAAiB;CAC/B,OAAO,eAAe,EAAE,SAAS,UAAU,CAAC,MAAM,iBAAiB,CAAC;AACtE;;;ACsBA,MAAa,mBAAmB;;AAGhC,MAAa,kBAAkB;;;AAI/B,SAAgB,cAAc,OAA+B;CAC3D,OACE,oBAAC,OAAD;EACE,WAAW,MAAM,aAAa;EAC9B,IAAI;EACJ,8BAA4B;EAE3B,UAAA,UAAU,CAAC,CAAC,QAAQ,QAAQ,QAAQ,oBAAC,eAAD,CAAgB,CAAA,IAAI,oBAAC,QAAD,CAAS,CAAA;CAC/D,CAAA;AAET;AAGA,SAAS,gBAAgB;CACvB,MAAM,SAAS,UAAqB;CACpC,MAAM,UAAU,SAAS;EAAE,QAAQ;EAAO,SAAS,UAAU,MAAM;CAAQ,CAAC;CAC5E,MAAM,aAAa,OAAO;CAE1B,MAAM,WADQ,UAAU,WAAW,WAAW,KAAA,EAAA,EACvB,QAAQ;CAC/B,OAAO,UAAU,oBAAC,SAAD,CAAU,CAAA,IAAI;AACjC;;AAGA,SAAgB,eAAe;CAE7B,IAAI,CADgB,eACL,GAAG,OAAO;CACzB,OACE,oBAAC,KAAD;EAAG,MAAK;EAAS,WAAU;EAAsB,UAAA;CAE9C,CAAA;AAEP;;;AC5DA,MAAM,mBAAmB;;AAGzB,SAAgB,SAAS,SAAkB;CACzC,OAAO,WAAW;AACpB;;AAGA,SAAgB,cAAc,SAAkB;CAC9C,OAAO,eAAe,SAAS,OAAO;AACxC;;AAGA,SAAgB,WACd,OACA,MACA,SACA;CACA,MAAM,QAAQ,QAAQ,MAAM,QAAQ,MAAM,MAAM,EAAE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