@powerhousedao/reactor-browser 6.2.3-dev.10 → 6.2.3-dev.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/{attachment-service-BW1v0OAT.d.ts → attachment-service-DXfpfp98.d.ts} +767 -108
  2. package/dist/attachment-service-DXfpfp98.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/client-1n_ZUXeu.js +135 -0
  6. package/dist/client-1n_ZUXeu.js.map +1 -0
  7. package/dist/{client-CxJD0Ck2.d.ts → client-BFk0MY6A.d.ts} +4 -3
  8. package/dist/client-BFk0MY6A.d.ts.map +1 -0
  9. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  10. package/dist/client-BFnMV-EO.js.map +1 -0
  11. package/dist/dispatch-Cylwl2Dk.js +1173 -0
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/document-by-id-DdvqanGR.js +16 -0
  14. package/dist/document-by-id-DdvqanGR.js.map +1 -0
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/document-operations-D5QXcJbV.js +4609 -0
  18. package/dist/document-operations-D5QXcJbV.js.map +1 -0
  19. package/dist/global-DAAmZGCO.d.ts +612 -0
  20. package/dist/global-DAAmZGCO.d.ts.map +1 -0
  21. package/dist/{index-CBjFO54H.d.ts → index-Bj1poVfa.d.ts} +31 -100
  22. package/dist/index-Bj1poVfa.d.ts.map +1 -0
  23. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  24. package/dist/index-rtDmzViP.d.ts.map +1 -0
  25. package/dist/index.d.ts +907 -411
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +851 -306
  28. package/dist/index.js.map +1 -1
  29. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  30. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  31. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  32. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D1RB45sA.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-rqK8sokh.js → renown-B3MUaiq7.js} +61 -31
  38. package/dist/renown-B3MUaiq7.js.map +1 -0
  39. package/dist/renown-CBoTdGrg.js +394 -0
  40. package/dist/renown-CBoTdGrg.js.map +1 -0
  41. package/dist/{types-N3Jy6Nry.d.ts → schema-Bn6L3QR1.d.ts} +255 -65
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/{client-D4bkR4pH.js → schema-D0G1oAo9.js} +247 -152
  44. package/dist/schema-D0G1oAo9.js.map +1 -0
  45. package/dist/src/ai/index.d.ts +313 -79
  46. package/dist/src/ai/index.d.ts.map +1 -1
  47. package/dist/src/ai/index.js +1030 -173
  48. package/dist/src/ai/index.js.map +1 -1
  49. package/dist/src/analytics/index.d.ts +36 -44
  50. package/dist/src/analytics/index.d.ts.map +1 -1
  51. package/dist/src/analytics/index.js +4 -4
  52. package/dist/src/analytics/index.js.map +1 -1
  53. package/dist/src/document-model.d.ts +3 -4
  54. package/dist/src/document-model.d.ts.map +1 -1
  55. package/dist/src/document-model.js.map +1 -1
  56. package/dist/src/graphql/client.d.ts +4 -3
  57. package/dist/src/graphql/client.js +1 -1
  58. package/dist/src/graphql-client/entry.d.ts +7 -4
  59. package/dist/src/graphql-client/entry.js +4 -4
  60. package/dist/src/relational/index.d.ts +15 -9
  61. package/dist/src/relational/index.d.ts.map +1 -1
  62. package/dist/src/relational/index.js +1 -1
  63. package/dist/src/renown/index.d.ts +3 -2
  64. package/dist/src/renown/index.js +3 -3
  65. package/dist/src/rpc/index.d.ts +217 -140
  66. package/dist/src/rpc/index.d.ts.map +1 -1
  67. package/dist/src/rpc/index.js +600 -623
  68. package/dist/src/rpc/index.js.map +1 -1
  69. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  70. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  71. package/dist/switchboard-directory-CWf5SRo7.js +435 -0
  72. package/dist/switchboard-directory-CWf5SRo7.js.map +1 -0
  73. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  74. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  75. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  76. package/dist/types-520nWrB3.d.ts.map +1 -0
  77. package/dist/types-CyPDurGV.d.ts +63 -0
  78. package/dist/types-CyPDurGV.d.ts.map +1 -0
  79. package/package.json +24 -23
  80. package/dist/attachment-service-BW1v0OAT.d.ts.map +0 -1
  81. package/dist/client-CxJD0Ck2.d.ts.map +0 -1
  82. package/dist/client-D4bkR4pH.js.map +0 -1
  83. package/dist/client-DjK30EQ-.js.map +0 -1
  84. package/dist/document-by-id-B4FIzG1w.js +0 -519
  85. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  86. package/dist/document-model-modules-bTP87nyr.js +0 -419
  87. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  88. package/dist/document-operations-Cm4EtaZs.js +0 -2603
  89. package/dist/document-operations-Cm4EtaZs.js.map +0 -1
  90. package/dist/global-CgCouXuH.d.ts +0 -401
  91. package/dist/global-CgCouXuH.d.ts.map +0 -1
  92. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  93. package/dist/index-CBjFO54H.d.ts.map +0 -1
  94. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  95. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  96. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  97. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  98. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  99. package/dist/relational-D1RB45sA.js.map +0 -1
  100. package/dist/renown-BHxwP7xU.js +0 -97
  101. package/dist/renown-BHxwP7xU.js.map +0 -1
  102. package/dist/renown-rqK8sokh.js.map +0 -1
  103. package/dist/switchboard-CaXQ4-5Q.js +0 -271
  104. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  105. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  106. package/dist/types-N3Jy6Nry.d.ts.map +0 -1
@@ -0,0 +1,710 @@
1
+ import { c as getPHStore, f as usePHStore, n as subscribeToPHValue, s as getActivePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { C as isDuplicateModuleError, S as isDuplicateManifestError, n as useDispatch } from "./dispatch-Cylwl2Dk.js";
3
+ import { $ as makeNodeSlug, C as getCurrentPathname, E as hasHostNavigation, G as extractNodeIdFromSlug, J as findDriveBySlug, K as extractNodeSlugFromPath, M as preloadTarget, U as extractDriveSlugFromPath, Z as makeDriveSlug, k as openTarget } from "./renown-CBoTdGrg.js";
4
+ import { createContext, useCallback, useContext, useEffect, useSyncExternalStore } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ import { logger } from "document-model";
7
+ //#region src/graphql-client/auth.ts
8
+ /** Lifetime requested for an ambient Renown token, in seconds. */
9
+ const ambientTokenExpiresInSeconds = 600;
10
+ /**
11
+ * The default token provider: the token of the currently logged-in Renown user.
12
+ *
13
+ * It is deliberately resolved from `window.ph` on every call rather than
14
+ * captured at construction time, so a client built before login starts sending
15
+ * the token as soon as there is one.
16
+ *
17
+ * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
18
+ * rejects tokens that carry an audience.
19
+ */
20
+ async function ambientRenownTokenProvider() {
21
+ if (typeof window === "undefined") return;
22
+ const renown = getPHStore()?.renown;
23
+ if (!renown?.user) return;
24
+ return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });
25
+ }
26
+ /**
27
+ * Builds the SDK middleware that authenticates every request.
28
+ *
29
+ * The token is resolved per request and never cached, so a login, a logout or
30
+ * an expiry between two calls is picked up by the next one. When no token is
31
+ * available the request goes out unauthenticated.
32
+ */
33
+ function makeAuthMiddleware(tokenProvider) {
34
+ return async (action) => {
35
+ const token = await tokenProvider();
36
+ if (!token) return action();
37
+ return action({ authorization: `Bearer ${token}` });
38
+ };
39
+ }
40
+ //#endregion
41
+ //#region src/utils/nodes.ts
42
+ /** Sorts nodes by name. */
43
+ function sortNodesByName(nodes) {
44
+ return nodes.toSorted((a, b) => a.name.localeCompare(b.name));
45
+ }
46
+ /** Returns whether a node is a file. */
47
+ function isFileNodeKind(node) {
48
+ if (!node) return false;
49
+ return node.kind.toUpperCase() === "FILE";
50
+ }
51
+ /** Returns whether a node is a folder. */
52
+ function isFolderNodeKind(node) {
53
+ if (!node) return false;
54
+ return node.kind.toUpperCase() === "FOLDER";
55
+ }
56
+ const NODE_PAGE_SIZE = 1e3;
57
+ /** Every node of a drive from `read.drives`, paged until the last page;
58
+ * `parentFolder` narrows it as `listNodes` does (null: the root level). */
59
+ async function listAllDriveNodes(reader, driveId, options = {}) {
60
+ const nodes = [];
61
+ let cursor = "";
62
+ for (;;) {
63
+ const page = await reader.listNodes(driveId, options.parentFolder, {
64
+ limit: NODE_PAGE_SIZE,
65
+ cursor
66
+ }, options.signal);
67
+ nodes.push(...page.results);
68
+ if (!page.nextCursor || page.results.length === 0) return nodes;
69
+ cursor = page.nextCursor;
70
+ }
71
+ }
72
+ //#endregion
73
+ //#region src/hooks/drive-nodes.ts
74
+ const driveNodesEventFunctions = makePHEventFunctions("driveNodes");
75
+ /** Returns the per-drive node caches */
76
+ const useDriveNodesCache = driveNodesEventFunctions.useValue;
77
+ /** Adds an event handler for the drive node cache */
78
+ const addDriveNodesEventHandler = driveNodesEventFunctions.addEventHandler;
79
+ const mounted = /* @__PURE__ */ new Map();
80
+ function retain(driveId) {
81
+ mounted.set(driveId, (mounted.get(driveId) ?? 0) + 1);
82
+ return () => {
83
+ const count = (mounted.get(driveId) ?? 1) - 1;
84
+ if (count > 0) mounted.set(driveId, count);
85
+ else mounted.delete(driveId);
86
+ };
87
+ }
88
+ function driveReader(store) {
89
+ const read = store?.reactorClient?.read;
90
+ if (read) return read.drives;
91
+ throw new Error("The reactor client is not initialized");
92
+ }
93
+ function entryOf(store, driveId) {
94
+ return store?.driveNodes?.get(driveId);
95
+ }
96
+ function setEntry(store, driveId, entry) {
97
+ if (!store) return;
98
+ const next = new Map(store.driveNodes);
99
+ if (entry) next.set(driveId, entry);
100
+ else next.delete(driveId);
101
+ store.driveNodes = next;
102
+ if (!getActivePHStore() && typeof window !== "undefined" && store === window.ph) window.dispatchEvent(new CustomEvent("ph:driveNodesUpdated"));
103
+ }
104
+ /** Loads every node of a drive into the cache, paging through
105
+ * `read.drives.listNodes`; served from the cache once loaded. */
106
+ function loadDriveNodes(driveId, options = {}) {
107
+ const store = options.store ?? getPHStore();
108
+ const current = entryOf(store, driveId);
109
+ if (current?.loading) {
110
+ if (options.refresh && !current.stale) setEntry(store, driveId, {
111
+ ...current,
112
+ stale: true
113
+ });
114
+ return current.loading;
115
+ }
116
+ if (!options.refresh && current?.loaded === "all" && current.nodes) return Promise.resolve(current.nodes);
117
+ const read = store?.reactorClient?.read;
118
+ if (!read) return Promise.reject(/* @__PURE__ */ new Error("The reactor client is not initialized"));
119
+ const reader = read.drives;
120
+ const loading = listAllDriveNodes(reader, driveId);
121
+ setEntry(store, driveId, {
122
+ byId: current?.byId ?? /* @__PURE__ */ new Map(),
123
+ nodes: current?.nodes,
124
+ loaded: current?.byId.size ? "partial" : "none",
125
+ loading
126
+ });
127
+ loading.then((nodes) => {
128
+ const settled = entryOf(store, driveId);
129
+ if (settled?.loading !== loading) return;
130
+ setEntry(store, driveId, {
131
+ byId: new Map(nodes.map((n) => [n.id, n])),
132
+ nodes,
133
+ loaded: "all"
134
+ });
135
+ if (settled.stale) {
136
+ if (mounted.has(driveId)) loadDriveNodes(driveId, {
137
+ store,
138
+ refresh: true
139
+ }).catch((error) => logger.error("Reloading drive nodes failed: @error", error));
140
+ else setEntry(store, driveId, void 0);
141
+ }
142
+ }, (error) => {
143
+ const entry = entryOf(store, driveId);
144
+ if (entry?.loading !== loading) return;
145
+ setEntry(store, driveId, {
146
+ ...entry,
147
+ loading: void 0,
148
+ error
149
+ });
150
+ });
151
+ return loading;
152
+ }
153
+ /** A node from the cache, else read through `read.drives.getNode`;
154
+ * undefined when the drive does not hold it. */
155
+ async function getDriveNode(driveId, nodeId, options = {}) {
156
+ const store = options.store ?? getPHStore();
157
+ const current = entryOf(store, driveId);
158
+ if (!options.refresh && current) {
159
+ const cached = current.byId.get(nodeId);
160
+ if (cached || current.loaded === "all") return cached;
161
+ }
162
+ const reader = driveReader(store);
163
+ let node;
164
+ try {
165
+ node = await reader.getNode(driveId, nodeId);
166
+ } catch {
167
+ return;
168
+ }
169
+ const entry = entryOf(store, driveId);
170
+ const byId = new Map(entry?.byId);
171
+ byId.set(node.id, node);
172
+ setEntry(store, driveId, {
173
+ ...entry,
174
+ byId,
175
+ nodes: entry?.nodes && replaceNode(entry.nodes, node),
176
+ loaded: entry?.loaded === "all" ? "all" : "partial"
177
+ });
178
+ return node;
179
+ }
180
+ function replaceNode(nodes, node) {
181
+ const at = nodes.findIndex((n) => n.id === node.id);
182
+ if (at < 0) return [...nodes, node];
183
+ return nodes.map((n, i) => i === at ? node : n);
184
+ }
185
+ /** A node from the cache only, without reading; for synchronous callers. */
186
+ function peekDriveNode(driveId, nodeId, store = getPHStore()) {
187
+ return entryOf(store, driveId)?.byId.get(nodeId);
188
+ }
189
+ /** Drops a drive's cached nodes; while a hook shows them, they reload and
190
+ * the old nodes stay visible until the new listing lands. */
191
+ function invalidateDriveNodes(driveId, store = getPHStore()) {
192
+ const current = entryOf(store, driveId);
193
+ if (!current) return;
194
+ if (current.loading) {
195
+ if (!current.stale) setEntry(store, driveId, {
196
+ ...current,
197
+ stale: true
198
+ });
199
+ return;
200
+ }
201
+ if (!mounted.has(driveId)) {
202
+ setEntry(store, driveId, void 0);
203
+ return;
204
+ }
205
+ setEntry(store, driveId, {
206
+ byId: current.byId,
207
+ nodes: current.nodes,
208
+ loaded: "partial"
209
+ });
210
+ loadDriveNodes(driveId, { store }).catch((error) => logger.error("Reloading drive nodes failed: @error", error));
211
+ }
212
+ /** Drives this tab has just written to; their next change is read at once. */
213
+ const localDriveWrites = /* @__PURE__ */ new Set();
214
+ /**
215
+ * Notes that this tab wrote to a drive, so the drive change handler re-reads
216
+ * it on the change that follows instead of waiting out its interval: the
217
+ * person who added, renamed or removed a node expects to see it, while a
218
+ * drive being filled by someone else can wait.
219
+ */
220
+ function markLocalDriveWrite(driveId) {
221
+ localDriveWrites.add(driveId);
222
+ }
223
+ /** Spends a drive's local-write mark; true when one was set. */
224
+ function takeLocalDriveWrite(driveId) {
225
+ return localDriveWrites.delete(driveId);
226
+ }
227
+ /** Takes a node out of a drive's cache after this tab removed it, so the
228
+ * listing drops it at once instead of after the next drive refresh. */
229
+ function dropDriveNode(driveId, nodeId, store = getPHStore()) {
230
+ const entry = entryOf(store, driveId);
231
+ if (!entry?.byId.has(nodeId)) return;
232
+ const byId = new Map(entry.byId);
233
+ byId.delete(nodeId);
234
+ setEntry(store, driveId, {
235
+ ...entry,
236
+ byId,
237
+ nodes: entry.nodes?.filter((n) => n.id !== nodeId)
238
+ });
239
+ }
240
+ function useDriveNodesEntry(driveId) {
241
+ const store = usePHStore() ?? getPHStore();
242
+ const cache = useDriveNodesCache();
243
+ return [store, driveId ? cache?.get(driveId) : void 0];
244
+ }
245
+ /** Every node of a drive, loaded on first use; undefined until loaded. */
246
+ function useDriveNodes(driveId) {
247
+ const [store, entry] = useDriveNodesEntry(driveId);
248
+ const needsLoad = !!driveId && !entry?.loading && !entry?.error && entry?.loaded !== "all";
249
+ useEffect(() => {
250
+ if (!driveId) return;
251
+ return retain(driveId);
252
+ }, [driveId]);
253
+ useEffect(() => {
254
+ if (!driveId || !needsLoad) return;
255
+ loadDriveNodes(driveId, { store }).catch((error) => logger.error("Loading drive nodes failed: @error", error));
256
+ }, [
257
+ driveId,
258
+ needsLoad,
259
+ store
260
+ ]);
261
+ return entry?.nodes;
262
+ }
263
+ /** One node of a drive, from the cache or read on its own. */
264
+ function useDriveNode(driveId, nodeId) {
265
+ const [store, entry] = useDriveNodesEntry(driveId);
266
+ const node = nodeId ? entry?.byId.get(nodeId) : void 0;
267
+ const needsFetch = !!driveId && !!nodeId && !node && entry?.loaded !== "all" && !entry?.loading;
268
+ useEffect(() => {
269
+ if (!driveId) return;
270
+ return retain(driveId);
271
+ }, [driveId]);
272
+ useEffect(() => {
273
+ if (!driveId || !nodeId || !needsFetch) return;
274
+ getDriveNode(driveId, nodeId, { store }).catch((error) => logger.error("Loading drive node failed: @error", error));
275
+ }, [
276
+ driveId,
277
+ nodeId,
278
+ needsFetch,
279
+ store
280
+ ]);
281
+ return node;
282
+ }
283
+ //#endregion
284
+ //#region src/hooks/reactor.ts
285
+ const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
286
+ const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
287
+ const reactorHalvesEventFunctions = makePHEventFunctions("reactor");
288
+ const fullReactorClientEventFunctions = makePHEventFunctions("fullReactorClient");
289
+ /** Returns the reactor client module (in-process or worker-backed) */
290
+ const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
291
+ /** Sets the reactor client module */
292
+ const setReactorClientModule = reactorClientModuleEventFunctions.setValue;
293
+ /** Adds an event handler for the reactor client module */
294
+ const addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;
295
+ /** Returns the reactor client */
296
+ const useReactorClient = reactorClientEventFunctions.useValue;
297
+ /**
298
+ * Sets the reactor client, and `window.ph.reactor` to its read and write
299
+ * halves. A client without halves leaves `reactor` unset.
300
+ */
301
+ const setReactorClient = (client) => {
302
+ reactorClientEventFunctions.setValue(client);
303
+ reactorHalvesEventFunctions.setValue(halvesOf(client));
304
+ };
305
+ /** Returns the reactor client's read and write halves */
306
+ const useReactorHalves = reactorHalvesEventFunctions.useValue;
307
+ /** Adds an event handler for the reactor client's halves */
308
+ const addReactorHalvesEventHandler = reactorHalvesEventFunctions.addEventHandler;
309
+ function halvesOf(client) {
310
+ const read = client?.read;
311
+ const write = client?.write;
312
+ return read && write ? {
313
+ read,
314
+ write
315
+ } : void 0;
316
+ }
317
+ /** Adds an event handler for the reactor client */
318
+ const addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;
319
+ /** Sets the client full-client actions use instead of the module's */
320
+ const setFullReactorClient = fullReactorClientEventFunctions.setValue;
321
+ /** Adds an event handler for the full reactor client */
322
+ const addFullReactorClientEventHandler = fullReactorClientEventFunctions.addEventHandler;
323
+ /** The client full-client actions use: the one set, else the module's. */
324
+ function getFullReactorClient() {
325
+ return getPHStore()?.fullReactorClient ?? getPHStore()?.reactorClientModule?.client;
326
+ }
327
+ const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
328
+ const useSyncList = () => {
329
+ return useSync()?.list() ?? [];
330
+ };
331
+ const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
332
+ const useDatabase = () => {
333
+ const module = useReactorClientModule();
334
+ return module?.kind === "browser" ? module.reactorModule?.database : void 0;
335
+ };
336
+ const usePGlite = () => {
337
+ const module = useReactorClientModule();
338
+ return module?.kind === "browser" ? module.reactorModule?.pg : void 0;
339
+ };
340
+ //#endregion
341
+ //#region src/routing/initial-sync.ts
342
+ /** The store's sync remotes; none before the reactor is ready. */
343
+ function listSyncRemotes(store) {
344
+ try {
345
+ return store?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list() ?? [];
346
+ } catch {
347
+ return [];
348
+ }
349
+ }
350
+ function isFirstPullInFlight(remote) {
351
+ try {
352
+ const { state, receivingPages, lastSuccessUtcMs, failureCount } = remote.channel.getConnectionState();
353
+ if (state === "connected") return receivingPages;
354
+ if (state === "reconnecting") return !lastSuccessUtcMs && !failureCount;
355
+ return state === "connecting" && (receivingPages || !lastSuccessUtcMs);
356
+ } catch {
357
+ return false;
358
+ }
359
+ }
360
+ /** Whether a remote, or one syncing `driveId` when given, is in its first pull. */
361
+ function isInitialSyncInFlight(store, driveId) {
362
+ return listSyncRemotes(store).some((remote) => (driveId === void 0 || remote.meta.collectionId.driveId === driveId) && isFirstPullInFlight(remote));
363
+ }
364
+ //#endregion
365
+ //#region src/hooks/drive-context.tsx
366
+ const DriveContext = createContext(void 0);
367
+ /** Hosts render a drive app inside this; `useSelectedDrive`, `useSelectedNode`
368
+ * and `useSelectedFolder` below read it, and opening nodes calls its `open`. */
369
+ function DriveProvider(props) {
370
+ return /* @__PURE__ */ jsx(DriveContext.Provider, {
371
+ value: props.value,
372
+ children: props.children
373
+ });
374
+ }
375
+ /** The nearest drive app's drive, or undefined outside one. */
376
+ function useDriveContext() {
377
+ return useContext(DriveContext);
378
+ }
379
+ //#endregion
380
+ //#region src/hooks/drives.ts
381
+ const drivesEventFunctions = makePHEventFunctions("drives");
382
+ /** Returns all of the drives in the reactor */
383
+ const useDrives = drivesEventFunctions.useValue;
384
+ /** Sets the drives in the reactor */
385
+ const setDrives = drivesEventFunctions.setValue;
386
+ /** Adds an event handler for the drives */
387
+ const addDrivesEventHandler = drivesEventFunctions.addEventHandler;
388
+ //#endregion
389
+ //#region src/hooks/set-selected-node.ts
390
+ const selectedNodeIdEventFunctions = makePHEventFunctions("selectedNodeId");
391
+ const useStoreSelectedNodeId = selectedNodeIdEventFunctions.useValue;
392
+ /** The selected node id: the drive app's open node, else the app's selection. */
393
+ function useSelectedNodeId() {
394
+ const context = useDriveContext();
395
+ const selectedNodeId = useStoreSelectedNodeId();
396
+ return context ? context.nodeId : selectedNodeId;
397
+ }
398
+ /** Sets the selected node id without touching the URL. */
399
+ const setSelectedNodeId = selectedNodeIdEventFunctions.setValue;
400
+ /** @deprecated `ph:setSelectedNodeId` bypasses the URL; use `setSelectedNode`. */
401
+ const addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;
402
+ function decodeSlug(slug) {
403
+ try {
404
+ return decodeURIComponent(slug);
405
+ } catch {
406
+ return slug;
407
+ }
408
+ }
409
+ function openDriveSlug(store, pathname) {
410
+ const selected = store?.drives?.find((d) => d.header.id === store.selectedDriveId);
411
+ if (selected) return makeDriveSlug(selected);
412
+ const driveSlug = extractDriveSlugFromPath(pathname);
413
+ return driveSlug ? decodeSlug(driveSlug) : void 0;
414
+ }
415
+ function nodeTarget(nodeSlug, drive) {
416
+ const driveSlug = drive ? makeDriveSlug(drive) : openDriveSlug(getPHStore(), getCurrentPathname());
417
+ if (!driveSlug) return void 0;
418
+ return {
419
+ driveSlug,
420
+ nodeSlug: nodeSlug || void 0
421
+ };
422
+ }
423
+ const toSlug = (node) => typeof node === "string" ? node : makeNodeSlug(node);
424
+ /** Selects a node in `drive`, else in the app's open drive. */
425
+ function selectNode(node, options, drive) {
426
+ const nodeSlug = toSlug(node);
427
+ if (!hasHostNavigation()) setSelectedNodeId(extractNodeIdFromSlug(nodeSlug));
428
+ const target = nodeTarget(nodeSlug, drive);
429
+ if (target) openTarget(target, options);
430
+ }
431
+ /** Sets the selected node (file or folder) of the app's store; `search` sets
432
+ * the params it opens with. Inside a drive app, use `useSetSelectedNode`. */
433
+ function setSelectedNode(node, options) {
434
+ selectNode(node, options);
435
+ }
436
+ function findNode(drive, node, store) {
437
+ if (typeof node !== "string") return node;
438
+ const id = extractNodeIdFromSlug(node);
439
+ return id ? peekDriveNode(drive.header.id, id, store) : void 0;
440
+ }
441
+ /** Opens a node: through the drive app's `open` when it has one, else the
442
+ * app's navigation in the drive app's drive. */
443
+ function useSetSelectedNode() {
444
+ const context = useDriveContext();
445
+ const store = usePHStore() ?? getPHStore();
446
+ return useCallback((node, options) => {
447
+ if (context?.open) {
448
+ context.open(findNode(context.drive, node, store), options);
449
+ return;
450
+ }
451
+ selectNode(node, options, context?.drive);
452
+ }, [context, store]);
453
+ }
454
+ /** Opens a node, or with `undefined` its drive. */
455
+ const useOpenNode = useSetSelectedNode;
456
+ /** Where a node of `drive`, else of the open drive, navigates to. */
457
+ function getNodeTarget(node, drive) {
458
+ return nodeTarget(makeNodeSlug(node), drive);
459
+ }
460
+ /** Where a node navigates to: in the drive app's drive, else the open drive. */
461
+ function useNodeTarget(node) {
462
+ return getNodeTarget(node, useDriveContext()?.drive);
463
+ }
464
+ /** Warms a node's view before it is opened, e.g. on hover. */
465
+ function preloadNode(node, drive) {
466
+ if (!node) return;
467
+ const target = nodeTarget(makeNodeSlug(node), drive);
468
+ if (target) preloadTarget(target);
469
+ }
470
+ /** `preloadNode` through the drive app's `preload`, if it has one. */
471
+ function usePreloadNode() {
472
+ const context = useDriveContext();
473
+ return useCallback((node) => {
474
+ if (context?.preload) context.preload(node);
475
+ else if (!context?.open) preloadNode(node, context?.drive);
476
+ }, [context]);
477
+ }
478
+ function addResetSelectedNodeEventHandler() {
479
+ subscribeToPHValue("selectedDriveId", () => {
480
+ setSelectedNodeId(void 0);
481
+ });
482
+ }
483
+ //#endregion
484
+ //#region src/hooks/selected-drive.ts
485
+ const selectedDriveIdEventFunctions = makePHEventFunctions("selectedDriveId");
486
+ const useStoreSelectedDriveId = selectedDriveIdEventFunctions.useValue;
487
+ /** Returns the selected drive id: the drive app's drive, else the app's selection. */
488
+ function useSelectedDriveId() {
489
+ const context = useDriveContext();
490
+ const selectedDriveId = useStoreSelectedDriveId();
491
+ return context ? context.drive.header.id : selectedDriveId;
492
+ }
493
+ /** Sets the selected drive id */
494
+ const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;
495
+ /** Adds an event handler for the selected drive id
496
+ * @deprecated `ph:setSelectedDriveId` bypasses the URL; use `setSelectedDrive`. */
497
+ const addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;
498
+ /** Returns the selected drive */
499
+ function useSelectedDrive() {
500
+ const drive = useSelectedDriveSafe();
501
+ if (!drive[0]) throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");
502
+ return drive;
503
+ }
504
+ /** Returns the selected drive, or undefined if no drive is selected */
505
+ function useSelectedDriveSafe() {
506
+ const context = useDriveContext();
507
+ const selectedDriveId = useStoreSelectedDriveId();
508
+ const drives = useDrives();
509
+ const selectedDrive = context ? void 0 : drives?.find((drive) => drive.header.id === selectedDriveId);
510
+ const [drive, dispatch] = useDispatch(selectedDrive);
511
+ if (context) return [context.drive, context.dispatch];
512
+ if (!selectedDrive) return [void 0, void 0];
513
+ return [drive, dispatch];
514
+ }
515
+ /** Selects a drive in the app's store. */
516
+ function setSelectedDrive(driveOrDriveSlug) {
517
+ selectDrive(driveOrDriveSlug);
518
+ }
519
+ /** `setSelectedDrive`, as a hook. */
520
+ function useSetSelectedDrive() {
521
+ return useCallback((drive) => selectDrive(drive), []);
522
+ }
523
+ /** Selects a drive in the app's store. */
524
+ function selectDrive(driveOrDriveSlug) {
525
+ const driveSlug = typeof driveOrDriveSlug === "string" ? driveOrDriveSlug : driveOrDriveSlug && makeDriveSlug(driveOrDriveSlug);
526
+ if (hasHostNavigation()) {
527
+ cancelPendingDriveSelection();
528
+ openTarget(driveSlug ? { driveSlug } : void 0);
529
+ return;
530
+ }
531
+ const drives = getPHStore()?.drives;
532
+ const driveId = (typeof driveOrDriveSlug === "object" && driveOrDriveSlug !== null ? driveOrDriveSlug : findDriveBySlug(drives, driveSlug))?.header.id;
533
+ if (!driveId && driveSlug && extractDriveSlugFromPath(getCurrentPathname()) === driveSlug) {
534
+ if (getPHStore()?.selectedDriveId) setSelectedDriveId(void 0);
535
+ deferDriveSelection(driveSlug);
536
+ return;
537
+ }
538
+ cancelPendingDriveSelection();
539
+ setSelectedDriveId(driveId);
540
+ openTarget(driveId && driveSlug ? { driveSlug } : void 0);
541
+ }
542
+ /** Warms a drive's view before it is opened, e.g. on hover. */
543
+ function preloadDrive(drive) {
544
+ if (drive) preloadTarget({ driveSlug: makeDriveSlug(drive) });
545
+ }
546
+ /** `preloadDrive`, as a hook. */
547
+ function usePreloadDrive() {
548
+ return useCallback((drive) => preloadDrive(drive), []);
549
+ }
550
+ const DEFERRED_DRIVE_TICK_MS = 2e3;
551
+ const DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;
552
+ let unsubscribePending;
553
+ let pendingTimeout;
554
+ function cancelPendingDriveSelection() {
555
+ if (unsubscribePending) {
556
+ unsubscribePending();
557
+ unsubscribePending = void 0;
558
+ }
559
+ if (pendingTimeout) {
560
+ clearTimeout(pendingTimeout);
561
+ pendingTimeout = void 0;
562
+ }
563
+ }
564
+ function deferDriveSelection(driveSlug) {
565
+ cancelPendingDriveSelection();
566
+ const nodeSlug = extractNodeSlugFromPath(getCurrentPathname());
567
+ const handler = () => {
568
+ if (!findDriveBySlug(getPHStore()?.drives, driveSlug)) return;
569
+ cancelPendingDriveSelection();
570
+ selectDrive(driveSlug);
571
+ selectNode(nodeSlug);
572
+ };
573
+ unsubscribePending = subscribeToPHValue("drives", handler);
574
+ const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;
575
+ const scheduleTick = () => {
576
+ pendingTimeout = setTimeout(() => {
577
+ if (Date.now() < deadline && isInitialSyncInFlight(getPHStore())) {
578
+ scheduleTick();
579
+ return;
580
+ }
581
+ cancelPendingDriveSelection();
582
+ openTarget(void 0);
583
+ }, DEFERRED_DRIVE_TICK_MS);
584
+ };
585
+ scheduleTick();
586
+ }
587
+ //#endregion
588
+ //#region src/hooks/switchboards.ts
589
+ const switchboardsEventFunctions = makePHEventFunctions("switchboards");
590
+ /** The switchboards the app reaches, from the provided store. */
591
+ const useSwitchboards = switchboardsEventFunctions.useValue;
592
+ /** Sets the app's switchboard directory; the host does this at boot. */
593
+ const setSwitchboards = switchboardsEventFunctions.setValue;
594
+ /** Registers the switchboards window event handler */
595
+ const addSwitchboardsEventHandler = switchboardsEventFunctions.addEventHandler;
596
+ //#endregion
597
+ //#region src/hooks/vetra-packages.ts
598
+ const vetraPackageManagerFunctions = makePHEventFunctions("vetraPackageManager");
599
+ const useVetraPackageManager = vetraPackageManagerFunctions.useValue;
600
+ const EMPTY_VETRA_PACKAGES = [];
601
+ const noPackageManagerUnsubscribe = () => {};
602
+ /**
603
+ * Returns all of the Vetra packages loaded by the Connect instance.
604
+ *
605
+ * The snapshot and subscription must keep stable identity while no package
606
+ * manager is registered: `useSyncExternalStore` loops when the snapshot
607
+ * changes on every read, which a fresh `[]` does.
608
+ */
609
+ const useVetraPackages = () => {
610
+ const packageManager = useVetraPackageManager();
611
+ const getPackages = () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES;
612
+ return useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, getPackages, getPackages);
613
+ };
614
+ /** Adds the Vetra package manager event handler */
615
+ const addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;
616
+ /**
617
+ * Non-react access to the Vetra package manager: calls `callback` once a
618
+ * manager is available - immediately when already set, otherwise when
619
+ * `setVetraPackageManager` publishes one. Returns an unsubscribe. The worker
620
+ * wiring uses this to forward package updates from plain boot code.
621
+ */
622
+ function onVetraPackageManager(callback) {
623
+ let delivered;
624
+ const deliver = () => {
625
+ const packageManager = vetraPackageManagerFunctions.getSnapshot();
626
+ if (!packageManager || packageManager === delivered) return;
627
+ delivered = packageManager;
628
+ callback(packageManager);
629
+ };
630
+ const unsubscribe = vetraPackageManagerFunctions.subscribeToValue(deliver);
631
+ deliver();
632
+ return unsubscribe;
633
+ }
634
+ /** Sets the Vetra package manager and registers its packages */
635
+ function setVetraPackageManager(packageManager) {
636
+ vetraPackageManagerFunctions.setValue(packageManager);
637
+ updateReactorClientDocumentModels(packageManager.packages);
638
+ updateReactorClientUpgradeManifests(packageManager.packages);
639
+ packageManager.subscribe(({ packages }) => {
640
+ updateReactorClientDocumentModels(packages);
641
+ updateReactorClientUpgradeManifests(packages);
642
+ });
643
+ }
644
+ function updateReactorClientDocumentModels(packages) {
645
+ const documentModelModules = packages.flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && (m.version ?? 1) === (module.version ?? 1)) === index);
646
+ const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
647
+ if (!registry || documentModelModules.length === 0) return;
648
+ const results = registry.registerModules(...documentModelModules);
649
+ const duplicateTypes = /* @__PURE__ */ new Set();
650
+ for (const result of results) if (result.status === "error") {
651
+ if (isDuplicateModuleError(result.error)) duplicateTypes.add(result.item.documentModel.global.id);
652
+ else console.error("Failed to register document model module:", result.error);
653
+ }
654
+ if (duplicateTypes.size > 0) {
655
+ registry.unregisterModules(...duplicateTypes);
656
+ registry.registerModules(...documentModelModules.filter((module) => duplicateTypes.has(module.documentModel.global.id)));
657
+ }
658
+ }
659
+ function updateReactorClientUpgradeManifests(packages) {
660
+ const upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);
661
+ const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
662
+ if (!registry || upgradeManifests.length === 0) return;
663
+ const results = registry.registerUpgradeManifests(...upgradeManifests);
664
+ const duplicates = [];
665
+ for (const result of results) if (result.status === "error") {
666
+ if (isDuplicateManifestError(result.error)) duplicates.push(result);
667
+ else console.error("Failed to register upgrade manifest:", result.error);
668
+ }
669
+ if (duplicates.length > 0) {
670
+ const duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);
671
+ registry.unregisterUpgradeManifests(...duplicateTypes);
672
+ registry.registerUpgradeManifests(...duplicates.map((r) => r.item));
673
+ }
674
+ }
675
+ //#endregion
676
+ //#region src/hooks/document-model-modules.ts
677
+ function useDocumentModelModules() {
678
+ return useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);
679
+ }
680
+ /**
681
+ * Resolves a document model module by document type, mirroring the registry's
682
+ * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the
683
+ * LATEST version of the type wins (`version ?? 1` as each module's default),
684
+ * with `version` given only an exact match is returned. The reactor resolves
685
+ * modules the same way when a document is created, so metadata read through
686
+ * this hook and the version a creation actually uses cannot disagree.
687
+ */
688
+ function useDocumentModelModuleById(id, version) {
689
+ const documentModelModules = useDocumentModelModules();
690
+ if (!id || !documentModelModules) return void 0;
691
+ let latestModule;
692
+ let latestVersion = -1;
693
+ for (const module of documentModelModules) {
694
+ if (module.documentModel.global.id !== id) continue;
695
+ const moduleVersion = module.version ?? 1;
696
+ if (version !== void 0) {
697
+ if (moduleVersion === version) return module;
698
+ continue;
699
+ }
700
+ if (moduleVersion > latestVersion) {
701
+ latestVersion = moduleVersion;
702
+ latestModule = module;
703
+ }
704
+ }
705
+ return latestModule;
706
+ }
707
+ //#endregion
708
+ export { useReactorHalves as $, usePreloadNode as A, addFullReactorClientEventHandler as B, getNodeTarget as C, setSelectedNodeId as D, setSelectedNode as E, useDrives as F, setFullReactorClient as G, addReactorClientModuleEventHandler as H, DriveProvider as I, useDatabase as J, setReactorClient as K, useDriveContext as L, useSetSelectedNode as M, addDrivesEventHandler as N, useNodeTarget as O, setDrives as P, useReactorClientModule as Q, isInitialSyncInFlight as R, addSelectedNodeIdEventHandler as S, selectNode as T, addReactorHalvesEventHandler as U, addReactorClientEventHandler as V, getFullReactorClient as W, usePGlite as X, useModelRegistry as Y, useReactorClient as Z, useSelectedDrive as _, ambientRenownTokenProvider as _t, setVetraPackageManager as a, invalidateDriveNodes as at, useSetSelectedDrive as b, addSwitchboardsEventHandler as c, peekDriveNode as ct, addSelectedDriveIdEventHandler as d, useDriveNodes as dt, useSync as et, preloadDrive as f, useDriveNodesCache as ft, usePreloadDrive as g, sortNodesByName as gt, setSelectedDriveId as h, listAllDriveNodes as ht, onVetraPackageManager as i, getDriveNode as it, useSelectedNodeId as j, useOpenNode as k, setSwitchboards as l, takeLocalDriveWrite as lt, setSelectedDrive as m, isFolderNodeKind as mt, useDocumentModelModules as n, addDriveNodesEventHandler as nt, useVetraPackageManager as o, loadDriveNodes as ot, selectDrive as p, isFileNodeKind as pt, setReactorClientModule as q, addVetraPackageManagerEventHandler as r, dropDriveNode as rt, useVetraPackages as s, markLocalDriveWrite as st, useDocumentModelModuleById as t, useSyncList as tt, useSwitchboards as u, useDriveNode as ut, useSelectedDriveId as v, makeAuthMiddleware as vt, preloadNode as w, addResetSelectedNodeEventHandler as x, useSelectedDriveSafe as y, listSyncRemotes as z };
709
+
710
+ //# sourceMappingURL=document-model-modules-BG-61uke.js.map