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

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,1173 @@
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
+ import { operationOutcome } from "@powerhousedao/shared/document-model";
5
+ //#region src/errors.ts
6
+ var UnsupportedDocumentTypeError = class extends Error {
7
+ constructor(documentType) {
8
+ super(`Document type ${documentType} is not supported`);
9
+ this.name = "UnsupportedDocumentTypeError";
10
+ }
11
+ static isError(error) {
12
+ return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
13
+ }
14
+ };
15
+ var DocumentModelNotFoundError = class extends Error {
16
+ documentType;
17
+ name = "DocumentModelNotFoundError";
18
+ constructor(documentType) {
19
+ super(`Document model module for type ${documentType} not found`);
20
+ this.documentType = documentType;
21
+ }
22
+ static isError(error) {
23
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
24
+ }
25
+ };
26
+ var DocumentTypeMismatchError = class extends Error {
27
+ constructor(documentId, expectedType, actualType) {
28
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
29
+ }
30
+ };
31
+ var NoSelectedDocumentError = class extends Error {
32
+ constructor() {
33
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
34
+ }
35
+ };
36
+ /** A dispatched action the document did not apply: its operation is stored at `index`, state
37
+ * unchanged, because the reducer threw (`reducer-error`) or the write was denied (`denied`). */
38
+ var OperationRejectedError = class OperationRejectedError extends Error {
39
+ documentId;
40
+ scope;
41
+ name = "OperationRejectedError";
42
+ actionId;
43
+ actionType;
44
+ index;
45
+ kind;
46
+ constructor(documentId, scope, operation, outcome) {
47
+ super(outcome.kind === "denied" ? outcome.reason : outcome.message);
48
+ this.documentId = documentId;
49
+ this.scope = scope;
50
+ this.actionId = operation.action.id;
51
+ this.actionType = operation.action.type;
52
+ this.index = operation.index;
53
+ this.kind = outcome.kind;
54
+ }
55
+ /** The rejection `operation` records, or undefined when it applied. */
56
+ static fromOperation(documentId, scope, operation) {
57
+ const outcome = operationOutcome(operation);
58
+ return outcome.kind === "applied" ? void 0 : new OperationRejectedError(documentId, scope, operation, outcome);
59
+ }
60
+ static isError(error) {
61
+ return Error.isError(error) && error.name === "OperationRejectedError";
62
+ }
63
+ };
64
+ //#endregion
65
+ //#region src/actions/queue.ts
66
+ async function queueActions(document, actionOrActions) {
67
+ if (!document) throw new Error("No document provided");
68
+ if (!actionOrActions) throw new Error("No actions provided");
69
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
70
+ if (actions.length === 0) throw new Error("No actions provided");
71
+ const reactorClient = getPHStore()?.reactorClient;
72
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
73
+ return await (await reactorClient.write.execute(document.header.id, "main", actions)).document();
74
+ }
75
+ async function queueOperations(documentId, operationOrOperations) {
76
+ if (!documentId) throw new Error("No documentId provided");
77
+ if (!operationOrOperations) throw new Error("No operations provided");
78
+ const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
79
+ if (operations.length === 0) throw new Error("No operations provided");
80
+ const reactorClient = getPHStore()?.reactorClient;
81
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
82
+ const actions = operations.map((op) => op.action);
83
+ return await (await reactorClient.write.execute(documentId, "main", actions)).document();
84
+ }
85
+ async function uploadOperations(documentId, allOperations, pushOperations, options) {
86
+ const operationsLimit = options?.operationsLimit || 50;
87
+ const onProgress = options?.onProgress;
88
+ logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
89
+ const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
90
+ const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
91
+ let uploadedOperations = 0;
92
+ for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
93
+ logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
94
+ const chunk = operations.slice(i, i + operationsLimit);
95
+ const operation = chunk.at(-1);
96
+ if (!operation) break;
97
+ const scope = operation.action.scope;
98
+ await pushOperations(documentId, chunk);
99
+ uploadedOperations += chunk.length;
100
+ if (onProgress) onProgress({
101
+ stage: "uploading",
102
+ progress: Math.round(uploadedOperations / totalOperations * 100),
103
+ totalOperations,
104
+ uploadedOperations
105
+ });
106
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
107
+ }
108
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
109
+ }
110
+ //#endregion
111
+ //#region src/actions/sign.ts
112
+ function addActionContext(action) {
113
+ const renown = getPHStore()?.renown;
114
+ if (!renown?.user) return action;
115
+ return {
116
+ context: { signer: {
117
+ app: {
118
+ name: "Connect",
119
+ key: renown.did
120
+ },
121
+ user: {
122
+ address: renown.user.address,
123
+ networkId: renown.user.networkId,
124
+ chainId: renown.user.chainId
125
+ },
126
+ signatures: []
127
+ } },
128
+ ...action
129
+ };
130
+ }
131
+ function makeSignedActionWithContext(action, document) {
132
+ if (!action) {
133
+ logger.error("No action found");
134
+ return;
135
+ }
136
+ if (!document) {
137
+ logger.error("No document found");
138
+ return;
139
+ }
140
+ return addActionContext(action);
141
+ }
142
+ function makeSignedActionsWithContext(actionOrActions, document) {
143
+ if (!actionOrActions) {
144
+ logger.error("No actions found");
145
+ return;
146
+ }
147
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
148
+ }
149
+ //#endregion
150
+ //#region src/actions/dispatch.ts
151
+ async function getDocument(documentId) {
152
+ try {
153
+ return await getPHStore()?.reactorClient?.get(documentId);
154
+ } catch (error) {
155
+ logger.debug(`Failed to get document with id ${documentId}:`, error);
156
+ return;
157
+ }
158
+ }
159
+ async function getOperationsSince(documentId, scope, sinceRevision) {
160
+ const reactorClient = getPHStore()?.reactorClient;
161
+ if (!reactorClient) return [];
162
+ const operations = [];
163
+ let paging;
164
+ do {
165
+ const page = await reactorClient.getOperations(documentId, {
166
+ branch: "main",
167
+ scopes: [scope]
168
+ }, { sinceRevision }, paging);
169
+ operations.push(...page.results);
170
+ paging = page.nextCursor && page.results.length ? {
171
+ cursor: page.nextCursor,
172
+ limit: page.options.limit
173
+ } : void 0;
174
+ } while (paging);
175
+ return operations;
176
+ }
177
+ /** The operations the dispatch produced in `scope`: a remote client returns them on the
178
+ * document, the local clients do not, so they are read from the revision before it. */
179
+ async function getDispatchedOperations(before, result, scope, actionIds) {
180
+ const returned = result.operations?.[scope];
181
+ if (returned?.some((op) => actionIds.has(op.action.id))) return returned;
182
+ return getOperationsSince(result.header.id, scope, before.header.revision[scope] ?? 0);
183
+ }
184
+ async function getActionErrors(before, result, actions) {
185
+ const actionIds = new Set(actions.map((action) => action.id));
186
+ const errors = [];
187
+ for (const scope of new Set(actions.map((action) => action.scope))) {
188
+ let operations;
189
+ try {
190
+ operations = await getDispatchedOperations(before, result, scope, actionIds);
191
+ } catch (error) {
192
+ logger.warn("Could not read the dispatched operations of @scope: @error", scope, error);
193
+ continue;
194
+ }
195
+ for (const action of actions) {
196
+ if (action.scope !== scope) continue;
197
+ const operation = operations.findLast((op) => op.action.id === action.id);
198
+ const error = operation && OperationRejectedError.fromOperation(result.header.id, scope, operation);
199
+ if (error) errors.push(error);
200
+ }
201
+ }
202
+ return errors;
203
+ }
204
+ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
205
+ const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
206
+ if (!document) {
207
+ const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;
208
+ logger.error(message);
209
+ onErrors?.([new Error(message)]);
210
+ return;
211
+ }
212
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
213
+ if (!signedActionsWithContext) {
214
+ const message = "No signed actions with context found";
215
+ logger.error(message);
216
+ onErrors?.([/* @__PURE__ */ new Error(message)]);
217
+ return;
218
+ }
219
+ const result = await queueActions(document, signedActionsWithContext);
220
+ const rejected = onErrors || onSuccess ? await getActionErrors(document, result, signedActionsWithContext) : [];
221
+ if (onErrors && rejected.length) onErrors(rejected);
222
+ onSuccess?.(result, { rejected });
223
+ return result;
224
+ }
225
+ //#endregion
226
+ //#region src/document-refetcher.ts
227
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
228
+ const IDLE_REFETCH_STATE = Object.freeze({
229
+ isRefetching: false,
230
+ error: void 0
231
+ });
232
+ function fulfilledPromise$1(value) {
233
+ const promise = Promise.resolve(value);
234
+ promise.status = "fulfilled";
235
+ promise.value = value;
236
+ return promise;
237
+ }
238
+ function rejectedPromise(reason) {
239
+ const promise = Promise.reject(reason);
240
+ promise.status = "rejected";
241
+ promise.reason = reason;
242
+ promise.catch(() => void 0);
243
+ return promise;
244
+ }
245
+ const MISSING_DOCUMENT_ERRORS = [
246
+ "DocumentNotFoundError",
247
+ "DocumentPurgedError",
248
+ "DocumentDeletedError"
249
+ ];
250
+ function isMissingDocumentError(error) {
251
+ if (!(error instanceof Error)) return false;
252
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
253
+ }
254
+ const noop = () => void 0;
255
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
256
+ var DocumentRefetcher = class {
257
+ host;
258
+ refetches = /* @__PURE__ */ new Map();
259
+ states = /* @__PURE__ */ new Map();
260
+ constructor(host) {
261
+ this.host = host;
262
+ }
263
+ getState(id) {
264
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
265
+ }
266
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
267
+ refetch(id) {
268
+ let entry = this.refetches.get(id);
269
+ if (!entry) {
270
+ entry = {
271
+ running: void 0,
272
+ queued: void 0
273
+ };
274
+ this.refetches.set(id, entry);
275
+ const current = this.host.documents.get(id);
276
+ if (current?.status !== "pending") return this.start(id, entry);
277
+ entry.running = current;
278
+ }
279
+ const inFlight = entry;
280
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
281
+ return inFlight.queued;
282
+ }
283
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
284
+ forget(id) {
285
+ this.refetches.delete(id);
286
+ this.states.delete(id);
287
+ }
288
+ clear() {
289
+ this.refetches.clear();
290
+ this.states.clear();
291
+ }
292
+ start(id, entry) {
293
+ entry.queued = void 0;
294
+ entry.running = this.run(id, entry);
295
+ return entry.running;
296
+ }
297
+ async run(id, entry) {
298
+ const isCurrent = () => this.refetches.get(id) === entry;
299
+ if (!isCurrent()) return this.host.fetch(id);
300
+ if (this.setState(id, {
301
+ isRefetching: true,
302
+ error: this.getState(id).error
303
+ })) this.host.notify(id);
304
+ try {
305
+ const document = await this.host.fetch(id);
306
+ if (isCurrent()) {
307
+ this.host.onFetched?.(id, document);
308
+ this.host.documents.set(id, fulfilledPromise$1(document));
309
+ this.finish(id, entry, void 0);
310
+ }
311
+ return document;
312
+ } catch (error) {
313
+ if (isCurrent()) {
314
+ if (isMissingDocumentError(error)) {
315
+ this.host.documents.set(id, rejectedPromise(error));
316
+ this.finish(id, entry, void 0);
317
+ } else {
318
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
319
+ this.finish(id, entry, error);
320
+ }
321
+ }
322
+ throw error;
323
+ }
324
+ }
325
+ finish(id, entry, error) {
326
+ if (!entry.queued) this.refetches.delete(id);
327
+ this.setState(id, {
328
+ isRefetching: entry.queued !== void 0,
329
+ error
330
+ });
331
+ this.host.notify(id);
332
+ }
333
+ /** Returns whether the snapshot changed; the caller notifies. */
334
+ setState(id, state) {
335
+ const current = this.getState(id);
336
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
337
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
338
+ else this.states.set(id, Object.freeze({ ...state }));
339
+ return true;
340
+ }
341
+ };
342
+ /**
343
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
344
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
345
+ * TypeScript string enum is nominal, so no string literal is assignable to it
346
+ * without one - and the two checks above are what make it safe.
347
+ */
348
+ const DOCUMENT_CHANGE_TYPE = {
349
+ Created: "created",
350
+ Deleted: "deleted",
351
+ Updated: "updated",
352
+ ParentAdded: "parent_added",
353
+ ParentRemoved: "parent_removed",
354
+ ChildAdded: "child_added",
355
+ ChildRemoved: "child_removed"
356
+ };
357
+ /**
358
+ * Structural equivalents of the reactor error classes' own static `isError`
359
+ * guards. Those guards match on `error.name` rather than the prototype chain
360
+ * (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is
361
+ * behaviour-preserving and does not need the class at runtime.
362
+ */
363
+ function isDuplicateModuleError(error) {
364
+ return Error.isError(error) && error.name === "DuplicateModuleError";
365
+ }
366
+ function isDuplicateManifestError(error) {
367
+ return Error.isError(error) && error.name === "DuplicateManifestError";
368
+ }
369
+ /** The error name a reactor reports for a job it does not know. */
370
+ const JOB_NOT_FOUND_ERROR_NAME = "JobNotFoundError";
371
+ //#endregion
372
+ //#region src/document-cache.ts
373
+ /** The most ids one `getMany` call is asked for. */
374
+ const GET_MANY_CHUNK_SIZE = 100;
375
+ function addPromiseState(promise) {
376
+ if ("status" in promise) return promise;
377
+ const promiseWithState = promise;
378
+ promiseWithState.status = "pending";
379
+ promiseWithState.then((value) => {
380
+ promiseWithState.status = "fulfilled";
381
+ promiseWithState.value = value;
382
+ }, (reason) => {
383
+ promiseWithState.status = "rejected";
384
+ promiseWithState.reason = reason;
385
+ throw reason;
386
+ });
387
+ return promiseWithState;
388
+ }
389
+ function readPromiseState(promise) {
390
+ return "status" in promise ? promise : { status: "pending" };
391
+ }
392
+ /**
393
+ * Resolves an array of document promises using `Promise.allSettled`,
394
+ * returning only the fulfilled values. A single missing/rejected
395
+ * document does not poison the whole batch. Rejected entries are
396
+ * logged at warn level so developers can see dangling references.
397
+ */
398
+ function fulfilledOnly(promises) {
399
+ return Promise.allSettled(promises).then((results) => {
400
+ const documents = [];
401
+ for (const result of results) if (result.status === "fulfilled") documents.push(result.value);
402
+ else console.warn("[DocumentCache] Skipped unavailable document:", result.reason);
403
+ return documents;
404
+ });
405
+ }
406
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
407
+ const IDLE_OPERATIONS_ENTRY = Object.freeze({
408
+ status: "idle",
409
+ operations: Object.freeze([]),
410
+ error: void 0,
411
+ hasNextPage: false
412
+ });
413
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
414
+ function isOperationCache(cache) {
415
+ if (typeof cache !== "object" || cache === null) return false;
416
+ const candidate = cache;
417
+ return typeof candidate.getOperationsState === "function" && typeof candidate.loadOperations === "function" && typeof candidate.loadMoreOperations === "function" && typeof candidate.invalidateOperations === "function" && typeof candidate.subscribeOperations === "function";
418
+ }
419
+ /** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */
420
+ const IDLE_DOCUMENTS_OF_TYPE_ENTRY = Object.freeze({
421
+ status: "idle",
422
+ ids: Object.freeze([]),
423
+ error: void 0,
424
+ hasNextPage: false
425
+ });
426
+ /** Whether a document cache also lists documents by type. */
427
+ function isDocumentTypeCache(cache) {
428
+ if (typeof cache !== "object" || cache === null) return false;
429
+ const candidate = cache;
430
+ return typeof candidate.getDocumentsOfTypeState === "function" && typeof candidate.loadDocumentsOfType === "function" && typeof candidate.loadMoreDocumentsOfType === "function" && typeof candidate.subscribeDocumentsOfType === "function";
431
+ }
432
+ function createDeferred() {
433
+ let resolve;
434
+ let reject;
435
+ return {
436
+ promise: new Promise((res, rej) => {
437
+ resolve = res;
438
+ reject = rej;
439
+ }),
440
+ resolve,
441
+ reject
442
+ };
443
+ }
444
+ /** A promise already settled with `value`, readable without awaiting. */
445
+ function fulfilledPromise(value) {
446
+ const promise = Promise.resolve(value);
447
+ promise.status = "fulfilled";
448
+ promise.value = value;
449
+ return promise;
450
+ }
451
+ const typeKey = (type, limit) => `${limit}:${type}`;
452
+ /**
453
+ * Page size used to refresh a scope whose request record has gone missing.
454
+ * A loaded scope always has one, so this is a floor rather than a default.
455
+ */
456
+ const FALLBACK_REFRESH_LIMIT = 100;
457
+ /**
458
+ * The highest revision among the operations loaded so far, or -1 for none.
459
+ * Pages arrive oldest first, so this is normally the last entry; it is
460
+ * computed rather than assumed because nothing in the cache enforces that.
461
+ */
462
+ function highestOperationIndex(operations) {
463
+ let highest = -1;
464
+ for (const operation of operations) if (operation.index > highest) highest = operation.index;
465
+ return highest;
466
+ }
467
+ /**
468
+ * Document cache implementation that uses the new ReactorClient API.
469
+ *
470
+ * This cache subscribes to document change events through the client's read half
471
+ * and automatically updates the cache when documents are created, updated, or deleted.
472
+ * It is built over a browser client, whose `read` half it uses, or over a read
473
+ * half directly.
474
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
475
+ * which is dropped for a document whenever a change event for it arrives.
476
+ */
477
+ var DocumentCache = class {
478
+ documents = /* @__PURE__ */ new Map();
479
+ batchPromises = /* @__PURE__ */ new Map();
480
+ listeners = /* @__PURE__ */ new Map();
481
+ refetcher = new DocumentRefetcher({
482
+ documents: this.documents,
483
+ fetch: (id) => this.client.get(id),
484
+ notify: (id) => this.notifyListeners(id),
485
+ onFetched: (id, document) => {
486
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
487
+ }
488
+ });
489
+ /**
490
+ * Cache keys that fetched a document under a name other than its id --
491
+ * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
492
+ * so without this mapping a slug-keyed entry (and its listeners) would never
493
+ * see an update: keyed by the id the events carry, valued by the other keys
494
+ * the same document is cached under.
495
+ */
496
+ aliasKeys = /* @__PURE__ */ new Map();
497
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
498
+ operationEntries = /* @__PURE__ */ new Map();
499
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
500
+ operationRequests = /* @__PURE__ */ new Map();
501
+ operationListeners = /* @__PURE__ */ new Map();
502
+ /** Documents by type and page size, keyed by typeKey. */
503
+ typeEntries = /* @__PURE__ */ new Map();
504
+ typeRequests = /* @__PURE__ */ new Map();
505
+ typeListeners = /* @__PURE__ */ new Map();
506
+ unsubscribe = null;
507
+ client;
508
+ constructor(client) {
509
+ this.client = readerOf(client);
510
+ this.unsubscribe = this.client.subscribe({}, (event) => {
511
+ this.handleDocumentChange(event);
512
+ });
513
+ }
514
+ handleDocumentChange(event) {
515
+ this.reloadTypesChangedBy(event);
516
+ if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
517
+ const documentId = event.context?.childId;
518
+ if (documentId) {
519
+ const keys = this.cacheKeysFor(documentId);
520
+ this.handleDocumentDeleted(documentId);
521
+ for (const key of keys) this.invalidateOperations(key);
522
+ }
523
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) {
524
+ const keys = this.cacheKeysFor(doc.header.id);
525
+ this.handleDocumentUpdated(doc.header.id).catch(console.warn);
526
+ for (const key of keys) this.refreshOperations(key);
527
+ }
528
+ }
529
+ handleDocumentDeleted(documentId) {
530
+ for (const key of this.cacheKeysFor(documentId)) {
531
+ const listeners = this.listeners.get(key);
532
+ this.documents.delete(key);
533
+ this.refetcher.forget(key);
534
+ this.invalidateBatchesContaining(key);
535
+ if (listeners) listeners.forEach((listener) => listener());
536
+ this.listeners.delete(key);
537
+ }
538
+ this.aliasKeys.delete(documentId);
539
+ }
540
+ async handleDocumentUpdated(documentId) {
541
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
542
+ await Promise.all(refetches);
543
+ }
544
+ notifyListeners(key) {
545
+ for (const listener of this.listeners.get(key) ?? []) listener();
546
+ }
547
+ /** The id an event dispatches by, plus every alias the document is cached under. */
548
+ cacheKeysFor(documentId) {
549
+ return [documentId, ...this.aliasKeys.get(documentId) ?? []];
550
+ }
551
+ /** Records that `key` cached the document change events know as `header.id`. */
552
+ recordAlias(documentId, key) {
553
+ const keys = this.aliasKeys.get(documentId) ?? /* @__PURE__ */ new Set();
554
+ keys.add(key);
555
+ this.aliasKeys.set(documentId, keys);
556
+ }
557
+ invalidateBatchesContaining(documentId) {
558
+ for (const key of this.batchPromises.keys()) if (key.split(",").includes(documentId)) this.batchPromises.delete(key);
559
+ }
560
+ get(id, refetch) {
561
+ const currentData = this.documents.get(id);
562
+ if (currentData && !refetch) return currentData;
563
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
564
+ this.refetcher.forget(id);
565
+ const documentPromise = this.client.get(id);
566
+ documentPromise.then((doc) => {
567
+ if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
568
+ }, () => void 0);
569
+ this.documents.set(id, addPromiseState(documentPromise));
570
+ return documentPromise;
571
+ }
572
+ getRefetchState(id) {
573
+ return this.refetcher.getState(id);
574
+ }
575
+ getBatch(ids) {
576
+ const key = ids.join(",");
577
+ const cached = this.batchPromises.get(key);
578
+ const hasDeletedDocuments = ids.some((id) => !this.documents.has(id));
579
+ if (hasDeletedDocuments) this.loadMany(ids);
580
+ const currentPromises = ids.map((id) => this.get(id));
581
+ if (hasDeletedDocuments) {
582
+ const batchPromise = fulfilledOnly(currentPromises);
583
+ this.batchPromises.set(key, {
584
+ promises: currentPromises,
585
+ promise: batchPromise
586
+ });
587
+ return batchPromise;
588
+ }
589
+ if (cached) {
590
+ if (currentPromises.every((p, i) => p === cached.promises[i])) return cached.promise;
591
+ }
592
+ const states = currentPromises.map((p) => readPromiseState(p));
593
+ if (states.every((s) => s.status !== "pending")) {
594
+ const values = states.filter((s) => s.status === "fulfilled").map((s) => s.value);
595
+ const batchPromise = Promise.resolve(values);
596
+ batchPromise.status = "fulfilled";
597
+ batchPromise.value = values;
598
+ this.batchPromises.set(key, {
599
+ promises: currentPromises,
600
+ promise: batchPromise
601
+ });
602
+ return batchPromise;
603
+ }
604
+ if (cached) return cached.promise;
605
+ const batchPromise = fulfilledOnly(currentPromises);
606
+ this.batchPromises.set(key, {
607
+ promises: currentPromises,
608
+ promise: batchPromise
609
+ });
610
+ return batchPromise;
611
+ }
612
+ /**
613
+ * Reserves an entry for every id not yet cached and fills them from
614
+ * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own
615
+ * entry, settled as `get` would settle it.
616
+ */
617
+ loadMany(ids) {
618
+ const getMany = this.client.getMany?.bind(this.client);
619
+ const missing = [...new Set(ids)].filter((id) => !this.documents.has(id));
620
+ if (!getMany || missing.length < 2) return;
621
+ const pending = /* @__PURE__ */ new Map();
622
+ for (const id of missing) {
623
+ const deferred = createDeferred();
624
+ pending.set(id, deferred);
625
+ this.refetcher.forget(id);
626
+ this.documents.set(id, addPromiseState(deferred.promise));
627
+ }
628
+ for (let i = 0; i < missing.length; i += 100) this.settleMany(missing.slice(i, i + 100), pending, getMany);
629
+ }
630
+ /**
631
+ * `getMany` rejects when any id is unavailable, so a failed chunk is split
632
+ * in half and retried; a single id is read with `get`, so it settles exactly
633
+ * as a single read would.
634
+ */
635
+ async settleMany(ids, pending, getMany) {
636
+ if (ids.length === 1) {
637
+ const id = ids[0];
638
+ try {
639
+ this.settleFetched(id, await this.client.get(id), pending);
640
+ } catch (error) {
641
+ pending.get(id)?.reject(error);
642
+ }
643
+ return;
644
+ }
645
+ let documents;
646
+ try {
647
+ documents = await getMany(ids);
648
+ } catch {
649
+ const half = Math.ceil(ids.length / 2);
650
+ await Promise.all([this.settleMany(ids.slice(0, half), pending, getMany), this.settleMany(ids.slice(half), pending, getMany)]);
651
+ return;
652
+ }
653
+ if (documents.length !== ids.length) {
654
+ await Promise.all(ids.map((id) => this.settleMany([id], pending, getMany)));
655
+ return;
656
+ }
657
+ ids.forEach((id, i) => this.settleFetched(id, documents[i], pending));
658
+ }
659
+ settleFetched(id, document, pending) {
660
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
661
+ pending.get(id)?.resolve(document);
662
+ }
663
+ subscribe(id, callback) {
664
+ const ids = Array.isArray(id) ? id : [id];
665
+ for (const docId of ids) {
666
+ const listeners = this.listeners.get(docId) ?? [];
667
+ this.listeners.set(docId, [...listeners, callback]);
668
+ }
669
+ return () => {
670
+ for (const docId of ids) {
671
+ const listeners = this.listeners.get(docId) ?? [];
672
+ this.listeners.set(docId, listeners.filter((listener) => listener !== callback));
673
+ }
674
+ };
675
+ }
676
+ getOperationsState(documentId, scope) {
677
+ return this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY;
678
+ }
679
+ loadOperations(documentId, scope, limit) {
680
+ const current = this.getOperationsState(documentId, scope);
681
+ if (current.status !== "idle") return;
682
+ const controller = new AbortController();
683
+ this.setOperationsRequest(documentId, scope, {
684
+ controller,
685
+ nextCursor: void 0,
686
+ limit
687
+ });
688
+ this.setOperationsEntry(documentId, scope, {
689
+ ...current,
690
+ status: "pending"
691
+ });
692
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
693
+ cursor: "",
694
+ limit
695
+ }, controller.signal), controller, limit);
696
+ }
697
+ loadMoreOperations(documentId, scope) {
698
+ const current = this.getOperationsState(documentId, scope);
699
+ const request = this.operationRequests.get(documentId)?.get(scope);
700
+ if (current.status !== "success" || !current.hasNextPage || !request?.nextCursor) return;
701
+ const controller = new AbortController();
702
+ const { nextCursor, limit } = request;
703
+ this.setOperationsRequest(documentId, scope, {
704
+ controller,
705
+ nextCursor,
706
+ limit
707
+ });
708
+ this.setOperationsEntry(documentId, scope, {
709
+ ...current,
710
+ status: "pending"
711
+ });
712
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
713
+ cursor: nextCursor,
714
+ limit
715
+ }, controller.signal), controller, limit);
716
+ }
717
+ /**
718
+ * Bring a document's cached scopes up to date after it changed, without
719
+ * throwing away what is already loaded.
720
+ *
721
+ * The operation stream is append-only: an update adds operations at higher
722
+ * revisions and never rewrites the ones below, so history already paged in
723
+ * is still correct. Dropping it meant a panel showing a fully loaded
724
+ * document re-walked every page on each edit -- the cost of which grows
725
+ * with the document, exactly where it hurts most. Each scope instead asks
726
+ * only for what comes after the newest revision it holds, using the
727
+ * `sinceRevision` filter, and appends the answer.
728
+ *
729
+ * A scope that has not finished paging is dropped as before: it has no
730
+ * meaningful "newest revision" to resume from, since asking for everything
731
+ * past the newest row it happens to hold would skip the pages between that
732
+ * row and the end of the stream.
733
+ */
734
+ refreshOperations(documentId) {
735
+ const scopes = this.operationEntries.get(documentId);
736
+ if (!scopes) return;
737
+ for (const [scope, entry] of [...scopes.entries()]) {
738
+ if (entry.status !== "success" || entry.hasNextPage) {
739
+ this.invalidateOperationsScope(documentId, scope);
740
+ continue;
741
+ }
742
+ const previous = this.operationRequests.get(documentId)?.get(scope);
743
+ const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;
744
+ previous?.controller.abort();
745
+ const controller = new AbortController();
746
+ this.setOperationsRequest(documentId, scope, {
747
+ controller,
748
+ nextCursor: void 0,
749
+ limit
750
+ });
751
+ this.setOperationsEntry(documentId, scope, {
752
+ ...entry,
753
+ status: "pending"
754
+ });
755
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, { sinceRevision: highestOperationIndex(entry.operations) + 1 }, {
756
+ cursor: "",
757
+ limit
758
+ }, controller.signal), controller, limit);
759
+ }
760
+ }
761
+ /** Drops one scope of a document, aborting its request if one is in flight. */
762
+ invalidateOperationsScope(documentId, scope) {
763
+ const requests = this.operationRequests.get(documentId);
764
+ const request = requests?.get(scope);
765
+ if (request && requests) {
766
+ request.controller.abort();
767
+ requests.delete(scope);
768
+ if (requests.size === 0) this.operationRequests.delete(documentId);
769
+ }
770
+ const scopes = this.operationEntries.get(documentId);
771
+ if (scopes?.delete(scope)) {
772
+ if (scopes.size === 0) this.operationEntries.delete(documentId);
773
+ this.notifyOperationListeners(documentId);
774
+ }
775
+ }
776
+ invalidateOperations(documentId) {
777
+ const requests = this.operationRequests.get(documentId);
778
+ if (requests) {
779
+ for (const request of requests.values()) request.controller.abort();
780
+ this.operationRequests.delete(documentId);
781
+ }
782
+ if (this.operationEntries.delete(documentId)) this.notifyOperationListeners(documentId);
783
+ }
784
+ subscribeOperations(documentId, callback) {
785
+ const listeners = this.operationListeners.get(documentId) ?? [];
786
+ this.operationListeners.set(documentId, [...listeners, callback]);
787
+ return () => {
788
+ const current = this.operationListeners.get(documentId) ?? [];
789
+ this.operationListeners.set(documentId, current.filter((listener) => listener !== callback));
790
+ };
791
+ }
792
+ settleOperationsPage(documentId, scope, page, controller, limit) {
793
+ page.then((result) => {
794
+ if (controller.signal.aborted) return;
795
+ const current = this.getOperationsState(documentId, scope);
796
+ this.setOperationsRequest(documentId, scope, {
797
+ controller,
798
+ nextCursor: result.nextCursor,
799
+ limit
800
+ });
801
+ this.setOperationsEntry(documentId, scope, {
802
+ status: "success",
803
+ operations: [...current.operations, ...result.results],
804
+ error: void 0,
805
+ hasNextPage: !!result.nextCursor
806
+ });
807
+ }, (reason) => {
808
+ if (controller.signal.aborted) return;
809
+ const current = this.getOperationsState(documentId, scope);
810
+ this.setOperationsEntry(documentId, scope, {
811
+ ...current,
812
+ status: "error",
813
+ error: reason
814
+ });
815
+ });
816
+ }
817
+ setOperationsEntry(documentId, scope, entry) {
818
+ const scopes = this.operationEntries.get(documentId) ?? /* @__PURE__ */ new Map();
819
+ scopes.set(scope, entry);
820
+ this.operationEntries.set(documentId, scopes);
821
+ this.notifyOperationListeners(documentId);
822
+ }
823
+ setOperationsRequest(documentId, scope, request) {
824
+ const scopes = this.operationRequests.get(documentId) ?? /* @__PURE__ */ new Map();
825
+ scopes.set(scope, request);
826
+ this.operationRequests.set(documentId, scopes);
827
+ }
828
+ notifyOperationListeners(documentId) {
829
+ for (const listener of this.operationListeners.get(documentId) ?? []) listener();
830
+ }
831
+ getDocumentsOfTypeState(type, limit) {
832
+ return this.typeEntries.get(typeKey(type, limit)) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;
833
+ }
834
+ loadDocumentsOfType(type, limit) {
835
+ const key = typeKey(type, limit);
836
+ const request = this.typeRequests.get(key);
837
+ if (request) return request.firstPage;
838
+ const controller = new AbortController();
839
+ const created = {
840
+ type,
841
+ limit,
842
+ firstPage: fulfilledPromise(void 0),
843
+ controller,
844
+ nextCursor: void 0
845
+ };
846
+ this.typeRequests.set(key, created);
847
+ created.firstPage = addPromiseState(this.loadTypePage(key, "", limit, controller, []));
848
+ return created.firstPage;
849
+ }
850
+ loadMoreDocumentsOfType(type, limit) {
851
+ const key = typeKey(type, limit);
852
+ const entry = this.getDocumentsOfTypeState(type, limit);
853
+ const request = this.typeRequests.get(key);
854
+ if (entry.status !== "success" || !request?.nextCursor) return;
855
+ this.loadTypePage(key, request.nextCursor, limit, request.controller, entry.ids);
856
+ }
857
+ subscribeDocumentsOfType(type, limit, callback) {
858
+ const key = typeKey(type, limit);
859
+ this.typeListeners.set(key, [...this.typeListeners.get(key) ?? [], callback]);
860
+ return () => {
861
+ const current = this.typeListeners.get(key) ?? [];
862
+ this.typeListeners.set(key, current.filter((listener) => listener !== callback));
863
+ };
864
+ }
865
+ /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */
866
+ async loadTypePage(key, cursor, limit, controller, before) {
867
+ const type = this.typeRequests.get(key)?.type ?? "";
868
+ this.setTypeEntry(key, {
869
+ ...this.getTypeEntry(key),
870
+ status: "pending"
871
+ });
872
+ try {
873
+ const page = await this.client.find({ type }, void 0, {
874
+ cursor,
875
+ limit
876
+ }, controller.signal);
877
+ if (controller.signal.aborted) return;
878
+ for (const document of page.results) this.primeDocument(document);
879
+ const request = this.typeRequests.get(key);
880
+ if (request) request.nextCursor = page.nextCursor;
881
+ this.setTypeEntry(key, {
882
+ status: "success",
883
+ ids: [...before, ...page.results.map((d) => d.header.id)],
884
+ error: void 0,
885
+ hasNextPage: !!page.nextCursor
886
+ });
887
+ } catch (error) {
888
+ if (controller.signal.aborted) return;
889
+ this.setTypeEntry(key, {
890
+ ...this.getTypeEntry(key),
891
+ status: "error",
892
+ error
893
+ });
894
+ }
895
+ }
896
+ /** Reloads every loaded page of a type a created or deleted document belongs to. */
897
+ reloadTypesChangedBy(event) {
898
+ if (this.typeRequests.size === 0) return;
899
+ let changed;
900
+ if (event.type === DOCUMENT_CHANGE_TYPE.Created) {
901
+ const types = new Set(event.documents.map((d) => d.header.documentType));
902
+ changed = (_key, type) => types.has(type);
903
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
904
+ const id = event.context?.childId;
905
+ if (!id) return;
906
+ changed = (key) => this.getTypeEntry(key).ids.includes(id);
907
+ } else return;
908
+ for (const [key, request] of this.typeRequests) {
909
+ if (!changed(key, request.type)) continue;
910
+ request.controller.abort();
911
+ const controller = new AbortController();
912
+ const created = event.type === DOCUMENT_CHANGE_TYPE.Created ? event.documents.filter((d) => d.header.documentType === request.type).length : 0;
913
+ const loaded = this.getTypeEntry(key).ids.length;
914
+ const limit = Math.max(request.limit, loaded + created);
915
+ request.controller = controller;
916
+ this.loadTypePage(key, "", limit, controller, []);
917
+ }
918
+ }
919
+ primeDocument(document) {
920
+ const current = this.documents.get(document.header.id);
921
+ if (current && current.status !== "rejected") return;
922
+ this.documents.set(document.header.id, fulfilledPromise(document));
923
+ }
924
+ getTypeEntry(key) {
925
+ return this.typeEntries.get(key) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;
926
+ }
927
+ setTypeEntry(key, entry) {
928
+ this.typeEntries.set(key, entry);
929
+ for (const listener of this.typeListeners.get(key) ?? []) listener();
930
+ }
931
+ /**
932
+ * Disposes of the cache and unsubscribes from document change events.
933
+ */
934
+ dispose() {
935
+ if (this.unsubscribe) {
936
+ this.unsubscribe();
937
+ this.unsubscribe = null;
938
+ }
939
+ for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
940
+ this.operationRequests.clear();
941
+ this.operationEntries.clear();
942
+ for (const request of this.typeRequests.values()) request.controller.abort();
943
+ this.typeRequests.clear();
944
+ this.typeEntries.clear();
945
+ this.typeListeners.clear();
946
+ this.refetcher.clear();
947
+ this.operationListeners.clear();
948
+ }
949
+ };
950
+ /** The read half of a browser client, or the reader itself. */
951
+ function readerOf(client) {
952
+ return client.read ?? client;
953
+ }
954
+ //#endregion
955
+ //#region src/hooks/document-cache.ts
956
+ const documentEventFunctions = makePHEventFunctions("documentCache");
957
+ /** Returns all documents in the reactor. */
958
+ const useDocumentCache = documentEventFunctions.useValue;
959
+ /** Sets all of the documents in the reactor. */
960
+ const setDocumentCache = documentEventFunctions.setValue;
961
+ /** Adds an event handler for all of the documents in the reactor. */
962
+ const addDocumentCacheEventHandler = documentEventFunctions.addEventHandler;
963
+ /**
964
+ * Reads the state of a document promise and converts it to a query state object.
965
+ * @param promise - The document promise to read
966
+ * @returns An object containing the status, data, error, and isPending flag
967
+ */
968
+ function getDocumentQueryState(promise) {
969
+ const state = readPromiseState(promise);
970
+ switch (state.status) {
971
+ case "pending": return {
972
+ status: "pending",
973
+ isPending: true,
974
+ error: void 0,
975
+ data: void 0
976
+ };
977
+ case "fulfilled": return {
978
+ status: "success",
979
+ isPending: false,
980
+ error: void 0,
981
+ data: state.value
982
+ };
983
+ case "rejected": return {
984
+ status: "error",
985
+ isPending: false,
986
+ error: state.reason,
987
+ data: void 0
988
+ };
989
+ }
990
+ }
991
+ /**
992
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
993
+ * This hook will suspend rendering while the document is loading.
994
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
995
+ * @returns The document if found, or undefined if id is null/undefined
996
+ */
997
+ function useDocument(id) {
998
+ const documentCache = useDocumentCache();
999
+ const getDocument = () => id ? documentCache?.get(id) : void 0;
1000
+ const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, getDocument, getDocument);
1001
+ return document ? use(document) : void 0;
1002
+ }
1003
+ /**
1004
+ * Retrieves a document from the reactor and subscribes to changes without
1005
+ * suspending or throwing. Use this when the ID might be stale (e.g., a
1006
+ * previously selected node that has since been deleted) and the consumer
1007
+ * wants to render a placeholder instead of crashing.
1008
+ *
1009
+ * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache
1010
+ * updates, so the returned state stays in sync with reactor changes.
1011
+ *
1012
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1013
+ * @returns An object containing:
1014
+ * - status: "initial" | "pending" | "success" | "error"
1015
+ * - data: The document if successfully loaded
1016
+ * - isPending: Whether the document is currently loading
1017
+ * - error: Any error that occurred during loading (e.g., document not found)
1018
+ * - reload: Function to force a refetch, or undefined when no id is supplied
1019
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1020
+ * - refetchError: The last refetch failure that kept the loaded document
1021
+ */
1022
+ function useDocumentSafe(id) {
1023
+ const documentCache = useDocumentCache();
1024
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
1025
+ const getPromise = () => id ? documentCache?.get(id) : void 0;
1026
+ const getRefetch = () => readRefetchState(documentCache, id);
1027
+ const promise = useSyncExternalStore(subscribe, getPromise, getPromise);
1028
+ const refetch = useSyncExternalStore(subscribe, getRefetch, getRefetch);
1029
+ const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
1030
+ const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
1031
+ useEffect(() => {
1032
+ if (!pendingPromise) return;
1033
+ let active = true;
1034
+ const settled = () => {
1035
+ if (active) bumpOnSettle();
1036
+ };
1037
+ pendingPromise.then(settled, settled);
1038
+ return () => {
1039
+ active = false;
1040
+ };
1041
+ }, [pendingPromise]);
1042
+ if (!promise || !documentCache || !id) return {
1043
+ status: "initial",
1044
+ isPending: false,
1045
+ error: void 0,
1046
+ data: void 0,
1047
+ reload: void 0,
1048
+ isRefetching: false,
1049
+ refetchError: void 0
1050
+ };
1051
+ return {
1052
+ ...getDocumentQueryState(promise),
1053
+ reload: () => documentCache.get(id, true),
1054
+ isRefetching: refetch.isRefetching,
1055
+ refetchError: refetch.error
1056
+ };
1057
+ }
1058
+ function readRefetchState(documentCache, id) {
1059
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
1060
+ }
1061
+ /**
1062
+ * Retrieves multiple documents from the reactor using React Suspense.
1063
+ * This hook will suspend rendering while any of the documents are loading.
1064
+ *
1065
+ * Uses getBatch from the document cache which handles promise caching internally,
1066
+ * ensuring stable references for useSyncExternalStore.
1067
+ *
1068
+ * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval
1069
+ * @returns An array of documents if found, or empty array if ids is null/undefined
1070
+ */
1071
+ function useDocuments(ids) {
1072
+ const documentCache = useDocumentCache();
1073
+ const getBatch = () => ids?.length && documentCache ? documentCache.getBatch(ids) : void 0;
1074
+ const documents = useSyncExternalStore((cb) => ids?.length && documentCache ? documentCache.subscribe(ids, cb) : () => {}, getBatch, getBatch);
1075
+ return documents ? use(documents) : [];
1076
+ }
1077
+ /**
1078
+ * Returns a function to retrieve a document from the cache.
1079
+ * The returned function fetches and returns a document by ID.
1080
+ * @returns A function that takes a document ID and returns a Promise of the document
1081
+ */
1082
+ function useGetDocument() {
1083
+ const documentCache = useDocumentCache();
1084
+ return useCallback((id) => {
1085
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
1086
+ return documentCache.get(id);
1087
+ }, [documentCache]);
1088
+ }
1089
+ /**
1090
+ * Returns a function to retrieve multiple documents from the cache.
1091
+ * The returned function fetches and returns documents by their IDs.
1092
+ * @returns A function that takes an array of document IDs and returns a Promise of the documents
1093
+ */
1094
+ function useGetDocuments() {
1095
+ const documentCache = useDocumentCache();
1096
+ return useCallback((ids) => {
1097
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
1098
+ return documentCache.getBatch(ids);
1099
+ }, [documentCache]);
1100
+ }
1101
+ /**
1102
+ * Retrieves a document from the reactor without suspending rendering.
1103
+ * Returns the current state of the document loading operation.
1104
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1105
+ * @returns An object containing:
1106
+ * - status: "initial" | "pending" | "success" | "error"
1107
+ * - data: The document if successfully loaded
1108
+ * - isPending: Boolean indicating if the document is currently loading
1109
+ * - error: Any error that occurred during loading
1110
+ * - reload: Function to force reload the document from cache
1111
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1112
+ * - refetchError: The last refetch failure that kept the loaded document
1113
+ */
1114
+ function useGetDocumentAsync(id) {
1115
+ const documentCache = useDocumentCache();
1116
+ if (!id || !documentCache) return {
1117
+ status: "initial",
1118
+ data: void 0,
1119
+ isPending: false,
1120
+ error: void 0,
1121
+ reload: void 0,
1122
+ isRefetching: false,
1123
+ refetchError: void 0
1124
+ };
1125
+ const state = getDocumentQueryState(documentCache.get(id));
1126
+ const refetch = readRefetchState(documentCache, id);
1127
+ return {
1128
+ ...state,
1129
+ reload: () => documentCache.get(id, true),
1130
+ isRefetching: refetch.isRefetching,
1131
+ refetchError: refetch.error
1132
+ };
1133
+ }
1134
+ //#endregion
1135
+ //#region src/hooks/dispatch.ts
1136
+ /** A dispatch to the document `getDocument` returns when it runs. */
1137
+ function createDispatch(getDocument) {
1138
+ /**
1139
+ * Dispatches actions to the document.
1140
+ * @param actionOrActions - The action or actions to dispatch.
1141
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
1142
+ * document did not apply, or with the failure when the dispatch itself did not complete.
1143
+ * Runs before `onSuccess`.
1144
+ * @param onSuccess - Callback invoked with the document once the write lands, after
1145
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
1146
+ */
1147
+ return function dispatch(actionOrActions, onErrors, onSuccess) {
1148
+ let answered = false;
1149
+ const reportErrors = onErrors && ((errors) => {
1150
+ answered = true;
1151
+ onErrors(errors);
1152
+ });
1153
+ const reportSuccess = onSuccess && ((result, outcome) => {
1154
+ answered = true;
1155
+ onSuccess(result, outcome);
1156
+ });
1157
+ dispatchActions(actionOrActions, getDocument(), reportErrors, reportSuccess).catch((error) => {
1158
+ logger.error("Failed to dispatch actions: @error", error);
1159
+ if (!answered) onErrors?.([error instanceof Error ? error : new Error(String(error))]);
1160
+ });
1161
+ };
1162
+ }
1163
+ /** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
1164
+ function useDispatch(document) {
1165
+ const latest = useRef(document);
1166
+ latest.current = document;
1167
+ const id = document?.header.id;
1168
+ return [document, useMemo(() => createDispatch(() => latest.current), [id])];
1169
+ }
1170
+ //#endregion
1171
+ export { DocumentModelNotFoundError as A, isDuplicateModuleError as C, queueActions as D, dispatchActions as E, NoSelectedDocumentError as M, OperationRejectedError as N, queueOperations as O, UnsupportedDocumentTypeError as P, isDuplicateManifestError as S, IDLE_REFETCH_STATE as T, isDocumentTypeCache as _, useDocument as a, DOCUMENT_CHANGE_TYPE as b, useDocuments as c, useGetDocuments as d, DocumentCache as f, addPromiseState as g, IDLE_OPERATIONS_ENTRY as h, setDocumentCache as i, DocumentTypeMismatchError as j, uploadOperations as k, useGetDocument as l, IDLE_DOCUMENTS_OF_TYPE_ENTRY as m, useDispatch as n, useDocumentCache as o, GET_MANY_CHUNK_SIZE as p, addDocumentCacheEventHandler as r, useDocumentSafe as s, createDispatch as t, useGetDocumentAsync as u, isOperationCache as v, DocumentRefetcher as w, JOB_NOT_FOUND_ERROR_NAME as x, readPromiseState as y };
1172
+
1173
+ //# sourceMappingURL=dispatch-Cylwl2Dk.js.map