@warp-drive/core 5.8.0-alpha.40 → 5.8.0-alpha.42

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 (95) hide show
  1. package/declarations/configure.d.ts +1 -1
  2. package/declarations/reactive/-private/default-mode.d.ts +1 -1
  3. package/declarations/reactive/-private/fields/extension.d.ts +1 -1
  4. package/declarations/reactive/-private/fields/managed-array.d.ts +2 -2
  5. package/declarations/reactive/-private/fields/managed-object.d.ts +1 -1
  6. package/declarations/reactive.d.ts +2 -3
  7. package/declarations/signals/-leaked.d.ts +2 -0
  8. package/declarations/signals/-private.d.ts +6 -0
  9. package/declarations/{store/-private/new-core-tmp → signals}/promise-state.d.ts +1 -1
  10. package/declarations/{store/-private/new-core-tmp → signals}/request-state.d.ts +5 -5
  11. package/declarations/{store/-private/new-core-tmp → signals}/request-subscription.d.ts +4 -4
  12. package/declarations/store/-private/cache-handler/types.d.ts +2 -16
  13. package/declarations/store/-private/managers/cache-manager.d.ts +1 -14
  14. package/declarations/store/-private/record-arrays/legacy-many-array.d.ts +1 -1
  15. package/declarations/store/-private/record-arrays/resource-array.d.ts +1 -1
  16. package/declarations/store/-private.d.ts +0 -5
  17. package/declarations/store/deprecated/-private.d.ts +1 -1
  18. package/declarations/types/schema/fields.d.ts +4 -4
  19. package/dist/configure-DPUFCemT.js +1940 -0
  20. package/dist/configure.js +2 -1
  21. package/dist/{request-oqoLC9rz.js → future-BKkJJkj7.js} +1 -48
  22. package/dist/graph/-private.js +3 -2
  23. package/dist/{index-BKcD4JZK.js → index-CQP2NSqg.js} +58 -1826
  24. package/dist/index.js +5 -5
  25. package/dist/reactive/-private.js +1 -1
  26. package/dist/reactive.js +4 -129
  27. package/dist/request.js +49 -1
  28. package/dist/signals/-leaked.js +1 -0
  29. package/dist/store/-private.js +1 -2
  30. package/dist/types/-private.js +1 -1
  31. package/dist/unpkg/dev/-leaked-Co0EI6Go.js +1939 -0
  32. package/dist/unpkg/dev/configure.js +1 -1
  33. package/dist/unpkg/dev/{request-CA9K0gXq.js → future-DFfOzSoe.js} +1 -48
  34. package/dist/unpkg/dev/graph/-private.js +3 -2
  35. package/dist/unpkg/dev/{index-DqhXrNZ_.js → index-CepUPZlc.js} +57 -1825
  36. package/dist/unpkg/dev/index.js +4 -4
  37. package/dist/unpkg/dev/reactive/-private.js +1 -1
  38. package/dist/unpkg/dev/reactive.js +3 -127
  39. package/dist/unpkg/dev/request.js +49 -1
  40. package/dist/unpkg/dev/signals/-leaked.js +1 -0
  41. package/dist/unpkg/dev/store/-private.js +2 -3
  42. package/dist/unpkg/dev/types/-private.js +1 -1
  43. package/dist/unpkg/dev-deprecated/-leaked-DjMeRqdU.js +1939 -0
  44. package/dist/unpkg/dev-deprecated/configure.js +1 -1
  45. package/dist/unpkg/dev-deprecated/{request-CA9K0gXq.js → future-DFfOzSoe.js} +1 -48
  46. package/dist/unpkg/dev-deprecated/graph/-private.js +3 -2
  47. package/dist/unpkg/dev-deprecated/{index-BBlq5is_.js → index-C_EEmn_3.js} +56 -1824
  48. package/dist/unpkg/dev-deprecated/index.js +2 -2
  49. package/dist/unpkg/dev-deprecated/reactive.js +2 -126
  50. package/dist/unpkg/dev-deprecated/request.js +49 -1
  51. package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -0
  52. package/dist/unpkg/dev-deprecated/store/-private.js +1 -2
  53. package/dist/unpkg/dev-deprecated/types/-private.js +1 -1
  54. package/dist/unpkg/prod/-leaked-DUONXQDB.js +1676 -0
  55. package/dist/unpkg/prod/{-private-3C1OkYtZ.js → -private-sql1_mdx.js} +1 -1
  56. package/dist/unpkg/prod/configure.js +2 -1
  57. package/dist/unpkg/prod/graph/-private.js +3 -2
  58. package/dist/unpkg/prod/{handler-LAyD1Y5l.js → handler-EU_8ncB2.js} +2 -2
  59. package/dist/unpkg/prod/index.js +7 -5
  60. package/dist/unpkg/prod/promise-cache-DIT8Ypjq.js +19 -0
  61. package/dist/unpkg/prod/reactive/-private.js +1 -1
  62. package/dist/unpkg/prod/reactive.js +26 -123
  63. package/dist/unpkg/prod/{request-CN2LxbYX.js → request-BrJSCG6r.js} +3 -19
  64. package/dist/unpkg/prod/request.js +2 -1
  65. package/dist/unpkg/prod/{promise-state-ipG60SdD.js → schema-BSkHyoWz.js} +53 -1572
  66. package/dist/unpkg/prod/signals/-leaked.js +1 -0
  67. package/dist/unpkg/prod/store/-private.js +3 -4
  68. package/dist/unpkg/prod/types/-private.js +1 -1
  69. package/dist/unpkg/prod-deprecated/-leaked-DRNv9VIX.js +1676 -0
  70. package/dist/unpkg/prod-deprecated/configure.js +2 -1
  71. package/dist/unpkg/prod-deprecated/graph/-private.js +3 -2
  72. package/dist/unpkg/prod-deprecated/{handler-D639oFvl.js → handler-CCIu4sQ3.js} +1 -1
  73. package/dist/unpkg/prod-deprecated/{hooks-DGvi9teJ.js → hooks-Dv4Np0MY.js} +1 -1
  74. package/dist/unpkg/prod-deprecated/index.js +7 -5
  75. package/dist/unpkg/prod-deprecated/promise-cache-DIT8Ypjq.js +19 -0
  76. package/dist/unpkg/prod-deprecated/reactive.js +4 -125
  77. package/dist/unpkg/prod-deprecated/{request-CN2LxbYX.js → request-BrJSCG6r.js} +3 -19
  78. package/dist/unpkg/prod-deprecated/request.js +2 -1
  79. package/dist/unpkg/prod-deprecated/{promise-state-CYvoIPna.js → schema-CJcjHv0E.js} +52 -1571
  80. package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -0
  81. package/dist/unpkg/prod-deprecated/store/-private.js +2 -3
  82. package/dist/unpkg/prod-deprecated/types/-private.js +1 -1
  83. package/package.json +3 -3
  84. package/declarations/store/-private/new-core-tmp/expensive-subscription.d.ts +0 -24
  85. package/dist/configure-C3x8YXzL.js +0 -181
  86. package/dist/unpkg/dev/configure-BC66sfNO.js +0 -183
  87. package/dist/unpkg/dev-deprecated/configure-BC66sfNO.js +0 -183
  88. package/dist/unpkg/prod/configure-C0C1LpG6.js +0 -158
  89. package/dist/unpkg/prod/hooks-BfiqDg3O.js +0 -26
  90. package/dist/unpkg/prod-deprecated/configure-BQ8CpIcW.js +0 -158
  91. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/configure.d.ts +0 -0
  92. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/internal.d.ts +0 -0
  93. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/signal.d.ts +0 -0
  94. /package/dist/{unpkg/dev/-private-3C1OkYtZ.js → symbols-3C1OkYtZ.js} +0 -0
  95. /package/dist/{symbols-sql1_mdx.js → unpkg/dev/-private-sql1_mdx.js} +0 -0
@@ -1,480 +1,17 @@
1
+ import { a as defineGate, c as withSignalStore, n as notifyInternalSignal, p as peekInternalSignal, j as willSyncFlushWatchers, k as getOrCreateInternalSignal, l as consumeInternalSignal, o as createInternalSignal, A as ARRAY_SIGNAL, S as Signals, q as createSignalDescriptor, b as defineSignal, e as entangleSignal, r as entangleInitiallyStaleSignal, O as OBJECT_SIGNAL, t as createInternalMemo, w as waitFor } from "./configure-DPUFCemT.js";
1
2
  import { deprecate, warn } from '@ember/debug';
2
3
  import { EnableHydration, SkipCache, STRUCTURED } from './types/request.js';
3
4
  import { macroCondition, getGlobalConfig, dependencySatisfies, importSync } from '@embroider/macros';
4
- import { D as Destroy, C as Context, S as SOURCE, a as Checkout, b as Commit } from "./symbols-sql1_mdx.js";
5
+ import { D as Destroy, a as Context, S as SOURCE, C as Checkout, b as Commit } from "./symbols-3C1OkYtZ.js";
5
6
  import { isResourceSchema } from './types/schema/fields.js';
6
- import { w as withBrand, g as getPromiseResult, s as setPromiseResult, c as cloneResponseProperties, I as IS_CACHE_HANDLER, a as assertValidRequest, e as executeNextHandler, b as getRequestResult, u as upgradePromise, d as clearRequestResult } from "./request-oqoLC9rz.js";
7
+ import { a as cloneResponseProperties, I as IS_CACHE_HANDLER, b as assertValidRequest, e as executeNextHandler, d as getRequestResult, u as upgradePromise, s as setPromiseResult, f as clearRequestResult } from "./future-BKkJJkj7.js";
7
8
  import { getOrSetGlobal, peekTransient, setTransient, peekUniversalTransient, setUniversalTransient } from './types/-private.js';
8
- import { c as createSignal, a as consumeSignal, n as notifySignal, b as createMemo, d as willSyncFlushWatchers, A as ARRAY_SIGNAL, O as OBJECT_SIGNAL, w as waitFor } from "./configure-C3x8YXzL.js";
9
+ import { D as DefaultCachePolicy } from "./default-cache-policy-D7_u4YRH.js";
10
+ import { withBrand } from './request.js';
9
11
  import { CACHE_OWNER, DEBUG_STALE_CACHE_OWNER, DEBUG_KEY_TYPE, DEBUG_CLIENT_ORIGINATED } from './types/identifier.js';
10
12
  import { dasherize } from './utils/string.js';
11
- import { D as DefaultCachePolicy } from "./default-cache-policy-D7_u4YRH.js";
12
13
  import { setLogging, getRuntimeConfig } from './types/runtime.js';
13
14
  import { RecordStore, Type } from './types/symbols.js';
14
- const INITIALIZER_PROTO = {
15
- isInitializer: true
16
- };
17
- function makeInitializer(fn) {
18
- // we use a prototype to ensure that the initializer is not enumerable
19
- // and does not interfere with the signal's value.
20
- return Object.assign(Object.create(INITIALIZER_PROTO), {
21
- value: fn
22
- });
23
- }
24
- function isInitializer(obj) {
25
- return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === INITIALIZER_PROTO;
26
- }
27
-
28
- /**
29
- * A WarpDriveSignal is a wrapper around a framework specific or TC39 signal
30
- * that enables us to store and manage the signal in a universal way.
31
- *
32
- * WarpDrive uses signals to manage three separate concepts:
33
- *
34
- * - as a `storage` for a value local to the object that we want to be reactive
35
- * (see `@local` schema field for an example)
36
- * - as a `gate` for a memoized getter that we want to act as a reactive property
37
- * but whose value is computed/pulled from a non-reactive source elsewhere
38
- * and whose latest value is stored in the signal
39
- * (see `field` schema field for an example)
40
- * - as a `gate` with a manually managed value updated on pull when `isStale` is true
41
- *
42
- *
43
- * It offers
44
- *
45
- * - a non-reactive way to access/update the current value
46
- * - a non-reactive way to mark the signal as dirtied
47
- * - a non-reactive way to store content for why the signal was dirtied
48
- * - access to the underlying Signal(s) in-use
49
- *
50
- * For debugging:
51
- * - the "key" or "name" of the signal
52
- * - the "object identity" or "context" to which the signal is attached
53
- *
54
- * @private
55
- */
56
-
57
- /**
58
- * We attach signals to their context object via
59
- * a Map attached to the object via this symbol.
60
- *
61
- * This allows us to store multiple signals
62
- * on the same object with smaller memory
63
- * overhead and no WeakMap lookups.
64
- *
65
- * Performance sensitive objects should
66
- * pre-warm their shape by assigning this
67
- * during initialization.
68
- *
69
- * ```ts
70
- * initializeSignalStore(obj);
71
- * ```
72
- *
73
- * @private
74
- */
75
- const Signals = getOrSetGlobal('Signals', Symbol('Signals'));
76
-
77
- /**
78
- * A util that will create a signal store on the object
79
- * if it does not already exist and returns the associated
80
- * signal store.
81
- *
82
- * @private
83
- */
84
- function withSignalStore(obj) {
85
- if (!obj[Signals]) {
86
- initializeSignalStore(obj);
87
- }
88
- return obj[Signals];
89
- }
90
-
91
- /**
92
- * A util that will create a signal store on the object
93
- * if it does not already exist.
94
- *
95
- * Useful for pre-warming the shape of an object to ensure
96
- * a key-transition to add it is not required later.
97
- *
98
- * @private
99
- */
100
- function initializeSignalStore(obj) {
101
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
102
- if (!test) {
103
- throw new Error(`Signal store already exists on object`);
104
- }
105
- })(!obj[Signals]) : {};
106
- obj[Signals] = new Map();
107
- }
108
- function createInternalSignal(signals, obj, key, initialValue) {
109
- const warpDriveSignal = {
110
- key,
111
- context: obj,
112
- signal: createSignal(obj, key),
113
- value: isInitializer(initialValue) ? initialValue.value.call(obj) : initialValue,
114
- isStale: false
115
- };
116
- signals.set(key, warpDriveSignal);
117
- return warpDriveSignal;
118
- }
119
- function getOrCreateInternalSignal(signals, obj, key, initialValue) {
120
- let signal = peekInternalSignal(signals, key);
121
- if (!signal) {
122
- signal = createInternalSignal(signals, obj, key, initialValue);
123
- }
124
- return signal;
125
- }
126
- function createInternalMemo(signals, object, key, fn) {
127
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
128
- if (!test) {
129
- throw new Error(`Expected no signal/memo to exist for key "${String(key)}"`);
130
- }
131
- })(!peekInternalSignal(signals, key)) : {};
132
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
133
- return withFrame(signals, object, key, fn);
134
- } else {
135
- const memo = createMemo(object, key, fn);
136
- signals.set(key, memo);
137
- return memo;
138
- }
139
- }
140
- function peekInternalSignal(signals, key) {
141
- return signals?.get(key);
142
- }
143
- function consumeInternalSignal(signal) {
144
- TrackingFrame?.signals.add(signal);
145
- consumeSignal(signal.signal);
146
- }
147
- function notifyInternalSignal(signal) {
148
- if (signal) {
149
- signal.isStale = true;
150
- notifySignal(signal.signal);
151
- }
152
- }
153
- let TrackingFrame = null;
154
-
155
- /**
156
- * This is currently just for signals debugging, but it could be used in production
157
- * if we wanted to eliminate the need for frameworks to implement createMemo / to
158
- * allow us to add our own Watcher.
159
- *
160
- * @internal
161
- */
162
- function withFrame(signals, object, key, fn) {
163
- const frameSignals = new Set();
164
- const frameFn = () => {
165
- if (frameSignals.size) {
166
- frameSignals.clear();
167
- }
168
- TrackingFrame = {
169
- object,
170
- key,
171
- signals: frameSignals,
172
- parent: TrackingFrame
173
- };
174
- try {
175
- return fn();
176
- } finally {
177
- TrackingFrame = TrackingFrame.parent;
178
- }
179
- };
180
- const memo = createMemo(object, key, frameFn);
181
- // @ts-expect-error
182
- memo.signals = frameSignals;
183
- signals.set(key, memo);
184
- return memo;
185
- }
186
- function isMemo(obj) {
187
- // @ts-expect-error
188
- return typeof obj === 'function' && obj.signals instanceof Set;
189
- }
190
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
191
- // @ts-expect-error adding to global API
192
- globalThis.debugWarpDriveSignals = (obj, key) => {
193
- const signals = obj[Signals];
194
- if (!signals) {
195
- log$1('The object has no associated signals');
196
- return false;
197
- }
198
- if (key) {
199
- const signal = signals.get(key);
200
- if (!signal) {
201
- log$1(`No signal found for key "${String(key)}"`);
202
- return false;
203
- }
204
- log$1(signal);
205
- if (isMemo(signal)) {
206
- colorizeLines(printMemo(signal, key));
207
- return true;
208
- } else {
209
- colorizeLines(printSignal(signal, key));
210
- return true;
211
- }
212
- }
213
- const lines = [];
214
- for (const [k, signal] of signals) {
215
- if (isMemo(signal)) continue;
216
- printSignal(signal, k, lines);
217
- }
218
- for (const [k, signal] of signals) {
219
- if (isMemo(signal)) {
220
- printMemo(signal, k, lines);
221
- }
222
- }
223
- log$1(signals);
224
- colorizeLines(lines);
225
- return true;
226
- };
227
- }
228
- const LightColors = {
229
- red: 'color: red;',
230
- green: 'color: green;',
231
- reset: 'color: inherit;'
232
- };
233
- const DarkColors = {
234
- red: 'color: red;',
235
- green: 'color: lightgreen;',
236
- reset: 'color: inherit;'
237
- };
238
- function isLightMode$1() {
239
- if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {
240
- return true;
241
- }
242
- return false;
243
- }
244
- const RED = {};
245
- const GREEN = {};
246
- const RESET = {};
247
- const EOL = {};
248
- function colorizeLines(lines) {
249
- const Colors = isLightMode$1() ? LightColors : DarkColors;
250
- const colors = [];
251
- let line = '';
252
- for (const str of lines) {
253
- if (str === RED) {
254
- colors.push(Colors.red);
255
- line += '%c';
256
- } else if (str === GREEN) {
257
- colors.push(Colors.green);
258
- line += '%c';
259
- } else if (str === RESET) {
260
- colors.push(Colors.reset);
261
- line += '%c';
262
- } else if (str === EOL) {
263
- line += '\n';
264
- } else {
265
- line += str;
266
- }
267
- }
268
- log$1(line, ...colors);
269
- }
270
- function log$1(...args) {
271
- // eslint-disable-next-line no-console
272
- console.log(...args);
273
- }
274
- function isDirty(signal) {
275
- return signal.isStale;
276
- }
277
- function isDirtyMemo(memo) {
278
- // iterate simple signals first to get fastest answer
279
- for (const signal of memo.signals) {
280
- if (isMemo(signal)) continue;
281
- if (isDirty(signal)) {
282
- return true;
283
- }
284
- }
285
- for (const signal of memo.signals) {
286
- if (isMemo(signal)) {
287
- return isDirtyMemo(signal);
288
- }
289
- }
290
- return false;
291
- }
292
- function printSignal(signal, key, lines = [], depth = 0) {
293
- const _dirty = isDirty(signal);
294
- lines.push(`${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `, _dirty ? RED : GREEN, `${String(key)}`, RESET, EOL);
295
- return lines;
296
- }
297
- function printMemo(memo, key, lines = [], depth = 0) {
298
- const _dirty = isDirtyMemo(memo);
299
- lines.push(`${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `, _dirty ? RED : GREEN, `<memo> ${String(key)}`, RESET, `: (consumes ${memo.signals.size} signals)`, EOL);
300
- for (const signal of memo.signals) {
301
- if (isMemo(signal)) continue;
302
- printSignal(signal, signal.key, lines, depth + 1);
303
- }
304
- for (const signal of memo.signals) {
305
- if (isMemo(signal)) {
306
- printMemo(signal, signal.key, lines, depth + 1);
307
- }
308
- }
309
- return lines;
310
- }
311
- function entangleSignal(signals, obj, key, initialValue) {
312
- let internalSignal = peekInternalSignal(signals, key);
313
- if (!internalSignal) {
314
- internalSignal = createInternalSignal(signals, obj, key, initialValue);
315
- }
316
- consumeInternalSignal(internalSignal);
317
- return internalSignal;
318
- }
319
- function entangleInitiallyStaleSignal(signals, obj, key, initialValue) {
320
- let internalSignal = peekInternalSignal(signals, key);
321
- if (!internalSignal) {
322
- internalSignal = createInternalSignal(signals, obj, key, initialValue);
323
- internalSignal.isStale = true; // mark it as stale
324
- }
325
- consumeInternalSignal(internalSignal);
326
- return internalSignal;
327
- }
328
- function createSignalDescriptor(key, intialValue) {
329
- return {
330
- enumerable: true,
331
- configurable: false,
332
- get() {
333
- const signals = withSignalStore(this);
334
- const internalSignal = entangleSignal(signals, this, key, intialValue);
335
- internalSignal.isStale = false; // reset stale state
336
- return internalSignal.value;
337
- },
338
- set(value) {
339
- const signals = withSignalStore(this);
340
- const internalSignal = getOrCreateInternalSignal(signals, this, key, intialValue);
341
- if (internalSignal.value !== value) {
342
- internalSignal.value = value;
343
- notifyInternalSignal(internalSignal);
344
- }
345
- }
346
- };
347
- }
348
-
349
- /**
350
- * define an enumerable signal property.
351
- *
352
- * Akin to Object.defineProperty.
353
- *
354
- * The signal will be lazily created when accessed and scoped to the
355
- * instance of the object.
356
- *
357
- * @private
358
- */
359
- function defineSignal(obj, key, v) {
360
- Object.defineProperty(obj, key, createSignalDescriptor(key, v));
361
- }
362
-
363
- /**
364
- * Define a non-enumerable signal property.
365
- *
366
- * @private
367
- */
368
- function defineNonEnumerableSignal(obj, key, v) {
369
- const desc = createSignalDescriptor(key, v);
370
- desc.enumerable = false;
371
- Object.defineProperty(obj, key, desc);
372
- }
373
- /**
374
- * Decorator version of creating a signal.
375
- */
376
- function signal(target, key, descriptor) {
377
- // Error on `@signal()`, `@signal(...args)``
378
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
379
- if (!test) {
380
- throw new Error('You attempted to use @signal(), which is not necessary nor supported. Remove the parentheses and you will be good to go!');
381
- }
382
- })(target !== undefined) : {};
383
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
384
- if (!test) {
385
- throw new Error(`You attempted to use @signal on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @signal(${Array.from(arguments).map(d => `'${d}'`).join(', ')}) ), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@signal`'}`);
386
- }
387
- })(typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3) : {};
388
- return createSignalDescriptor(key, descriptor.initializer ? makeInitializer(descriptor.initializer) : null);
389
- }
390
-
391
- /**
392
- * Decorator version of creating a memoized getter
393
- */
394
- function memoized(target, key, descriptor) {
395
- // Error on `@memoized()`, `@memoized(...args)`, and `@memoized propName = value;`
396
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
397
- if (!test) {
398
- throw new Error('You attempted to use @memoized(), which is not necessary nor supported. Remove the parentheses and you will be good to go!');
399
- }
400
- })(target !== undefined) : {};
401
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
402
- if (!test) {
403
- throw new Error(`You attempted to use @memoized on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @memoized(${Array.from(arguments).map(d => `'${d}'`).join(', ')}), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@memoized`'}`);
404
- }
405
- })(typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3) : {};
406
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
407
- if (!test) {
408
- throw new Error(`The @memoized decorator must be applied to getters. '${key}' is not a getter.`);
409
- }
410
- })(typeof descriptor.get === 'function') : {};
411
-
412
- // eslint-disable-next-line @typescript-eslint/unbound-method
413
- const getter = descriptor.get;
414
- descriptor.get = function () {
415
- const signals = withSignalStore(this);
416
- let memoSignal = signals.get(key);
417
- if (!memoSignal) {
418
- memoSignal = createInternalMemo(signals, this, key, getter.bind(this));
419
- }
420
- return memoSignal();
421
- };
422
- return descriptor;
423
- }
424
-
425
- /**
426
- * Decorator version of creating a gate.
427
- *
428
- * @private
429
- */
430
- function gate(_target, key, desc) {
431
- // eslint-disable-next-line @typescript-eslint/unbound-method
432
- const getter = desc.get;
433
- // eslint-disable-next-line @typescript-eslint/unbound-method
434
- const setter = desc.set;
435
- const isLocal = desc.isLocal;
436
- desc.get = function () {
437
- const signals = withSignalStore(this);
438
- let internalSignal = peekInternalSignal(signals, key);
439
- if (!internalSignal) {
440
- internalSignal = createInternalSignal(signals, this, key, getter.call(this));
441
- } else if (internalSignal.isStale) {
442
- internalSignal.isStale = false;
443
- internalSignal.value = getter.call(this);
444
- }
445
- consumeInternalSignal(internalSignal);
446
- return internalSignal.value;
447
- };
448
- if (setter) {
449
- desc.set = function (v) {
450
- const signals = withSignalStore(this);
451
- let internalSignal = peekInternalSignal(signals, key);
452
- if (!internalSignal) {
453
- // we can't use `v` as initialValue here because setters don't
454
- // return the value and the final value may be different
455
- // than what the setter was called with.
456
- internalSignal = createInternalSignal(signals, this, key, undefined);
457
- internalSignal.isStale = true;
458
- }
459
- setter.call(this, v);
460
- // when a gate is set, we do not notify the signal
461
- // as its update is controlled externally.
462
- // unless it specifically sets itself to be locally managed
463
- if (isLocal) {
464
- internalSignal.isStale = true;
465
- notifyInternalSignal(internalSignal);
466
- }
467
- };
468
- }
469
- return desc;
470
- }
471
- function defineGate(obj, key, desc) {
472
- const options = Object.assign({
473
- enumerable: true,
474
- configurable: false
475
- }, gate(obj, key, desc));
476
- Object.defineProperty(obj, key, options);
477
- }
478
15
  function urlFromLink(link) {
479
16
  if (typeof link === 'string') return link;
480
17
  return link.href;
@@ -2290,8 +1827,6 @@ class CacheManager {
2290
1827
  * a `content` member and therefor must not assume the existence
2291
1828
  * of `request` and `response` on the document.
2292
1829
  *
2293
- * @param {StructuredDocument} doc
2294
- * @return {ResourceDocument}
2295
1830
  * @public
2296
1831
  */
2297
1832
  put(doc) {
@@ -2303,7 +1838,6 @@ class CacheManager {
2303
1838
  *
2304
1839
  * @public
2305
1840
  * @param op the operation to perform
2306
- * @return {void}
2307
1841
  */
2308
1842
  patch(op) {
2309
1843
  this.___cache.patch(op);
@@ -2314,7 +1848,6 @@ class CacheManager {
2314
1848
  * on relationships only.
2315
1849
  *
2316
1850
  * @public
2317
- * @param mutation
2318
1851
  */
2319
1852
  mutate(mutation) {
2320
1853
  this.___cache.mutate(mutation);
@@ -2348,8 +1881,7 @@ class CacheManager {
2348
1881
  * notifications for relational data.
2349
1882
  *
2350
1883
  * @public
2351
- * @param {ResourceKey | RequestKey} cacheKey
2352
- * @return {ResourceDocument | ResourceBlob | null} the known resource data
1884
+ * @return the known resource data
2353
1885
  */
2354
1886
 
2355
1887
  peek(cacheKey) {
@@ -2362,8 +1894,6 @@ class CacheManager {
2362
1894
  * Peek the Cache for the existing request data associated with
2363
1895
  * a cacheable request
2364
1896
  *
2365
- * @param {RequestKey}
2366
- * @return {RequestKey | null}
2367
1897
  * @public
2368
1898
  */
2369
1899
  peekRequest(key) {
@@ -2391,7 +1921,6 @@ class CacheManager {
2391
1921
  * utilize this method to fork the cache.
2392
1922
  *
2393
1923
  * @public
2394
- * @return {Promise<Cache>}
2395
1924
  */
2396
1925
  fork() {
2397
1926
  return this.___cache.fork();
@@ -2404,9 +1933,7 @@ class CacheManager {
2404
1933
  * preferring instead to merge at the Store level, which will
2405
1934
  * utilize this method to merge the caches.
2406
1935
  *
2407
- * @param {Cache} cache
2408
1936
  * @public
2409
- * @return {Promise<void>}
2410
1937
  */
2411
1938
  merge(cache) {
2412
1939
  return this.___cache.merge(cache);
@@ -2456,7 +1983,6 @@ class CacheManager {
2456
1983
  * which may be fed back into a new instance of the same Cache
2457
1984
  * via `cache.hydrate`.
2458
1985
  *
2459
- * @return {Promise<ReadableStream>}
2460
1986
  * @public
2461
1987
  */
2462
1988
  dump() {
@@ -2475,8 +2001,6 @@ class CacheManager {
2475
2001
  * behavior supports optimizing pre/fetching of data for route transitions
2476
2002
  * via data-only SSR modes.
2477
2003
  *
2478
- * @param {ReadableStream} stream
2479
- * @return {Promise<void>}
2480
2004
  * @public
2481
2005
  */
2482
2006
  hydrate(stream) {
@@ -4480,7 +4004,7 @@ class RequestStateService {
4480
4004
  */
4481
4005
 
4482
4006
  // this import location is deprecated but breaks in 4.8 and older
4483
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
4007
+ if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
4484
4008
  // @ts-expect-error adding to globalThis
4485
4009
  globalThis.setWarpDriveLogging = setLogging;
4486
4010
 
@@ -5902,7 +5426,7 @@ class RecordReference {
5902
5426
  simplest usage of this API is similar to `store.push`: you provide a
5903
5427
  normalized hash of data and the object represented by the reference
5904
5428
  will update.
5905
- If you pass a promise to `push`, Ember Data will not ask the adapter
5429
+ If you pass a promise to `push`, WarpDrive will not ask the adapter
5906
5430
  for the data if another attempt to fetch it is made in the
5907
5431
  interim. When the promise resolves, the underlying object is updated
5908
5432
  with the new data, and the promise returned by *this function* is resolved
@@ -7210,1184 +6734,59 @@ function mutate(collection, mutation, _SIGNAL) {
7210
6734
  manager.mutate(mutation);
7211
6735
  notifyInternalSignal(_SIGNAL);
7212
6736
  }
7213
- function decorateMethodV2(prototype, prop, decorators) {
7214
- const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
7215
- let desc = {
7216
- ...origDesc
7217
- };
7218
- for (let decorator of decorators) {
7219
- desc = decorator(prototype, prop, desc) || desc;
7220
- }
7221
- if (desc.initializer !== void 0) {
7222
- desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
7223
- desc.initializer = void 0;
7224
- }
7225
- Object.defineProperty(prototype, prop, desc);
6737
+ function getAliasField(context) {
6738
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
6739
+ {
6740
+ throw new Error(`Alias field access is not implemented`);
6741
+ }
6742
+ })() : {};
7226
6743
  }
7227
-
7228
- // default to 30 seconds unavailable before we refresh
7229
- const DEFAULT_DEADLINE = 30_000;
7230
- const DISPOSE = Symbol.dispose || Symbol.for('dispose');
7231
- function isNeverString(val) {
7232
- return val;
6744
+ function setAliasField(context) {
6745
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
6746
+ {
6747
+ throw new Error(`Alias field setting is not implemented`);
6748
+ }
6749
+ })() : {};
6750
+ return false;
6751
+ }
6752
+ const ARRAY_GETTER_METHODS = new Set([Symbol.iterator, 'concat', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'flat', 'flatMap', 'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'reduce', 'reduceRight', 'slice', 'some', 'values']);
6753
+ // const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
6754
+ const SYNC_PROPS = new Set(['[]', 'length']);
6755
+ function isArrayGetter(prop) {
6756
+ return ARRAY_GETTER_METHODS.has(prop);
6757
+ }
6758
+ const ARRAY_SETTER_METHODS = new Set(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
6759
+ function isArraySetter(prop) {
6760
+ return ARRAY_SETTER_METHODS.has(prop);
7233
6761
  }
7234
6762
 
7235
- /**
7236
- * Utilities to assist in recovering from the error.
7237
- */
7238
-
7239
- /** @deprecated use {@link RecoveryFeatures} */
7240
-
7241
- /**
7242
- * Utilities for keeping the request fresh
7243
- */
7244
-
7245
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
7246
-
7247
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
7248
-
7249
- /**
7250
- * A reactive class
7251
- *
7252
- * @hideconstructor
7253
- */
7254
- class RequestSubscription {
7255
- /**
7256
- * Whether the browser reports that the network is online.
7257
- */
7258
-
7259
- /**
7260
- * Whether the browser reports that the tab is hidden.
7261
- */
6763
+ // function isSelfProp<T extends object>(self: T, prop: KeyType): prop is keyof T {
6764
+ // return prop in self;
6765
+ // }
7262
6766
 
7263
- /**
7264
- * Whether the component is currently refreshing the request.
7265
- */
6767
+ function convertToInt(prop) {
6768
+ if (typeof prop === 'symbol') return null;
6769
+ const num = Number(prop);
6770
+ if (isNaN(num)) return null;
6771
+ return num % 1 === 0 ? num : null;
6772
+ }
6773
+ function safeForEach(instance, arr, store, callback, target) {
6774
+ if (target === undefined) {
6775
+ target = null;
6776
+ }
6777
+ // clone to prevent mutation
6778
+ arr = arr.slice();
6779
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
6780
+ if (!test) {
6781
+ throw new Error('`forEach` expects a function as first argument.');
6782
+ }
6783
+ })(typeof callback === 'function') : {};
7266
6784
 
7267
- /**
7268
- * The most recent blocking request that was made, typically
7269
- * the result of a reload.
7270
- *
7271
- * This will never be the original request passed as an arg to
7272
- * the component.
7273
- *
7274
- * @internal
7275
- */
7276
-
7277
- /**
7278
- * The most recent request that was made, typically due to either a
7279
- * reload or a refresh.
7280
- *
7281
- * This will never be the original request passed as an arg to
7282
- * the component.
7283
- *
7284
- * @internal
7285
- */
7286
-
7287
- /**
7288
- * The time at which the network was reported as offline.
7289
- *
7290
- * @internal
7291
- */
7292
-
7293
- /** @internal */
7294
-
7295
- /** @internal */
7296
-
7297
- /** @internal */
7298
-
7299
- /** @internal */
7300
-
7301
- /** @internal */
7302
-
7303
- /**
7304
- * The event listener for network status changes,
7305
- * cached to use the reference for removal.
7306
- *
7307
- * @internal
7308
- */
7309
-
7310
- /**
7311
- * The event listener for visibility status changes,
7312
- * cached to use the reference for removal.
7313
- *
7314
- * @internal
7315
- */
7316
-
7317
- /**
7318
- * The last request passed as an arg to the component,
7319
- * cached for comparison.
7320
- *
7321
- * @internal
7322
- */
7323
-
7324
- /**
7325
- * The last query passed as an arg to the component,
7326
- * cached for comparison.
7327
- *
7328
- * @internal
7329
- */
7330
-
7331
- /** @internal */
7332
-
7333
- /** @internal */
7334
-
7335
- /** @internal */
7336
-
7337
- /**
7338
- * The Store this subscription subscribes to or the RequestManager
7339
- * which issues this request.
7340
- */
7341
-
7342
- /**
7343
- * The Store or RequestManager that the last subscription is attached to.
7344
- *
7345
- * This differs from 'store' because a <Request /> may be passed a
7346
- * request originating from a different store than the <Request />
7347
- * component would use if it were to issue the request itself.
7348
- *
7349
- * @internal
7350
- */
7351
- _requester;
7352
- constructor(store, args) {
7353
- this._args = args;
7354
- this.store = store;
7355
- this._subscribedTo = null;
7356
- this._subscription = null;
7357
- this._intervalStart = null;
7358
- this._invalidated = false;
7359
- this._nextInterval = null;
7360
- this._requester = null;
7361
- this.isDestroyed = false;
7362
- this[DISPOSE] = _DISPOSE;
7363
- this._installListeners();
7364
- void this._beginPolling();
7365
- }
7366
-
7367
- /**
7368
- * @internal
7369
- */
7370
- async _beginPolling() {
7371
- // await the initial request
7372
- try {
7373
- if (!this.isIdle) {
7374
- await this.request;
7375
- }
7376
- } catch {
7377
- // ignore errors here, we just want to wait for the request to finish
7378
- } finally {
7379
- if (!this.isDestroyed) {
7380
- void this._scheduleInterval();
7381
- }
7382
- }
7383
- }
7384
- get isIdle() {
7385
- const {
7386
- request,
7387
- query
7388
- } = this._args;
7389
- return Boolean(!request && !query);
7390
- }
7391
- static {
7392
- decorateMethodV2(this.prototype, "isIdle", [memoized]);
7393
- }
7394
- get autorefreshTypes() {
7395
- const {
7396
- autorefresh
7397
- } = this._args;
7398
- let types;
7399
- if (autorefresh === true) {
7400
- types = ['online', 'invalid'];
7401
- } else if (typeof autorefresh === 'string') {
7402
- types = autorefresh.split(',');
7403
- } else {
7404
- types = [];
7405
- }
7406
- return new Set(types);
7407
- }
7408
-
7409
- // we only run this function on component creation
7410
- // and when an update is triggered, so it does not
7411
- // react to changes in the autorefreshThreshold
7412
- // or autorefresh args.
7413
- //
7414
- // if we need to react to those changes, we can
7415
- // use a modifier or internal component or some
7416
- // such to trigger a re-run of this function.
7417
- /** @internal */
7418
- static {
7419
- decorateMethodV2(this.prototype, "autorefreshTypes", [memoized]);
7420
- }
7421
- async _scheduleInterval() {
7422
- const {
7423
- autorefreshThreshold
7424
- } = this._args;
7425
- const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;
7426
- if (
7427
- // dont schedule in SSR
7428
- typeof window === 'undefined' ||
7429
- // dont schedule without a threshold
7430
- !hasValidThreshold ||
7431
- // dont schedule if we weren't told to
7432
- !this.autorefreshTypes.has('interval') ||
7433
- // dont schedule if we're already scheduled
7434
- this._intervalStart !== null) {
7435
- return;
7436
- }
7437
-
7438
- // if we have a current request, wait for it to finish
7439
- // before scheduling the next one
7440
- if (this._latestRequest) {
7441
- try {
7442
- await this._latestRequest;
7443
- } catch {
7444
- // ignore errors here, we just want to wait for the request to finish
7445
- }
7446
- if (this.isDestroyed) {
7447
- return;
7448
- }
7449
- }
7450
-
7451
- // setup the next interval
7452
- this._intervalStart = Date.now();
7453
- this._nextInterval = setTimeout(() => {
7454
- this._maybeUpdate();
7455
- }, autorefreshThreshold);
7456
- }
7457
-
7458
- /** @internal */
7459
- _clearInterval() {
7460
- if (this._nextInterval) {
7461
- clearTimeout(this._nextInterval);
7462
- this._intervalStart = null;
7463
- }
7464
- }
7465
- /**
7466
- * @internal
7467
- */
7468
- _updateSubscriptions() {
7469
- if (this.isIdle) {
7470
- return;
7471
- }
7472
- const requestId = this._request.lid;
7473
-
7474
- // if we're already subscribed to this request, we don't need to do anything
7475
- if (this._subscribedTo === requestId) {
7476
- return;
7477
- }
7478
-
7479
- // if we're subscribed to a different request, we need to unsubscribe
7480
- this._removeSubscriptions();
7481
-
7482
- // if we have a request, we need to subscribe to it
7483
- const store = this._getRequester();
7484
- this._requester = store;
7485
- if (requestId && isStore(store)) {
7486
- this._subscribedTo = requestId;
7487
- this._subscription = store.notifications.subscribe(requestId, (_id, op) => {
7488
- // ignore subscription events that occur while our own component's request
7489
- // is occurring
7490
- if (this._isUpdating) {
7491
- return;
7492
- }
7493
- switch (op) {
7494
- case 'invalidated':
7495
- {
7496
- // if we're subscribed to invalidations, we need to update
7497
- if (this.autorefreshTypes.has('invalid')) {
7498
- this._invalidated = true;
7499
- this._maybeUpdate();
7500
- }
7501
- break;
7502
- }
7503
- case 'state':
7504
- {
7505
- const latest = store.requestManager._deduped.get(requestId);
7506
- const priority = latest?.priority;
7507
- const state = this.reqState;
7508
- if (!priority) {
7509
- // if there is no priority, we have completed whatever request
7510
- // was occurring and so we are no longer refreshing (if we were)
7511
- this.isRefreshing = false;
7512
- } else if (priority.blocking && !state.isLoading) {
7513
- // if we are blocking, there is an active request for this identity
7514
- // that MUST be fulfilled from network (not cache).
7515
- // Thus this is not "refreshing" because we should clear out and
7516
- // block on this request.
7517
- //
7518
- // we receive state notifications when either a request initiates
7519
- // or completes.
7520
- //
7521
- // In the completes case: we may receive the state notification
7522
- // slightly before the request is finalized because the NotificationManager
7523
- // may sync flush it (and thus deliver it before the microtask completes)
7524
- //
7525
- // In the initiates case: we aren't supposed to receive one unless there
7526
- // is no other request in flight for this identity.
7527
- //
7528
- // However, there is a race condition here where the completed
7529
- // notification can trigger an update that generates a new request
7530
- // thus giving us an initiated notification before the older request
7531
- // finalizes.
7532
- //
7533
- // When this occurs, if the triggered update happens to have caused
7534
- // a new request to be made for the same identity AND that request
7535
- // is the one passed into this component as the @request arg, then
7536
- // getRequestState will return the state of the new request.
7537
- // We can detect this by checking if the request state is "loading"
7538
- // as outside of this case we would have a completed request.
7539
- //
7540
- // That is the reason for the `&& !state.isLoading` check above.
7541
-
7542
- // TODO should we just treat this as refreshing?
7543
- this.isRefreshing = false;
7544
- this._maybeUpdate('policy', true);
7545
- } else {
7546
- this.isRefreshing = true;
7547
- }
7548
- }
7549
- }
7550
- });
7551
- }
7552
- }
7553
-
7554
- /**
7555
- * @internal
7556
- */
7557
- _removeSubscriptions() {
7558
- const store = this._requester;
7559
- if (this._subscription && store && isStore(store)) {
7560
- store.notifications.unsubscribe(this._subscription);
7561
- this._subscribedTo = null;
7562
- this._subscription = null;
7563
- this._requester = null;
7564
- }
7565
- }
7566
-
7567
- /**
7568
- * Install the event listeners for network and visibility changes.
7569
- * This is only done in browser environments with a global `window`.
7570
- *
7571
- * @internal
7572
- */
7573
- _installListeners() {
7574
- if (typeof window === 'undefined') {
7575
- return;
7576
- }
7577
- this.isOnline = window.navigator.onLine;
7578
- this._unavailableStart = this.isOnline ? null : Date.now();
7579
- this.isHidden = document.visibilityState === 'hidden';
7580
- this._onlineChanged = event => {
7581
- this.isOnline = event.type === 'online';
7582
- if (event.type === 'offline' && this._unavailableStart === null) {
7583
- this._unavailableStart = Date.now();
7584
- }
7585
- this._maybeUpdate();
7586
- };
7587
- this._backgroundChanged = () => {
7588
- const isHidden = document.visibilityState === 'hidden';
7589
- this.isHidden = isHidden;
7590
- if (isHidden && this._unavailableStart === null) {
7591
- this._unavailableStart = Date.now();
7592
- }
7593
- this._maybeUpdate();
7594
- };
7595
- window.addEventListener('online', this._onlineChanged, {
7596
- passive: true,
7597
- capture: true
7598
- });
7599
- window.addEventListener('offline', this._onlineChanged, {
7600
- passive: true,
7601
- capture: true
7602
- });
7603
- document.addEventListener('visibilitychange', this._backgroundChanged, {
7604
- passive: true,
7605
- capture: true
7606
- });
7607
- }
7608
-
7609
- /**
7610
- * If the network is online and the tab is visible, either reload or refresh the request
7611
- * based on the component's configuration and the requested update mode.
7612
- *
7613
- * Valid modes are:
7614
- *
7615
- * - `'reload'`: Force a reload of the request.
7616
- * - `'refresh'`: Refresh the request in the background.
7617
- * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.
7618
- * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.
7619
- *
7620
- * @internal
7621
- */
7622
- _maybeUpdate(mode, silent) {
7623
- if (this.isIdle) {
7624
- return;
7625
- }
7626
- const {
7627
- reqState
7628
- } = this;
7629
- if (reqState.isPending) {
7630
- return;
7631
- }
7632
- const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));
7633
- if (!canAttempt) {
7634
- if (!silent && mode && mode !== '_invalidated') {
7635
- throw new Error(`Reload not available: the network is not online or the tab is hidden`);
7636
- }
7637
- return;
7638
- }
7639
- const {
7640
- autorefreshTypes
7641
- } = this;
7642
- let shouldAttempt = this._invalidated || Boolean(mode);
7643
- if (!shouldAttempt && autorefreshTypes.has('online')) {
7644
- const {
7645
- _unavailableStart
7646
- } = this;
7647
- const {
7648
- autorefreshThreshold
7649
- } = this._args;
7650
- const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;
7651
- shouldAttempt = Boolean(_unavailableStart && Date.now() - _unavailableStart > deadline);
7652
- }
7653
- if (!shouldAttempt && autorefreshTypes.has('interval')) {
7654
- const {
7655
- _intervalStart
7656
- } = this;
7657
- const {
7658
- autorefreshThreshold
7659
- } = this._args;
7660
- if (_intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {
7661
- shouldAttempt = Boolean(Date.now() - _intervalStart >= autorefreshThreshold);
7662
- }
7663
- }
7664
- this._unavailableStart = null;
7665
- this._invalidated = false;
7666
- if (shouldAttempt) {
7667
- this._clearInterval();
7668
- this._isUpdating = true;
7669
- const realMode = mode === '_invalidated' ? null : mode;
7670
- const val = realMode ?? this._args.autorefreshBehavior ?? 'policy';
7671
-
7672
- // if the future was generated by an older store version, it may not have
7673
- // a requester set. In this case we append it to ensure that reload and
7674
- // refresh will work appropriately.
7675
- const requester = this._getRequester();
7676
- if (!reqState._request.requester) {
7677
- reqState._request.requester = requester;
7678
- }
7679
- switch (val) {
7680
- case 'reload':
7681
- this._latestRequest = reqState.reload();
7682
- break;
7683
- case 'refresh':
7684
- this._latestRequest = reqState.refresh();
7685
- break;
7686
- case 'policy':
7687
- this._latestRequest = reqState.refresh(true);
7688
- break;
7689
- default:
7690
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
7691
- {
7692
- throw new Error(`Invalid ${mode ? 'update mode' : '@autorefreshBehavior'} for <Request />: ${isNeverString(val)}`);
7693
- }
7694
- })() : {};
7695
- }
7696
- if (val !== 'refresh') {
7697
- this._localRequest = this._latestRequest;
7698
- }
7699
- void this._scheduleInterval();
7700
- void this._latestRequest.finally(() => {
7701
- this._isUpdating = false;
7702
- });
7703
- }
7704
- }
7705
-
7706
- /**
7707
- * @internal
7708
- */
7709
- _getRequester() {
7710
- // Note: we check for the requester's presence
7711
- // as well as the request's presence because we may
7712
- // be subscribed to a request issued by a store from an older
7713
- // version of the library that didn't yet set requester.
7714
- if (this._args.request?.requester) {
7715
- return this._args.request.requester;
7716
- }
7717
- return this.store;
7718
- }
7719
-
7720
- /**
7721
- * Retry the request, reloading it from the server.
7722
- */
7723
- retry = async () => {
7724
- this._maybeUpdate('reload');
7725
- await this._localRequest;
7726
- };
7727
-
7728
- /**
7729
- * Refresh the request, updating it in the background.
7730
- */
7731
- refresh = async () => {
7732
- this._maybeUpdate('refresh');
7733
- await this._latestRequest;
7734
- };
7735
-
7736
- /**
7737
- * features to yield to the error slot of a component
7738
- */
7739
- get errorFeatures() {
7740
- return {
7741
- isHidden: this.isHidden,
7742
- isOnline: this.isOnline,
7743
- retry: this.retry
7744
- };
7745
- }
7746
-
7747
- /**
7748
- * features to yield to the content slot of a component
7749
- */
7750
- static {
7751
- decorateMethodV2(this.prototype, "errorFeatures", [memoized]);
7752
- }
7753
- get contentFeatures() {
7754
- const feat = {
7755
- isHidden: this.isHidden,
7756
- isOnline: this.isOnline,
7757
- reload: this.retry,
7758
- refresh: this.refresh,
7759
- isRefreshing: this.isRefreshing,
7760
- latestRequest: this._latestRequest
7761
- };
7762
- if (feat.isRefreshing) {
7763
- feat.abort = () => {
7764
- this._latestRequest?.abort();
7765
- };
7766
- }
7767
- return feat;
7768
- }
7769
-
7770
- /**
7771
- * @internal
7772
- */
7773
- static {
7774
- decorateMethodV2(this.prototype, "contentFeatures", [memoized]);
7775
- }
7776
- get _request() {
7777
- const {
7778
- request,
7779
- query
7780
- } = this._args;
7781
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
7782
- if (!test) {
7783
- throw new Error(`Cannot use both @request and @query args with the <Request> component`);
7784
- }
7785
- })(!request || !query) : {};
7786
- const {
7787
- _localRequest,
7788
- _originalRequest,
7789
- _originalQuery
7790
- } = this;
7791
- const isOriginalRequest = request === _originalRequest && query === _originalQuery;
7792
- if (_localRequest && isOriginalRequest) {
7793
- return _localRequest;
7794
- }
7795
-
7796
- // update state checks for the next time
7797
- this._originalQuery = query;
7798
- this._originalRequest = request;
7799
- if (request) {
7800
- return request;
7801
- }
7802
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
7803
- if (!test) {
7804
- throw new Error(`You must provide either @request or an @query arg with the <Request> component`);
7805
- }
7806
- })(query) : {};
7807
- return this.store.request(query);
7808
- }
7809
- static {
7810
- decorateMethodV2(this.prototype, "_request", [memoized]);
7811
- }
7812
- get request() {
7813
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
7814
- try {
7815
- const request = this._request;
7816
- this._updateSubscriptions();
7817
- return request;
7818
- } catch (e) {
7819
- // eslint-disable-next-line no-console
7820
- console.log(e);
7821
- throw new Error(`Unable to initialize the request`, {
7822
- cause: e
7823
- });
7824
- }
7825
- } else {
7826
- const request = this._request;
7827
- this._updateSubscriptions();
7828
- return request;
7829
- }
7830
- }
7831
- static {
7832
- decorateMethodV2(this.prototype, "request", [memoized]);
7833
- }
7834
- get reqState() {
7835
- return getRequestState(this.request);
7836
- }
7837
- get result() {
7838
- return this.reqState.result;
7839
- }
7840
- }
7841
- defineSignal(RequestSubscription.prototype, 'isOnline', true);
7842
- defineSignal(RequestSubscription.prototype, 'isHidden', false);
7843
- defineSignal(RequestSubscription.prototype, 'isRefreshing', false);
7844
- defineSignal(RequestSubscription.prototype, '_localRequest', undefined);
7845
- defineSignal(RequestSubscription.prototype, '_latestRequest', undefined);
7846
- function isStore(store) {
7847
- return 'requestManager' in store;
7848
- }
7849
- function createRequestSubscription(store, args) {
7850
- return new RequestSubscription(store, args);
7851
- }
7852
- function upgradeSubscription(sub) {
7853
- return sub;
7854
- }
7855
- function _DISPOSE() {
7856
- const self = upgradeSubscription(this);
7857
- self.isDestroyed = true;
7858
- self._removeSubscriptions();
7859
- if (typeof window === 'undefined') {
7860
- return;
7861
- }
7862
- self._clearInterval();
7863
- window.removeEventListener('online', self._onlineChanged, {
7864
- passive: true,
7865
- capture: true
7866
- });
7867
- window.removeEventListener('offline', self._onlineChanged, {
7868
- passive: true,
7869
- capture: true
7870
- });
7871
- document.removeEventListener('visibilitychange', self._backgroundChanged, {
7872
- passive: true,
7873
- capture: true
7874
- });
7875
- }
7876
- const RequestCache = new WeakMap();
7877
- function isAbortError(error) {
7878
- return error instanceof DOMException && error.name === 'AbortError';
7879
- }
7880
- function upgradeLoadingState(state) {
7881
- return state;
7882
- }
7883
- async function watchStream(stream, loadingState) {
7884
- const state = upgradeLoadingState(loadingState);
7885
- const reader = stream.getReader();
7886
- let bytesLoaded = 0;
7887
- let shouldForward = state._stream !== null && state._stream.readable.locked;
7888
- let isForwarding = shouldForward;
7889
- let writer = state._stream?.writable.getWriter();
7890
- const buffer = [];
7891
- state._isPending = false;
7892
- state._isStarted = true;
7893
- state._startTime = performance.now();
7894
- while (true) {
7895
- const {
7896
- value,
7897
- done
7898
- } = await reader.read();
7899
- if (done) {
7900
- break;
7901
- }
7902
- bytesLoaded += value.byteLength;
7903
- state._bytesLoaded = bytesLoaded;
7904
- state._lastPacketTime = performance.now();
7905
- shouldForward = shouldForward || state._stream !== null && state._stream.readable.locked;
7906
- if (shouldForward) {
7907
- if (!isForwarding) {
7908
- isForwarding = true;
7909
- writer = state._stream.writable.getWriter();
7910
- for (const item of buffer) {
7911
- await writer.ready;
7912
- await writer.write(item);
7913
- }
7914
- buffer.length = 0;
7915
- }
7916
- await writer.ready;
7917
- await writer.write(value);
7918
- } else {
7919
- buffer.push(value);
7920
- }
7921
- }
7922
-
7923
- // if we are still forwarding, we need to close the writer
7924
- if (isForwarding) {
7925
- await writer.ready;
7926
- await writer.close();
7927
- } else if (state._stream) {
7928
- // if we are not forwarding, we need to cancel the stream
7929
- await state._stream.readable.cancel('The Stream Has Already Ended');
7930
- state._stream = null;
7931
- }
7932
- const endTime = performance.now();
7933
- state._endTime = endTime;
7934
- state._isComplete = true;
7935
- state._isStarted = false;
7936
- }
7937
-
7938
- /**
7939
- * Lazily consumes the stream of a request, providing a number of
7940
- * reactive properties that can be used to build UIs that respond
7941
- * to the progress of a request.
7942
- *
7943
- * @hideconstructor
7944
- */
7945
- class RequestLoadingState {
7946
- /** @internal */
7947
-
7948
- /** @internal */
7949
-
7950
- /** @internal */
7951
-
7952
- /** @internal */
7953
-
7954
- /** @internal */
7955
-
7956
- /** @internal */
7957
-
7958
- /** @internal */
7959
-
7960
- /** @internal */
7961
-
7962
- /** @internal */
7963
-
7964
- /** @internal */
7965
-
7966
- /** @internal */
7967
-
7968
- /** @internal */
7969
- _stream = null;
7970
- /** @internal */
7971
- _future;
7972
- /** @internal */
7973
- _triggered = false;
7974
- /** @internal */
7975
- _trigger() {
7976
- if (this._triggered) {
7977
- return;
7978
- }
7979
- this._triggered = true;
7980
- const future = this._future;
7981
- const promise = future.getStream();
7982
- if (promise.sizeHint) {
7983
- this._sizeHint = promise.sizeHint;
7984
- }
7985
- this.promise = promise.then(stream => {
7986
- if (!stream) {
7987
- this._isPending = false;
7988
- this._isComplete = true;
7989
- return;
7990
- }
7991
- return watchStream(stream, this);
7992
- }, error => {
7993
- this._isPending = false;
7994
- this._isStarted = false;
7995
- if (isAbortError(error)) {
7996
- this._isCancelled = true;
7997
- this._isComplete = true;
7998
- }
7999
- this._isErrored = true;
8000
- this._error = error;
8001
- });
8002
- }
8003
- promise = null;
8004
- get isPending() {
8005
- this._trigger();
8006
- return this._isPending;
8007
- }
8008
- get sizeHint() {
8009
- this._trigger();
8010
- return this._sizeHint;
8011
- }
8012
- get stream() {
8013
- this._trigger();
8014
- if (!this._stream) {
8015
- if (this._isComplete || this._isCancelled || this._isErrored) {
8016
- return null;
8017
- }
8018
- this._stream = new TransformStream();
8019
- }
8020
- return this._stream.readable;
8021
- }
8022
- get isStarted() {
8023
- this._trigger();
8024
- return this._isStarted;
8025
- }
8026
- get bytesLoaded() {
8027
- this._trigger();
8028
- return this._bytesLoaded;
8029
- }
8030
- get startTime() {
8031
- this._trigger();
8032
- return this._startTime;
8033
- }
8034
- get endTime() {
8035
- this._trigger();
8036
- return this._endTime;
8037
- }
8038
- get lastPacketTime() {
8039
- this._trigger();
8040
- return this._lastPacketTime;
8041
- }
8042
- get isComplete() {
8043
- this._trigger();
8044
- return this._isComplete;
8045
- }
8046
- get isCancelled() {
8047
- this._trigger();
8048
- return this._isCancelled;
8049
- }
8050
- get isErrored() {
8051
- this._trigger();
8052
- return this._isErrored;
8053
- }
8054
- get error() {
8055
- this._trigger();
8056
- return this._error;
8057
- }
8058
- get elapsedTime() {
8059
- return (this.endTime || this.lastPacketTime) - this.startTime;
8060
- }
8061
- get completedRatio() {
8062
- return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;
8063
- }
8064
- get remainingRatio() {
8065
- return 1 - this.completedRatio;
8066
- }
8067
- get duration() {
8068
- return this.endTime - this.startTime;
8069
- }
8070
- get speed() {
8071
- // bytes per second
8072
- return this.bytesLoaded / (this.elapsedTime / 1000);
8073
- }
8074
- constructor(future) {
8075
- this._future = future;
8076
- }
8077
- abort = () => {
8078
- this._future.abort();
8079
- };
8080
- }
8081
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_isPending', true);
8082
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_isStarted', false);
8083
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_isComplete', false);
8084
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_isCancelled', false);
8085
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_isErrored', false);
8086
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_error', null);
8087
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_sizeHint', 0);
8088
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_bytesLoaded', 0);
8089
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_startTime', 0);
8090
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_endTime', 0);
8091
- defineNonEnumerableSignal(RequestLoadingState.prototype, '_lastPacketTime', 0);
8092
-
8093
- /**
8094
- * The state of a request in the "pending"
8095
- * state. This is the default initial state.
8096
- *
8097
- * Extends the {@link PendingPromise} interface.
8098
- *
8099
- */
8100
-
8101
- /**
8102
- * The state of a request in the "fulfilled" state.
8103
- * This is the state of a request that has resolved
8104
- * successfully.
8105
- *
8106
- * Extends the {@link ResolvedPromise} interface.
8107
- *
8108
- */
8109
-
8110
- /**
8111
- * The state of a request in the "rejected" state.
8112
- * This is the state of a request that has rejected
8113
- * with an error.
8114
- *
8115
- * Extends the {@link RejectedPromise} interface.
8116
- *
8117
- */
8118
-
8119
- /**
8120
- * The state of a request in the "cancelled" state.
8121
- * This is the state of a promise that has been
8122
- * cancelled.
8123
- *
8124
- */
8125
-
8126
- /**
8127
- * RequestState extends the concept of {@link PromiseState} to provide a reactive
8128
- * wrapper for a request {@link Future} which allows you write declarative code
8129
- * around a Future's control flow.
8130
- *
8131
- * It is useful in both Template and JavaScript contexts, allowing you
8132
- * to quickly derive behaviors and data from pending, error and success
8133
- * states.
8134
- *
8135
- * The key difference between a {@link Promise} and a Future is that Futures provide
8136
- * access to a {@link ReadableStream | stream} of their content, the {@link RequestKey} of the request (if any)
8137
- * as well as the ability to attempt to {@link Future.abort | abort} the request.
8138
- *
8139
- * ```ts
8140
- * interface Future<T> extends Promise<T>> {
8141
- * getStream(): Promise<ReadableStream>;
8142
- * abort(): void;
8143
- * lid: RequestKey | null;
8144
- * }
8145
- * ```
8146
- *
8147
- * These additional APIs allow us to craft even richer state experiences.
8148
- *
8149
- * To get the state of a request, use {@link getRequestState}.
8150
- *
8151
- * See also:
8152
- * - {@link PendingRequest}
8153
- * - {@link ResolvedRequest}
8154
- * - {@link RejectedRequest}
8155
- * - {@link CancelledRequest}
8156
- *
8157
- */
8158
-
8159
- const RequestStateProto = {};
8160
- function performRefresh(requester, request, isReload) {
8161
- const req = Object.assign({}, request);
8162
- const cacheOptions = Object.assign({}, req.cacheOptions);
8163
- if (isReload) {
8164
- // force direct to network
8165
- cacheOptions.reload = true;
8166
- } else if (isReload === false) {
8167
- // delete reload to ensure we use backgroundReload / policy
8168
- delete cacheOptions.reload;
8169
- cacheOptions.backgroundReload = true;
8170
- } else {
8171
- // delete props to ensure we use the policy
8172
- delete cacheOptions.backgroundReload;
8173
- delete cacheOptions.reload;
8174
- }
8175
- req.cacheOptions = cacheOptions;
8176
- return requester.request(req);
8177
- }
8178
-
8179
- // TODO introduce a new mechanism for defining multiple properties
8180
- // that share a common signal
8181
- defineSignal(RequestStateProto, 'reason', null);
8182
- defineSignal(RequestStateProto, 'value', null);
8183
- defineSignal(RequestStateProto, 'result', null);
8184
- defineSignal(RequestStateProto, 'error', null);
8185
- defineSignal(RequestStateProto, 'status', 'pending');
8186
- defineSignal(RequestStateProto, 'isPending', true);
8187
- defineSignal(RequestStateProto, 'isLoading', true);
8188
- defineSignal(RequestStateProto, 'isSuccess', false);
8189
- defineSignal(RequestStateProto, 'isError', false);
8190
- defineSignal(RequestStateProto, 'request', null);
8191
- defineSignal(RequestStateProto, 'response', null);
8192
- Object.defineProperty(RequestStateProto, 'isCancelled', {
8193
- get() {
8194
- return this.isError && isAbortError(this.reason);
8195
- }
8196
- });
8197
- Object.defineProperty(RequestStateProto, 'loadingState', {
8198
- get() {
8199
- if (!this._loadingState) {
8200
- this._loadingState = new RequestLoadingState(this._request);
8201
- }
8202
- return this._loadingState;
8203
- }
8204
- });
8205
- function createRequestState(future) {
8206
- const state = getPromiseResult(future);
8207
- const promiseState = Object.create(RequestStateProto);
8208
- promiseState._request = future;
8209
- // @ts-expect-error - we still attach it for PendingState
8210
- promiseState.reload = () => {
8211
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
8212
- if (!test) {
8213
- throw new Error(`Cannot reload a request that is still pending. Await or abort the original request first.`);
8214
- }
8215
- })(!promiseState.isPending) : {};
8216
- return performRefresh(future.requester, promiseState.request, true);
8217
- };
8218
-
8219
- // @ts-expect-error - we still attach it for PendingState
8220
- promiseState.refresh = (usePolicy = false) => {
8221
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
8222
- if (!test) {
8223
- throw new Error(`Cannot refresh a request that is still pending. Await or abort the original request first.`);
8224
- }
8225
- })(!promiseState.isPending) : {};
8226
- return performRefresh(future.requester, promiseState.request, usePolicy === true ? null : false);
8227
- };
8228
- if (state) {
8229
- if (state.isError) {
8230
- promiseState.error = state.result;
8231
- promiseState.reason = state.result;
8232
- promiseState.status = 'rejected';
8233
- promiseState.isError = true;
8234
- promiseState.isPending = false;
8235
- promiseState.isLoading = false;
8236
- promiseState.request = state.result.request;
8237
- promiseState.response = state.result.response;
8238
- } else {
8239
- promiseState.result = state.result.content;
8240
- promiseState.value = state.result.content;
8241
- promiseState.status = 'fulfilled';
8242
- promiseState.isSuccess = true;
8243
- promiseState.isPending = false;
8244
- promiseState.isLoading = false;
8245
- promiseState.request = state.result.request;
8246
- promiseState.response = state.result.response;
8247
- }
8248
- } else {
8249
- void future.then(result => {
8250
- setPromiseResult(future, {
8251
- isError: false,
8252
- result
8253
- });
8254
- promiseState.result = result.content;
8255
- promiseState.value = result.content;
8256
- promiseState.status = 'fulfilled';
8257
- promiseState.isSuccess = true;
8258
- promiseState.isPending = false;
8259
- promiseState.isLoading = false;
8260
- promiseState.request = result.request;
8261
- promiseState.response = result.response;
8262
- }, error => {
8263
- setPromiseResult(future, {
8264
- isError: true,
8265
- result: error
8266
- });
8267
- promiseState.error = error;
8268
- promiseState.reason = error;
8269
- promiseState.status = 'rejected';
8270
- promiseState.isError = true;
8271
- promiseState.isPending = false;
8272
- promiseState.isLoading = false;
8273
- promiseState.request = error.request;
8274
- promiseState.response = error.response;
8275
- });
8276
- }
8277
- return promiseState;
8278
- }
8279
-
8280
- /**
8281
- * `getRequestState` can be used in both JavaScript and Template contexts.
8282
- *
8283
- * ```ts
8284
- * import { getRequestState } from '@warp-drive/ember';
8285
- *
8286
- * const state = getRequestState(future);
8287
- * ```
8288
- *
8289
- * For instance, we could write a getter on a component that updates whenever
8290
- * the request state advances or the future changes, by combining the function
8291
- * with the use of `@cached`
8292
- *
8293
- * ```ts
8294
- * class Component {
8295
- * @cached
8296
- * get title() {
8297
- * const state = getRequestState(this.args.request);
8298
- * if (state.isPending) {
8299
- * return 'loading...';
8300
- * }
8301
- * if (state.isError) { return null; }
8302
- * return state.result.title;
8303
- * }
8304
- * }
8305
- * ```
8306
- *
8307
- * Or in a template as a helper:
8308
- *
8309
- * ```gjs
8310
- * import { getRequestState } from '@warp-drive/ember';
8311
- *
8312
- * <template>
8313
- * {{#let (getRequestState @request) as |state|}}
8314
- * {{#if state.isPending}}
8315
- * <Spinner />
8316
- * {{else if state.isError}}
8317
- * <ErrorForm @error={{state.error}} />
8318
- * {{else}}
8319
- * <h1>{{state.result.title}}</h1>
8320
- * {{/if}}
8321
- * {{/let}}
8322
- * </template>
8323
- * ```
8324
- *
8325
- * If looking to use in a template, consider also the `<Request />` component
8326
- * which offers a number of additional capabilities for requests *beyond* what
8327
- * `RequestState` provides.
8328
- *
8329
- */
8330
- function getRequestState(future) {
8331
- let state = RequestCache.get(future);
8332
- if (!state) {
8333
- state = createRequestState(future);
8334
- RequestCache.set(future, state);
8335
- }
8336
- return state;
8337
- }
8338
- function getAliasField(context) {
8339
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
8340
- {
8341
- throw new Error(`Alias field access is not implemented`);
8342
- }
8343
- })() : {};
8344
- }
8345
- function setAliasField(context) {
8346
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
8347
- {
8348
- throw new Error(`Alias field setting is not implemented`);
8349
- }
8350
- })() : {};
8351
- return false;
8352
- }
8353
- const ARRAY_GETTER_METHODS = new Set([Symbol.iterator, 'concat', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'flat', 'flatMap', 'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'reduce', 'reduceRight', 'slice', 'some', 'values']);
8354
- // const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
8355
- const SYNC_PROPS = new Set(['[]', 'length']);
8356
- function isArrayGetter(prop) {
8357
- return ARRAY_GETTER_METHODS.has(prop);
8358
- }
8359
- const ARRAY_SETTER_METHODS = new Set(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
8360
- function isArraySetter(prop) {
8361
- return ARRAY_SETTER_METHODS.has(prop);
8362
- }
8363
-
8364
- // function isSelfProp<T extends object>(self: T, prop: KeyType): prop is keyof T {
8365
- // return prop in self;
8366
- // }
8367
-
8368
- function convertToInt(prop) {
8369
- if (typeof prop === 'symbol') return null;
8370
- const num = Number(prop);
8371
- if (isNaN(num)) return null;
8372
- return num % 1 === 0 ? num : null;
8373
- }
8374
- function safeForEach(instance, arr, store, callback, target) {
8375
- if (target === undefined) {
8376
- target = null;
8377
- }
8378
- // clone to prevent mutation
8379
- arr = arr.slice();
8380
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
8381
- if (!test) {
8382
- throw new Error('`forEach` expects a function as first argument.');
8383
- }
8384
- })(typeof callback === 'function') : {};
8385
-
8386
- // because we retrieveLatest above we need not worry if array is mutated during iteration
8387
- // by unloadRecord/rollbackAttributes
8388
- // push/add/removeObject may still be problematic
8389
- // but this is a more traditionally expected forEach bug.
8390
- const length = arr.length; // we need to access length to ensure we are consumed
6785
+ // because we retrieveLatest above we need not worry if array is mutated during iteration
6786
+ // by unloadRecord/rollbackAttributes
6787
+ // push/add/removeObject may still be problematic
6788
+ // but this is a more traditionally expected forEach bug.
6789
+ const length = arr.length; // we need to access length to ensure we are consumed
8391
6790
 
8392
6791
  for (let index = 0; index < length; index++) {
8393
6792
  callback.call(target, arr[index], index, instance);
@@ -11127,173 +9526,6 @@ function mergeMap(base, toApply) {
11127
9526
  base.set(key, value);
11128
9527
  }
11129
9528
  }
11130
- const PromiseCache = new WeakMap();
11131
-
11132
- /**
11133
- * The state of a promise in the "pending"
11134
- * state. This is the default initial state.
11135
- *
11136
- */
11137
-
11138
- /**
11139
- * The state of a promise in the "fulfilled" state.
11140
- * This is the state of a promise that has resolved
11141
- * successfully.
11142
- *
11143
- */
11144
-
11145
- /**
11146
- * The state of a promise in the "rejected" state.
11147
- * This is the state of a promise that has rejected
11148
- * with an error.
11149
- *
11150
- */
11151
-
11152
- /**
11153
- * The state of a promise. This is the type that is returned
11154
- * from `getPromiseState`.
11155
- *
11156
- * See also:
11157
- * - {@link PendingPromise}
11158
- * - {@link ResolvedPromise}
11159
- * - {@link RejectedPromise}
11160
- *
11161
- */
11162
-
11163
- const PromiseStateProto = {};
11164
-
11165
- // TODO introduce a new mechanism for defining multiple properties
11166
- // that share a common signal
11167
- defineSignal(PromiseStateProto, 'reason', null);
11168
- defineSignal(PromiseStateProto, 'value', null);
11169
- defineSignal(PromiseStateProto, 'result', null);
11170
- defineSignal(PromiseStateProto, 'error', null);
11171
- defineSignal(PromiseStateProto, 'status', 'pending');
11172
- defineSignal(PromiseStateProto, 'isPending', true);
11173
- defineSignal(PromiseStateProto, 'isLoading', true);
11174
- defineSignal(PromiseStateProto, 'isSuccess', false);
11175
- defineSignal(PromiseStateProto, 'isError', false);
11176
- function createPromiseState(promise) {
11177
- const state = getPromiseResult(promise);
11178
- const promiseState = Object.create(PromiseStateProto);
11179
- if (state) {
11180
- if (state.isError) {
11181
- promiseState.error = state.result;
11182
- promiseState.reason = state.result;
11183
- promiseState.status = 'rejected';
11184
- promiseState.isError = true;
11185
- promiseState.isPending = false;
11186
- promiseState.isLoading = false;
11187
- } else {
11188
- promiseState.result = state.result;
11189
- promiseState.value = state.result;
11190
- promiseState.status = 'fulfilled';
11191
- promiseState.isSuccess = true;
11192
- promiseState.isPending = false;
11193
- promiseState.isLoading = false;
11194
- }
11195
- } else {
11196
- void promise.then(result => {
11197
- setPromiseResult(promise, {
11198
- isError: false,
11199
- result
11200
- });
11201
- promiseState.result = result;
11202
- promiseState.value = result;
11203
- promiseState.status = 'fulfilled';
11204
- promiseState.isSuccess = true;
11205
- promiseState.isPending = false;
11206
- promiseState.isLoading = false;
11207
- }, error => {
11208
- setPromiseResult(promise, {
11209
- isError: true,
11210
- result: error
11211
- });
11212
- promiseState.error = error;
11213
- promiseState.reason = error;
11214
- promiseState.status = 'rejected';
11215
- promiseState.isError = true;
11216
- promiseState.isPending = false;
11217
- promiseState.isLoading = false;
11218
- });
11219
- }
11220
- return promiseState;
11221
- }
11222
- const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
11223
- function isLegacyAwaitable(promise) {
11224
- return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;
11225
- }
11226
- function getPromise(promise) {
11227
- return isLegacyAwaitable(promise) ? promise.promise : promise;
11228
- }
11229
-
11230
- /**
11231
- * Returns a reactive state-machine for the provided promise or awaitable.
11232
- *
11233
- * Repeat calls to `getPromiseState` with the same promise will return the same state object
11234
- * making is safe and easy to use in templates and JavaScript code to produce reactive
11235
- * behaviors around promises.
11236
- *
11237
- * `getPromiseState` can be used in both JavaScript and Template contexts.
11238
- *
11239
- * ```ts
11240
- * import { getPromiseState } from '@warp-drive/ember';
11241
- *
11242
- * const state = getPromiseState(promise);
11243
- * ```
11244
- *
11245
- * For instance, we could write a getter on a component that updates whenever
11246
- * the promise state advances or the promise changes, by combining the function
11247
- * with the use of `@cached`
11248
- *
11249
- * ```ts
11250
- * class Component {
11251
- * @cached
11252
- * get title() {
11253
- * const state = getPromiseState(this.args.request);
11254
- * if (state.isPending) {
11255
- * return 'loading...';
11256
- * }
11257
- * if (state.isError) { return null; }
11258
- * return state.result.title;
11259
- * }
11260
- * }
11261
- * ```
11262
- *
11263
- * Or in a template as a helper:
11264
- *
11265
- * ```gjs
11266
- * import { getPromiseState } from '@warp-drive/ember';
11267
- *
11268
- * <template>
11269
- * {{#let (getPromiseState @request) as |state|}}
11270
- * {{#if state.isPending}} <Spinner />
11271
- * {{else if state.isError}} <ErrorForm @error={{state.error}} />
11272
- * {{else}}
11273
- * <h1>{{state.result.title}}</h1>
11274
- * {{/if}}
11275
- * {{/let}}
11276
- * </template>
11277
- * ```
11278
- *
11279
- * If looking to use in a template, consider also the `<Await />` component.
11280
- *
11281
- * See also {@link PromiseState}
11282
- */
11283
- function getPromiseState(promise) {
11284
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
11285
- if (!test) {
11286
- throw new Error(`getPromiseState expects to be called with a promise: called with ${String(promise)}`);
11287
- }
11288
- })(promise) : {};
11289
- const _promise = getPromise(promise);
11290
- let state = PromiseCache.get(_promise);
11291
- if (!state) {
11292
- state = createPromiseState(_promise);
11293
- PromiseCache.set(_promise, state);
11294
- }
11295
- return state;
11296
- }
11297
9529
 
11298
9530
  // Lazily close over fetch to avoid breaking Mirage
11299
9531
  const _fetch = typeof fetch !== 'undefined' ? (...args) => fetch(...args) : typeof FastBoot !== 'undefined' ? (...args) => FastBoot.require('node-fetch')(...args) : () => {
@@ -11662,7 +9894,7 @@ class RequestManager {
11662
9894
  * @mergeModuleWith <project>
11663
9895
  */
11664
9896
 
11665
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
9897
+ if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
11666
9898
  // @ts-expect-error adding to globalThis
11667
9899
  globalThis.setWarpDriveLogging = setLogging;
11668
9900
 
@@ -11747,4 +9979,4 @@ function useRecommendedStore(options, StoreKlass = Store) {
11747
9979
  }
11748
9980
  };
11749
9981
  }
11750
- export { setIdentifierForgetMethod as $, defineNonEnumerableSignal as A, Signals as B, CacheHandler as C, DISPOSE as D, peekInternalSignal as E, createInternalMemo as F, withSignalStore as G, notifyInternalSignal as H, consumeInternalSignal as I, getOrCreateInternalSignal as J, checkout as K, instantiateRecord as L, teardownRecord as M, SchemaService as N, withDefaults as O, fromIdentity as P, registerDerivations as Q, RecordArrayManager as R, Store as S, commit as T, getPromiseState as U, Fetch as V, RequestManager as W, useRecommendedStore as X, setIdentifierGenerationMethod as Y, setIdentifierUpdateMethod as Z, _clearCaches as _, isRequestKey as a, setIdentifierResetMethod as a0, setKeyInfoForResource as a1, coerceId as b, constructResource as c, assertPrivateStore as d, ensureStringId as e, fastPush as f, isPrivateStore as g, assertPrivateCapabilities as h, isResourceKey as i, setRecordIdentifier as j, StoreMap as k, createLegacyManyArray as l, log as m, normalizeModelName as n, logGroup as o, createRequestSubscription as p, getRequestState as q, recordIdentifierFor as r, storeFor as s, signal as t, memoized as u, gate as v, entangleSignal as w, entangleInitiallyStaleSignal as x, defineSignal as y, defineGate as z };
9982
+ export { useRecommendedStore as A, setIdentifierGenerationMethod as B, CacheHandler as C, setIdentifierUpdateMethod as D, setIdentifierForgetMethod as E, Fetch as F, setIdentifierResetMethod as G, setKeyInfoForResource as H, RecordArrayManager as R, Store as S, _clearCaches as _, isRequestKey as a, coerceId as b, constructResource as c, assertPrivateStore as d, ensureStringId as e, fastPush as f, isPrivateStore as g, assertPrivateCapabilities as h, isResourceKey as i, setRecordIdentifier as j, StoreMap as k, createLegacyManyArray as l, log as m, normalizeModelName as n, logGroup as o, checkout as p, instantiateRecord as q, recordIdentifierFor as r, storeFor as s, teardownRecord as t, SchemaService as u, fromIdentity as v, withDefaults as w, registerDerivations as x, commit as y, RequestManager as z };