@powerhousedao/reactor-browser 6.2.3-dev.6 → 6.2.3-dev.61

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 (88) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-DG6UkyMv.d.ts} +362 -65
  2. package/dist/attachment-service-DG6UkyMv.d.ts.map +1 -0
  3. package/dist/{client-BIHN_UyR.d.ts → client-BnGewICj.d.ts} +3 -3
  4. package/dist/client-BnGewICj.d.ts.map +1 -0
  5. package/dist/{client-D66jVnot.js → client-CXDpILj6.js} +232 -32
  6. package/dist/client-CXDpILj6.js.map +1 -0
  7. package/dist/{client-DjK30EQ-.js → client-Cq5avLW5.js} +35 -22
  8. package/dist/client-Cq5avLW5.js.map +1 -0
  9. package/dist/{document-by-id-B4FIzG1w.js → dispatch-C1VVTn5S.js} +393 -54
  10. package/dist/dispatch-C1VVTn5S.js.map +1 -0
  11. package/dist/document-by-id-BRDkvmpn.js +16 -0
  12. package/dist/document-by-id-BRDkvmpn.js.map +1 -0
  13. package/dist/{document-model-modules-bTP87nyr.js → document-model-modules-Gsh1Xr7j.js} +60 -68
  14. package/dist/document-model-modules-Gsh1Xr7j.js.map +1 -0
  15. package/dist/{document-operations-WeE6wIDt.js → document-operations-BSzcF0mu.js} +805 -167
  16. package/dist/document-operations-BSzcF0mu.js.map +1 -0
  17. package/dist/{global-OuINvEGT.d.ts → global-BuSwbbY0.d.ts} +59 -13
  18. package/dist/global-BuSwbbY0.d.ts.map +1 -0
  19. package/dist/{index-B33TKEqp.d.ts → index-ewIc3pEO.d.ts} +19 -98
  20. package/dist/index-ewIc3pEO.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 +395 -371
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +116 -47
  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-DBq3iWYn.js → make-ph-event-functions-CdsvEl5t.js} +4 -2
  30. package/dist/{make-ph-event-functions-DBq3iWYn.js.map → make-ph-event-functions-CdsvEl5t.js.map} +1 -1
  31. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  32. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  33. package/dist/{relational-D1RB45sA.js → relational-DxHuX41f.js} +66 -5
  34. package/dist/relational-DxHuX41f.js.map +1 -0
  35. package/dist/{renown-rqK8sokh.js → renown-CPAeJt5L.js} +7 -8
  36. package/dist/{renown-rqK8sokh.js.map → renown-CPAeJt5L.js.map} +1 -1
  37. package/dist/{renown-BHxwP7xU.js → renown-D05wkobG.js} +2 -2
  38. package/dist/{renown-BHxwP7xU.js.map → renown-D05wkobG.js.map} +1 -1
  39. package/dist/src/ai/index.d.ts +51 -62
  40. package/dist/src/ai/index.d.ts.map +1 -1
  41. package/dist/src/ai/index.js +5 -8
  42. package/dist/src/ai/index.js.map +1 -1
  43. package/dist/src/analytics/index.d.ts +36 -44
  44. package/dist/src/analytics/index.d.ts.map +1 -1
  45. package/dist/src/analytics/index.js +2 -2
  46. package/dist/src/analytics/index.js.map +1 -1
  47. package/dist/src/document-model.d.ts +3 -4
  48. package/dist/src/document-model.d.ts.map +1 -1
  49. package/dist/src/document-model.js.map +1 -1
  50. package/dist/src/graphql/client.d.ts +4 -3
  51. package/dist/src/graphql/client.js +1 -1
  52. package/dist/src/graphql-client/entry.d.ts +5 -4
  53. package/dist/src/graphql-client/entry.js +4 -4
  54. package/dist/src/relational/index.d.ts +15 -9
  55. package/dist/src/relational/index.d.ts.map +1 -1
  56. package/dist/src/relational/index.js +1 -1
  57. package/dist/src/renown/index.d.ts +3 -2
  58. package/dist/src/renown/index.js +2 -2
  59. package/dist/src/rpc/index.d.ts +176 -138
  60. package/dist/src/rpc/index.d.ts.map +1 -1
  61. package/dist/src/rpc/index.js +421 -618
  62. package/dist/src/rpc/index.js.map +1 -1
  63. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  64. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  65. package/dist/{switchboard-CaXQ4-5Q.js → switchboard-3vHbIV5W.js} +58 -6
  66. package/dist/switchboard-3vHbIV5W.js.map +1 -0
  67. package/dist/{types-Dcv1ZLoW.d.ts → types-0Fh1tNjy.d.ts} +242 -17
  68. package/dist/types-0Fh1tNjy.d.ts.map +1 -0
  69. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  70. package/dist/types-520nWrB3.d.ts.map +1 -0
  71. package/package.json +19 -20
  72. package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
  73. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  74. package/dist/client-D66jVnot.js.map +0 -1
  75. package/dist/client-DjK30EQ-.js.map +0 -1
  76. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  77. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  78. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  79. package/dist/global-OuINvEGT.d.ts.map +0 -1
  80. package/dist/index-B33TKEqp.d.ts.map +0 -1
  81. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  82. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  83. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  84. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  85. package/dist/relational-D1RB45sA.js.map +0 -1
  86. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  87. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  88. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -1,6 +1,5 @@
1
- import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
1
+ import { t as makePHEventFunctions } from "./make-ph-event-functions-CdsvEl5t.js";
2
2
  import { logger } from "document-model";
3
- import { buildSignedAction } from "@powerhousedao/shared/document-model";
4
3
  import { use, useCallback, useEffect, useReducer, useSyncExternalStore } from "react";
5
4
  //#region src/actions/queue.ts
6
5
  async function queueActions(document, actionOrActions) {
@@ -49,16 +48,6 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
49
48
  }
50
49
  //#endregion
51
50
  //#region src/actions/sign.ts
52
- async function signAction(action, document) {
53
- const renown = window.ph?.renown;
54
- if (!renown?.user) return action;
55
- if (!action.context?.signer) return action;
56
- const reactorClient = window.ph?.reactorClientModule?.client;
57
- if (!reactorClient) return action;
58
- const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
59
- const actionSigner = action.context.signer;
60
- return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
61
- }
62
51
  function addActionContext(action) {
63
52
  const renown = window.ph?.renown;
64
53
  if (!renown?.user) return action;
@@ -78,7 +67,7 @@ function addActionContext(action) {
78
67
  ...action
79
68
  };
80
69
  }
81
- async function makeSignedActionWithContext(action, document) {
70
+ function makeSignedActionWithContext(action, document) {
82
71
  if (!action) {
83
72
  logger.error("No action found");
84
73
  return;
@@ -87,15 +76,14 @@ async function makeSignedActionWithContext(action, document) {
87
76
  logger.error("No document found");
88
77
  return;
89
78
  }
90
- return addActionContext(await signAction(action, document));
79
+ return addActionContext(action);
91
80
  }
92
- async function makeSignedActionsWithContext(actionOrActions, document) {
81
+ function makeSignedActionsWithContext(actionOrActions, document) {
93
82
  if (!actionOrActions) {
94
83
  logger.error("No actions found");
95
84
  return;
96
85
  }
97
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
98
- return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
86
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
99
87
  }
100
88
  //#endregion
101
89
  //#region src/actions/dispatch.ts
@@ -119,12 +107,16 @@ function getActionErrors(result, actions) {
119
107
  async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
120
108
  const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
121
109
  if (!document) {
122
- logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
110
+ const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;
111
+ logger.error(message);
112
+ onErrors?.([new Error(message)]);
123
113
  return;
124
114
  }
125
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
115
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
126
116
  if (!signedActionsWithContext) {
127
- logger.error("No signed actions with context found");
117
+ const message = "No signed actions with context found";
118
+ logger.error(message);
119
+ onErrors?.([/* @__PURE__ */ new Error(message)]);
128
120
  return;
129
121
  }
130
122
  const result = await queueActions(document, signedActionsWithContext);
@@ -135,6 +127,123 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
135
127
  if (onSuccess && result) onSuccess(result);
136
128
  return result;
137
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
+ };
138
247
  /**
139
248
  * The reactor's `DocumentChangeType` members, typed as the enum so they can be
140
249
  * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
@@ -195,16 +304,55 @@ function fulfilledOnly(promises) {
195
304
  return documents;
196
305
  });
197
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
+ }
198
335
  /**
199
336
  * Document cache implementation that uses the new ReactorClient API.
200
337
  *
201
338
  * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
202
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.
203
342
  */
204
343
  var DocumentCache = class {
344
+ client;
205
345
  documents = /* @__PURE__ */ new Map();
206
346
  batchPromises = /* @__PURE__ */ new Map();
207
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
+ });
208
356
  /**
209
357
  * Cache keys that fetched a document under a name other than its id --
210
358
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -213,6 +361,11 @@ var DocumentCache = class {
213
361
  * the same document is cached under.
214
362
  */
215
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();
216
369
  unsubscribe = null;
217
370
  constructor(client) {
218
371
  this.client = client;
@@ -223,13 +376,22 @@ var DocumentCache = class {
223
376
  handleDocumentChange(event) {
224
377
  if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
225
378
  const documentId = event.context?.childId;
226
- if (documentId) this.handleDocumentDeleted(documentId);
227
- } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) this.handleDocumentUpdated(doc.header.id).catch(console.warn);
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
+ }
228
389
  }
229
390
  handleDocumentDeleted(documentId) {
230
391
  for (const key of this.cacheKeysFor(documentId)) {
231
392
  const listeners = this.listeners.get(key);
232
393
  this.documents.delete(key);
394
+ this.refetcher.forget(key);
233
395
  this.invalidateBatchesContaining(key);
234
396
  if (listeners) listeners.forEach((listener) => listener());
235
397
  this.listeners.delete(key);
@@ -237,12 +399,11 @@ var DocumentCache = class {
237
399
  this.aliasKeys.delete(documentId);
238
400
  }
239
401
  async handleDocumentUpdated(documentId) {
240
- for (const key of this.cacheKeysFor(documentId)) {
241
- if (!this.documents.has(key)) continue;
242
- await this.get(key, true);
243
- const listeners = this.listeners.get(key);
244
- if (listeners) listeners.forEach((listener) => listener());
245
- }
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();
246
407
  }
247
408
  /** The id an event dispatches by, plus every alias the document is cached under. */
248
409
  cacheKeysFor(documentId) {
@@ -259,10 +420,9 @@ var DocumentCache = class {
259
420
  }
260
421
  get(id, refetch) {
261
422
  const currentData = this.documents.get(id);
262
- if (currentData) {
263
- if (currentData.status === "pending") return currentData;
264
- if (!refetch) return currentData;
265
- }
423
+ if (currentData && !refetch) return currentData;
424
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
425
+ this.refetcher.forget(id);
266
426
  const documentPromise = this.client.get(id);
267
427
  documentPromise.then((doc) => {
268
428
  if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
@@ -270,6 +430,9 @@ var DocumentCache = class {
270
430
  this.documents.set(id, addPromiseState(documentPromise));
271
431
  return documentPromise;
272
432
  }
433
+ getRefetchState(id) {
434
+ return this.refetcher.getState(id);
435
+ }
273
436
  getBatch(ids) {
274
437
  const key = ids.join(",");
275
438
  const cached = this.batchPromises.get(key);
@@ -319,6 +482,161 @@ var DocumentCache = class {
319
482
  }
320
483
  };
321
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
+ }
322
640
  /**
323
641
  * Disposes of the cache and unsubscribes from document change events.
324
642
  */
@@ -327,6 +645,11 @@ var DocumentCache = class {
327
645
  this.unsubscribe();
328
646
  this.unsubscribe = null;
329
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();
330
653
  }
331
654
  };
332
655
  //#endregion
@@ -393,10 +716,14 @@ function useDocument(id) {
393
716
  * - isPending: Whether the document is currently loading
394
717
  * - error: Any error that occurred during loading (e.g., document not found)
395
718
  * - reload: Function to force a refetch, or undefined when no id is supplied
719
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
720
+ * - refetchError: The last refetch failure that kept the loaded document
396
721
  */
397
722
  function useDocumentSafe(id) {
398
723
  const documentCache = useDocumentCache();
399
- const promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
724
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
725
+ const promise = useSyncExternalStore(subscribe, () => id ? documentCache?.get(id) : void 0);
726
+ const refetch = useSyncExternalStore(subscribe, () => readRefetchState(documentCache, id));
400
727
  const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
401
728
  const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
402
729
  useEffect(() => {
@@ -415,13 +742,20 @@ function useDocumentSafe(id) {
415
742
  isPending: false,
416
743
  error: void 0,
417
744
  data: void 0,
418
- reload: void 0
745
+ reload: void 0,
746
+ isRefetching: false,
747
+ refetchError: void 0
419
748
  };
420
749
  return {
421
750
  ...getDocumentQueryState(promise),
422
- reload: () => documentCache.get(id, true)
751
+ reload: () => documentCache.get(id, true),
752
+ isRefetching: refetch.isRefetching,
753
+ refetchError: refetch.error
423
754
  };
424
755
  }
756
+ function readRefetchState(documentCache, id) {
757
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
758
+ }
425
759
  /**
426
760
  * Retrieves multiple documents from the reactor using React Suspense.
427
761
  * This hook will suspend rendering while any of the documents are loading.
@@ -471,6 +805,8 @@ function useGetDocuments() {
471
805
  * - isPending: Boolean indicating if the document is currently loading
472
806
  * - error: Any error that occurred during loading
473
807
  * - reload: Function to force reload the document from cache
808
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
809
+ * - refetchError: The last refetch failure that kept the loaded document
474
810
  */
475
811
  function useGetDocumentAsync(id) {
476
812
  const documentCache = useDocumentCache();
@@ -479,11 +815,17 @@ function useGetDocumentAsync(id) {
479
815
  data: void 0,
480
816
  isPending: false,
481
817
  error: void 0,
482
- reload: void 0
818
+ reload: void 0,
819
+ isRefetching: false,
820
+ refetchError: void 0
483
821
  };
822
+ const state = getDocumentQueryState(documentCache.get(id));
823
+ const refetch = readRefetchState(documentCache, id);
484
824
  return {
485
- ...getDocumentQueryState(documentCache.get(id)),
486
- reload: () => documentCache.get(id, true)
825
+ ...state,
826
+ reload: () => documentCache.get(id, true),
827
+ isRefetching: refetch.isRefetching,
828
+ refetchError: refetch.error
487
829
  };
488
830
  }
489
831
  //#endregion
@@ -492,28 +834,25 @@ function useDispatch(document) {
492
834
  /**
493
835
  * Dispatches actions to the document.
494
836
  * @param actionOrActions - The action or actions to dispatch.
495
- * @param onErrors - Callback invoked with any errors that occurred during action execution.
837
+ * @param onErrors - Callback invoked with any errors that occurred during action execution,
838
+ * or with the failure when the dispatch itself did not complete.
496
839
  */
497
840
  function dispatch(actionOrActions, onErrors, onSuccess) {
498
- dispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {
841
+ let answered = false;
842
+ dispatchActions(actionOrActions, document, onErrors && ((errors) => {
843
+ answered = true;
844
+ onErrors(errors);
845
+ }), onSuccess && ((result) => {
846
+ answered = true;
847
+ onSuccess(result);
848
+ })).catch((error) => {
499
849
  logger.error("Failed to dispatch actions: @error", error);
850
+ if (!answered) onErrors?.([error instanceof Error ? error : new Error(String(error))]);
500
851
  });
501
852
  }
502
853
  return [document, dispatch];
503
854
  }
504
855
  //#endregion
505
- //#region src/hooks/document-by-id.ts
506
- /** Returns a document by id. */
507
- function useDocumentById(id) {
508
- const document = useDocument(id);
509
- const [, dispatch] = useDispatch(document);
510
- return [document, dispatch];
511
- }
512
- /** Returns documents by ids. */
513
- function useDocumentsByIds(ids) {
514
- return useDocuments(ids);
515
- }
516
- //#endregion
517
- export { uploadOperations as S, isDuplicateManifestError as _, setDocumentCache as a, queueActions as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, DOCUMENT_CHANGE_TYPE as g, readPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, addPromiseState as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, isDuplicateModuleError as v, queueOperations as x, dispatchActions as y };
856
+ export { queueOperations as C, queueActions as S, isDuplicateManifestError as _, useDocumentCache as a, IDLE_REFETCH_STATE as b, useGetDocument as c, DocumentCache as d, IDLE_OPERATIONS_ENTRY as f, DOCUMENT_CHANGE_TYPE as g, readPromiseState as h, useDocument as i, useGetDocumentAsync as l, isOperationCache as m, addDocumentCacheEventHandler as n, useDocumentSafe as o, addPromiseState as p, setDocumentCache as r, useDocuments as s, useDispatch as t, useGetDocuments as u, isDuplicateModuleError as v, uploadOperations as w, dispatchActions as x, DocumentRefetcher as y };
518
857
 
519
- //# sourceMappingURL=document-by-id-B4FIzG1w.js.map
858
+ //# sourceMappingURL=dispatch-C1VVTn5S.js.map