@bgub/fig 2.0.0 → 2.2.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 +110 -0
  2. package/README.md +21 -22
  3. package/dist/{element-B4LrR2ZB.d.ts → element-Ba2mDNM_.d.ts} +74 -17
  4. package/dist/{element-j7AKp0nu.js → element-DpXdLgOZ.js} +6 -68
  5. package/dist/element-DpXdLgOZ.js.map +1 -0
  6. package/dist/{hooks-QSWYd3Vl.d.ts → hooks-CUdLWnbQ.d.ts} +21 -23
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +4 -4
  9. package/dist/internal.d.ts +12 -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-YO25HR7G.js → dist/resource-DEDmLSNk.js} +5 -18
  18. package/dist/resource-DEDmLSNk.js.map +1 -0
  19. package/dist/{transition-DJfG2ZSm.js → transition-C03gUimZ.js} +510 -83
  20. package/dist/transition-C03gUimZ.js.map +1 -0
  21. package/dist-development/{element-DzmNF67v.js → element-DbzJUf5a.js} +6 -68
  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-Lwjz_b4h.js → dist-development/resource-BZOBllE_.js} +5 -18
  30. package/dist-development/resource-BZOBllE_.js.map +1 -0
  31. package/dist-development/{transition-CrIF0Kz_.js → transition-BZTyeaMo.js} +513 -84
  32. package/dist-development/transition-BZTyeaMo.js.map +1 -0
  33. package/package.json +1 -1
  34. package/dist/element-j7AKp0nu.js.map +0 -1
  35. package/dist/resource-Lwjz_b4h.js.map +0 -1
  36. package/dist/transition-DJfG2ZSm.js.map +0 -1
  37. package/dist-development/element-DzmNF67v.js.map +0 -1
  38. package/dist-development/resource-YO25HR7G.js.map +0 -1
  39. package/dist-development/transition-CrIF0Kz_.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { $ as getCurrentDataStore, Q as defineLoadContextCapabilities, Z as dataResourceKeysForError, et as isAttributableError, it as setCurrentDataStore, nt as markDataResourceError, rt as resolveCurrentDataStore } from "./element-DzmNF67v.js";
2
- import { y as isThenable$1 } from "./resource-YO25HR7G.js";
1
+ import { P as readBrowser } from "./element-DbzJUf5a.js";
2
+ import { y as isThenable$1 } from "./resource-BZOBllE_.js";
3
3
  //#region src/context.ts
4
4
  /** The Fig context symbol. */
5
5
  const FigContextSymbol = Symbol.for("fig.context");
@@ -15,6 +15,88 @@ function isContext(value) {
15
15
  return typeof value === "function" && "$$typeof" in value && value.$$typeof === FigContextSymbol;
16
16
  }
17
17
  //#endregion
18
+ //#region src/data.ts
19
+ const LoadContextCapabilitiesSymbol = Symbol.for("fig.data-load-context");
20
+ /** Define load context capabilities. */
21
+ function defineLoadContextCapabilities(context, capabilities) {
22
+ Object.defineProperty(context, LoadContextCapabilitiesSymbol, {
23
+ configurable: true,
24
+ enumerable: false,
25
+ value: capabilities
26
+ });
27
+ }
28
+ /** Load context capabilities. */
29
+ function loadContextCapabilities(context) {
30
+ return context[LoadContextCapabilitiesSymbol];
31
+ }
32
+ const objectDataErrors = /* @__PURE__ */ new WeakMap();
33
+ let currentDataStore$1 = null;
34
+ /** Captures an optional data store for synchronous scope re-entry. */
35
+ function getCurrentDataStore() {
36
+ return currentDataStore$1;
37
+ }
38
+ /** Resolves current data store. */
39
+ function resolveCurrentDataStore(message = "Data resource APIs require a Fig data store.") {
40
+ if (currentDataStore$1 === null) throw new Error(message);
41
+ return currentDataStore$1;
42
+ }
43
+ /** Sets current data store. */
44
+ function setCurrentDataStore(store) {
45
+ const previousStore = currentDataStore$1;
46
+ currentDataStore$1 = store;
47
+ return previousStore;
48
+ }
49
+ /** Marks data resource error. */
50
+ function markDataResourceError(error, key) {
51
+ if (!isAttributableError(error)) return;
52
+ let keys = objectDataErrors.get(error);
53
+ if (keys === void 0) {
54
+ keys = [];
55
+ objectDataErrors.set(error, keys);
56
+ }
57
+ if (keys.some((existing) => sameDataResourceKey(existing, key))) return;
58
+ keys.push(key);
59
+ }
60
+ /** Data resource keys for error. */
61
+ function dataResourceKeysForError(error) {
62
+ if (!isAttributableError(error)) return void 0;
63
+ const keys = objectDataErrors.get(error);
64
+ return keys === void 0 || keys.length === 0 ? void 0 : [...keys];
65
+ }
66
+ function sameDataResourceKey(a, b) {
67
+ return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
68
+ }
69
+ function isAttributableError(value) {
70
+ return (typeof value === "object" || typeof value === "function") && value !== null;
71
+ }
72
+ const MissingCapabilityBrand = Symbol.for("fig.data-missing-capability");
73
+ /**
74
+ * Thrown by `requireCapability`: this load cannot run in the current
75
+ * environment. During server rendering, a read of the entry leaves the
76
+ * nearest Suspense fallback for the browser to render.
77
+ */
78
+ var MissingCapabilityError = class extends Error {
79
+ [MissingCapabilityBrand] = true;
80
+ reason;
81
+ constructor(reason) {
82
+ super("This data cannot be loaded here.");
83
+ this.name = "MissingCapabilityError";
84
+ this.reason = reason;
85
+ }
86
+ };
87
+ /**
88
+ * Asserts that a load's required capability is available. A false condition
89
+ * throws MissingCapabilityError; a true condition narrows it and lets the
90
+ * load continue in environments that provide the capability.
91
+ */
92
+ function requireCapability(condition, reason) {
93
+ if (!condition) throw new MissingCapabilityError(reason);
94
+ }
95
+ /** Checks whether a value is a missing-capability error. */
96
+ function isMissingCapability(value) {
97
+ return typeof value === "object" && value !== null && value[MissingCapabilityBrand] === true;
98
+ }
99
+ //#endregion
18
100
  //#region src/data-store.ts
19
101
  const DataResourceSymbol = Symbol.for("fig.data-resource");
20
102
  const DataStoreFactorySymbol = Symbol.for("fig.data-store-factory");
@@ -24,38 +106,19 @@ const DEFAULT_PRELOAD_RETENTION_MS = 3e4;
24
106
  const dataStoreFactory = createRendererDataStore;
25
107
  /** Data resource. */
26
108
  function dataResource(options) {
109
+ if (typeof options.transfer === "function" && options.load === void 0) throw new Error("A data resource with a transfer function requires a loader.");
27
110
  return {
28
111
  $$typeof: DataResourceSymbol,
29
112
  [DataStoreFactorySymbol]: dataStoreFactory,
30
113
  debugArgs: options.debugArgs,
114
+ equals: options.equals,
115
+ inactiveRetentionMs: options.inactiveRetentionMs,
31
116
  key: options.key,
32
- load: options.load
117
+ load: options.load,
118
+ transfer: options.transfer,
119
+ watch: options.watch
33
120
  };
34
121
  }
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
122
  /** Reads data store. */
60
123
  function readDataStore() {
61
124
  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 +128,10 @@ function createDataStore(options = {}) {
65
128
  const state = { host: null };
66
129
  const store = createRendererDataStore({
67
130
  getLane: () => state.host === null ? null : state.host.getLane(),
68
- partition: options.partition,
69
- schedule: (owner, lane) => state.host?.schedule(owner, lane)
131
+ schedule: (owner, lane) => state.host?.schedule(owner, lane),
132
+ get watchSources() {
133
+ return state.host?.watchSources === true;
134
+ }
70
135
  });
71
136
  Object.defineProperty(store, DataStoreControllerSymbol, { value: state });
72
137
  if (options.initialData !== void 0) store.hydrate(options.initialData);
@@ -78,16 +143,13 @@ function isDataStoreController(value) {
78
143
  }
79
144
  /** Attach data store. */
80
145
  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.");
146
+ if (initialData !== void 0) throw new Error("Pass initialData to createDataStore(), not the renderer, when adopting a data store.");
82
147
  const state = controller[DataStoreControllerSymbol];
83
148
  if (state === void 0) throw new Error("dataStore must be created with createDataStore().");
84
149
  if (state.host !== null) throw new Error("A data store can only be adopted by one Fig renderer.");
85
150
  state.host = host;
86
151
  return controller;
87
152
  }
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
153
  /** Creates renderer data store. */
92
154
  function createRendererDataStore(host) {
93
155
  return new DefaultDataStore(host);
@@ -99,15 +161,15 @@ function normalizeDataResourceKey(key) {
99
161
  var DefaultDataStore = class {
100
162
  host;
101
163
  entries = /* @__PURE__ */ new Map();
164
+ awaitedForms = /* @__PURE__ */ new Set();
102
165
  inactiveRetentionMs;
103
166
  ownerKeys = /* @__PURE__ */ new WeakMap();
104
- partitionKey;
105
167
  preloadRetentionMs;
106
168
  disposed = false;
169
+ pendingWatchReconciles = null;
107
170
  constructor(host) {
108
171
  this.host = host;
109
172
  this.inactiveRetentionMs = host.inactiveRetentionMs ?? DEFAULT_INACTIVE_RETENTION_MS;
110
- this.partitionKey = host.partition === void 0 ? "" : encodeValue(host.partition, createEncodePath("partition"));
111
173
  this.preloadRetentionMs = host.preloadRetentionMs ?? DEFAULT_PRELOAD_RETENTION_MS;
112
174
  }
113
175
  areDataDependenciesConsistent(reads) {
@@ -135,11 +197,16 @@ var DefaultDataStore = class {
135
197
  if (entry !== void 0) {
136
198
  this.clearInactiveTimer(entry);
137
199
  entry.subscribers.add(owner);
200
+ if (reads !== void 0) entry.retainers?.delete(reads);
138
201
  this.notifyEntryChange(entry);
139
202
  }
140
203
  }
141
204
  }
142
205
  if (orphanCandidates !== null) for (const entry of orphanCandidates) this.abortOrphanedLoad(entry);
206
+ if (nextKeys !== null) for (const key of nextKeys) {
207
+ const entry = this.entries.get(key);
208
+ if (entry !== void 0) this.scheduleWatchReconcile(entry);
209
+ }
143
210
  const consistent = reads === void 0 || this.areDataDependenciesConsistent(reads);
144
211
  reads?.clear();
145
212
  return consistent;
@@ -158,7 +225,10 @@ var DefaultDataStore = class {
158
225
  if (entry === void 0) continue;
159
226
  entry.subscribers.delete(owner);
160
227
  this.notifyEntryChange(entry);
161
- if (retainedKeys?.has(key) !== true) this.scheduleInactiveCleanup(entry);
228
+ if (retainedKeys?.has(key) !== true) {
229
+ this.scheduleInactiveCleanup(entry);
230
+ this.scheduleWatchReconcile(entry);
231
+ }
162
232
  }
163
233
  }
164
234
  collectSubscribedEntries(keys, into) {
@@ -173,41 +243,104 @@ var DefaultDataStore = class {
173
243
  return into;
174
244
  }
175
245
  abortOrphanedLoad(entry) {
176
- if (this.entries.get(entry.storeKey) !== entry) return;
177
- if (entry.subscribers.size > 0 || entry.preloadTimer !== null || entry.ensureRetainers > 0 || entry.pending === null || entryHasValue(entry)) return;
246
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
247
+ if (isHeld(entry) || entry.preloadTimer !== null || entry.pending === null || entryHasValue(entry)) return;
178
248
  this.evictEntry(entry, "evicted");
179
249
  }
180
250
  dispose() {
181
251
  this.disposed = true;
252
+ this.awaitedForms.clear();
253
+ let failure;
254
+ for (const entry of this.entries.values()) try {
255
+ const transferred = transferValue(entry);
256
+ if (transferred === void 0) continue;
257
+ entry.value = transferred.value;
258
+ entry.transferred = true;
259
+ } catch (error) {
260
+ failure ??= { error };
261
+ }
182
262
  for (const entry of this.entries.values()) {
183
263
  this.clearInactiveTimer(entry);
184
264
  this.clearPreloadTimer(entry);
185
265
  this.abortEntryGenerations(entry, "store-disposed");
186
266
  this.notifyEntryChange(entry);
187
267
  }
268
+ if (failure !== void 0) throw failure.error;
188
269
  }
189
270
  hydrate(entries) {
271
+ this.hydrateEntries(entries, true);
272
+ }
273
+ hydrateMissing(entries) {
274
+ this.hydrateEntries(entries, false);
275
+ }
276
+ hydrateEntries(entries, replaceValues) {
190
277
  if (this.disposed) return;
191
278
  for (const hydrated of entries) {
192
279
  if (this.disposed) return;
193
280
  const normalized = normalizeKey(hydrated.key);
194
- const storeKey = this.storeKey(normalized.canonical);
281
+ const storeKey = normalized.canonical;
195
282
  const current = this.entries.get(storeKey);
283
+ this.awaitedForms.delete(storeKey);
196
284
  if (current !== void 0) {
197
- this.hydrateEntry(current, normalized.key, hydrated.value);
285
+ if (current.parkedLoad !== null) {
286
+ current.seed = { value: hydrated.value };
287
+ runParkedLoad(current);
288
+ continue;
289
+ }
290
+ if (replaceValues || !entryHasValue(current)) this.hydrateEntry(current, normalized.key, hydrated.value, true);
198
291
  continue;
199
292
  }
200
- const entry = this.createEntry(normalized, storeKey, null, null, "fulfilled", hydrated.value);
293
+ const entry = this.createEntry(normalized, null, null, "fulfilled", hydrated.value);
294
+ entry.transferred = true;
201
295
  this.entries.set(storeKey, entry);
202
296
  this.notifyEntryChange(entry);
203
297
  }
204
298
  }
299
+ awaitTransferForms(keys) {
300
+ if (this.disposed) return;
301
+ for (const key of keys) {
302
+ const canonical = normalizeKey(key).canonical;
303
+ const entry = this.entries.get(canonical);
304
+ if (entry !== void 0 && (entryHasValue(entry) || entry.pending !== null)) continue;
305
+ this.awaitedForms.add(canonical);
306
+ }
307
+ }
308
+ releaseTransferForms() {
309
+ const keys = [...this.awaitedForms];
310
+ this.awaitedForms.clear();
311
+ for (const key of keys) {
312
+ const entry = this.entries.get(key);
313
+ if (entry !== void 0) runParkedLoad(entry);
314
+ }
315
+ }
205
316
  snapshot() {
317
+ return this.snapshotKeys(this.entries.keys());
318
+ }
319
+ snapshotKeys(canonicalKeys, deferred) {
320
+ const sources = /* @__PURE__ */ new Map();
321
+ for (const entry of this.entries.values()) for (const retainer of entry.retainers ?? []) {
322
+ const retained = sources.get(retainer);
323
+ if (retained === void 0) sources.set(retainer, [entry]);
324
+ else retained.push(entry);
325
+ }
206
326
  const entries = [];
207
- for (const entry of this.entries.values()) if (entryHasValue(entry)) entries.push({
208
- key: entry.key,
209
- value: entry.value
210
- });
327
+ const visited = /* @__PURE__ */ new Set();
328
+ const requested = new Set(canonicalKeys);
329
+ const visit = (entry) => {
330
+ if (entry === void 0 || visited.has(entry)) return;
331
+ visited.add(entry);
332
+ const signal = entry.valueController?.signal;
333
+ if (signal !== void 0) sources.get(signal)?.forEach(visit);
334
+ const isRequested = requested.has(entry.canonicalKey);
335
+ if (!isRequested && typeof entry.resource?.transfer !== "function") return;
336
+ const transferred = transferValue(entry);
337
+ if (transferred === void 0) return;
338
+ (isRequested ? entries : deferred ?? entries).push({
339
+ key: entry.key,
340
+ value: transferred.value
341
+ });
342
+ };
343
+ for (const key of requested) visit(this.entries.get(key));
211
344
  return entries;
212
345
  }
213
346
  inspectDataEntries() {
@@ -254,8 +387,12 @@ var DefaultDataStore = class {
254
387
  for (const entry of this.entries.values()) if (canonicalKeyStartsWith(entry.canonicalKey, prefixCanonical)) entries.push(entry);
255
388
  this.invalidateEntries(entries);
256
389
  }
257
- async ensureData(resource, ...args) {
390
+ ensureData(resource, ...args) {
391
+ return this.ensureDataUntil(resource, args, void 0);
392
+ }
393
+ async ensureDataUntil(resource, args, until) {
258
394
  for (;;) {
395
+ if (until?.aborted === true) throw until.reason;
259
396
  if (this.disposed) throw new Error("ensureData() requires a live data store; this store was disposed.");
260
397
  const entry = this.entryFor(resource, args, true);
261
398
  this.clearInactiveTimer(entry);
@@ -265,16 +402,24 @@ var DefaultDataStore = class {
265
402
  return entry.value;
266
403
  }
267
404
  if (entry.status === "rejected") throwDataResourceError(entry);
268
- entry.ensureRetainers += 1;
405
+ const retainer = {};
406
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(retainer);
269
407
  try {
270
- if (entry.pending !== null) await entry.pending.promise;
271
- else await this.startLoad(entry, resource, args, {
408
+ this.recordWatchSource(entry, resource, args);
409
+ let settled;
410
+ if (entry.pending !== null) settled = entry.pending.promise;
411
+ else if (this.waitsOnWatch(resource)) settled = this.beginWatchPending(entry).promise;
412
+ else settled = this.startLoad(entry, resource, args, {
272
413
  lane: this.host.getLane(),
273
414
  refresh: false
274
415
  });
416
+ await (until === void 0 ? settled : untilAborted(settled, until));
275
417
  } finally {
276
- entry.ensureRetainers -= 1;
277
- if (this.entries.get(entry.storeKey) === entry) this.retainPreload(entry);
418
+ entry.retainers?.delete(retainer);
419
+ if (this.entries.get(entry.canonicalKey) === entry) {
420
+ this.retainPreload(entry);
421
+ this.scheduleWatchReconcile(entry);
422
+ }
278
423
  }
279
424
  }
280
425
  }
@@ -294,14 +439,21 @@ var DefaultDataStore = class {
294
439
  const entry = this.entryFor(resource, args, true);
295
440
  this.clearInactiveTimer(entry);
296
441
  this.clearPreloadTimer(entry);
297
- if (reads !== void 0 && !reads.has(entry.storeKey)) reads.set(entry.storeKey, void 0);
442
+ if (reads !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
443
+ if (reads !== void 0 && !reads.has(entry.canonicalKey)) reads.set(entry.canonicalKey, void 0);
444
+ this.recordWatchSource(entry, resource, args);
298
445
  this.revalidateIfStale(entry, resource, args);
299
- if (entry.status === "pending" && entry.pending === null) this.startLoad(entry, resource, args, {
300
- lane: this.host.getLane(),
301
- refresh: false
302
- });
446
+ if (entry.status === "pending" && entry.pending === null) {
447
+ const seeded = entry.seed !== null;
448
+ if (this.waitsOnWatch(resource)) this.beginWatchPending(entry);
449
+ else this.startLoad(entry, resource, args, {
450
+ lane: this.host.getLane(),
451
+ refresh: false
452
+ });
453
+ if (seeded && loaderReturnedThenable(entry)) throw new Error(`Data resource "${entry.canonicalKey}" was read in render with a transferred value, but its load returned a promise for it. Return the value synchronously when \`transferred\` is set (a load declared \`async\` always returns a promise).`);
454
+ }
303
455
  const value = this.readCurrentValue(entry);
304
- if (reads !== void 0 && reads.get(entry.storeKey) === void 0) reads.set(entry.storeKey, { value });
456
+ if (reads !== void 0 && reads.get(entry.canonicalKey) === void 0) reads.set(entry.canonicalKey, { value });
305
457
  return value;
306
458
  }
307
459
  refreshData(resource, ...args) {
@@ -335,14 +487,17 @@ var DefaultDataStore = class {
335
487
  entryFor(resource, args, create) {
336
488
  const normalized = normalizeKey(resource.key(...args));
337
489
  const fingerprint = fingerprintFor(resource, args);
338
- const key = this.storeKey(normalized.canonical);
490
+ const key = normalized.canonical;
339
491
  const current = this.entries.get(key);
340
492
  if (current !== void 0) {
493
+ if (resource.inactiveRetentionMs !== void 0) current.inactiveRetentionMs = resource.inactiveRetentionMs;
341
494
  diagnoseEntryDrift(current, resource, normalized.canonical, fingerprint);
495
+ this.adoptResource(current, resource);
342
496
  return current;
343
497
  }
344
498
  if (!create) return null;
345
- const entry = this.createEntry(normalized, key, resource, fingerprint, "pending", void 0);
499
+ const entry = this.createEntry(normalized, resource, fingerprint, "pending", void 0);
500
+ entry.inactiveRetentionMs = resource.inactiveRetentionMs;
346
501
  if (this.disposed) return entry;
347
502
  this.entries.set(key, entry);
348
503
  this.notifyEntryChange(entry);
@@ -355,18 +510,30 @@ var DefaultDataStore = class {
355
510
  refresh: true
356
511
  });
357
512
  }
513
+ adoptResource(entry, resource) {
514
+ entry.resource ??= resource;
515
+ if (!entry.transferred || typeof resource.transfer !== "function" || resource.load === void 0 || !entryHasValue(entry)) return;
516
+ entry.transferred = false;
517
+ entry.seed = { value: entry.value };
518
+ entry.value = void 0;
519
+ entry.status = "pending";
520
+ }
358
521
  entryForKey(key) {
359
522
  const normalized = normalizeKey(key);
360
- return this.entries.get(this.storeKey(normalized.canonical)) ?? null;
523
+ return this.entries.get(normalized.canonical) ?? null;
361
524
  }
362
- createEntry(normalized, storeKey, resource, fingerprint, status, value) {
525
+ createEntry(normalized, resource, fingerprint, status, value) {
363
526
  return {
364
527
  canonicalKey: normalized.canonical,
365
- ensureRetainers: 0,
528
+ retainers: null,
366
529
  error: void 0,
367
530
  fingerprint,
368
531
  invalidationVersion: 0,
532
+ inactiveRetentionMs: void 0,
369
533
  inactiveTimer: null,
534
+ transferred: false,
535
+ seed: null,
536
+ parkedLoad: null,
370
537
  key: normalized.key,
371
538
  lane: null,
372
539
  pending: null,
@@ -376,14 +543,191 @@ var DefaultDataStore = class {
376
543
  resource,
377
544
  stale: false,
378
545
  status,
379
- storeKey,
380
546
  subscribers: /* @__PURE__ */ new Set(),
381
547
  value,
382
548
  valueController: null,
383
- valueErrors: /* @__PURE__ */ new WeakSet()
549
+ valueErrors: /* @__PURE__ */ new WeakSet(),
550
+ watchController: null,
551
+ watchSource: null
552
+ };
553
+ }
554
+ recordWatchSource(entry, resource, args) {
555
+ if (resource.watch === void 0 || entry.watchSource !== null) return;
556
+ entry.watchSource = {
557
+ args,
558
+ resource
559
+ };
560
+ }
561
+ waitsOnWatch(resource) {
562
+ return resource.load === void 0 && resource.watch !== void 0 && this.host.watchSources === true;
563
+ }
564
+ beginWatchPending(entry) {
565
+ if (entry.pending !== null) return entry.pending;
566
+ const pending = createPendingLoad(new AbortController());
567
+ pending.watch = true;
568
+ entry.pending = pending;
569
+ entry.status = "pending";
570
+ this.notifyEntryChange(entry);
571
+ this.scheduleWatchReconcile(entry);
572
+ return pending;
573
+ }
574
+ dependentHandle(signal) {
575
+ const retain = (entry) => {
576
+ if (signal.aborted || entry.retainers?.has(signal)) return;
577
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(signal);
578
+ this.clearInactiveTimer(entry);
579
+ signal.addEventListener("abort", () => this.releaseRetainer(entry, signal), { once: true });
580
+ };
581
+ return {
582
+ ensureData: (resource, ...args) => {
583
+ if (signal.aborted) return Promise.reject(signal.reason);
584
+ if (!this.disposed) {
585
+ const entry = this.entryFor(resource, args, true);
586
+ this.recordWatchSource(entry, resource, args);
587
+ retain(entry);
588
+ this.scheduleWatchReconcile(entry);
589
+ }
590
+ return this.ensureDataUntil(resource, args, signal);
591
+ },
592
+ hydrate: (entries) => this.hydrate(entries),
593
+ invalidateData: (resource, ...args) => this.invalidateData(resource, ...args),
594
+ invalidateDataError: (error) => this.invalidateDataError(error),
595
+ invalidateDataKey: (key) => this.invalidateDataKey(key),
596
+ invalidateDataPrefix: (prefix) => this.invalidateDataPrefix(prefix),
597
+ preloadData: (resource, ...args) => this.preloadData(resource, ...args),
598
+ refreshData: (resource, ...args) => this.refreshData(resource, ...args),
599
+ run: (callback) => this.run(callback)
384
600
  };
385
601
  }
386
- hydrateEntry(entry, key, value) {
602
+ keepEqualValue(entry, stale) {
603
+ entry.error = void 0;
604
+ entry.pending = null;
605
+ entry.refreshError = void 0;
606
+ entry.refreshFailed = false;
607
+ entry.stale = stale;
608
+ entry.status = "fulfilled";
609
+ this.notifyEntryChange(entry);
610
+ this.scheduleInactiveCleanup(entry);
611
+ }
612
+ scheduleWatchReconcile(entry) {
613
+ if (entry.watchSource === null && entry.watchController === null) return;
614
+ if (this.pendingWatchReconciles !== null) {
615
+ this.pendingWatchReconciles.add(entry);
616
+ return;
617
+ }
618
+ const entries = /* @__PURE__ */ new Set([entry]);
619
+ this.pendingWatchReconciles = entries;
620
+ queueMicrotask(() => {
621
+ this.pendingWatchReconciles = null;
622
+ for (const pending of entries) this.reconcileWatch(pending);
623
+ });
624
+ }
625
+ wantsWatch(entry) {
626
+ const source = entry.watchSource;
627
+ if (source === null || this.disposed || this.host.watchSources !== true || this.entries.get(entry.canonicalKey) !== entry) return false;
628
+ if (entry.subscribers.size > 0) return true;
629
+ return source.resource.load === void 0 && isHeld(entry);
630
+ }
631
+ reconcileWatch(entry) {
632
+ const wanted = this.wantsWatch(entry);
633
+ if (wanted && entry.watchController === null) this.startWatch(entry);
634
+ else if (!wanted && entry.watchController !== null) this.stopWatch(entry, "released");
635
+ if (!wanted && entry.pending?.watch === true && !isHeld(entry)) this.evictEntry(entry, "evicted");
636
+ }
637
+ holdDataRead(reads, canonicalKey) {
638
+ if (!reads.has(canonicalKey)) reads.set(canonicalKey, void 0);
639
+ const entry = this.entries.get(canonicalKey);
640
+ if (entry !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
641
+ }
642
+ releaseDataReads(reads) {
643
+ for (const key of reads.keys()) {
644
+ const entry = this.entries.get(key);
645
+ if (entry !== void 0) this.releaseRetainer(entry, reads);
646
+ }
647
+ }
648
+ releaseRetainer(entry, owner) {
649
+ if (!entry.retainers?.delete(owner) || this.entries.get(entry.canonicalKey) !== entry) return;
650
+ this.scheduleInactiveCleanup(entry);
651
+ this.scheduleWatchReconcile(entry);
652
+ }
653
+ startWatch(entry) {
654
+ const source = entry.watchSource;
655
+ const watch = source?.resource.watch;
656
+ if (source === null || watch === void 0) return;
657
+ const controller = new AbortController();
658
+ entry.watchController = controller;
659
+ this.notifyEntryChange(entry);
660
+ const context = this.createWatchContext(entry, source, controller);
661
+ try {
662
+ watch(...source.args, context);
663
+ } catch (error) {
664
+ context.fail(error);
665
+ }
666
+ }
667
+ stopWatch(entry, reason) {
668
+ const controller = entry.watchController;
669
+ if (controller === null) return;
670
+ entry.watchController = null;
671
+ if (reason === "released" && entryHasValue(entry)) entry.stale = true;
672
+ this.notifyEntryChange(entry);
673
+ controller.abort(reason);
674
+ }
675
+ createWatchContext(entry, source, controller) {
676
+ const live = () => !this.disposed && !controller.signal.aborted && this.entries.get(entry.canonicalKey) === entry;
677
+ return {
678
+ data: this.dependentHandle(controller.signal),
679
+ signal: controller.signal,
680
+ publish: (value) => {
681
+ if (!live()) return;
682
+ const equals = source.resource.equals ?? Object.is;
683
+ if (!(entry.transferred && typeof source.resource.transfer === "function") && entryHasValue(entry) && equals(entry.value, value)) {
684
+ const pending = entry.pending;
685
+ entry.invalidationVersion = 0;
686
+ entry.lane = null;
687
+ this.keepEqualValue(entry, false);
688
+ pending?.resolve(abortedRefreshResult(entry, "superseded"));
689
+ pending?.controller.abort("superseded");
690
+ return;
691
+ }
692
+ this.hydrateEntry(entry, entry.key, value, false);
693
+ this.scheduleWatchReconcile(entry);
694
+ },
695
+ fail: (error) => {
696
+ if (!live()) return;
697
+ this.failWatchedEntry(entry, error);
698
+ },
699
+ refresh: () => {
700
+ if (live()) return this.refreshData(source.resource, ...source.args);
701
+ const reason = this.disposed ? "store-disposed" : controller.signal.reason === "released" ? "released" : "evicted";
702
+ return Promise.resolve(abortedRefreshResult(entry, reason));
703
+ },
704
+ invalidate: () => {
705
+ if (!live()) return;
706
+ this.invalidateEntry(entry, this.host.getLane());
707
+ }
708
+ };
709
+ }
710
+ failWatchedEntry(entry, error) {
711
+ if (entryHasValue(entry)) {
712
+ entry.refreshError = error;
713
+ entry.refreshFailed = true;
714
+ entry.stale = true;
715
+ this.publish(entry);
716
+ return;
717
+ }
718
+ const pending = entry.pending;
719
+ entry.pending = null;
720
+ entry.error = error;
721
+ entry.status = "rejected";
722
+ markDataResourceError(error, entry.key);
723
+ pending?.resolve({
724
+ error,
725
+ status: "rejected"
726
+ });
727
+ this.publish(entry);
728
+ pending?.controller.abort(error);
729
+ }
730
+ hydrateEntry(entry, key, value, transferred) {
387
731
  this.clearInactiveTimer(entry);
388
732
  const valueController = entry.valueController;
389
733
  const pending = entry.pending;
@@ -399,14 +743,13 @@ var DefaultDataStore = class {
399
743
  entry.stale = false;
400
744
  entry.status = "fulfilled";
401
745
  entry.value = value;
746
+ entry.transferred = transferred;
747
+ entry.seed = null;
402
748
  pending?.resolve(abortedRefreshResult(entry, "superseded"));
403
749
  this.publish(entry);
404
750
  pending?.controller.abort("superseded");
405
751
  valueController?.abort("superseded");
406
752
  }
407
- storeKey(canonicalKey) {
408
- return this.partitionKey === "" ? canonicalKey : `${this.partitionKey}:${canonicalKey}`;
409
- }
410
753
  startLoad(entry, resource, args, options) {
411
754
  const hadValue = entryHasValue(entry);
412
755
  const load = resource.load;
@@ -419,6 +762,7 @@ var DefaultDataStore = class {
419
762
  this.notifyEntryChange(entry);
420
763
  return Promise.resolve(unsupportedRefreshResult(entry));
421
764
  }
765
+ if (this.awaitedForms.has(entry.canonicalKey)) return this.parkLoad(entry, resource, args, options);
422
766
  const previousPending = entry.pending;
423
767
  const controller = new AbortController();
424
768
  const valueErrors = /* @__PURE__ */ new WeakSet();
@@ -432,10 +776,14 @@ var DefaultDataStore = class {
432
776
  this.notifyEntryChange(entry);
433
777
  if (controller.signal.aborted) return pending.promise;
434
778
  let loaded;
779
+ let missingCapability;
780
+ let threw = false;
435
781
  try {
436
782
  loaded = load(...args, this.createLoadContext(entry, controller, valueErrors));
437
783
  } catch (error) {
784
+ if (isMissingCapability(error)) missingCapability = error;
438
785
  loaded = Promise.reject(error);
786
+ threw = true;
439
787
  }
440
788
  const settleAborted = () => {
441
789
  const result = abortedRefreshResult(entry, "superseded");
@@ -444,6 +792,23 @@ var DefaultDataStore = class {
444
792
  };
445
793
  const fulfill = (value) => {
446
794
  if (entry.pending !== pending || controller.signal.aborted) return settleAborted();
795
+ const equals = resource.equals ?? Object.is;
796
+ let equal;
797
+ try {
798
+ equal = entryHasValue(entry) && equals(entry.value, value);
799
+ } catch (error) {
800
+ return reject(error);
801
+ }
802
+ if (equal) {
803
+ this.keepEqualValue(entry, entry.invalidationVersion !== invalidationVersion);
804
+ const result = {
805
+ status: "fulfilled",
806
+ value: entry.value
807
+ };
808
+ pending.resolve(result);
809
+ controller.abort("superseded");
810
+ return result;
811
+ }
447
812
  const superseded = entry.valueController;
448
813
  entry.valueController = controller;
449
814
  entry.valueErrors = valueErrors;
@@ -454,6 +819,7 @@ var DefaultDataStore = class {
454
819
  entry.stale = entry.invalidationVersion !== invalidationVersion;
455
820
  entry.status = "fulfilled";
456
821
  entry.value = value;
822
+ entry.transferred = false;
457
823
  const result = {
458
824
  status: "fulfilled",
459
825
  value
@@ -493,6 +859,11 @@ var DefaultDataStore = class {
493
859
  controller.abort(error);
494
860
  return result;
495
861
  };
862
+ if (missingCapability !== void 0) {
863
+ loaded.catch(() => void 0);
864
+ reject(missingCapability);
865
+ return pending.promise;
866
+ }
496
867
  let thenable;
497
868
  try {
498
869
  thenable = isThenable(loaded);
@@ -500,12 +871,32 @@ var DefaultDataStore = class {
500
871
  reject(error);
501
872
  return pending.promise;
502
873
  }
503
- if (thenable) Promise.resolve(loaded).then(fulfill, reject);
504
- else fulfill(loaded);
874
+ if (thenable) {
875
+ if (!threw) pending.returnedThenable = true;
876
+ Promise.resolve(loaded).then(fulfill, reject);
877
+ } else fulfill(loaded);
505
878
  return pending.promise;
506
879
  }
880
+ parkLoad(entry, resource, args, options) {
881
+ if (entry.pending !== null) return entry.pending.promise;
882
+ const parked = createPendingLoad(new AbortController());
883
+ entry.pending = parked;
884
+ entry.status = "pending";
885
+ entry.parkedLoad = () => {
886
+ if (entry.pending !== parked) return;
887
+ entry.pending = null;
888
+ this.startLoad(entry, resource, args, options).then(parked.resolve);
889
+ };
890
+ this.notifyEntryChange(entry);
891
+ return parked.promise;
892
+ }
507
893
  createLoadContext(entry, controller, valueErrors) {
508
- const context = { signal: controller.signal };
894
+ const context = {
895
+ data: this.dependentHandle(controller.signal),
896
+ signal: controller.signal,
897
+ transferred: entry.seed?.value
898
+ };
899
+ entry.seed = null;
509
900
  defineLoadContextCapabilities(context, {
510
901
  key: entry.key,
511
902
  attributeError: (error) => {
@@ -515,7 +906,7 @@ var DefaultDataStore = class {
515
906
  },
516
907
  hydrate: (entries) => {
517
908
  if (this.disposed || controller.signal.aborted) return;
518
- const foreign = entries.filter((hydrated) => this.storeKey(normalizeKey(hydrated.key).canonical) !== entry.storeKey);
909
+ const foreign = entries.filter((hydrated) => normalizeKey(hydrated.key).canonical !== entry.canonicalKey);
519
910
  if (foreign.length !== entries.length) warn(`Data rows targeting the loading key ${entry.canonicalKey} were skipped: a loader cannot hydrate its own entry.`);
520
911
  for (const hydrated of foreign) {
521
912
  if (controller.signal.aborted) return;
@@ -541,13 +932,14 @@ var DefaultDataStore = class {
541
932
  pending?.resolve(abortedRefreshResult(entry, reason));
542
933
  pending?.controller.abort(reason);
543
934
  valueController?.abort(reason);
935
+ this.stopWatch(entry, reason);
544
936
  }
545
937
  retainPreload(entry) {
546
938
  this.clearPreloadTimer(entry);
547
939
  if (this.disposed || !Number.isFinite(this.preloadRetentionMs)) return;
548
940
  entry.preloadTimer = scheduleStoreTimer(() => {
549
941
  entry.preloadTimer = null;
550
- if (entry.subscribers.size === 0 && entry.ensureRetainers === 0 && entry.pending !== null && !entryHasValue(entry)) {
942
+ if (!isHeld(entry) && entry.pending !== null && !entryHasValue(entry)) {
551
943
  this.evictEntry(entry, "evicted");
552
944
  return;
553
945
  }
@@ -555,19 +947,20 @@ var DefaultDataStore = class {
555
947
  }, Math.max(0, this.preloadRetentionMs));
556
948
  }
557
949
  scheduleInactiveCleanup(entry) {
558
- if (this.disposed || entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0 || !Number.isFinite(this.inactiveRetentionMs)) return;
950
+ const retention = entry.inactiveRetentionMs ?? this.inactiveRetentionMs;
951
+ if (this.disposed || isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null || !Number.isFinite(retention)) return;
559
952
  this.clearInactiveTimer(entry);
560
953
  entry.inactiveTimer = scheduleStoreTimer(() => {
561
954
  entry.inactiveTimer = null;
562
- if (entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0) return;
955
+ if (isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null) return;
563
956
  this.evictEntry(entry, "evicted");
564
- }, Math.max(0, this.inactiveRetentionMs));
957
+ }, Math.max(0, retention));
565
958
  }
566
959
  evictEntry(entry, reason) {
567
- if (this.entries.get(entry.storeKey) !== entry) return;
960
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
568
961
  this.clearInactiveTimer(entry);
569
962
  this.clearPreloadTimer(entry);
570
- this.entries.delete(entry.storeKey);
963
+ this.entries.delete(entry.canonicalKey);
571
964
  this.abortEntryGenerations(entry, reason);
572
965
  this.host.onEntryEvict?.(this.snapshotEntry(entry));
573
966
  }
@@ -596,12 +989,16 @@ var DefaultDataStore = class {
596
989
  stale: entry.stale,
597
990
  status: entry.status,
598
991
  subscriberCount: entry.subscribers.size,
599
- value: hasValue ? entry.value : void 0
992
+ value: hasValue ? entry.value : void 0,
993
+ ...entry.watchController === null ? {} : { watching: true }
600
994
  };
601
995
  }
602
996
  readCurrentValue(entry) {
603
997
  if (entryHasValue(entry)) return entry.value;
604
- if (entry.status === "rejected") throwDataResourceError(entry);
998
+ if (entry.status === "rejected") {
999
+ if (isMissingCapability(entry.error)) readBrowser(entry.error.reason);
1000
+ throwDataResourceError(entry);
1001
+ }
605
1002
  if (entry.pending === null) throw new Error(`Data resource "${entry.canonicalKey}" has no pending load.`);
606
1003
  throw entry.pending.promise;
607
1004
  }
@@ -616,6 +1013,7 @@ var DefaultDataStore = class {
616
1013
  entry.valueController = null;
617
1014
  entry.valueErrors = /* @__PURE__ */ new WeakSet();
618
1015
  entry.value = void 0;
1016
+ entry.transferred = false;
619
1017
  entry.error = void 0;
620
1018
  entry.status = "pending";
621
1019
  } else if (entry.status === "rejected") {
@@ -644,6 +1042,21 @@ function canonicalKeyStartsWith(key, prefix) {
644
1042
  const arrayPrefix = prefix.slice(0, -1);
645
1043
  return key.startsWith(arrayPrefix) && key[arrayPrefix.length] === ",";
646
1044
  }
1045
+ function isHeld(entry) {
1046
+ return entry.subscribers.size > 0 || (entry.retainers?.size ?? 0) > 0;
1047
+ }
1048
+ function transferValue(entry) {
1049
+ const transfer = entry.resource?.transfer;
1050
+ if (!entryHasValue(entry) || transfer === false) return void 0;
1051
+ if (entry.transferred || transfer === void 0) return { value: entry.value };
1052
+ const value = transfer(entry.value);
1053
+ return value === void 0 ? void 0 : { value };
1054
+ }
1055
+ function runParkedLoad(entry) {
1056
+ const run = entry.parkedLoad;
1057
+ entry.parkedLoad = null;
1058
+ run?.();
1059
+ }
647
1060
  function entryHasValue(entry) {
648
1061
  return entry.status === "fulfilled" || entry.status === "refreshing";
649
1062
  }
@@ -675,8 +1088,7 @@ function fingerprintFor(resource, args) {
675
1088
  }
676
1089
  }
677
1090
  function diagnoseEntryDrift(entry, resource, key, fingerprint) {
678
- if (entry.resource === null) entry.resource = resource;
679
- else if (entry.resource !== resource) warn(`Data resource key ${key} was read by multiple resource definitions.`);
1091
+ if (entry.resource !== null && entry.resource !== resource) warn(`Data resource key ${key} was read by multiple resource definitions.`);
680
1092
  if (entry.fingerprint !== null && fingerprint !== null && entry.fingerprint !== fingerprint) warn(`Data resource key ${key} was read with different argument fingerprints.`);
681
1093
  }
682
1094
  function warn(message) {
@@ -735,6 +1147,23 @@ function encodeValue(value, path) {
735
1147
  function isThenable(value) {
736
1148
  return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
737
1149
  }
1150
+ function untilAborted(promise, signal) {
1151
+ if (signal.aborted) return Promise.reject(signal.reason);
1152
+ return new Promise((resolve, reject) => {
1153
+ const abort = () => reject(signal.reason);
1154
+ signal.addEventListener("abort", abort, { once: true });
1155
+ promise.then((value) => {
1156
+ signal.removeEventListener("abort", abort);
1157
+ resolve(value);
1158
+ }, (error) => {
1159
+ signal.removeEventListener("abort", abort);
1160
+ reject(error);
1161
+ });
1162
+ });
1163
+ }
1164
+ function loaderReturnedThenable(entry) {
1165
+ return entry.pending?.returnedThenable === true;
1166
+ }
738
1167
  function createPendingLoad(controller) {
739
1168
  let resolve = () => void 0;
740
1169
  return {
@@ -807,6 +1236,6 @@ function setTransitionHandler(handler) {
807
1236
  return previous;
808
1237
  }
809
1238
  //#endregion
810
- 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 };
1239
+ export { isContext as C, createContext as S, markDataResourceError as _, createDataStore as a, setCurrentDataStore as b, dataResource as c, readDataStore as d, runWithDataStore as f, loadContextCapabilities as g, defineLoadContextCapabilities as h, attachDataStore as i, isDataStoreController as l, dataResourceKeysForError as m, setTransitionHandler as n, createRendererDataStore as o, MissingCapabilityError as p, transition as r, currentDataStore as s, runTransitionScope as t, normalizeDataResourceKey as u, requireCapability as v, FigContextSymbol as x, resolveCurrentDataStore as y };
811
1240
 
812
- //# sourceMappingURL=transition-CrIF0Kz_.js.map
1241
+ //# sourceMappingURL=transition-BZTyeaMo.js.map