@powerhousedao/connect-core 6.2.3-dev.86 → 6.2.3-dev.88
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/{index-ZFFeYX4A.d.ts → index-BNdsbq2I.d.ts} +42 -17
- package/dist/index-BNdsbq2I.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{multi-reactor-Dvwv69u1.js → multi-reactor-91g8OeBB.js} +17 -12
- package/dist/multi-reactor-91g8OeBB.js.map +1 -0
- package/dist/{runtime-LvAkxbdf.js → runtime-CtZfHUnR.js} +107 -11
- package/dist/runtime-CtZfHUnR.js.map +1 -0
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +2 -2
- package/package.json +8 -8
- package/src/runtime/app-reactor-client.ts +27 -4
- package/src/runtime/drive-placement.ts +12 -0
- package/src/runtime/index.ts +7 -0
- package/src/runtime/multi-reactor.ts +38 -17
- package/src/runtime/new-drive.ts +126 -0
- package/src/runtime/reactor-client-mode.ts +44 -5
- package/dist/index-ZFFeYX4A.d.ts.map +0 -1
- package/dist/multi-reactor-Dvwv69u1.js.map +0 -1
- package/dist/runtime-LvAkxbdf.js.map +0 -1
|
@@ -2,6 +2,7 @@ import type { PHReactorClientMode } from "@powerhousedao/shared/clis";
|
|
|
2
2
|
import { getRuntimeConfig } from "./runtime-config.js";
|
|
3
3
|
import { isMultiReactorEnabled } from "./multi-reactor-flag.js";
|
|
4
4
|
import { isReactorWorkerEnabled } from "./reactor-worker-flag.js";
|
|
5
|
+
import { logger } from "document-model";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Which of the four reactor clients Connect boots. Standardized by the
|
|
@@ -34,7 +35,16 @@ export const REACTOR_CLIENT_STORAGE_KEY = "ph:reactorClient";
|
|
|
34
35
|
const asMode = (value: string | null | undefined) =>
|
|
35
36
|
value && MODES.has(value) ? (value as ReactorClientMode) : undefined;
|
|
36
37
|
|
|
37
|
-
|
|
38
|
+
const LOCAL_ONLY: ReadonlySet<ReactorClientMode> = new Set([
|
|
39
|
+
"in-process",
|
|
40
|
+
"worker",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** Set while this page load keeps its reactor to itself against the host's `newDrives`. */
|
|
44
|
+
let blockedNewDrives: Error | undefined;
|
|
45
|
+
|
|
46
|
+
/** While new drives go to a switchboard, a local-only override applies only from the URL, never from storage. */
|
|
47
|
+
function fromTab(newDrives: string | undefined): ReactorClientMode | undefined {
|
|
38
48
|
if (typeof window === "undefined") return undefined;
|
|
39
49
|
let query: ReactorClientMode | undefined;
|
|
40
50
|
try {
|
|
@@ -44,12 +54,28 @@ function fromTab(): ReactorClientMode | undefined {
|
|
|
44
54
|
} catch {
|
|
45
55
|
return undefined;
|
|
46
56
|
}
|
|
57
|
+
const localOnly = (mode: ReactorClientMode | undefined) =>
|
|
58
|
+
newDrives !== undefined && mode !== undefined && LOCAL_ONLY.has(mode);
|
|
47
59
|
try {
|
|
48
60
|
if (query) {
|
|
49
|
-
|
|
61
|
+
if (localOnly(query)) {
|
|
62
|
+
window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);
|
|
63
|
+
} else {
|
|
64
|
+
window.localStorage.setItem(REACTOR_CLIENT_STORAGE_KEY, query);
|
|
65
|
+
}
|
|
50
66
|
return query;
|
|
51
67
|
}
|
|
52
|
-
|
|
68
|
+
const stored = asMode(
|
|
69
|
+
window.localStorage.getItem(REACTOR_CLIENT_STORAGE_KEY),
|
|
70
|
+
);
|
|
71
|
+
if (!localOnly(stored)) return stored;
|
|
72
|
+
window.localStorage.removeItem(REACTOR_CLIENT_STORAGE_KEY);
|
|
73
|
+
logger.warn(
|
|
74
|
+
"Ignoring the stored ?reactorClient=@mode: new drives go to @switchboard",
|
|
75
|
+
stored,
|
|
76
|
+
newDrives,
|
|
77
|
+
);
|
|
78
|
+
return undefined;
|
|
53
79
|
} catch {
|
|
54
80
|
// Blocked storage: the query still applies for this page load.
|
|
55
81
|
return query;
|
|
@@ -57,12 +83,25 @@ function fromTab(): ReactorClientMode | undefined {
|
|
|
57
83
|
}
|
|
58
84
|
|
|
59
85
|
export function resolveReactorClientMode(): ReactorClientMode {
|
|
60
|
-
const
|
|
86
|
+
const instance = getRuntimeConfig().connect.instance;
|
|
87
|
+
const newDrives = instance?.router?.newDrives;
|
|
88
|
+
const override = fromTab(newDrives);
|
|
89
|
+
blockedNewDrives =
|
|
90
|
+
override && newDrives !== undefined && LOCAL_ONLY.has(override)
|
|
91
|
+
? new Error(
|
|
92
|
+
`New drives go to ${newDrives}, but this browser is set to keep its reactor to itself (?reactorClient=${override}).`,
|
|
93
|
+
)
|
|
94
|
+
: undefined;
|
|
61
95
|
if (override) return override;
|
|
62
|
-
const configured =
|
|
96
|
+
const configured = instance?.reactorClient;
|
|
63
97
|
if (configured && MODES.has(configured)) return configured;
|
|
64
98
|
// Legacy fallback — unchanged behaviour for configs without reactorClient.
|
|
65
99
|
if (isMultiReactorEnabled()) return "router";
|
|
66
100
|
if (isReactorWorkerEnabled()) return "worker";
|
|
67
101
|
return "in-process";
|
|
68
102
|
}
|
|
103
|
+
|
|
104
|
+
/** Why this page load can't create a drive where the host says, or undefined when it can. */
|
|
105
|
+
export function newDrivesBlocked(): Error | undefined {
|
|
106
|
+
return blockedNewDrives;
|
|
107
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-ZFFeYX4A.d.ts","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/drive-placement.ts","../src/runtime/multi-reactor.ts","../src/runtime/app-reactor-client.ts","../src/runtime/drive-placements.ts","../src/runtime/ph-store.ts","../src/runtime/local-package.ts"],"mappings":";;;;;;;;;;KAAY;EACV;EACA;EACA;;iBAIc,mBAAmB,OAAO;KAY9B;EACV;EACA;EACA;;iBAKc,qBAAqB,MAAM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AK,iBAAiB,kBAAkB;;EA+C9C,MAAM,kBAAkB;;EAMlB,UAAU;;UAkBF;UA8BA;UAYA;UAaN;UAYA;;;;;;iBC7UM,qBAAqB;;;;KCNzB,kBAAkB;GAC3B,OAAO;;KAGE,eAAe,wBAAwB;;KAGvC,qBAAqB,sBAAsB,QAAQ;;iBAG/C,iBACd,QAAQ,iCACP,mBAAmB,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"multi-reactor-Dvwv69u1.js","names":[],"sources":["../src/runtime/multi-reactor.ts"],"sourcesContent":["import {\n createReactorInspector,\n type ReactorInfo,\n} from \"@powerhousedao/reactor\";\nimport {\n ambientRenownSigner,\n ambientRenownTokenProvider,\n createSwitchboardBackend,\n type BrowserReactorClientModule,\n type SwitchboardBackend,\n type WorkerReactorClientModule,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n FanInPartialFailureError,\n fromReactorClient,\n RoutingReactorClient,\n type CollectionRequirementsInput,\n type ReactorReach,\n type RoutableBackendConfig,\n type RouterDiagnostic,\n type RoutingClientOptions,\n} from \"@powerhousedao/reactor-router\";\nimport type {\n DocumentModelModule,\n ISigner,\n} from \"@powerhousedao/shared/document-model\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { logger } from \"document-model\";\nimport { LOCAL_BACKEND_NAME } from \"./drive-placement.js\";\n\nexport { LOCAL_BACKEND_NAME } from \"./drive-placement.js\";\nexport const REMOTE_BACKEND_NAME = \"switchboard-remote\";\n\nexport type LocalReactorModule =\n | BrowserReactorClientModule\n | WorkerReactorClientModule;\n\n/** Only the tab's reactor is inspectable here, so new collections land on it. */\nexport const PLACE_ON_LOCAL: CollectionRequirementsInput = Object.freeze({\n inspectable: true,\n});\n\nexport function localReach(kind: LocalReactorModule[\"kind\"]): ReactorReach {\n return kind === \"worker\"\n ? { hosting: \"worker\", inspection: \"rpc\" }\n : { hosting: \"in-process\", inspection: \"direct\" };\n}\n\n/** Read at every refresh, never kept: a rebuilt reactor reports its own. */\nexport function localFacts(\n module: LocalReactorModule,\n): () => Promise<ReactorInfo> {\n if (module.kind === \"worker\") {\n return () => module.inspector.info();\n }\n return async () => {\n const reactorModule = module.reactorModule;\n if (!reactorModule) {\n throw new Error(\"The in-tab reactor exposes no module to inspect\");\n }\n return createReactorInspector(reactorModule).info();\n };\n}\n\n/** `<origin>[/<prefix>]/d/<slug>` -> `<origin>[/<prefix>]/graphql`. */\nexport function deriveSwitchboardGraphqlUrl(\n remoteDriveUrl: string,\n): string | undefined {\n return switchboardOfDrive(remoteDriveUrl)?.graphql;\n}\n\n/** A switchboard the router reaches, by its router backend name. */\nexport type SwitchboardRemote = { name: string; graphqlUrl: string };\n\n/** The loaded document models, or a getter that reads the current ones. */\nexport type LoadedDocumentModels =\n | readonly DocumentModelModule[]\n | (() => readonly DocumentModelModule[]);\n\nexport type MultiReactorParams = {\n /** The local module, built and ready. Undefined builds a REMOTE-ONLY router\n * (no local backend → no local reactor, no PGlite): the `remote` client. */\n module: LocalReactorModule | undefined;\n /** One per switchboard; `remoteGraphqlUrl` alone is one named `switchboard-remote`. */\n remotes?: readonly SwitchboardRemote[];\n remoteGraphqlUrl?: string;\n /** Collection key or drive id -> backend; names no backend here are dropped. */\n collections?: Readonly<Record<string, string>>;\n /** Signs routed writes; unsigned (anonymous) without one. */\n signer?: ISigner;\n /** Signing models when the local module exposes no registry; the router asks the local reactor (or, remote-only, the loaded set). */\n documentModelModules: LoadedDocumentModels;\n onDiagnostic?: RouterDiagnostic;\n};\n\n/** Remote-only placement: the Switchboard serves every collection. (It offers\n * no inspection surface over GraphQL, so PLACE_ON_LOCAL's `inspectable`\n * requirement must NOT apply, or no backend would be eligible.) */\nexport const PLACE_ON_REMOTE: CollectionRequirementsInput = Object.freeze({});\n\n/**\n * The local answer stands when only the Switchboard could not answer -- but\n * only when there IS a local backend. Remote-only has nothing to fall back to,\n * so its errors surface. Installed as the router's `answerFailedIdCheck`, so\n * the facade and `write.isDocumentIdTaken` both apply it.\n */\nfunction localIdCheckAnswer(\n documentId: string,\n error: unknown,\n remoteNames: ReadonlySet<string>,\n): boolean | undefined {\n if (!failedOnlyOnRemote(error, remoteNames)) {\n return undefined;\n }\n logger.warn(\n \"The Switchboard could not say whether @id is taken; using the local reactor's answer: @error\",\n documentId,\n error,\n );\n return false;\n}\n\n/** The router Connect installs, with Connect's handling of credentials and id checks. */\nexport class ConnectRoutingClient extends RoutingReactorClient {\n private readonly remotes: readonly SwitchboardBackend[];\n\n constructor(\n backends: readonly RoutableBackendConfig[],\n options: RoutingClientOptions,\n remotes: readonly SwitchboardBackend[],\n hasLocal: boolean,\n ) {\n const remoteNames = new Set(remotes.map((remote) => remote.config.name));\n super(backends, {\n ...options,\n answerFailedIdCheck: hasLocal\n ? (id, error) => localIdCheckAnswer(id, error, remoteNames)\n : options.answerFailedIdCheck,\n });\n this.remotes = remotes;\n }\n\n /** Renown's sign-in and sign-out call this on whatever client is installed. */\n notifyCredentialsChanged(): void {\n for (const remote of this.remotes) remote.notifyCredentialsChanged();\n }\n}\n\nfunction failedOnlyOnRemote(\n error: unknown,\n remoteNames: ReadonlySet<string>,\n): boolean {\n return (\n error instanceof FanInPartialFailureError &&\n error.failures.every((failure) => remoteNames.has(failure.backend))\n );\n}\n\n/** The remotes to build, one per switchboard: the first link to a base wins. */\nfunction remotesOf(params: MultiReactorParams): SwitchboardRemote[] {\n const listed: readonly SwitchboardRemote[] = params.remotes?.length\n ? params.remotes\n : params.remoteGraphqlUrl\n ? [{ name: REMOTE_BACKEND_NAME, graphqlUrl: params.remoteGraphqlUrl }]\n : [];\n const seen = new Set<string>();\n return listed.filter((remote) => {\n if (seen.has(remote.graphqlUrl)) {\n logger.warn(\n \"@name opens the same switchboard as an earlier backend; skipping it\",\n remote.name,\n );\n return false;\n }\n seen.add(remote.graphqlUrl);\n return true;\n });\n}\n\n/**\n * Build the Connect routing client. With a local `module` it is the router\n * over the tab's reactor (primary) and the Switchboard; WITHOUT one it is the\n * `remote` client — a remote-only router whose single backend is the\n * Switchboard, so no local reactor (and no PGlite) is built. Either way the\n * result is a full IReactorClient the app graph consumes unchanged.\n */\nexport async function buildMultiReactorClient(\n params: MultiReactorParams,\n): Promise<ConnectRoutingClient> {\n const module = params.module;\n const registry = module?.reactorModule?.documentModelRegistry;\n const loaded = params.documentModelModules;\n const loadedModules = typeof loaded === \"function\" ? loaded : () => loaded;\n const listed = remotesOf(params);\n if (listed.length === 0) {\n throw new Error(\"A routing client needs at least one switchboard\");\n }\n // The logged-in Renown user's token and signer, read per request as before.\n const remotes = listed.map((remote) =>\n createSwitchboardBackend({\n name: remote.name,\n url: remote.graphqlUrl,\n tokenProvider: ambientRenownTokenProvider,\n signer: ambientRenownSigner,\n documentModels: () => registry?.getAllModules() ?? loadedModules(),\n inspection: \"none\",\n }),\n );\n const remoteBackends = remotes.map((remote) => remote.config);\n const backends: RoutableBackendConfig[] = module\n ? [\n {\n name: LOCAL_BACKEND_NAME,\n backend: fromReactorClient(module.client),\n facts: localFacts(module),\n reach: localReach(module.kind),\n refusesMisroutes: false,\n },\n ...remoteBackends,\n ]\n : remoteBackends;\n const names = new Set(backends.map((backend) => backend.name));\n const collections = Object.fromEntries(\n Object.entries(params.collections ?? {}).filter(([, backend]) =>\n names.has(backend),\n ),\n );\n const router = new ConnectRoutingClient(\n backends,\n {\n // Remote-only: the first Switchboard is primary; with a local reactor,\n // new collections land on it (inspectable).\n primaryBackend: module ? LOCAL_BACKEND_NAME : remoteBackends[0].name,\n defaultRequirements: module ? PLACE_ON_LOCAL : PLACE_ON_REMOTE,\n collections,\n signer: params.signer,\n onDiagnostic: params.onDiagnostic,\n // The Switchboard serves no models over GraphQL; remote-only uses the loaded set.\n documentModelModules: module ? undefined : loadedModules,\n },\n remotes,\n Boolean(module),\n );\n await router.refreshFacts();\n return router;\n}\n"],"mappings":";;;;;;;AA+BA,MAAa,sBAAsB;;AAOnC,MAAa,iBAA8C,OAAO,OAAO,EACvE,aAAa,KACf,CA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AAA,IAAY;CAC7C,GACA,SACA,QAAQ,MAAM,CAChB;CACA,MAAM,OAAO,aAAa;CAC1B,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-LvAkxbdf.js","names":[],"sources":["../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/drive-placement.ts","../src/runtime/drive-placements.ts","../src/runtime/ph-store.ts","../src/runtime/local-package.ts"],"sourcesContent":["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\";\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 the LEGACY booleans — so a config that only sets\n * reactorWorker/multiReactor behaves exactly as before.\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\nfunction fromTab(): 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 try {\n if (query) {\n window.localStorage.setItem(REACTOR_CLIENT_STORAGE_KEY, query);\n return query;\n }\n return asMode(window.localStorage.getItem(REACTOR_CLIENT_STORAGE_KEY));\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 override = fromTab();\n if (override) return override;\n const configured = getRuntimeConfig().connect.instance?.reactorClient;\n if (configured && MODES.has(configured)) return configured;\n // Legacy fallback — unchanged behaviour for configs without reactorClient.\n if (isMultiReactorEnabled()) return \"router\";\n if (isReactorWorkerEnabled()) return \"worker\";\n return \"in-process\";\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 { 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 { name: string; url: string }[];\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 = params.remoteBackends?.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 { name, url } of listed) {\n const graphqlUrl = switchboardOfDrive(url)?.graphql;\n if (graphqlUrl) remotes.push({ name, 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 if (remotes.length === 0) {\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 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 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 signer: params.signer,\n documentModelModules: params.documentModelModules,\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\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 { RoutingReactorClient } 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 copy has caught up once every scope is at least at the source's revision. */\nexport function caughtUp(\n local: Readonly<Record<string, number>>,\n source: Readonly<Record<string, number>>,\n): boolean {\n return Object.entries(source).every(\n ([scope, revision]) => (local[scope] ?? -1) >= revision,\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":";;;;;;;;;AAGA,SAAgB,wBAAiC;CAC/C,OAAO,iBAAiB,CAAC,CAAC,QAAQ,UAAU,gBAAgB;AAC9D;;;ACEA,MAAa,2BAA2B;AACxC,MAAa,6BAA6B;AAI1C,SAAgB,4BACd,OACS;CACT,OAAO,mBAAmB,KAAK;AACjC;AAEA,SAAgB,yBAAkC;CAChD,OAAO,qBAAqB;EAC1B,UAAU;EACV,YAAY;EACZ,sBACE,iBAAiB,CAAC,CAAC,QAAQ,UAAU,iBAAiB;CAC1D,CAAC;AACH;;;ACFA,MAAM,wBAA6B,IAA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