@powerhousedao/reactor-browser 6.2.3-dev.7 → 6.2.3-dev.70

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 (94) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-CAf9N-15.d.ts} +365 -66
  2. package/dist/attachment-service-CAf9N-15.d.ts.map +1 -0
  3. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  4. package/dist/client-BFnMV-EO.js.map +1 -0
  5. package/dist/{client-BIHN_UyR.d.ts → client-BnGewICj.d.ts} +3 -3
  6. package/dist/client-BnGewICj.d.ts.map +1 -0
  7. package/dist/{client-D66jVnot.js → client-CXDpILj6.js} +232 -32
  8. package/dist/client-CXDpILj6.js.map +1 -0
  9. package/dist/dispatch-Dd_WEz35.js +870 -0
  10. package/dist/dispatch-Dd_WEz35.js.map +1 -0
  11. package/dist/document-by-id-DqAyjr9P.js +16 -0
  12. package/dist/document-by-id-DqAyjr9P.js.map +1 -0
  13. package/dist/document-model-modules-DROQT_yu.js +431 -0
  14. package/dist/document-model-modules-DROQT_yu.js.map +1 -0
  15. package/dist/{document-operations-WeE6wIDt.js → document-operations-C6khz2If.js} +958 -204
  16. package/dist/document-operations-C6khz2If.js.map +1 -0
  17. package/dist/{global-OuINvEGT.d.ts → global-D-VZTZRz.d.ts} +113 -20
  18. package/dist/global-D-VZTZRz.d.ts.map +1 -0
  19. package/dist/{index-B33TKEqp.d.ts → index-XfcUiODQ.d.ts} +19 -98
  20. package/dist/index-XfcUiODQ.d.ts.map +1 -0
  21. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  22. package/dist/index-rtDmzViP.d.ts.map +1 -0
  23. package/dist/index.d.ts +693 -391
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +469 -72
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/navigation-BqphkrOB.js +302 -0
  32. package/dist/navigation-BqphkrOB.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-BtjgHBjH.js} +33 -28
  38. package/dist/{renown-rqK8sokh.js.map → renown-BtjgHBjH.js.map} +1 -1
  39. package/dist/{renown-BHxwP7xU.js → renown-BxkZYzbQ.js} +2 -2
  40. package/dist/{renown-BHxwP7xU.js.map → renown-BxkZYzbQ.js.map} +1 -1
  41. package/dist/src/ai/index.d.ts +51 -62
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +6 -9
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.d.ts +36 -44
  46. package/dist/src/analytics/index.d.ts.map +1 -1
  47. package/dist/src/analytics/index.js +4 -4
  48. package/dist/src/analytics/index.js.map +1 -1
  49. package/dist/src/document-model.d.ts +3 -4
  50. package/dist/src/document-model.d.ts.map +1 -1
  51. package/dist/src/document-model.js.map +1 -1
  52. package/dist/src/graphql/client.d.ts +4 -3
  53. package/dist/src/graphql/client.js +1 -1
  54. package/dist/src/graphql-client/entry.d.ts +5 -4
  55. package/dist/src/graphql-client/entry.js +4 -4
  56. package/dist/src/relational/index.d.ts +15 -9
  57. package/dist/src/relational/index.d.ts.map +1 -1
  58. package/dist/src/relational/index.js +1 -1
  59. package/dist/src/renown/index.d.ts +3 -2
  60. package/dist/src/renown/index.js +2 -2
  61. package/dist/src/rpc/index.d.ts +178 -138
  62. package/dist/src/rpc/index.d.ts.map +1 -1
  63. package/dist/src/rpc/index.js +420 -619
  64. package/dist/src/rpc/index.js.map +1 -1
  65. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  66. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  67. package/dist/{switchboard-CaXQ4-5Q.js → switchboard-cwUp3FxP.js} +98 -11
  68. package/dist/switchboard-cwUp3FxP.js.map +1 -0
  69. package/dist/{types-Dcv1ZLoW.d.ts → types-0Fh1tNjy.d.ts} +242 -17
  70. package/dist/types-0Fh1tNjy.d.ts.map +1 -0
  71. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  72. package/dist/types-520nWrB3.d.ts.map +1 -0
  73. package/package.json +20 -21
  74. package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
  75. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  76. package/dist/client-D66jVnot.js.map +0 -1
  77. package/dist/client-DjK30EQ-.js.map +0 -1
  78. package/dist/document-by-id-B4FIzG1w.js +0 -519
  79. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  80. package/dist/document-model-modules-bTP87nyr.js +0 -419
  81. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  82. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  83. package/dist/global-OuINvEGT.d.ts.map +0 -1
  84. package/dist/index-B33TKEqp.d.ts.map +0 -1
  85. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  86. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  87. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  88. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  89. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  90. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  91. package/dist/relational-D1RB45sA.js.map +0 -1
  92. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  93. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  94. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -0,0 +1,870 @@
1
+ import { c as getPHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { use, useCallback, useEffect, useMemo, useReducer, useRef, useSyncExternalStore } from "react";
3
+ import { logger } from "document-model";
4
+ //#region src/actions/queue.ts
5
+ async function queueActions(document, actionOrActions) {
6
+ if (!document) throw new Error("No document provided");
7
+ if (!actionOrActions) throw new Error("No actions provided");
8
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
9
+ if (actions.length === 0) throw new Error("No actions provided");
10
+ const reactorClient = getPHStore()?.reactorClient;
11
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
12
+ return await reactorClient.execute(document.header.id, "main", actions);
13
+ }
14
+ async function queueOperations(documentId, operationOrOperations) {
15
+ if (!documentId) throw new Error("No documentId provided");
16
+ if (!operationOrOperations) throw new Error("No operations provided");
17
+ const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
18
+ if (operations.length === 0) throw new Error("No operations provided");
19
+ const reactorClient = getPHStore()?.reactorClient;
20
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
21
+ const actions = operations.map((op) => op.action);
22
+ return await reactorClient.execute(documentId, "main", actions);
23
+ }
24
+ async function uploadOperations(documentId, allOperations, pushOperations, options) {
25
+ const operationsLimit = options?.operationsLimit || 50;
26
+ const onProgress = options?.onProgress;
27
+ logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
28
+ const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
29
+ const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
30
+ let uploadedOperations = 0;
31
+ for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
32
+ logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
33
+ const chunk = operations.slice(i, i + operationsLimit);
34
+ const operation = chunk.at(-1);
35
+ if (!operation) break;
36
+ const scope = operation.action.scope;
37
+ await pushOperations(documentId, chunk);
38
+ uploadedOperations += chunk.length;
39
+ if (onProgress) onProgress({
40
+ stage: "uploading",
41
+ progress: Math.round(uploadedOperations / totalOperations * 100),
42
+ totalOperations,
43
+ uploadedOperations
44
+ });
45
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
46
+ }
47
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
48
+ }
49
+ //#endregion
50
+ //#region src/actions/sign.ts
51
+ function addActionContext(action) {
52
+ const renown = getPHStore()?.renown;
53
+ if (!renown?.user) return action;
54
+ return {
55
+ context: { signer: {
56
+ app: {
57
+ name: "Connect",
58
+ key: renown.did
59
+ },
60
+ user: {
61
+ address: renown.user.address,
62
+ networkId: renown.user.networkId,
63
+ chainId: renown.user.chainId
64
+ },
65
+ signatures: []
66
+ } },
67
+ ...action
68
+ };
69
+ }
70
+ function makeSignedActionWithContext(action, document) {
71
+ if (!action) {
72
+ logger.error("No action found");
73
+ return;
74
+ }
75
+ if (!document) {
76
+ logger.error("No document found");
77
+ return;
78
+ }
79
+ return addActionContext(action);
80
+ }
81
+ function makeSignedActionsWithContext(actionOrActions, document) {
82
+ if (!actionOrActions) {
83
+ logger.error("No actions found");
84
+ return;
85
+ }
86
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
87
+ }
88
+ //#endregion
89
+ //#region src/actions/dispatch.ts
90
+ async function getDocument(documentId) {
91
+ try {
92
+ return await getPHStore()?.reactorClient?.get(documentId);
93
+ } catch (error) {
94
+ logger.debug(`Failed to get document with id ${documentId}:`, error);
95
+ return;
96
+ }
97
+ }
98
+ function getActionErrors(result, actions) {
99
+ return actions.reduce((errors, a) => {
100
+ const scopeOperations = result.operations[a.scope];
101
+ if (!scopeOperations) return errors;
102
+ const op = scopeOperations.findLast((op) => op.action.id === a.id);
103
+ if (op?.error) errors.push(new Error(op.error));
104
+ return errors;
105
+ }, new Array());
106
+ }
107
+ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
108
+ const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
109
+ if (!document) {
110
+ const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;
111
+ logger.error(message);
112
+ onErrors?.([new Error(message)]);
113
+ return;
114
+ }
115
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
116
+ if (!signedActionsWithContext) {
117
+ const message = "No signed actions with context found";
118
+ logger.error(message);
119
+ onErrors?.([/* @__PURE__ */ new Error(message)]);
120
+ return;
121
+ }
122
+ const result = await queueActions(document, signedActionsWithContext);
123
+ if (onErrors && result) {
124
+ const errors = getActionErrors(result, signedActionsWithContext);
125
+ if (errors.length) onErrors(errors);
126
+ }
127
+ if (onSuccess && result) onSuccess(result);
128
+ return result;
129
+ }
130
+ //#endregion
131
+ //#region src/document-refetcher.ts
132
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
133
+ const IDLE_REFETCH_STATE = Object.freeze({
134
+ isRefetching: false,
135
+ error: void 0
136
+ });
137
+ function fulfilledPromise(value) {
138
+ const promise = Promise.resolve(value);
139
+ promise.status = "fulfilled";
140
+ promise.value = value;
141
+ return promise;
142
+ }
143
+ function rejectedPromise(reason) {
144
+ const promise = Promise.reject(reason);
145
+ promise.status = "rejected";
146
+ promise.reason = reason;
147
+ promise.catch(() => void 0);
148
+ return promise;
149
+ }
150
+ const MISSING_DOCUMENT_ERRORS = [
151
+ "DocumentNotFoundError",
152
+ "DocumentPurgedError",
153
+ "DocumentDeletedError"
154
+ ];
155
+ function isMissingDocumentError(error) {
156
+ if (!(error instanceof Error)) return false;
157
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
158
+ }
159
+ const noop = () => void 0;
160
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
161
+ var DocumentRefetcher = class {
162
+ host;
163
+ refetches = /* @__PURE__ */ new Map();
164
+ states = /* @__PURE__ */ new Map();
165
+ constructor(host) {
166
+ this.host = host;
167
+ }
168
+ getState(id) {
169
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
170
+ }
171
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
172
+ refetch(id) {
173
+ let entry = this.refetches.get(id);
174
+ if (!entry) {
175
+ entry = {
176
+ running: void 0,
177
+ queued: void 0
178
+ };
179
+ this.refetches.set(id, entry);
180
+ const current = this.host.documents.get(id);
181
+ if (current?.status !== "pending") return this.start(id, entry);
182
+ entry.running = current;
183
+ }
184
+ const inFlight = entry;
185
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
186
+ return inFlight.queued;
187
+ }
188
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
189
+ forget(id) {
190
+ this.refetches.delete(id);
191
+ this.states.delete(id);
192
+ }
193
+ clear() {
194
+ this.refetches.clear();
195
+ this.states.clear();
196
+ }
197
+ start(id, entry) {
198
+ entry.queued = void 0;
199
+ entry.running = this.run(id, entry);
200
+ return entry.running;
201
+ }
202
+ async run(id, entry) {
203
+ const isCurrent = () => this.refetches.get(id) === entry;
204
+ if (!isCurrent()) return this.host.fetch(id);
205
+ if (this.setState(id, {
206
+ isRefetching: true,
207
+ error: this.getState(id).error
208
+ })) this.host.notify(id);
209
+ try {
210
+ const document = await this.host.fetch(id);
211
+ if (isCurrent()) {
212
+ this.host.onFetched?.(id, document);
213
+ this.host.documents.set(id, fulfilledPromise(document));
214
+ this.finish(id, entry, void 0);
215
+ }
216
+ return document;
217
+ } catch (error) {
218
+ if (isCurrent()) {
219
+ if (isMissingDocumentError(error)) {
220
+ this.host.documents.set(id, rejectedPromise(error));
221
+ this.finish(id, entry, void 0);
222
+ } else {
223
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
224
+ this.finish(id, entry, error);
225
+ }
226
+ }
227
+ throw error;
228
+ }
229
+ }
230
+ finish(id, entry, error) {
231
+ if (!entry.queued) this.refetches.delete(id);
232
+ this.setState(id, {
233
+ isRefetching: entry.queued !== void 0,
234
+ error
235
+ });
236
+ this.host.notify(id);
237
+ }
238
+ /** Returns whether the snapshot changed; the caller notifies. */
239
+ setState(id, state) {
240
+ const current = this.getState(id);
241
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
242
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
243
+ else this.states.set(id, Object.freeze({ ...state }));
244
+ return true;
245
+ }
246
+ };
247
+ /**
248
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
249
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
250
+ * TypeScript string enum is nominal, so no string literal is assignable to it
251
+ * without one - and the two checks above are what make it safe.
252
+ */
253
+ const DOCUMENT_CHANGE_TYPE = {
254
+ Created: "created",
255
+ Deleted: "deleted",
256
+ Updated: "updated",
257
+ ParentAdded: "parent_added",
258
+ ParentRemoved: "parent_removed",
259
+ ChildAdded: "child_added",
260
+ ChildRemoved: "child_removed"
261
+ };
262
+ /**
263
+ * Structural equivalents of the reactor error classes' own static `isError`
264
+ * guards. Those guards match on `error.name` rather than the prototype chain
265
+ * (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is
266
+ * behaviour-preserving and does not need the class at runtime.
267
+ */
268
+ function isDuplicateModuleError(error) {
269
+ return Error.isError(error) && error.name === "DuplicateModuleError";
270
+ }
271
+ function isDuplicateManifestError(error) {
272
+ return Error.isError(error) && error.name === "DuplicateManifestError";
273
+ }
274
+ //#endregion
275
+ //#region src/document-cache.ts
276
+ function addPromiseState(promise) {
277
+ if ("status" in promise) return promise;
278
+ const promiseWithState = promise;
279
+ promiseWithState.status = "pending";
280
+ promiseWithState.then((value) => {
281
+ promiseWithState.status = "fulfilled";
282
+ promiseWithState.value = value;
283
+ }, (reason) => {
284
+ promiseWithState.status = "rejected";
285
+ promiseWithState.reason = reason;
286
+ throw reason;
287
+ });
288
+ return promiseWithState;
289
+ }
290
+ function readPromiseState(promise) {
291
+ return "status" in promise ? promise : { status: "pending" };
292
+ }
293
+ /**
294
+ * Resolves an array of document promises using `Promise.allSettled`,
295
+ * returning only the fulfilled values. A single missing/rejected
296
+ * document does not poison the whole batch. Rejected entries are
297
+ * logged at warn level so developers can see dangling references.
298
+ */
299
+ function fulfilledOnly(promises) {
300
+ return Promise.allSettled(promises).then((results) => {
301
+ const documents = [];
302
+ for (const result of results) if (result.status === "fulfilled") documents.push(result.value);
303
+ else console.warn("[DocumentCache] Skipped unavailable document:", result.reason);
304
+ return documents;
305
+ });
306
+ }
307
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
308
+ const IDLE_OPERATIONS_ENTRY = Object.freeze({
309
+ status: "idle",
310
+ operations: Object.freeze([]),
311
+ error: void 0,
312
+ hasNextPage: false
313
+ });
314
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
315
+ function isOperationCache(cache) {
316
+ if (typeof cache !== "object" || cache === null) return false;
317
+ const candidate = cache;
318
+ return typeof candidate.getOperationsState === "function" && typeof candidate.loadOperations === "function" && typeof candidate.loadMoreOperations === "function" && typeof candidate.invalidateOperations === "function" && typeof candidate.subscribeOperations === "function";
319
+ }
320
+ /**
321
+ * Page size used to refresh a scope whose request record has gone missing.
322
+ * A loaded scope always has one, so this is a floor rather than a default.
323
+ */
324
+ const FALLBACK_REFRESH_LIMIT = 100;
325
+ /**
326
+ * The highest revision among the operations loaded so far, or -1 for none.
327
+ * Pages arrive oldest first, so this is normally the last entry; it is
328
+ * computed rather than assumed because nothing in the cache enforces that.
329
+ */
330
+ function highestOperationIndex(operations) {
331
+ let highest = -1;
332
+ for (const operation of operations) if (operation.index > highest) highest = operation.index;
333
+ return highest;
334
+ }
335
+ /**
336
+ * Document cache implementation that uses the new ReactorClient API.
337
+ *
338
+ * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
339
+ * and automatically updates the cache when documents are created, updated, or deleted.
340
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
341
+ * which is dropped for a document whenever a change event for it arrives.
342
+ */
343
+ var DocumentCache = class {
344
+ client;
345
+ documents = /* @__PURE__ */ new Map();
346
+ batchPromises = /* @__PURE__ */ new Map();
347
+ listeners = /* @__PURE__ */ new Map();
348
+ refetcher = new DocumentRefetcher({
349
+ documents: this.documents,
350
+ fetch: (id) => this.client.get(id),
351
+ notify: (id) => this.notifyListeners(id),
352
+ onFetched: (id, document) => {
353
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
354
+ }
355
+ });
356
+ /**
357
+ * Cache keys that fetched a document under a name other than its id --
358
+ * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
359
+ * so without this mapping a slug-keyed entry (and its listeners) would never
360
+ * see an update: keyed by the id the events carry, valued by the other keys
361
+ * the same document is cached under.
362
+ */
363
+ aliasKeys = /* @__PURE__ */ new Map();
364
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
365
+ operationEntries = /* @__PURE__ */ new Map();
366
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
367
+ operationRequests = /* @__PURE__ */ new Map();
368
+ operationListeners = /* @__PURE__ */ new Map();
369
+ unsubscribe = null;
370
+ constructor(client) {
371
+ this.client = client;
372
+ this.unsubscribe = client.subscribe({}, (event) => {
373
+ this.handleDocumentChange(event);
374
+ });
375
+ }
376
+ handleDocumentChange(event) {
377
+ if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
378
+ const documentId = event.context?.childId;
379
+ if (documentId) {
380
+ const keys = this.cacheKeysFor(documentId);
381
+ this.handleDocumentDeleted(documentId);
382
+ for (const key of keys) this.invalidateOperations(key);
383
+ }
384
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) {
385
+ const keys = this.cacheKeysFor(doc.header.id);
386
+ this.handleDocumentUpdated(doc.header.id).catch(console.warn);
387
+ for (const key of keys) this.refreshOperations(key);
388
+ }
389
+ }
390
+ handleDocumentDeleted(documentId) {
391
+ for (const key of this.cacheKeysFor(documentId)) {
392
+ const listeners = this.listeners.get(key);
393
+ this.documents.delete(key);
394
+ this.refetcher.forget(key);
395
+ this.invalidateBatchesContaining(key);
396
+ if (listeners) listeners.forEach((listener) => listener());
397
+ this.listeners.delete(key);
398
+ }
399
+ this.aliasKeys.delete(documentId);
400
+ }
401
+ async handleDocumentUpdated(documentId) {
402
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
403
+ await Promise.all(refetches);
404
+ }
405
+ notifyListeners(key) {
406
+ for (const listener of this.listeners.get(key) ?? []) listener();
407
+ }
408
+ /** The id an event dispatches by, plus every alias the document is cached under. */
409
+ cacheKeysFor(documentId) {
410
+ return [documentId, ...this.aliasKeys.get(documentId) ?? []];
411
+ }
412
+ /** Records that `key` cached the document change events know as `header.id`. */
413
+ recordAlias(documentId, key) {
414
+ const keys = this.aliasKeys.get(documentId) ?? /* @__PURE__ */ new Set();
415
+ keys.add(key);
416
+ this.aliasKeys.set(documentId, keys);
417
+ }
418
+ invalidateBatchesContaining(documentId) {
419
+ for (const key of this.batchPromises.keys()) if (key.split(",").includes(documentId)) this.batchPromises.delete(key);
420
+ }
421
+ get(id, refetch) {
422
+ const currentData = this.documents.get(id);
423
+ if (currentData && !refetch) return currentData;
424
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
425
+ this.refetcher.forget(id);
426
+ const documentPromise = this.client.get(id);
427
+ documentPromise.then((doc) => {
428
+ if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
429
+ }, () => void 0);
430
+ this.documents.set(id, addPromiseState(documentPromise));
431
+ return documentPromise;
432
+ }
433
+ getRefetchState(id) {
434
+ return this.refetcher.getState(id);
435
+ }
436
+ getBatch(ids) {
437
+ const key = ids.join(",");
438
+ const cached = this.batchPromises.get(key);
439
+ const hasDeletedDocuments = ids.some((id) => !this.documents.has(id));
440
+ const currentPromises = ids.map((id) => this.get(id));
441
+ if (hasDeletedDocuments) {
442
+ const batchPromise = fulfilledOnly(currentPromises);
443
+ this.batchPromises.set(key, {
444
+ promises: currentPromises,
445
+ promise: batchPromise
446
+ });
447
+ return batchPromise;
448
+ }
449
+ if (cached) {
450
+ if (currentPromises.every((p, i) => p === cached.promises[i])) return cached.promise;
451
+ }
452
+ const states = currentPromises.map((p) => readPromiseState(p));
453
+ if (states.every((s) => s.status !== "pending")) {
454
+ const values = states.filter((s) => s.status === "fulfilled").map((s) => s.value);
455
+ const batchPromise = Promise.resolve(values);
456
+ batchPromise.status = "fulfilled";
457
+ batchPromise.value = values;
458
+ this.batchPromises.set(key, {
459
+ promises: currentPromises,
460
+ promise: batchPromise
461
+ });
462
+ return batchPromise;
463
+ }
464
+ if (cached) return cached.promise;
465
+ const batchPromise = fulfilledOnly(currentPromises);
466
+ this.batchPromises.set(key, {
467
+ promises: currentPromises,
468
+ promise: batchPromise
469
+ });
470
+ return batchPromise;
471
+ }
472
+ subscribe(id, callback) {
473
+ const ids = Array.isArray(id) ? id : [id];
474
+ for (const docId of ids) {
475
+ const listeners = this.listeners.get(docId) ?? [];
476
+ this.listeners.set(docId, [...listeners, callback]);
477
+ }
478
+ return () => {
479
+ for (const docId of ids) {
480
+ const listeners = this.listeners.get(docId) ?? [];
481
+ this.listeners.set(docId, listeners.filter((listener) => listener !== callback));
482
+ }
483
+ };
484
+ }
485
+ getOperationsState(documentId, scope) {
486
+ return this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY;
487
+ }
488
+ loadOperations(documentId, scope, limit) {
489
+ const current = this.getOperationsState(documentId, scope);
490
+ if (current.status !== "idle") return;
491
+ const controller = new AbortController();
492
+ this.setOperationsRequest(documentId, scope, {
493
+ controller,
494
+ nextCursor: void 0,
495
+ limit
496
+ });
497
+ this.setOperationsEntry(documentId, scope, {
498
+ ...current,
499
+ status: "pending"
500
+ });
501
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
502
+ cursor: "",
503
+ limit
504
+ }, controller.signal), controller, limit);
505
+ }
506
+ loadMoreOperations(documentId, scope) {
507
+ const current = this.getOperationsState(documentId, scope);
508
+ const request = this.operationRequests.get(documentId)?.get(scope);
509
+ if (current.status !== "success" || !current.hasNextPage || !request?.nextCursor) return;
510
+ const controller = new AbortController();
511
+ const { nextCursor, limit } = request;
512
+ this.setOperationsRequest(documentId, scope, {
513
+ controller,
514
+ nextCursor,
515
+ limit
516
+ });
517
+ this.setOperationsEntry(documentId, scope, {
518
+ ...current,
519
+ status: "pending"
520
+ });
521
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
522
+ cursor: nextCursor,
523
+ limit
524
+ }, controller.signal), controller, limit);
525
+ }
526
+ /**
527
+ * Bring a document's cached scopes up to date after it changed, without
528
+ * throwing away what is already loaded.
529
+ *
530
+ * The operation stream is append-only: an update adds operations at higher
531
+ * revisions and never rewrites the ones below, so history already paged in
532
+ * is still correct. Dropping it meant a panel showing a fully loaded
533
+ * document re-walked every page on each edit -- the cost of which grows
534
+ * with the document, exactly where it hurts most. Each scope instead asks
535
+ * only for what comes after the newest revision it holds, using the
536
+ * `sinceRevision` filter, and appends the answer.
537
+ *
538
+ * A scope that has not finished paging is dropped as before: it has no
539
+ * meaningful "newest revision" to resume from, since asking for everything
540
+ * past the newest row it happens to hold would skip the pages between that
541
+ * row and the end of the stream.
542
+ */
543
+ refreshOperations(documentId) {
544
+ const scopes = this.operationEntries.get(documentId);
545
+ if (!scopes) return;
546
+ for (const [scope, entry] of [...scopes.entries()]) {
547
+ if (entry.status !== "success" || entry.hasNextPage) {
548
+ this.invalidateOperationsScope(documentId, scope);
549
+ continue;
550
+ }
551
+ const previous = this.operationRequests.get(documentId)?.get(scope);
552
+ const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;
553
+ previous?.controller.abort();
554
+ const controller = new AbortController();
555
+ this.setOperationsRequest(documentId, scope, {
556
+ controller,
557
+ nextCursor: void 0,
558
+ limit
559
+ });
560
+ this.setOperationsEntry(documentId, scope, {
561
+ ...entry,
562
+ status: "pending"
563
+ });
564
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, { sinceRevision: highestOperationIndex(entry.operations) + 1 }, {
565
+ cursor: "",
566
+ limit
567
+ }, controller.signal), controller, limit);
568
+ }
569
+ }
570
+ /** Drops one scope of a document, aborting its request if one is in flight. */
571
+ invalidateOperationsScope(documentId, scope) {
572
+ const requests = this.operationRequests.get(documentId);
573
+ const request = requests?.get(scope);
574
+ if (request && requests) {
575
+ request.controller.abort();
576
+ requests.delete(scope);
577
+ if (requests.size === 0) this.operationRequests.delete(documentId);
578
+ }
579
+ const scopes = this.operationEntries.get(documentId);
580
+ if (scopes?.delete(scope)) {
581
+ if (scopes.size === 0) this.operationEntries.delete(documentId);
582
+ this.notifyOperationListeners(documentId);
583
+ }
584
+ }
585
+ invalidateOperations(documentId) {
586
+ const requests = this.operationRequests.get(documentId);
587
+ if (requests) {
588
+ for (const request of requests.values()) request.controller.abort();
589
+ this.operationRequests.delete(documentId);
590
+ }
591
+ if (this.operationEntries.delete(documentId)) this.notifyOperationListeners(documentId);
592
+ }
593
+ subscribeOperations(documentId, callback) {
594
+ const listeners = this.operationListeners.get(documentId) ?? [];
595
+ this.operationListeners.set(documentId, [...listeners, callback]);
596
+ return () => {
597
+ const current = this.operationListeners.get(documentId) ?? [];
598
+ this.operationListeners.set(documentId, current.filter((listener) => listener !== callback));
599
+ };
600
+ }
601
+ settleOperationsPage(documentId, scope, page, controller, limit) {
602
+ page.then((result) => {
603
+ if (controller.signal.aborted) return;
604
+ const current = this.getOperationsState(documentId, scope);
605
+ this.setOperationsRequest(documentId, scope, {
606
+ controller,
607
+ nextCursor: result.nextCursor,
608
+ limit
609
+ });
610
+ this.setOperationsEntry(documentId, scope, {
611
+ status: "success",
612
+ operations: [...current.operations, ...result.results],
613
+ error: void 0,
614
+ hasNextPage: !!result.nextCursor
615
+ });
616
+ }, (reason) => {
617
+ if (controller.signal.aborted) return;
618
+ const current = this.getOperationsState(documentId, scope);
619
+ this.setOperationsEntry(documentId, scope, {
620
+ ...current,
621
+ status: "error",
622
+ error: reason
623
+ });
624
+ });
625
+ }
626
+ setOperationsEntry(documentId, scope, entry) {
627
+ const scopes = this.operationEntries.get(documentId) ?? /* @__PURE__ */ new Map();
628
+ scopes.set(scope, entry);
629
+ this.operationEntries.set(documentId, scopes);
630
+ this.notifyOperationListeners(documentId);
631
+ }
632
+ setOperationsRequest(documentId, scope, request) {
633
+ const scopes = this.operationRequests.get(documentId) ?? /* @__PURE__ */ new Map();
634
+ scopes.set(scope, request);
635
+ this.operationRequests.set(documentId, scopes);
636
+ }
637
+ notifyOperationListeners(documentId) {
638
+ for (const listener of this.operationListeners.get(documentId) ?? []) listener();
639
+ }
640
+ /**
641
+ * Disposes of the cache and unsubscribes from document change events.
642
+ */
643
+ dispose() {
644
+ if (this.unsubscribe) {
645
+ this.unsubscribe();
646
+ this.unsubscribe = null;
647
+ }
648
+ for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
649
+ this.operationRequests.clear();
650
+ this.operationEntries.clear();
651
+ this.refetcher.clear();
652
+ this.operationListeners.clear();
653
+ }
654
+ };
655
+ //#endregion
656
+ //#region src/hooks/document-cache.ts
657
+ const documentEventFunctions = makePHEventFunctions("documentCache");
658
+ /** Returns all documents in the reactor. */
659
+ const useDocumentCache = documentEventFunctions.useValue;
660
+ /** Sets all of the documents in the reactor. */
661
+ const setDocumentCache = documentEventFunctions.setValue;
662
+ /** Adds an event handler for all of the documents in the reactor. */
663
+ const addDocumentCacheEventHandler = documentEventFunctions.addEventHandler;
664
+ /**
665
+ * Reads the state of a document promise and converts it to a query state object.
666
+ * @param promise - The document promise to read
667
+ * @returns An object containing the status, data, error, and isPending flag
668
+ */
669
+ function getDocumentQueryState(promise) {
670
+ const state = readPromiseState(promise);
671
+ switch (state.status) {
672
+ case "pending": return {
673
+ status: "pending",
674
+ isPending: true,
675
+ error: void 0,
676
+ data: void 0
677
+ };
678
+ case "fulfilled": return {
679
+ status: "success",
680
+ isPending: false,
681
+ error: void 0,
682
+ data: state.value
683
+ };
684
+ case "rejected": return {
685
+ status: "error",
686
+ isPending: false,
687
+ error: state.reason,
688
+ data: void 0
689
+ };
690
+ }
691
+ }
692
+ /**
693
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
694
+ * This hook will suspend rendering while the document is loading.
695
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
696
+ * @returns The document if found, or undefined if id is null/undefined
697
+ */
698
+ function useDocument(id) {
699
+ const documentCache = useDocumentCache();
700
+ const getDocument = () => id ? documentCache?.get(id) : void 0;
701
+ const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, getDocument, getDocument);
702
+ return document ? use(document) : void 0;
703
+ }
704
+ /**
705
+ * Retrieves a document from the reactor and subscribes to changes without
706
+ * suspending or throwing. Use this when the ID might be stale (e.g., a
707
+ * previously selected node that has since been deleted) and the consumer
708
+ * wants to render a placeholder instead of crashing.
709
+ *
710
+ * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache
711
+ * updates, so the returned state stays in sync with reactor changes.
712
+ *
713
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
714
+ * @returns An object containing:
715
+ * - status: "initial" | "pending" | "success" | "error"
716
+ * - data: The document if successfully loaded
717
+ * - isPending: Whether the document is currently loading
718
+ * - error: Any error that occurred during loading (e.g., document not found)
719
+ * - reload: Function to force a refetch, or undefined when no id is supplied
720
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
721
+ * - refetchError: The last refetch failure that kept the loaded document
722
+ */
723
+ function useDocumentSafe(id) {
724
+ const documentCache = useDocumentCache();
725
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
726
+ const getPromise = () => id ? documentCache?.get(id) : void 0;
727
+ const getRefetch = () => readRefetchState(documentCache, id);
728
+ const promise = useSyncExternalStore(subscribe, getPromise, getPromise);
729
+ const refetch = useSyncExternalStore(subscribe, getRefetch, getRefetch);
730
+ const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
731
+ const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
732
+ useEffect(() => {
733
+ if (!pendingPromise) return;
734
+ let active = true;
735
+ const settled = () => {
736
+ if (active) bumpOnSettle();
737
+ };
738
+ pendingPromise.then(settled, settled);
739
+ return () => {
740
+ active = false;
741
+ };
742
+ }, [pendingPromise]);
743
+ if (!promise || !documentCache || !id) return {
744
+ status: "initial",
745
+ isPending: false,
746
+ error: void 0,
747
+ data: void 0,
748
+ reload: void 0,
749
+ isRefetching: false,
750
+ refetchError: void 0
751
+ };
752
+ return {
753
+ ...getDocumentQueryState(promise),
754
+ reload: () => documentCache.get(id, true),
755
+ isRefetching: refetch.isRefetching,
756
+ refetchError: refetch.error
757
+ };
758
+ }
759
+ function readRefetchState(documentCache, id) {
760
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
761
+ }
762
+ /**
763
+ * Retrieves multiple documents from the reactor using React Suspense.
764
+ * This hook will suspend rendering while any of the documents are loading.
765
+ *
766
+ * Uses getBatch from the document cache which handles promise caching internally,
767
+ * ensuring stable references for useSyncExternalStore.
768
+ *
769
+ * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval
770
+ * @returns An array of documents if found, or empty array if ids is null/undefined
771
+ */
772
+ function useDocuments(ids) {
773
+ const documentCache = useDocumentCache();
774
+ const getBatch = () => ids?.length && documentCache ? documentCache.getBatch(ids) : void 0;
775
+ const documents = useSyncExternalStore((cb) => ids?.length && documentCache ? documentCache.subscribe(ids, cb) : () => {}, getBatch, getBatch);
776
+ return documents ? use(documents) : [];
777
+ }
778
+ /**
779
+ * Returns a function to retrieve a document from the cache.
780
+ * The returned function fetches and returns a document by ID.
781
+ * @returns A function that takes a document ID and returns a Promise of the document
782
+ */
783
+ function useGetDocument() {
784
+ const documentCache = useDocumentCache();
785
+ return useCallback((id) => {
786
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
787
+ return documentCache.get(id);
788
+ }, [documentCache]);
789
+ }
790
+ /**
791
+ * Returns a function to retrieve multiple documents from the cache.
792
+ * The returned function fetches and returns documents by their IDs.
793
+ * @returns A function that takes an array of document IDs and returns a Promise of the documents
794
+ */
795
+ function useGetDocuments() {
796
+ const documentCache = useDocumentCache();
797
+ return useCallback((ids) => {
798
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
799
+ return documentCache.getBatch(ids);
800
+ }, [documentCache]);
801
+ }
802
+ /**
803
+ * Retrieves a document from the reactor without suspending rendering.
804
+ * Returns the current state of the document loading operation.
805
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
806
+ * @returns An object containing:
807
+ * - status: "initial" | "pending" | "success" | "error"
808
+ * - data: The document if successfully loaded
809
+ * - isPending: Boolean indicating if the document is currently loading
810
+ * - error: Any error that occurred during loading
811
+ * - reload: Function to force reload the document from cache
812
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
813
+ * - refetchError: The last refetch failure that kept the loaded document
814
+ */
815
+ function useGetDocumentAsync(id) {
816
+ const documentCache = useDocumentCache();
817
+ if (!id || !documentCache) return {
818
+ status: "initial",
819
+ data: void 0,
820
+ isPending: false,
821
+ error: void 0,
822
+ reload: void 0,
823
+ isRefetching: false,
824
+ refetchError: void 0
825
+ };
826
+ const state = getDocumentQueryState(documentCache.get(id));
827
+ const refetch = readRefetchState(documentCache, id);
828
+ return {
829
+ ...state,
830
+ reload: () => documentCache.get(id, true),
831
+ isRefetching: refetch.isRefetching,
832
+ refetchError: refetch.error
833
+ };
834
+ }
835
+ //#endregion
836
+ //#region src/hooks/dispatch.ts
837
+ /** A dispatch to the document `getDocument` returns when it runs. */
838
+ function createDispatch(getDocument) {
839
+ /**
840
+ * Dispatches actions to the document.
841
+ * @param actionOrActions - The action or actions to dispatch.
842
+ * @param onErrors - Callback invoked with any errors that occurred during action execution,
843
+ * or with the failure when the dispatch itself did not complete.
844
+ */
845
+ return function dispatch(actionOrActions, onErrors, onSuccess) {
846
+ let answered = false;
847
+ const reportErrors = onErrors && ((errors) => {
848
+ answered = true;
849
+ onErrors(errors);
850
+ });
851
+ const reportSuccess = onSuccess && ((result) => {
852
+ answered = true;
853
+ onSuccess(result);
854
+ });
855
+ dispatchActions(actionOrActions, getDocument(), reportErrors, reportSuccess).catch((error) => {
856
+ logger.error("Failed to dispatch actions: @error", error);
857
+ if (!answered) onErrors?.([error instanceof Error ? error : new Error(String(error))]);
858
+ });
859
+ };
860
+ }
861
+ function useDispatch(document) {
862
+ const latest = useRef(document);
863
+ latest.current = document;
864
+ const id = document?.header.id;
865
+ return [document, useMemo(() => createDispatch(() => latest.current), [id])];
866
+ }
867
+ //#endregion
868
+ export { queueActions as C, dispatchActions as S, uploadOperations as T, DOCUMENT_CHANGE_TYPE as _, useDocument as a, DocumentRefetcher as b, useDocuments as c, useGetDocuments as d, DocumentCache as f, readPromiseState as g, isOperationCache as h, setDocumentCache as i, useGetDocument as l, addPromiseState as m, useDispatch as n, useDocumentCache as o, IDLE_OPERATIONS_ENTRY as p, addDocumentCacheEventHandler as r, useDocumentSafe as s, createDispatch as t, useGetDocumentAsync as u, isDuplicateManifestError as v, queueOperations as w, IDLE_REFETCH_STATE as x, isDuplicateModuleError as y };
869
+
870
+ //# sourceMappingURL=dispatch-Dd_WEz35.js.map