@bgub/fig 1.0.0 → 2.1.0

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 (39) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/README.md +21 -22
  3. package/dist/{element-9MtOc5qb.d.ts → element-DT9ziqWN.d.ts} +49 -17
  4. package/dist/{element-CssKOG37.js → element-DpXdLgOZ.js} +11 -69
  5. package/dist/element-DpXdLgOZ.js.map +1 -0
  6. package/dist/{hooks-Blgy3bby.d.ts → hooks-GeZ4mX7W.d.ts} +15 -19
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +4 -4
  9. package/dist/internal.d.ts +7 -9
  10. package/dist/internal.js +8 -4
  11. package/dist/internal.js.map +1 -1
  12. package/dist/jsx-runtime.d.ts +1 -1
  13. package/dist/jsx-runtime.js +1 -1
  14. package/dist/payload-format-B9UbNtxo.js.map +1 -1
  15. package/dist/payload.d.ts +1 -1
  16. package/dist/payload.js +2 -2
  17. package/{dist-development/resource-Bt8LOhv4.js → dist/resource-DEDmLSNk.js} +20 -27
  18. package/dist/resource-DEDmLSNk.js.map +1 -0
  19. package/dist/{transition-B7vpLnb1.js → transition-BFLGYE4q.js} +433 -134
  20. package/dist/transition-BFLGYE4q.js.map +1 -0
  21. package/dist-development/{element-CKdh2VTU.js → element-DbzJUf5a.js} +11 -69
  22. package/dist-development/element-DbzJUf5a.js.map +1 -0
  23. package/dist-development/index.js +4 -4
  24. package/dist-development/internal.js +8 -4
  25. package/dist-development/internal.js.map +1 -1
  26. package/dist-development/jsx-runtime.js +1 -1
  27. package/dist-development/payload-format-B9UbNtxo.js.map +1 -1
  28. package/dist-development/payload.js +2 -2
  29. package/{dist/resource-BlZob4k1.js → dist-development/resource-BZOBllE_.js} +20 -27
  30. package/dist-development/resource-BZOBllE_.js.map +1 -0
  31. package/dist-development/{transition-DEVMhyYg.js → transition-CWjp9qRO.js} +430 -133
  32. package/dist-development/transition-CWjp9qRO.js.map +1 -0
  33. package/package.json +1 -1
  34. package/dist/element-CssKOG37.js.map +0 -1
  35. package/dist/resource-BlZob4k1.js.map +0 -1
  36. package/dist/transition-B7vpLnb1.js.map +0 -1
  37. package/dist-development/element-CKdh2VTU.js.map +0 -1
  38. package/dist-development/resource-Bt8LOhv4.js.map +0 -1
  39. package/dist-development/transition-DEVMhyYg.js.map +0 -1
@@ -1,5 +1,4 @@
1
- import { $ as getCurrentDataStore, Q as defineLoadContextCapabilities, Z as dataResourceKeysForError, et as isAttributableError, it as setCurrentDataStore, nt as markDataResourceError, rt as resolveCurrentDataStore } from "./element-CKdh2VTU.js";
2
- import { y as isThenable$1 } from "./resource-Bt8LOhv4.js";
1
+ import { y as isThenable$1 } from "./resource-BZOBllE_.js";
3
2
  //#region src/context.ts
4
3
  /** The Fig context symbol. */
5
4
  const FigContextSymbol = Symbol.for("fig.context");
@@ -15,6 +14,61 @@ function isContext(value) {
15
14
  return typeof value === "function" && "$$typeof" in value && value.$$typeof === FigContextSymbol;
16
15
  }
17
16
  //#endregion
17
+ //#region src/data.ts
18
+ const LoadContextCapabilitiesSymbol = Symbol.for("fig.data-load-context");
19
+ /** Define load context capabilities. */
20
+ function defineLoadContextCapabilities(context, capabilities) {
21
+ Object.defineProperty(context, LoadContextCapabilitiesSymbol, {
22
+ configurable: true,
23
+ enumerable: false,
24
+ value: capabilities
25
+ });
26
+ }
27
+ /** Load context capabilities. */
28
+ function loadContextCapabilities(context) {
29
+ return context[LoadContextCapabilitiesSymbol];
30
+ }
31
+ const objectDataErrors = /* @__PURE__ */ new WeakMap();
32
+ let currentDataStore$1 = null;
33
+ /** Captures an optional data store for synchronous scope re-entry. */
34
+ function getCurrentDataStore() {
35
+ return currentDataStore$1;
36
+ }
37
+ /** Resolves current data store. */
38
+ function resolveCurrentDataStore(message = "Data resource APIs require a Fig data store.") {
39
+ if (currentDataStore$1 === null) throw new Error(message);
40
+ return currentDataStore$1;
41
+ }
42
+ /** Sets current data store. */
43
+ function setCurrentDataStore(store) {
44
+ const previousStore = currentDataStore$1;
45
+ currentDataStore$1 = store;
46
+ return previousStore;
47
+ }
48
+ /** Marks data resource error. */
49
+ function markDataResourceError(error, key) {
50
+ if (!isAttributableError(error)) return;
51
+ let keys = objectDataErrors.get(error);
52
+ if (keys === void 0) {
53
+ keys = [];
54
+ objectDataErrors.set(error, keys);
55
+ }
56
+ if (keys.some((existing) => sameDataResourceKey(existing, key))) return;
57
+ keys.push(key);
58
+ }
59
+ /** Data resource keys for error. */
60
+ function dataResourceKeysForError(error) {
61
+ if (!isAttributableError(error)) return void 0;
62
+ const keys = objectDataErrors.get(error);
63
+ return keys === void 0 || keys.length === 0 ? void 0 : [...keys];
64
+ }
65
+ function sameDataResourceKey(a, b) {
66
+ return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
67
+ }
68
+ function isAttributableError(value) {
69
+ return (typeof value === "object" || typeof value === "function") && value !== null;
70
+ }
71
+ //#endregion
18
72
  //#region src/data-store.ts
19
73
  const DataResourceSymbol = Symbol.for("fig.data-resource");
20
74
  const DataStoreFactorySymbol = Symbol.for("fig.data-store-factory");
@@ -28,34 +82,13 @@ function dataResource(options) {
28
82
  $$typeof: DataResourceSymbol,
29
83
  [DataStoreFactorySymbol]: dataStoreFactory,
30
84
  debugArgs: options.debugArgs,
85
+ equals: options.equals,
86
+ inactiveRetentionMs: options.inactiveRetentionMs,
31
87
  key: options.key,
32
- load: options.load
88
+ load: options.load,
89
+ watch: options.watch
33
90
  };
34
91
  }
35
- /** Ensures data. */
36
- function ensureData(resource, ...args) {
37
- return resolveDataMutationStore("ensureData").ensureData(resource, ...args);
38
- }
39
- /** Invalidates data. */
40
- function invalidateData(resource, ...args) {
41
- resolveDataMutationStore("invalidateData").invalidateData(resource, ...args);
42
- }
43
- /** Invalidates data error. */
44
- function invalidateDataError(error) {
45
- return resolveDataMutationStore("invalidateDataError").invalidateDataError(error);
46
- }
47
- /** Invalidates data key. */
48
- function invalidateDataKey(key) {
49
- resolveDataMutationStore("invalidateDataKey").invalidateDataKey(key);
50
- }
51
- /** Invalidates data prefix. */
52
- function invalidateDataPrefix(prefix) {
53
- resolveDataMutationStore("invalidateDataPrefix").invalidateDataPrefix(prefix);
54
- }
55
- /** Refreshes data. */
56
- function refreshData(resource, ...args) {
57
- return resolveDataMutationStore("refreshData").refreshData(resource, ...args);
58
- }
59
92
  /** Reads data store. */
60
93
  function readDataStore() {
61
94
  return resolveCurrentDataStore("readDataStore() must be called synchronously while Fig is executing — during render, an event handler, an action, or an effect. Capture the handle there and use it after awaits.");
@@ -65,8 +98,10 @@ function createDataStore(options = {}) {
65
98
  const state = { host: null };
66
99
  const store = createRendererDataStore({
67
100
  getLane: () => state.host === null ? null : state.host.getLane(),
68
- partition: options.partition,
69
- schedule: (owner, lane) => state.host?.schedule(owner, lane)
101
+ schedule: (owner, lane) => state.host?.schedule(owner, lane),
102
+ get watchSources() {
103
+ return state.host?.watchSources === true;
104
+ }
70
105
  });
71
106
  Object.defineProperty(store, DataStoreControllerSymbol, { value: state });
72
107
  if (options.initialData !== void 0) store.hydrate(options.initialData);
@@ -78,16 +113,13 @@ function isDataStoreController(value) {
78
113
  }
79
114
  /** Attach data store. */
80
115
  function attachDataStore(controller, host, initialData) {
81
- if (host.partition !== void 0 || initialData !== void 0) throw new Error("Pass partition and initialData to createDataStore(), not the renderer, when adopting a data store.");
116
+ if (initialData !== void 0) throw new Error("Pass initialData to createDataStore(), not the renderer, when adopting a data store.");
82
117
  const state = controller[DataStoreControllerSymbol];
83
118
  if (state === void 0) throw new Error("dataStore must be created with createDataStore().");
84
119
  if (state.host !== null) throw new Error("A data store can only be adopted by one Fig renderer.");
85
120
  state.host = host;
86
121
  return controller;
87
122
  }
88
- function resolveDataMutationStore(name) {
89
- return resolveCurrentDataStore(`${name}() must be called synchronously while Fig is executing — during render, an event handler, an action, or an effect. Capture readDataStore() (or root.data) synchronously and call the handle instead.`);
90
- }
91
123
  /** Creates renderer data store. */
92
124
  function createRendererDataStore(host) {
93
125
  return new DefaultDataStore(host);
@@ -101,22 +133,27 @@ var DefaultDataStore = class {
101
133
  entries = /* @__PURE__ */ new Map();
102
134
  inactiveRetentionMs;
103
135
  ownerKeys = /* @__PURE__ */ new WeakMap();
104
- pendingOwnerKeys = /* @__PURE__ */ new WeakMap();
105
- partitionKey;
106
136
  preloadRetentionMs;
107
137
  disposed = false;
138
+ pendingWatchReconciles = null;
108
139
  constructor(host) {
109
140
  this.host = host;
110
141
  this.inactiveRetentionMs = host.inactiveRetentionMs ?? DEFAULT_INACTIVE_RETENTION_MS;
111
- this.partitionKey = host.partition === void 0 ? "" : encodeValue(host.partition, createEncodePath("partition"));
112
142
  this.preloadRetentionMs = host.preloadRetentionMs ?? DEFAULT_PRELOAD_RETENTION_MS;
113
143
  }
114
- commitDataDependencies(owner, previousOwner) {
115
- const nextKeys = this.pendingOwnerKeys.get(owner) ?? null;
144
+ areDataDependenciesConsistent(reads) {
145
+ for (const [key, snapshot] of reads) {
146
+ if (snapshot === void 0) continue;
147
+ const entry = this.entries.get(key);
148
+ if (entry === void 0 || !entryHasValue(entry) || !Object.is(snapshot.value, entry.value)) return false;
149
+ }
150
+ return true;
151
+ }
152
+ commitDataDependencies(owner, previousOwner, reads) {
153
+ const nextKeys = reads === void 0 ? null : new Set(reads.keys());
116
154
  const ownerKeys = this.ownerKeys.get(owner) ?? null;
117
155
  const previousOwnerKeys = previousOwner === null ? null : this.ownerKeys.get(previousOwner) ?? null;
118
- this.pendingOwnerKeys.delete(owner);
119
- if ((nextKeys === null || nextKeys.size === 0) && ownerKeys === null && previousOwnerKeys === null) return;
156
+ if ((nextKeys === null || nextKeys.size === 0) && ownerKeys === null && previousOwnerKeys === null) return true;
120
157
  let orphanCandidates = null;
121
158
  orphanCandidates = this.collectSubscribedEntries(ownerKeys, orphanCandidates);
122
159
  orphanCandidates = this.collectSubscribedEntries(previousOwnerKeys, orphanCandidates);
@@ -129,22 +166,26 @@ var DefaultDataStore = class {
129
166
  if (entry !== void 0) {
130
167
  this.clearInactiveTimer(entry);
131
168
  entry.subscribers.add(owner);
169
+ if (reads !== void 0) entry.retainers?.delete(reads);
132
170
  this.notifyEntryChange(entry);
133
171
  }
134
172
  }
135
173
  }
136
174
  if (orphanCandidates !== null) for (const entry of orphanCandidates) this.abortOrphanedLoad(entry);
175
+ if (nextKeys !== null) for (const key of nextKeys) {
176
+ const entry = this.entries.get(key);
177
+ if (entry !== void 0) this.scheduleWatchReconcile(entry);
178
+ }
179
+ const consistent = reads === void 0 || this.areDataDependenciesConsistent(reads);
180
+ reads?.clear();
181
+ return consistent;
137
182
  }
138
183
  releaseDataOwner(owner) {
139
184
  const orphanCandidates = this.collectSubscribedEntries(this.ownerKeys.get(owner) ?? null, null);
140
185
  this.deleteDataOwner(owner);
141
186
  if (orphanCandidates !== null) for (const entry of orphanCandidates) this.abortOrphanedLoad(entry);
142
187
  }
143
- resetDataDependencies(owner) {
144
- this.pendingOwnerKeys.delete(owner);
145
- }
146
188
  deleteDataOwner(owner, retainedKeys = null) {
147
- this.pendingOwnerKeys.delete(owner);
148
189
  const keys = this.ownerKeys.get(owner);
149
190
  if (keys === void 0) return;
150
191
  this.ownerKeys.delete(owner);
@@ -153,7 +194,10 @@ var DefaultDataStore = class {
153
194
  if (entry === void 0) continue;
154
195
  entry.subscribers.delete(owner);
155
196
  this.notifyEntryChange(entry);
156
- if (retainedKeys?.has(key) !== true) this.scheduleInactiveCleanup(entry);
197
+ if (retainedKeys?.has(key) !== true) {
198
+ this.scheduleInactiveCleanup(entry);
199
+ this.scheduleWatchReconcile(entry);
200
+ }
157
201
  }
158
202
  }
159
203
  collectSubscribedEntries(keys, into) {
@@ -168,8 +212,8 @@ var DefaultDataStore = class {
168
212
  return into;
169
213
  }
170
214
  abortOrphanedLoad(entry) {
171
- if (this.entries.get(entry.storeKey) !== entry) return;
172
- if (entry.subscribers.size > 0 || entry.preloadTimer !== null || entry.ensureRetainers > 0 || entry.pending === null || entryHasValue(entry)) return;
215
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
216
+ if (isHeld(entry) || entry.preloadTimer !== null || entry.pending === null || entryHasValue(entry)) return;
173
217
  this.evictEntry(entry, "evicted");
174
218
  }
175
219
  dispose() {
@@ -182,27 +226,39 @@ var DefaultDataStore = class {
182
226
  }
183
227
  }
184
228
  hydrate(entries) {
229
+ this.hydrateEntries(entries, true);
230
+ }
231
+ hydrateMissing(entries) {
232
+ this.hydrateEntries(entries, false);
233
+ }
234
+ hydrateEntries(entries, replaceValues) {
185
235
  if (this.disposed) return;
186
236
  for (const hydrated of entries) {
237
+ if (this.disposed) return;
187
238
  const normalized = normalizeKey(hydrated.key);
188
- const storeKey = this.storeKey(normalized.canonical);
239
+ const storeKey = normalized.canonical;
189
240
  const current = this.entries.get(storeKey);
190
241
  if (current !== void 0) {
191
- this.hydrateEntry(current, normalized.key, hydrated.value);
192
- this.publish(current);
242
+ if (replaceValues || !entryHasValue(current)) this.hydrateEntry(current, normalized.key, hydrated.value);
193
243
  continue;
194
244
  }
195
- const entry = this.createEntry(normalized, storeKey, null, null, "fulfilled", hydrated.value);
245
+ const entry = this.createEntry(normalized, null, null, "fulfilled", hydrated.value);
196
246
  this.entries.set(storeKey, entry);
197
247
  this.notifyEntryChange(entry);
198
248
  }
199
249
  }
200
250
  snapshot() {
251
+ return this.snapshotKeys(this.entries.keys());
252
+ }
253
+ snapshotKeys(canonicalKeys) {
201
254
  const entries = [];
202
- for (const entry of this.entries.values()) if (entryHasValue(entry)) entries.push({
203
- key: entry.key,
204
- value: entry.value
205
- });
255
+ for (const key of canonicalKeys) {
256
+ const entry = this.entries.get(key);
257
+ if (entry !== void 0 && entryHasValue(entry)) entries.push({
258
+ key: entry.key,
259
+ value: entry.value
260
+ });
261
+ }
206
262
  return entries;
207
263
  }
208
264
  inspectDataEntries() {
@@ -249,8 +305,12 @@ var DefaultDataStore = class {
249
305
  for (const entry of this.entries.values()) if (canonicalKeyStartsWith(entry.canonicalKey, prefixCanonical)) entries.push(entry);
250
306
  this.invalidateEntries(entries);
251
307
  }
252
- async ensureData(resource, ...args) {
308
+ ensureData(resource, ...args) {
309
+ return this.ensureDataUntil(resource, args, void 0);
310
+ }
311
+ async ensureDataUntil(resource, args, until) {
253
312
  for (;;) {
313
+ if (until?.aborted === true) throw until.reason;
254
314
  if (this.disposed) throw new Error("ensureData() requires a live data store; this store was disposed.");
255
315
  const entry = this.entryFor(resource, args, true);
256
316
  this.clearInactiveTimer(entry);
@@ -260,16 +320,24 @@ var DefaultDataStore = class {
260
320
  return entry.value;
261
321
  }
262
322
  if (entry.status === "rejected") throwDataResourceError(entry);
263
- entry.ensureRetainers += 1;
323
+ const retainer = {};
324
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(retainer);
264
325
  try {
265
- if (entry.pending !== null) await entry.pending.promise;
266
- else await this.startLoad(entry, resource, args, {
326
+ this.recordWatchSource(entry, resource, args);
327
+ let settled;
328
+ if (entry.pending !== null) settled = entry.pending.promise;
329
+ else if (this.waitsOnWatch(resource)) settled = this.beginWatchPending(entry).promise;
330
+ else settled = this.startLoad(entry, resource, args, {
267
331
  lane: this.host.getLane(),
268
332
  refresh: false
269
333
  });
334
+ await (until === void 0 ? settled : untilAborted(settled, until));
270
335
  } finally {
271
- entry.ensureRetainers -= 1;
272
- if (this.entries.get(entry.storeKey) === entry) this.retainPreload(entry);
336
+ entry.retainers?.delete(retainer);
337
+ if (this.entries.get(entry.canonicalKey) === entry) {
338
+ this.retainPreload(entry);
339
+ this.scheduleWatchReconcile(entry);
340
+ }
273
341
  }
274
342
  }
275
343
  }
@@ -285,17 +353,24 @@ var DefaultDataStore = class {
285
353
  refresh: entry.status === "fulfilled"
286
354
  });
287
355
  }
288
- readData(resource, args, owner) {
356
+ readData(resource, args, reads) {
289
357
  const entry = this.entryFor(resource, args, true);
290
358
  this.clearInactiveTimer(entry);
291
359
  this.clearPreloadTimer(entry);
292
- this.addOwnerKey(owner, entry.storeKey);
360
+ if (reads !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
361
+ if (reads !== void 0 && !reads.has(entry.canonicalKey)) reads.set(entry.canonicalKey, void 0);
362
+ this.recordWatchSource(entry, resource, args);
293
363
  this.revalidateIfStale(entry, resource, args);
294
- if (entry.status === "pending" && entry.pending === null) this.startLoad(entry, resource, args, {
295
- lane: this.host.getLane(),
296
- refresh: false
297
- });
298
- return this.readCurrentValue(entry);
364
+ if (entry.status === "pending" && entry.pending === null) {
365
+ if (this.waitsOnWatch(resource)) this.beginWatchPending(entry);
366
+ else this.startLoad(entry, resource, args, {
367
+ lane: this.host.getLane(),
368
+ refresh: false
369
+ });
370
+ }
371
+ const value = this.readCurrentValue(entry);
372
+ if (reads !== void 0 && reads.get(entry.canonicalKey) === void 0) reads.set(entry.canonicalKey, { value });
373
+ return value;
299
374
  }
300
375
  refreshData(resource, ...args) {
301
376
  if (this.disposed) return Promise.resolve({
@@ -325,32 +400,26 @@ var DefaultDataStore = class {
325
400
  setCurrentDataStore(previousStore);
326
401
  }
327
402
  }
328
- addOwnerKey(owner, key) {
329
- let keys = this.pendingOwnerKeys.get(owner);
330
- if (keys === void 0) {
331
- keys = /* @__PURE__ */ new Set();
332
- this.pendingOwnerKeys.set(owner, keys);
333
- }
334
- keys.add(key);
335
- }
336
403
  entryFor(resource, args, create) {
337
404
  const normalized = normalizeKey(resource.key(...args));
338
405
  const fingerprint = fingerprintFor(resource, args);
339
- const key = this.storeKey(normalized.canonical);
406
+ const key = normalized.canonical;
340
407
  const current = this.entries.get(key);
341
408
  if (current !== void 0) {
409
+ if (resource.inactiveRetentionMs !== void 0) current.inactiveRetentionMs = resource.inactiveRetentionMs;
342
410
  diagnoseEntryDrift(current, resource, normalized.canonical, fingerprint);
343
411
  return current;
344
412
  }
345
413
  if (!create) return null;
346
- const entry = this.createEntry(normalized, key, resource, fingerprint, "pending", void 0);
414
+ const entry = this.createEntry(normalized, resource, fingerprint, "pending", void 0);
415
+ entry.inactiveRetentionMs = resource.inactiveRetentionMs;
347
416
  if (this.disposed) return entry;
348
417
  this.entries.set(key, entry);
349
418
  this.notifyEntryChange(entry);
350
419
  return entry;
351
420
  }
352
421
  revalidateIfStale(entry, resource, args) {
353
- if (entry.status !== "fulfilled" || !entry.stale || entry.pending !== null || entry.refreshError !== void 0 || resource.load === void 0) return;
422
+ if (entry.status !== "fulfilled" || !entry.stale || entry.pending !== null || entry.refreshFailed || resource.load === void 0) return;
354
423
  this.startLoad(entry, resource, args, {
355
424
  lane: this.host.getLane(),
356
425
  refresh: true
@@ -358,49 +427,230 @@ var DefaultDataStore = class {
358
427
  }
359
428
  entryForKey(key) {
360
429
  const normalized = normalizeKey(key);
361
- return this.entries.get(this.storeKey(normalized.canonical)) ?? null;
430
+ return this.entries.get(normalized.canonical) ?? null;
362
431
  }
363
- createEntry(normalized, storeKey, resource, fingerprint, status, value) {
432
+ createEntry(normalized, resource, fingerprint, status, value) {
364
433
  return {
365
434
  canonicalKey: normalized.canonical,
366
- controller: null,
367
- ensureRetainers: 0,
435
+ retainers: null,
368
436
  error: void 0,
369
437
  fingerprint,
370
- generation: 0,
371
438
  invalidationVersion: 0,
439
+ inactiveRetentionMs: void 0,
372
440
  inactiveTimer: null,
373
441
  key: normalized.key,
374
442
  lane: null,
375
443
  pending: null,
376
444
  preloadTimer: null,
377
445
  refreshError: void 0,
446
+ refreshFailed: false,
378
447
  resource,
379
448
  stale: false,
380
449
  status,
381
- storeKey,
382
450
  subscribers: /* @__PURE__ */ new Set(),
383
451
  value,
384
452
  valueController: null,
385
- valueErrors: /* @__PURE__ */ new WeakSet()
453
+ valueErrors: /* @__PURE__ */ new WeakSet(),
454
+ watchController: null,
455
+ watchSource: null
456
+ };
457
+ }
458
+ recordWatchSource(entry, resource, args) {
459
+ if (resource.watch === void 0 || entry.watchSource !== null) return;
460
+ entry.watchSource = {
461
+ args,
462
+ resource
463
+ };
464
+ }
465
+ waitsOnWatch(resource) {
466
+ return resource.load === void 0 && resource.watch !== void 0 && this.host.watchSources === true;
467
+ }
468
+ beginWatchPending(entry) {
469
+ if (entry.pending !== null) return entry.pending;
470
+ const pending = createPendingLoad(new AbortController());
471
+ pending.watch = true;
472
+ entry.pending = pending;
473
+ entry.status = "pending";
474
+ this.notifyEntryChange(entry);
475
+ this.scheduleWatchReconcile(entry);
476
+ return pending;
477
+ }
478
+ dependentHandle(signal) {
479
+ const retain = (entry) => {
480
+ if (signal.aborted || entry.retainers?.has(signal)) return;
481
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(signal);
482
+ this.clearInactiveTimer(entry);
483
+ signal.addEventListener("abort", () => this.releaseRetainer(entry, signal), { once: true });
484
+ };
485
+ return {
486
+ ensureData: (resource, ...args) => {
487
+ if (signal.aborted) return Promise.reject(signal.reason);
488
+ if (!this.disposed) {
489
+ const entry = this.entryFor(resource, args, true);
490
+ this.recordWatchSource(entry, resource, args);
491
+ retain(entry);
492
+ this.scheduleWatchReconcile(entry);
493
+ }
494
+ return this.ensureDataUntil(resource, args, signal);
495
+ },
496
+ hydrate: (entries) => this.hydrate(entries),
497
+ invalidateData: (resource, ...args) => this.invalidateData(resource, ...args),
498
+ invalidateDataError: (error) => this.invalidateDataError(error),
499
+ invalidateDataKey: (key) => this.invalidateDataKey(key),
500
+ invalidateDataPrefix: (prefix) => this.invalidateDataPrefix(prefix),
501
+ preloadData: (resource, ...args) => this.preloadData(resource, ...args),
502
+ refreshData: (resource, ...args) => this.refreshData(resource, ...args),
503
+ run: (callback) => this.run(callback)
386
504
  };
387
505
  }
506
+ keepEqualValue(entry, stale) {
507
+ entry.error = void 0;
508
+ entry.pending = null;
509
+ entry.refreshError = void 0;
510
+ entry.refreshFailed = false;
511
+ entry.stale = stale;
512
+ entry.status = "fulfilled";
513
+ this.notifyEntryChange(entry);
514
+ this.scheduleInactiveCleanup(entry);
515
+ }
516
+ scheduleWatchReconcile(entry) {
517
+ if (entry.watchSource === null && entry.watchController === null) return;
518
+ if (this.pendingWatchReconciles !== null) {
519
+ this.pendingWatchReconciles.add(entry);
520
+ return;
521
+ }
522
+ const entries = /* @__PURE__ */ new Set([entry]);
523
+ this.pendingWatchReconciles = entries;
524
+ queueMicrotask(() => {
525
+ this.pendingWatchReconciles = null;
526
+ for (const pending of entries) this.reconcileWatch(pending);
527
+ });
528
+ }
529
+ wantsWatch(entry) {
530
+ const source = entry.watchSource;
531
+ if (source === null || this.disposed || this.host.watchSources !== true || this.entries.get(entry.canonicalKey) !== entry) return false;
532
+ if (entry.subscribers.size > 0) return true;
533
+ return source.resource.load === void 0 && isHeld(entry);
534
+ }
535
+ reconcileWatch(entry) {
536
+ const wanted = this.wantsWatch(entry);
537
+ if (wanted && entry.watchController === null) this.startWatch(entry);
538
+ else if (!wanted && entry.watchController !== null) this.stopWatch(entry, "released");
539
+ if (!wanted && entry.pending?.watch === true && !isHeld(entry)) this.evictEntry(entry, "evicted");
540
+ }
541
+ holdDataRead(reads, canonicalKey) {
542
+ if (!reads.has(canonicalKey)) reads.set(canonicalKey, void 0);
543
+ const entry = this.entries.get(canonicalKey);
544
+ if (entry !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
545
+ }
546
+ releaseDataReads(reads) {
547
+ for (const key of reads.keys()) {
548
+ const entry = this.entries.get(key);
549
+ if (entry !== void 0) this.releaseRetainer(entry, reads);
550
+ }
551
+ }
552
+ releaseRetainer(entry, owner) {
553
+ if (!entry.retainers?.delete(owner) || this.entries.get(entry.canonicalKey) !== entry) return;
554
+ this.scheduleInactiveCleanup(entry);
555
+ this.scheduleWatchReconcile(entry);
556
+ }
557
+ startWatch(entry) {
558
+ const source = entry.watchSource;
559
+ const watch = source?.resource.watch;
560
+ if (source === null || watch === void 0) return;
561
+ const controller = new AbortController();
562
+ entry.watchController = controller;
563
+ this.notifyEntryChange(entry);
564
+ const context = this.createWatchContext(entry, source, controller);
565
+ try {
566
+ watch(...source.args, context);
567
+ } catch (error) {
568
+ context.fail(error);
569
+ }
570
+ }
571
+ stopWatch(entry, reason) {
572
+ const controller = entry.watchController;
573
+ if (controller === null) return;
574
+ entry.watchController = null;
575
+ if (reason === "released" && entryHasValue(entry)) entry.stale = true;
576
+ this.notifyEntryChange(entry);
577
+ controller.abort(reason);
578
+ }
579
+ createWatchContext(entry, source, controller) {
580
+ const live = () => !this.disposed && !controller.signal.aborted && this.entries.get(entry.canonicalKey) === entry;
581
+ return {
582
+ data: this.dependentHandle(controller.signal),
583
+ signal: controller.signal,
584
+ publish: (value) => {
585
+ if (!live()) return;
586
+ const equals = source.resource.equals ?? Object.is;
587
+ if (entryHasValue(entry) && equals(entry.value, value)) {
588
+ const pending = entry.pending;
589
+ entry.invalidationVersion = 0;
590
+ entry.lane = null;
591
+ this.keepEqualValue(entry, false);
592
+ pending?.resolve(abortedRefreshResult(entry, "superseded"));
593
+ pending?.controller.abort("superseded");
594
+ return;
595
+ }
596
+ this.hydrateEntry(entry, entry.key, value);
597
+ this.scheduleWatchReconcile(entry);
598
+ },
599
+ fail: (error) => {
600
+ if (!live()) return;
601
+ this.failWatchedEntry(entry, error);
602
+ },
603
+ refresh: () => {
604
+ if (live()) return this.refreshData(source.resource, ...source.args);
605
+ const reason = this.disposed ? "store-disposed" : controller.signal.reason === "released" ? "released" : "evicted";
606
+ return Promise.resolve(abortedRefreshResult(entry, reason));
607
+ },
608
+ invalidate: () => {
609
+ if (!live()) return;
610
+ this.invalidateEntry(entry, this.host.getLane());
611
+ }
612
+ };
613
+ }
614
+ failWatchedEntry(entry, error) {
615
+ if (entryHasValue(entry)) {
616
+ entry.refreshError = error;
617
+ entry.refreshFailed = true;
618
+ entry.stale = true;
619
+ this.publish(entry);
620
+ return;
621
+ }
622
+ const pending = entry.pending;
623
+ entry.pending = null;
624
+ entry.error = error;
625
+ entry.status = "rejected";
626
+ markDataResourceError(error, entry.key);
627
+ pending?.resolve({
628
+ error,
629
+ status: "rejected"
630
+ });
631
+ this.publish(entry);
632
+ pending?.controller.abort(error);
633
+ }
388
634
  hydrateEntry(entry, key, value) {
389
635
  this.clearInactiveTimer(entry);
390
- this.abortEntryGenerations(entry, "superseded");
636
+ const valueController = entry.valueController;
637
+ const pending = entry.pending;
638
+ entry.valueController = null;
639
+ entry.pending = null;
391
640
  entry.error = void 0;
392
- entry.generation += 1;
393
641
  entry.valueErrors = /* @__PURE__ */ new WeakSet();
394
642
  entry.invalidationVersion = 0;
395
643
  entry.key = key;
396
644
  entry.lane = null;
397
645
  entry.refreshError = void 0;
646
+ entry.refreshFailed = false;
398
647
  entry.stale = false;
399
648
  entry.status = "fulfilled";
400
649
  entry.value = value;
401
- }
402
- storeKey(canonicalKey) {
403
- return this.partitionKey === "" ? canonicalKey : `${this.partitionKey}:${canonicalKey}`;
650
+ pending?.resolve(abortedRefreshResult(entry, "superseded"));
651
+ this.publish(entry);
652
+ pending?.controller.abort("superseded");
653
+ valueController?.abort("superseded");
404
654
  }
405
655
  startLoad(entry, resource, args, options) {
406
656
  const hadValue = entryHasValue(entry);
@@ -414,18 +664,18 @@ var DefaultDataStore = class {
414
664
  this.notifyEntryChange(entry);
415
665
  return Promise.resolve(unsupportedRefreshResult(entry));
416
666
  }
417
- this.abortPendingLoad(entry, "superseded");
667
+ const previousPending = entry.pending;
418
668
  const controller = new AbortController();
419
669
  const valueErrors = /* @__PURE__ */ new WeakSet();
420
- const generation = entry.generation + 1;
421
670
  const invalidationVersion = entry.invalidationVersion;
422
- const pending = createPendingResult();
423
- entry.controller = controller;
424
- entry.generation = generation;
671
+ const pending = createPendingLoad(controller);
425
672
  entry.lane = options.lane;
426
673
  entry.pending = pending;
427
674
  entry.status = options.refresh && hadValue ? "refreshing" : "pending";
675
+ previousPending?.resolve(abortedRefreshResult(entry, "superseded"));
676
+ previousPending?.controller.abort("superseded");
428
677
  this.notifyEntryChange(entry);
678
+ if (controller.signal.aborted) return pending.promise;
429
679
  let loaded;
430
680
  try {
431
681
  loaded = load(...args, this.createLoadContext(entry, controller, valueErrors));
@@ -438,64 +688,89 @@ var DefaultDataStore = class {
438
688
  return result;
439
689
  };
440
690
  const fulfill = (value) => {
441
- if (entry.generation !== generation || controller.signal.aborted) return settleAborted();
691
+ if (entry.pending !== pending || controller.signal.aborted) return settleAborted();
692
+ const equals = resource.equals ?? Object.is;
693
+ let equal;
694
+ try {
695
+ equal = entryHasValue(entry) && equals(entry.value, value);
696
+ } catch (error) {
697
+ return reject(error);
698
+ }
699
+ if (equal) {
700
+ this.keepEqualValue(entry, entry.invalidationVersion !== invalidationVersion);
701
+ const result = {
702
+ status: "fulfilled",
703
+ value: entry.value
704
+ };
705
+ pending.resolve(result);
706
+ controller.abort("superseded");
707
+ return result;
708
+ }
442
709
  const superseded = entry.valueController;
443
- entry.controller = null;
444
710
  entry.valueController = controller;
445
711
  entry.valueErrors = valueErrors;
446
712
  entry.error = void 0;
447
713
  entry.pending = null;
448
714
  entry.refreshError = void 0;
715
+ entry.refreshFailed = false;
449
716
  entry.stale = entry.invalidationVersion !== invalidationVersion;
450
717
  entry.status = "fulfilled";
451
718
  entry.value = value;
452
- this.publish(entry);
453
- superseded?.abort("superseded");
454
719
  const result = {
455
720
  status: "fulfilled",
456
721
  value
457
722
  };
458
723
  pending.resolve(result);
724
+ this.publish(entry);
725
+ superseded?.abort("superseded");
459
726
  return result;
460
727
  };
461
728
  const reject = (error) => {
462
- if (entry.generation !== generation || controller.signal.aborted) return settleAborted();
463
- entry.controller = null;
464
- controller.abort(error);
729
+ if (entry.pending !== pending || controller.signal.aborted) return settleAborted();
465
730
  entry.pending = null;
466
731
  if (hadValue && entryHasValue(entry)) {
467
732
  entry.refreshError = error;
733
+ entry.refreshFailed = true;
468
734
  entry.stale = true;
469
735
  entry.status = "fulfilled";
470
- this.publish(entry);
471
736
  const result = {
472
737
  error,
473
738
  staleValue: entry.value,
474
739
  status: "rejected"
475
740
  };
476
741
  pending.resolve(result);
742
+ this.publish(entry);
743
+ controller.abort(error);
477
744
  return result;
478
745
  }
479
746
  entry.error = error;
480
747
  entry.status = "rejected";
481
748
  markDataResourceError(error, entry.key);
482
- this.publish(entry);
483
749
  const result = {
484
750
  error,
485
751
  status: "rejected"
486
752
  };
487
753
  pending.resolve(result);
754
+ this.publish(entry);
755
+ controller.abort(error);
488
756
  return result;
489
757
  };
490
- if (!isThenable(loaded)) {
491
- fulfill(loaded);
758
+ let thenable;
759
+ try {
760
+ thenable = isThenable(loaded);
761
+ } catch (error) {
762
+ reject(error);
492
763
  return pending.promise;
493
764
  }
494
- Promise.resolve(loaded).then(fulfill, reject);
765
+ if (thenable) Promise.resolve(loaded).then(fulfill, reject);
766
+ else fulfill(loaded);
495
767
  return pending.promise;
496
768
  }
497
769
  createLoadContext(entry, controller, valueErrors) {
498
- const context = { signal: controller.signal };
770
+ const context = {
771
+ data: this.dependentHandle(controller.signal),
772
+ signal: controller.signal
773
+ };
499
774
  defineLoadContextCapabilities(context, {
500
775
  key: entry.key,
501
776
  attributeError: (error) => {
@@ -505,9 +780,12 @@ var DefaultDataStore = class {
505
780
  },
506
781
  hydrate: (entries) => {
507
782
  if (this.disposed || controller.signal.aborted) return;
508
- const foreign = entries.filter((hydrated) => this.storeKey(normalizeKey(hydrated.key).canonical) !== entry.storeKey);
783
+ const foreign = entries.filter((hydrated) => normalizeKey(hydrated.key).canonical !== entry.canonicalKey);
509
784
  if (foreign.length !== entries.length) warn(`Data rows targeting the loading key ${entry.canonicalKey} were skipped: a loader cannot hydrate its own entry.`);
510
- if (foreign.length > 0) this.hydrate(foreign);
785
+ for (const hydrated of foreign) {
786
+ if (controller.signal.aborted) return;
787
+ this.hydrate([hydrated]);
788
+ }
511
789
  }
512
790
  });
513
791
  return context;
@@ -520,25 +798,22 @@ var DefaultDataStore = class {
520
798
  scheduleSubscribers(entry, lane) {
521
799
  for (const subscriber of entry.subscribers) this.host.schedule(subscriber, lane);
522
800
  }
523
- abortPendingLoad(entry, reason) {
524
- entry.controller?.abort(reason);
525
- entry.controller = null;
526
- const pending = entry.pending;
527
- if (pending === null) return;
528
- entry.pending = null;
529
- pending.resolve(abortedRefreshResult(entry, reason));
530
- }
531
801
  abortEntryGenerations(entry, reason) {
532
- this.abortPendingLoad(entry, reason);
533
- entry.valueController?.abort(reason);
802
+ const valueController = entry.valueController;
803
+ const pending = entry.pending;
534
804
  entry.valueController = null;
805
+ entry.pending = null;
806
+ pending?.resolve(abortedRefreshResult(entry, reason));
807
+ pending?.controller.abort(reason);
808
+ valueController?.abort(reason);
809
+ this.stopWatch(entry, reason);
535
810
  }
536
811
  retainPreload(entry) {
537
812
  this.clearPreloadTimer(entry);
538
813
  if (this.disposed || !Number.isFinite(this.preloadRetentionMs)) return;
539
814
  entry.preloadTimer = scheduleStoreTimer(() => {
540
815
  entry.preloadTimer = null;
541
- if (entry.subscribers.size === 0 && entry.ensureRetainers === 0 && entry.pending !== null && !entryHasValue(entry)) {
816
+ if (!isHeld(entry) && entry.pending !== null && !entryHasValue(entry)) {
542
817
  this.evictEntry(entry, "evicted");
543
818
  return;
544
819
  }
@@ -546,20 +821,21 @@ var DefaultDataStore = class {
546
821
  }, Math.max(0, this.preloadRetentionMs));
547
822
  }
548
823
  scheduleInactiveCleanup(entry) {
549
- if (this.disposed || entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0 || !Number.isFinite(this.inactiveRetentionMs)) return;
824
+ const retention = entry.inactiveRetentionMs ?? this.inactiveRetentionMs;
825
+ if (this.disposed || isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null || !Number.isFinite(retention)) return;
550
826
  this.clearInactiveTimer(entry);
551
827
  entry.inactiveTimer = scheduleStoreTimer(() => {
552
828
  entry.inactiveTimer = null;
553
- if (entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0) return;
829
+ if (isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null) return;
554
830
  this.evictEntry(entry, "evicted");
555
- }, Math.max(0, this.inactiveRetentionMs));
831
+ }, Math.max(0, retention));
556
832
  }
557
833
  evictEntry(entry, reason) {
558
- if (this.entries.get(entry.storeKey) !== entry) return;
834
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
559
835
  this.clearInactiveTimer(entry);
560
836
  this.clearPreloadTimer(entry);
837
+ this.entries.delete(entry.canonicalKey);
561
838
  this.abortEntryGenerations(entry, reason);
562
- this.entries.delete(entry.storeKey);
563
839
  this.host.onEntryEvict?.(this.snapshotEntry(entry));
564
840
  }
565
841
  clearInactiveTimer(entry) {
@@ -587,7 +863,8 @@ var DefaultDataStore = class {
587
863
  stale: entry.stale,
588
864
  status: entry.status,
589
865
  subscriberCount: entry.subscribers.size,
590
- value: hasValue ? entry.value : void 0
866
+ value: hasValue ? entry.value : void 0,
867
+ ...entry.watchController === null ? {} : { watching: true }
591
868
  };
592
869
  }
593
870
  readCurrentValue(entry) {
@@ -600,8 +877,10 @@ var DefaultDataStore = class {
600
877
  entry.invalidationVersion += 1;
601
878
  entry.stale = true;
602
879
  entry.refreshError = void 0;
880
+ entry.refreshFailed = false;
881
+ let retiredController = null;
603
882
  if (isAttributableError(attributedError) && entry.valueErrors.has(attributedError)) {
604
- entry.valueController?.abort(attributedError);
883
+ retiredController = entry.valueController;
605
884
  entry.valueController = null;
606
885
  entry.valueErrors = /* @__PURE__ */ new WeakSet();
607
886
  entry.value = void 0;
@@ -612,8 +891,8 @@ var DefaultDataStore = class {
612
891
  entry.status = "pending";
613
892
  }
614
893
  this.notifyEntryChange(entry);
615
- if (entry.subscribers.size === 0) return;
616
894
  this.scheduleSubscribers(entry, lane);
895
+ retiredController?.abort(attributedError);
617
896
  }
618
897
  invalidateEntries(entries, attributedError) {
619
898
  if (entries.length === 0) return;
@@ -633,6 +912,9 @@ function canonicalKeyStartsWith(key, prefix) {
633
912
  const arrayPrefix = prefix.slice(0, -1);
634
913
  return key.startsWith(arrayPrefix) && key[arrayPrefix.length] === ",";
635
914
  }
915
+ function isHeld(entry) {
916
+ return entry.subscribers.size > 0 || (entry.retainers?.size ?? 0) > 0;
917
+ }
636
918
  function entryHasValue(entry) {
637
919
  return entry.status === "fulfilled" || entry.status === "refreshing";
638
920
  }
@@ -724,9 +1006,24 @@ function encodeValue(value, path) {
724
1006
  function isThenable(value) {
725
1007
  return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
726
1008
  }
727
- function createPendingResult() {
1009
+ function untilAborted(promise, signal) {
1010
+ if (signal.aborted) return Promise.reject(signal.reason);
1011
+ return new Promise((resolve, reject) => {
1012
+ const abort = () => reject(signal.reason);
1013
+ signal.addEventListener("abort", abort, { once: true });
1014
+ promise.then((value) => {
1015
+ signal.removeEventListener("abort", abort);
1016
+ resolve(value);
1017
+ }, (error) => {
1018
+ signal.removeEventListener("abort", abort);
1019
+ reject(error);
1020
+ });
1021
+ });
1022
+ }
1023
+ function createPendingLoad(controller) {
728
1024
  let resolve = () => void 0;
729
1025
  return {
1026
+ controller,
730
1027
  promise: new Promise((settle) => {
731
1028
  resolve = settle;
732
1029
  }),
@@ -795,6 +1092,6 @@ function setTransitionHandler(handler) {
795
1092
  return previous;
796
1093
  }
797
1094
  //#endregion
798
- export { refreshData as _, createDataStore as a, createContext as b, dataResource as c, invalidateDataError as d, invalidateDataKey as f, readDataStore as g, normalizeDataResourceKey as h, attachDataStore as i, ensureData as l, isDataStoreController as m, setTransitionHandler as n, createRendererDataStore as o, invalidateDataPrefix as p, transition as r, currentDataStore as s, runTransitionScope as t, invalidateData as u, runWithDataStore as v, isContext as x, FigContextSymbol as y };
1095
+ export { resolveCurrentDataStore as _, createDataStore as a, createContext as b, dataResource as c, readDataStore as d, runWithDataStore as f, markDataResourceError as g, loadContextCapabilities as h, attachDataStore as i, isDataStoreController as l, defineLoadContextCapabilities as m, setTransitionHandler as n, createRendererDataStore as o, dataResourceKeysForError as p, transition as r, currentDataStore as s, runTransitionScope as t, normalizeDataResourceKey as u, setCurrentDataStore as v, isContext as x, FigContextSymbol as y };
799
1096
 
800
- //# sourceMappingURL=transition-DEVMhyYg.js.map
1097
+ //# sourceMappingURL=transition-CWjp9qRO.js.map