@warp-drive/ember 0.0.0-alpha.9 → 0.0.0-alpha.90

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.
package/dist/index.js ADDED
@@ -0,0 +1,1083 @@
1
+ import { tracked, cached } from '@glimmer/tracking';
2
+ import { getPromiseResult, setPromiseResult } from '@ember-data/request';
3
+ import { service } from '@ember/service';
4
+ import Component from '@glimmer/component';
5
+ import { macroCondition, moduleExists, importSync, getGlobalConfig } from '@embroider/macros';
6
+ import { EnableHydration } from '@warp-drive/core-types/request';
7
+ import { precompileTemplate } from '@ember/template-compilation';
8
+ import { setComponentTemplate } from '@ember/component';
9
+ const deferred = /* @__PURE__ */new WeakMap();
10
+ function deferDecorator(proto, prop, desc) {
11
+ let map = deferred.get(proto);
12
+ if (!map) {
13
+ map = /* @__PURE__ */new Map();
14
+ deferred.set(proto, map);
15
+ }
16
+ map.set(prop, desc);
17
+ }
18
+ function findDeferredDecorator(target, prop) {
19
+ var _a;
20
+ let cursor = target.prototype;
21
+ while (cursor) {
22
+ let desc = (_a = deferred.get(cursor)) == null ? void 0 : _a.get(prop);
23
+ if (desc) {
24
+ return desc;
25
+ }
26
+ cursor = cursor.prototype;
27
+ }
28
+ }
29
+ function decorateFieldV2(prototype, prop, decorators, initializer) {
30
+ let desc = {
31
+ configurable: true,
32
+ enumerable: true,
33
+ writable: true,
34
+ initializer: null
35
+ };
36
+ if (initializer) {
37
+ desc.initializer = initializer;
38
+ }
39
+ for (let decorator of decorators) {
40
+ desc = decorator(prototype, prop, desc) || desc;
41
+ }
42
+ if (desc.initializer === void 0) {
43
+ Object.defineProperty(prototype, prop, desc);
44
+ } else {
45
+ deferDecorator(prototype, prop, desc);
46
+ }
47
+ }
48
+ function decorateMethodV2(prototype, prop, decorators) {
49
+ const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
50
+ let desc = {
51
+ ...origDesc
52
+ };
53
+ for (let decorator of decorators) {
54
+ desc = decorator(prototype, prop, desc) || desc;
55
+ }
56
+ if (desc.initializer !== void 0) {
57
+ desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
58
+ desc.initializer = void 0;
59
+ }
60
+ Object.defineProperty(prototype, prop, desc);
61
+ }
62
+ function initializeDeferredDecorator(target, prop) {
63
+ let desc = findDeferredDecorator(target.constructor, prop);
64
+ if (desc) {
65
+ Object.defineProperty(target, prop, {
66
+ enumerable: desc.enumerable,
67
+ configurable: desc.configurable,
68
+ writable: desc.writable,
69
+ value: desc.initializer ? desc.initializer.call(target) : void 0
70
+ });
71
+ }
72
+ }
73
+ const RequestCache = new WeakMap();
74
+ function isAbortError(error) {
75
+ return error instanceof DOMException && error.name === 'AbortError';
76
+ }
77
+ async function watchStream(stream, state) {
78
+ const reader = stream.getReader();
79
+ let bytesLoaded = 0;
80
+ let shouldForward = state._stream !== null && state._stream.readable.locked;
81
+ let isForwarding = shouldForward;
82
+ let writer = state._stream?.writable.getWriter();
83
+ const buffer = [];
84
+ state._isPending = false;
85
+ state._isStarted = true;
86
+ state._startTime = performance.now();
87
+
88
+ // eslint-disable-next-line no-constant-condition
89
+ while (true) {
90
+ const {
91
+ value,
92
+ done
93
+ } = await reader.read();
94
+ if (done) {
95
+ break;
96
+ }
97
+ bytesLoaded += value.byteLength;
98
+ state._bytesLoaded = bytesLoaded;
99
+ state._lastPacketTime = performance.now();
100
+ shouldForward = shouldForward || state._stream !== null && state._stream.readable.locked;
101
+ if (shouldForward) {
102
+ if (!isForwarding) {
103
+ isForwarding = true;
104
+ writer = state._stream.writable.getWriter();
105
+ for (const item of buffer) {
106
+ await writer.ready;
107
+ await writer.write(item);
108
+ }
109
+ buffer.length = 0;
110
+ }
111
+ await writer.ready;
112
+ await writer.write(value);
113
+ } else {
114
+ buffer.push(value);
115
+ }
116
+ }
117
+
118
+ // if we are still forwarding, we need to close the writer
119
+ if (isForwarding) {
120
+ await writer.ready;
121
+ await writer.close();
122
+ } else if (state._stream) {
123
+ // if we are not forwarding, we need to cancel the stream
124
+ await state._stream.readable.cancel('The Stream Has Already Ended');
125
+ state._stream = null;
126
+ }
127
+ const endTime = performance.now();
128
+ state._endTime = endTime;
129
+ state._isComplete = true;
130
+ state._isStarted = false;
131
+ }
132
+ class RequestLoadingState {
133
+ _stream = null;
134
+ _future;
135
+ _triggered = false;
136
+ _trigger() {
137
+ if (this._triggered) {
138
+ return;
139
+ }
140
+ this._triggered = true;
141
+ const future = this._future;
142
+ const promise = future.getStream();
143
+ if (promise.sizeHint) {
144
+ this._sizeHint = promise.sizeHint;
145
+ }
146
+ this.promise = promise.then(stream => {
147
+ if (!stream) {
148
+ this._isPending = false;
149
+ this._isComplete = true;
150
+ return;
151
+ }
152
+ return watchStream(stream, this);
153
+ }, error => {
154
+ this._isPending = false;
155
+ this._isStarted = false;
156
+ if (isAbortError(error)) {
157
+ this._isCancelled = true;
158
+ this._isComplete = true;
159
+ }
160
+ this._isErrored = true;
161
+ this._error = error;
162
+ });
163
+ }
164
+ promise = null;
165
+ static {
166
+ decorateFieldV2(this.prototype, "_sizeHint", [tracked], function () {
167
+ return 0;
168
+ });
169
+ }
170
+ #_sizeHint = (initializeDeferredDecorator(this, "_sizeHint"), void 0);
171
+ static {
172
+ decorateFieldV2(this.prototype, "_bytesLoaded", [tracked], function () {
173
+ return 0;
174
+ });
175
+ }
176
+ #_bytesLoaded = (initializeDeferredDecorator(this, "_bytesLoaded"), void 0);
177
+ static {
178
+ decorateFieldV2(this.prototype, "_startTime", [tracked], function () {
179
+ return 0;
180
+ });
181
+ }
182
+ #_startTime = (initializeDeferredDecorator(this, "_startTime"), void 0);
183
+ static {
184
+ decorateFieldV2(this.prototype, "_endTime", [tracked], function () {
185
+ return 0;
186
+ });
187
+ }
188
+ #_endTime = (initializeDeferredDecorator(this, "_endTime"), void 0);
189
+ static {
190
+ decorateFieldV2(this.prototype, "_lastPacketTime", [tracked], function () {
191
+ return 0;
192
+ });
193
+ }
194
+ #_lastPacketTime = (initializeDeferredDecorator(this, "_lastPacketTime"), void 0);
195
+ static {
196
+ decorateFieldV2(this.prototype, "_isPending", [tracked], function () {
197
+ return true;
198
+ });
199
+ }
200
+ #_isPending = (initializeDeferredDecorator(this, "_isPending"), void 0);
201
+ static {
202
+ decorateFieldV2(this.prototype, "_isStarted", [tracked], function () {
203
+ return false;
204
+ });
205
+ }
206
+ #_isStarted = (initializeDeferredDecorator(this, "_isStarted"), void 0);
207
+ static {
208
+ decorateFieldV2(this.prototype, "_isComplete", [tracked], function () {
209
+ return false;
210
+ });
211
+ }
212
+ #_isComplete = (initializeDeferredDecorator(this, "_isComplete"), void 0);
213
+ static {
214
+ decorateFieldV2(this.prototype, "_isCancelled", [tracked], function () {
215
+ return false;
216
+ });
217
+ }
218
+ #_isCancelled = (initializeDeferredDecorator(this, "_isCancelled"), void 0);
219
+ static {
220
+ decorateFieldV2(this.prototype, "_isErrored", [tracked], function () {
221
+ return false;
222
+ });
223
+ }
224
+ #_isErrored = (initializeDeferredDecorator(this, "_isErrored"), void 0);
225
+ static {
226
+ decorateFieldV2(this.prototype, "_error", [tracked], function () {
227
+ return null;
228
+ });
229
+ }
230
+ #_error = (initializeDeferredDecorator(this, "_error"), void 0);
231
+ get isPending() {
232
+ this._trigger();
233
+ return this._isPending;
234
+ }
235
+ get sizeHint() {
236
+ this._trigger();
237
+ return this._sizeHint;
238
+ }
239
+ get stream() {
240
+ this._trigger();
241
+ if (!this._stream) {
242
+ if (this._isComplete || this._isCancelled || this._isErrored) {
243
+ return null;
244
+ }
245
+ this._stream = new TransformStream();
246
+ }
247
+ return this._stream.readable;
248
+ }
249
+ get isStarted() {
250
+ this._trigger();
251
+ return this._isStarted;
252
+ }
253
+ get bytesLoaded() {
254
+ this._trigger();
255
+ return this._bytesLoaded;
256
+ }
257
+ get startTime() {
258
+ this._trigger();
259
+ return this._startTime;
260
+ }
261
+ get endTime() {
262
+ this._trigger();
263
+ return this._endTime;
264
+ }
265
+ get lastPacketTime() {
266
+ this._trigger();
267
+ return this._lastPacketTime;
268
+ }
269
+ get isComplete() {
270
+ this._trigger();
271
+ return this._isComplete;
272
+ }
273
+ get isCancelled() {
274
+ this._trigger();
275
+ return this._isCancelled;
276
+ }
277
+ get isErrored() {
278
+ this._trigger();
279
+ return this._isErrored;
280
+ }
281
+ get error() {
282
+ this._trigger();
283
+ return this._error;
284
+ }
285
+ get elapsedTime() {
286
+ return (this.endTime || this.lastPacketTime) - this.startTime;
287
+ }
288
+ get completedRatio() {
289
+ return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;
290
+ }
291
+ get remainingRatio() {
292
+ return 1 - this.completedRatio;
293
+ }
294
+ get duration() {
295
+ return this.endTime - this.startTime;
296
+ }
297
+ get speed() {
298
+ // bytes per second
299
+ return this.bytesLoaded / (this.elapsedTime / 1000);
300
+ }
301
+ constructor(future) {
302
+ this._future = future;
303
+ }
304
+ abort = () => {
305
+ this._future.abort();
306
+ };
307
+ }
308
+ class RequestState {
309
+ #request;
310
+ #loadingState = null;
311
+ static {
312
+ decorateFieldV2(this.prototype, "result", [tracked], function () {
313
+ return null;
314
+ });
315
+ }
316
+ #result = (initializeDeferredDecorator(this, "result"), void 0);
317
+ static {
318
+ decorateFieldV2(this.prototype, "error", [tracked], function () {
319
+ return null;
320
+ });
321
+ }
322
+ #error = (initializeDeferredDecorator(this, "error"), void 0);
323
+ static {
324
+ decorateFieldV2(this.prototype, "isLoading", [tracked], function () {
325
+ return true;
326
+ });
327
+ }
328
+ #isLoading = (initializeDeferredDecorator(this, "isLoading"), void 0);
329
+ static {
330
+ decorateFieldV2(this.prototype, "isSuccess", [tracked], function () {
331
+ return false;
332
+ });
333
+ }
334
+ #isSuccess = (initializeDeferredDecorator(this, "isSuccess"), void 0);
335
+ static {
336
+ decorateFieldV2(this.prototype, "isError", [tracked], function () {
337
+ return false;
338
+ });
339
+ }
340
+ #isError = (initializeDeferredDecorator(this, "isError"), void 0);
341
+ static {
342
+ decorateFieldV2(this.prototype, "request", [tracked], function () {
343
+ return null;
344
+ });
345
+ }
346
+ #request_ = (initializeDeferredDecorator(this, "request"), void 0);
347
+ static {
348
+ decorateFieldV2(this.prototype, "response", [tracked], function () {
349
+ return null;
350
+ });
351
+ }
352
+ #response = (initializeDeferredDecorator(this, "response"), void 0);
353
+ get isCancelled() {
354
+ return this.isError && isAbortError(this.error);
355
+ }
356
+ get loadingState() {
357
+ if (!this.#loadingState) {
358
+ this.#loadingState = new RequestLoadingState(this.#request);
359
+ }
360
+ return this.#loadingState;
361
+ }
362
+ constructor(future) {
363
+ this.#request = future;
364
+ const state = getPromiseResult(future);
365
+ if (state) {
366
+ this.request = state.result.request;
367
+ this.response = state.result.response;
368
+ this.isLoading = false;
369
+ if (state.isError) {
370
+ this.error = state.result;
371
+ this.isError = true;
372
+ } else {
373
+ this.result = state.result.content;
374
+ this.isSuccess = true;
375
+ }
376
+ } else {
377
+ void future.then(result => {
378
+ setPromiseResult(future, {
379
+ isError: false,
380
+ result
381
+ });
382
+ this.result = result.content;
383
+ this.isSuccess = true;
384
+ this.isLoading = false;
385
+ this.request = result.request;
386
+ this.response = result.response;
387
+ }, error => {
388
+ setPromiseResult(future, {
389
+ isError: true,
390
+ result: error
391
+ });
392
+ this.error = error;
393
+ this.isError = true;
394
+ this.isLoading = false;
395
+ this.request = error.request;
396
+ this.response = error.response;
397
+ });
398
+ }
399
+ }
400
+ }
401
+ function getRequestState(future) {
402
+ let state = RequestCache.get(future);
403
+ if (!state) {
404
+ state = new RequestState(future);
405
+ RequestCache.set(future, state);
406
+ }
407
+ return state;
408
+ }
409
+ const PromiseCache = new WeakMap();
410
+ class PromiseState {
411
+ static {
412
+ decorateFieldV2(this.prototype, "result", [tracked], function () {
413
+ return null;
414
+ });
415
+ }
416
+ #result = (initializeDeferredDecorator(this, "result"), void 0);
417
+ static {
418
+ decorateFieldV2(this.prototype, "error", [tracked], function () {
419
+ return null;
420
+ });
421
+ }
422
+ #error = (initializeDeferredDecorator(this, "error"), void 0);
423
+ static {
424
+ decorateFieldV2(this.prototype, "isPending", [tracked], function () {
425
+ return true;
426
+ });
427
+ }
428
+ #isPending = (initializeDeferredDecorator(this, "isPending"), void 0);
429
+ static {
430
+ decorateFieldV2(this.prototype, "isSuccess", [tracked], function () {
431
+ return false;
432
+ });
433
+ }
434
+ #isSuccess = (initializeDeferredDecorator(this, "isSuccess"), void 0);
435
+ static {
436
+ decorateFieldV2(this.prototype, "isError", [tracked], function () {
437
+ return false;
438
+ });
439
+ }
440
+ #isError = (initializeDeferredDecorator(this, "isError"), void 0);
441
+ constructor(promise) {
442
+ const state = getPromiseResult(promise);
443
+ if (state) {
444
+ if (state.isError) {
445
+ this.error = state.result;
446
+ this.isError = true;
447
+ this.isPending = false;
448
+ } else {
449
+ this.result = state.result;
450
+ this.isSuccess = true;
451
+ this.isPending = false;
452
+ }
453
+ } else {
454
+ void promise.then(result => {
455
+ setPromiseResult(promise, {
456
+ isError: false,
457
+ result
458
+ });
459
+ this.result = result;
460
+ this.isSuccess = true;
461
+ this.isPending = false;
462
+ }, error => {
463
+ setPromiseResult(promise, {
464
+ isError: true,
465
+ result: error
466
+ });
467
+ this.error = error;
468
+ this.isError = true;
469
+ this.isPending = false;
470
+ });
471
+ }
472
+ }
473
+ }
474
+ const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
475
+ function isLegacyAwaitable(promise) {
476
+ return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;
477
+ }
478
+ function getPromise(promise) {
479
+ return isLegacyAwaitable(promise) ? promise.promise : promise;
480
+ }
481
+ function getPromiseState(promise) {
482
+ const _promise = getPromise(promise);
483
+ let state = PromiseCache.get(_promise);
484
+ if (!state) {
485
+ state = new PromiseState(_promise);
486
+ PromiseCache.set(_promise, state);
487
+ }
488
+ return state;
489
+ }
490
+ const and = (x, y) => Boolean(x && y);
491
+ class Throw extends Component {
492
+ constructor(owner, args) {
493
+ super(owner, args);
494
+ // this error is opaque (user supplied) so we don't validate it
495
+ // as an Error instance.
496
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
497
+ throw this.args.error;
498
+ }
499
+ static {
500
+ setComponentTemplate(precompileTemplate("", {
501
+ strictMode: true
502
+ }), this);
503
+ }
504
+ }
505
+ class Await extends Component {
506
+ get state() {
507
+ return getPromiseState(this.args.promise);
508
+ }
509
+ get error() {
510
+ return this.state.error;
511
+ }
512
+ get result() {
513
+ return this.state.result;
514
+ }
515
+ static {
516
+ setComponentTemplate(precompileTemplate("\n {{#if this.state.isPending}}\n {{yield to=\"pending\"}}\n {{else if (and this.state.isError (has-block \"error\"))}}\n {{yield this.error to=\"error\"}}\n {{else if this.state.isSuccess}}\n {{yield this.result to=\"success\"}}\n {{else}}\n <Throw @error={{this.error}} />\n {{/if}}\n ", {
517
+ strictMode: true,
518
+ scope: () => ({
519
+ and,
520
+ Throw
521
+ })
522
+ }), this);
523
+ }
524
+ }
525
+ function notNull(x) {
526
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
527
+ if (!test) {
528
+ throw new Error('Expected a non-null value, but got null');
529
+ }
530
+ })(x !== null) : {};
531
+ return x;
532
+ }
533
+ const not = x => !x;
534
+ // default to 30 seconds unavailable before we refresh
535
+ const DEFAULT_DEADLINE = 30_000;
536
+ const IdleBlockMissingError = new Error('No idle block provided for <Request> component, and no query or request was provided.');
537
+ let consume = service;
538
+ if (macroCondition(moduleExists('ember-provide-consume-context'))) {
539
+ const {
540
+ consume: contextConsume
541
+ } = importSync('ember-provide-consume-context');
542
+ consume = contextConsume;
543
+ }
544
+ function isNeverString(val) {
545
+ return val;
546
+ }
547
+ /**
548
+ * The `<Request>` component is a powerful tool for managing data fetching and
549
+ * state in your Ember application. It provides declarative reactive control-flow
550
+ * for managing requests and state in your application.
551
+ *
552
+ * @typedoc
553
+ */
554
+ class Request extends Component {
555
+ static {
556
+ decorateFieldV2(this.prototype, "_store", [consume('store')]);
557
+ }
558
+ #_store = (initializeDeferredDecorator(this, "_store"), void 0);
559
+ /**
560
+ * The store instance to use for making requests. If contexts are available, this
561
+ * will be the `store` on the context, else it will be the store service.
562
+ *
563
+ * @internal
564
+ */
565
+ static {
566
+ decorateFieldV2(this.prototype, "isOnline", [tracked], function () {
567
+ return true;
568
+ });
569
+ }
570
+ #isOnline = (initializeDeferredDecorator(this, "isOnline"), void 0);
571
+ /**
572
+ * Whether the browser reports that the network is online.
573
+ *
574
+ * @internal
575
+ */
576
+ static {
577
+ decorateFieldV2(this.prototype, "isHidden", [tracked], function () {
578
+ return true;
579
+ });
580
+ }
581
+ #isHidden = (initializeDeferredDecorator(this, "isHidden"), void 0);
582
+ /**
583
+ * Whether the browser reports that the tab is hidden.
584
+ *
585
+ * @internal
586
+ */
587
+ static {
588
+ decorateFieldV2(this.prototype, "isRefreshing", [tracked], function () {
589
+ return false;
590
+ });
591
+ }
592
+ #isRefreshing = (initializeDeferredDecorator(this, "isRefreshing"), void 0);
593
+ /**
594
+ * Whether the component is currently refreshing the request.
595
+ *
596
+ * @internal
597
+ */
598
+ static {
599
+ decorateFieldV2(this.prototype, "_localRequest", [tracked]);
600
+ }
601
+ #_localRequest = (initializeDeferredDecorator(this, "_localRequest"), void 0);
602
+ /**
603
+ * The most recent blocking request that was made, typically
604
+ * the result of a reload.
605
+ *
606
+ * This will never be the original request passed as an arg to
607
+ * the component.
608
+ *
609
+ * @internal
610
+ */
611
+ static {
612
+ decorateFieldV2(this.prototype, "_latestRequest", [tracked]);
613
+ }
614
+ #_latestRequest = (initializeDeferredDecorator(this, "_latestRequest"), void 0);
615
+ /**
616
+ * The most recent request that was made, typically due to either a
617
+ * reload or a refresh.
618
+ *
619
+ * This will never be the original request passed as an arg to
620
+ * the component.
621
+ *
622
+ * @internal
623
+ */
624
+ /**
625
+ * The time at which the network was reported as offline.
626
+ *
627
+ * @internal
628
+ */
629
+ unavailableStart;
630
+ intervalStart;
631
+ nextInterval;
632
+ invalidated;
633
+ isUpdating;
634
+ /**
635
+ * The event listener for network status changes,
636
+ * cached to use the reference for removal.
637
+ *
638
+ * @internal
639
+ */
640
+ onlineChanged;
641
+ /**
642
+ * The event listener for visibility status changes,
643
+ * cached to use the reference for removal.
644
+ *
645
+ * @internal
646
+ */
647
+ backgroundChanged;
648
+ /**
649
+ * The last request passed as an arg to the component,
650
+ * cached for comparison.
651
+ *
652
+ * @internal
653
+ */
654
+ _originalRequest;
655
+ /**
656
+ * The last query passed as an arg to the component,
657
+ * cached for comparison.
658
+ *
659
+ * @internal
660
+ */
661
+ _originalQuery;
662
+ _subscription;
663
+ _subscribedTo;
664
+ constructor(owner, args) {
665
+ super(owner, args);
666
+ this._subscribedTo = null;
667
+ this._subscription = null;
668
+ this.intervalStart = null;
669
+ this.invalidated = false;
670
+ this.nextInterval = null;
671
+ this.installListeners();
672
+ void this.beginPolling();
673
+ }
674
+ async beginPolling() {
675
+ // await the initial request
676
+ try {
677
+ await this.request;
678
+ } catch {
679
+ // ignore errors here, we just want to wait for the request to finish
680
+ } finally {
681
+ if (!this.isDestroyed) {
682
+ void this.scheduleInterval();
683
+ }
684
+ }
685
+ }
686
+ get isIdle() {
687
+ const {
688
+ request,
689
+ query
690
+ } = this.args;
691
+ return Boolean(!request && !query);
692
+ }
693
+ static {
694
+ decorateMethodV2(this.prototype, "isIdle", [cached]);
695
+ }
696
+ get autorefreshTypes() {
697
+ const {
698
+ autorefresh
699
+ } = this.args;
700
+ let types;
701
+ if (autorefresh === true) {
702
+ types = ['online', 'invalid'];
703
+ } else if (typeof autorefresh === 'string') {
704
+ types = autorefresh.split(',');
705
+ } else {
706
+ types = [];
707
+ }
708
+ return new Set(types);
709
+ }
710
+ // we only run this function on component creation
711
+ // and when an update is triggered, so it does not
712
+ // react to changes in the autorefreshThreshold
713
+ // or autorefresh args.
714
+ //
715
+ // if we need to react to those changes, we can
716
+ // use a modifier or internal component or some
717
+ // such to trigger a re-run of this function.
718
+ static {
719
+ decorateMethodV2(this.prototype, "autorefreshTypes", [cached]);
720
+ }
721
+ async scheduleInterval() {
722
+ const {
723
+ autorefreshThreshold
724
+ } = this.args;
725
+ const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;
726
+ if (
727
+ // dont schedule in SSR
728
+ typeof window === 'undefined' ||
729
+ // dont schedule without a threshold
730
+ !hasValidThreshold ||
731
+ // dont schedule if we weren't told to
732
+ !this.autorefreshTypes.has('interval') ||
733
+ // dont schedule if we're already scheduled
734
+ this.intervalStart !== null) {
735
+ return;
736
+ }
737
+ // if we have a current request, wait for it to finish
738
+ // before scheduling the next one
739
+ if (this._latestRequest) {
740
+ try {
741
+ await this._latestRequest;
742
+ } catch {
743
+ // ignore errors here, we just want to wait for the request to finish
744
+ }
745
+ if (this.isDestroyed) {
746
+ return;
747
+ }
748
+ }
749
+ // setup the next interval
750
+ this.intervalStart = Date.now();
751
+ this.nextInterval = setTimeout(() => {
752
+ this.maybeUpdate();
753
+ }, autorefreshThreshold);
754
+ }
755
+ clearInterval() {
756
+ if (this.nextInterval) {
757
+ clearTimeout(this.nextInterval);
758
+ this.intervalStart = null;
759
+ }
760
+ }
761
+ updateSubscriptions() {
762
+ if (this.isIdle) {
763
+ return;
764
+ }
765
+ const requestId = this._request.lid;
766
+ // if we're already subscribed to this request, we don't need to do anything
767
+ if (this._subscribedTo === requestId) {
768
+ return;
769
+ }
770
+ // if we're subscribed to a different request, we need to unsubscribe
771
+ this.removeSubscriptions();
772
+ // if we have a request, we need to subscribe to it
773
+ if (requestId) {
774
+ this._subscribedTo = requestId;
775
+ this._subscription = this.store.notifications.subscribe(requestId, (_id, op) => {
776
+ // ignore subscription events that occur while our own component's request
777
+ // is ocurring
778
+ if (this.isUpdating) {
779
+ return;
780
+ }
781
+ switch (op) {
782
+ case 'invalidated':
783
+ {
784
+ // if we're subscribed to invalidations, we need to update
785
+ if (this.autorefreshTypes.has('invalid')) {
786
+ this.invalidated = true;
787
+ this.maybeUpdate();
788
+ }
789
+ break;
790
+ }
791
+ case 'state':
792
+ {
793
+ const latest = this.store.requestManager._deduped.get(requestId);
794
+ const priority = latest?.priority;
795
+ if (!priority) {
796
+ this.isRefreshing = false;
797
+ } else if (priority.blocking) {
798
+ // TODO should we just treat this as refreshing?
799
+ this.isRefreshing = false;
800
+ this.maybeUpdate('policy', true);
801
+ } else {
802
+ this.isRefreshing = true;
803
+ }
804
+ }
805
+ }
806
+ });
807
+ }
808
+ }
809
+ removeSubscriptions() {
810
+ if (this._subscription) {
811
+ this.store.notifications.unsubscribe(this._subscription);
812
+ this._subscribedTo = null;
813
+ this._subscription = null;
814
+ }
815
+ }
816
+ /**
817
+ * Install the event listeners for network and visibility changes.
818
+ * This is only done in browser environments with a global `window`.
819
+ *
820
+ * @internal
821
+ */
822
+ installListeners() {
823
+ if (typeof window === 'undefined') {
824
+ return;
825
+ }
826
+ this.isOnline = window.navigator.onLine;
827
+ this.unavailableStart = this.isOnline ? null : Date.now();
828
+ this.isHidden = document.visibilityState === 'hidden';
829
+ this.onlineChanged = event => {
830
+ this.isOnline = event.type === 'online';
831
+ if (event.type === 'offline' && this.unavailableStart === null) {
832
+ this.unavailableStart = Date.now();
833
+ }
834
+ this.maybeUpdate();
835
+ };
836
+ this.backgroundChanged = () => {
837
+ const isHidden = document.visibilityState === 'hidden';
838
+ this.isHidden = isHidden;
839
+ if (isHidden && this.unavailableStart === null) {
840
+ this.unavailableStart = Date.now();
841
+ }
842
+ this.maybeUpdate();
843
+ };
844
+ window.addEventListener('online', this.onlineChanged, {
845
+ passive: true,
846
+ capture: true
847
+ });
848
+ window.addEventListener('offline', this.onlineChanged, {
849
+ passive: true,
850
+ capture: true
851
+ });
852
+ document.addEventListener('visibilitychange', this.backgroundChanged, {
853
+ passive: true,
854
+ capture: true
855
+ });
856
+ }
857
+ /**
858
+ * If the network is online and the tab is visible, either reload or refresh the request
859
+ * based on the component's configuration and the requested update mode.
860
+ *
861
+ * Valid modes are:
862
+ *
863
+ * - `'reload'`: Force a reload of the request.
864
+ * - `'refresh'`: Refresh the request in the background.
865
+ * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.
866
+ * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.
867
+ *
868
+ * @internal
869
+ */
870
+ maybeUpdate(mode, silent) {
871
+ if (this.isIdle) {
872
+ return;
873
+ }
874
+ const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));
875
+ if (!canAttempt) {
876
+ if (!silent && mode && mode !== 'invalidated') {
877
+ throw new Error(`Reload not available: the network is not online or the tab is hidden`);
878
+ }
879
+ return;
880
+ }
881
+ const {
882
+ autorefreshTypes
883
+ } = this;
884
+ let shouldAttempt = this.invalidated || Boolean(mode);
885
+ if (!shouldAttempt && autorefreshTypes.has('online')) {
886
+ const {
887
+ unavailableStart
888
+ } = this;
889
+ const {
890
+ autorefreshThreshold
891
+ } = this.args;
892
+ const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;
893
+ shouldAttempt = Boolean(unavailableStart && Date.now() - unavailableStart > deadline);
894
+ }
895
+ if (!shouldAttempt && autorefreshTypes.has('interval')) {
896
+ const {
897
+ intervalStart
898
+ } = this;
899
+ const {
900
+ autorefreshThreshold
901
+ } = this.args;
902
+ if (intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {
903
+ shouldAttempt = Boolean(Date.now() - intervalStart >= autorefreshThreshold);
904
+ }
905
+ }
906
+ this.unavailableStart = null;
907
+ this.invalidated = false;
908
+ if (shouldAttempt) {
909
+ this.clearInterval();
910
+ const request = Object.assign({}, this.reqState.request);
911
+ const realMode = mode === 'invalidated' ? null : mode;
912
+ const val = realMode ?? this.args.autorefreshBehavior ?? 'policy';
913
+ switch (val) {
914
+ case 'reload':
915
+ request.cacheOptions = Object.assign({}, request.cacheOptions, {
916
+ reload: true
917
+ });
918
+ break;
919
+ case 'refresh':
920
+ request.cacheOptions = Object.assign({}, request.cacheOptions, {
921
+ backgroundReload: true
922
+ });
923
+ break;
924
+ case 'policy':
925
+ break;
926
+ default:
927
+ throw new Error(`Invalid ${mode ? 'update mode' : '@autorefreshBehavior'} for <Request />: ${isNeverString(val)}`);
928
+ }
929
+ const wasStoreRequest = request[EnableHydration] === true;
930
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
931
+ if (!test) {
932
+ throw new Error(`Cannot supply a different store via context than was used to create the request`);
933
+ }
934
+ })(!request.store || request.store === this.store) : {};
935
+ this.isUpdating = true;
936
+ this._latestRequest = wasStoreRequest ? this.store.request(request) : this.store.requestManager.request(request);
937
+ if (val !== 'refresh') {
938
+ this._localRequest = this._latestRequest;
939
+ }
940
+ void this.scheduleInterval();
941
+ void this._latestRequest.finally(() => {
942
+ this.isUpdating = false;
943
+ });
944
+ }
945
+ }
946
+ /**
947
+ * Retry the request, reloading it from the server.
948
+ *
949
+ * @internal
950
+ */
951
+ retry = async () => {
952
+ this.maybeUpdate('reload');
953
+ await this._localRequest;
954
+ };
955
+ /**
956
+ * Refresh the request, updating it in the background.
957
+ *
958
+ * @internal
959
+ */
960
+ refresh = async () => {
961
+ this.maybeUpdate('refresh');
962
+ await this._latestRequest;
963
+ };
964
+ get errorFeatures() {
965
+ return {
966
+ isHidden: this.isHidden,
967
+ isOnline: this.isOnline,
968
+ retry: this.retry
969
+ };
970
+ }
971
+ static {
972
+ decorateMethodV2(this.prototype, "errorFeatures", [cached]);
973
+ }
974
+ get contentFeatures() {
975
+ const feat = {
976
+ isHidden: this.isHidden,
977
+ isOnline: this.isOnline,
978
+ reload: this.retry,
979
+ refresh: this.refresh,
980
+ isRefreshing: this.isRefreshing,
981
+ latestRequest: this._latestRequest
982
+ };
983
+ if (feat.isRefreshing) {
984
+ feat.abort = () => {
985
+ this._latestRequest?.abort();
986
+ };
987
+ }
988
+ return feat;
989
+ }
990
+ static {
991
+ decorateMethodV2(this.prototype, "contentFeatures", [cached]);
992
+ }
993
+ willDestroy() {
994
+ this.removeSubscriptions();
995
+ if (typeof window === 'undefined') {
996
+ return;
997
+ }
998
+ this.clearInterval();
999
+ window.removeEventListener('online', this.onlineChanged, {
1000
+ passive: true,
1001
+ capture: true
1002
+ });
1003
+ window.removeEventListener('offline', this.onlineChanged, {
1004
+ passive: true,
1005
+ capture: true
1006
+ });
1007
+ document.removeEventListener('visibilitychange', this.backgroundChanged, {
1008
+ passive: true,
1009
+ capture: true
1010
+ });
1011
+ }
1012
+ get _request() {
1013
+ const {
1014
+ request,
1015
+ query
1016
+ } = this.args;
1017
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1018
+ if (!test) {
1019
+ throw new Error(`Cannot use both @request and @query args with the <Request> component`);
1020
+ }
1021
+ })(!request || !query) : {};
1022
+ const {
1023
+ _localRequest,
1024
+ _originalRequest,
1025
+ _originalQuery
1026
+ } = this;
1027
+ const isOriginalRequest = request === _originalRequest && query === _originalQuery;
1028
+ if (_localRequest && isOriginalRequest) {
1029
+ return _localRequest;
1030
+ }
1031
+ // update state checks for the next time
1032
+ this._originalQuery = query;
1033
+ this._originalRequest = request;
1034
+ if (request) {
1035
+ return request;
1036
+ }
1037
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1038
+ if (!test) {
1039
+ throw new Error(`You must provide either @request or an @query arg with the <Request> component`);
1040
+ }
1041
+ })(query) : {};
1042
+ return this.store.request(query);
1043
+ }
1044
+ static {
1045
+ decorateMethodV2(this.prototype, "_request", [cached]);
1046
+ }
1047
+ get request() {
1048
+ const request = this._request;
1049
+ this.updateSubscriptions();
1050
+ return request;
1051
+ }
1052
+ static {
1053
+ decorateMethodV2(this.prototype, "request", [cached]);
1054
+ }
1055
+ get store() {
1056
+ const store = this.args.store || this._store;
1057
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1058
+ if (!test) {
1059
+ throw new Error(moduleExists('ember-provide-consume-context') ? `No store was provided to the <Request> component. Either provide a store via the @store arg or via the context API provided by ember-provide-consume-context.` : `No store was provided to the <Request> component. Either provide a store via the @store arg or by registering a store service.`);
1060
+ }
1061
+ })(store) : {};
1062
+ return store;
1063
+ }
1064
+ get reqState() {
1065
+ return getRequestState(this.request);
1066
+ }
1067
+ get result() {
1068
+ return this.reqState.result;
1069
+ }
1070
+ static {
1071
+ setComponentTemplate(precompileTemplate("\n {{#if (and this.isIdle (has-block \"idle\"))}}\n {{yield to=\"idle\"}}\n {{else if this.isIdle}}\n <Throw @error={{IdleBlockMissingError}} />\n {{else if this.reqState.isLoading}}\n {{yield this.reqState.loadingState to=\"loading\"}}\n {{else if (and this.reqState.isCancelled (has-block \"cancelled\"))}}\n {{yield (notNull this.reqState.error) this.errorFeatures to=\"cancelled\"}}\n {{else if (and this.reqState.isError (has-block \"error\"))}}\n {{yield (notNull this.reqState.error) this.errorFeatures to=\"error\"}}\n {{else if this.reqState.isSuccess}}\n {{yield this.result this.contentFeatures to=\"content\"}}\n {{else if (not this.reqState.isCancelled)}}\n <Throw @error={{(notNull this.reqState.error)}} />\n {{/if}}\n {{yield this.reqState to=\"always\"}}\n ", {
1072
+ strictMode: true,
1073
+ scope: () => ({
1074
+ and,
1075
+ Throw,
1076
+ IdleBlockMissingError,
1077
+ notNull,
1078
+ not
1079
+ })
1080
+ }), this);
1081
+ }
1082
+ }
1083
+ export { Await, Request, Throw, getPromiseState, getRequestState };