@ember-data-mirror/request 4.13.0-alpha.1

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,687 @@
1
+ import { macroCondition, getGlobalConfig, importSync } from '@embroider/macros';
2
+ import { peekUniversalTransient, setUniversalTransient } from '@warp-drive-mirror/core-types/-private';
3
+ import { I as IS_CACHE_HANDLER, a as assertValidRequest, e as executeNextHandler, g as getRequestResult, u as upgradePromise, s as setPromiseResult, c as clearRequestResult } from "./debug-D0st-bv4.js";
4
+ export { b as createDeferred, d as getPromiseResult } from "./debug-D0st-bv4.js";
5
+
6
+ /* eslint-disable no-irregular-whitespace */
7
+ /**
8
+ *
9
+ <p align="center">
10
+ <img
11
+ class="project-logo"
12
+ src="https://raw.githubusercontent.com/emberjs/data/4612c9354e4c54d53327ec2cf21955075ce21294/ember-data-logo-light.svg#gh-light-mode-only"
13
+ alt="EmberData RequestManager"
14
+ width="240px"
15
+ title="EmberData RequestManager"
16
+ />
17
+ </p>
18
+
19
+ <p align="center">⚡️ a simple abstraction over fetch to enable easy management of request/response flows</p>
20
+
21
+ This package provides [*Ember*‍**Data**](https://github.com/emberjs/data/)'s `RequestManager`, a framework agnostic library that can be integrated with any Javascript application to make [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) happen.
22
+
23
+ - [Installation](#installation)
24
+ - [Basic Usage](#🚀-basic-usage)
25
+ - [Architecture](#🪜-architecture)
26
+ - [Usage](#usage)
27
+ - [Making Requests](#making-requests)
28
+ - [Using The Response](#using-the-response)
29
+ - [Request Handlers](#handling-requests)
30
+ - [Handling Errors](#handling-errors)
31
+ - [Handling Abort](#handling-abort)
32
+ - [Stream Currying](#stream-currying)
33
+ - [Automatic Currying](#automatic-currying-of-stream-and-response)
34
+ - [Using as a Service](#using-as-a-service)
35
+ - [Using with `@ember-data-mirror/store`](#using-with-ember-datastore)
36
+ - [Using with `ember-data`](#using-with-ember-data)
37
+
38
+ ---
39
+
40
+ ## Installation
41
+
42
+ Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
43
+
44
+ ```no-highlight
45
+ pnpm add @ember-data-mirror/request
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 🚀 Basic Usage
51
+
52
+ A `RequestManager` provides a request/response flow in which configured handlers are successively given the opportunity to handle, modify, or pass-along a request.
53
+
54
+ The RequestManager on its own does not know how to fulfill requests. For this we must register at least one handler. A basic `Fetch` handler is provided that will take the request options provided and execute `fetch`.
55
+
56
+ ```ts
57
+ import RequestManager from '@ember-data-mirror/request';
58
+ import Fetch from '@ember-data-mirror/request/fetch';
59
+ import { apiUrl } from './config';
60
+
61
+ // ... create manager and add our Fetch handler
62
+ const manager = new RequestManager();
63
+ manager.use([Fetch]);
64
+
65
+ // ... execute a request
66
+ const response = await manager.request({
67
+ url: `${apiUrl}/users`
68
+ });
69
+ ```
70
+
71
+ ---
72
+
73
+ ## 🪜 Architecture
74
+
75
+ A `RequestManager` receives a request and manages fulfillment via configured handlers. It may be used standalone from the rest of *Ember*‍**Data** and is not specific to any library or framework.
76
+
77
+ Each handler may choose to fulfill the request using some source of data or to pass the request along to other handlers.
78
+
79
+ The same or a separate instance of a `RequestManager` may also be used to fulfill requests issued by [*Ember*‍**Data**{Store}](https://github.com/emberjs/data/tree/main/packages/store)
80
+
81
+ When the same instance is used by both this allows for simple coordination throughout the application. Requests issued by the Store will use the in-memory cache
82
+ and return hydrated responses, requests issued directly to the RequestManager
83
+ will skip the in-memory cache and return raw responses.
84
+
85
+ ---
86
+
87
+ ## Usage
88
+
89
+ ```ts
90
+ const userList = await manager.request({
91
+ url: `/api/v1/users.list`
92
+ });
93
+
94
+ const users = userList.content;
95
+ ```
96
+
97
+ ---
98
+
99
+ ### Making Requests
100
+
101
+ `RequestManager` has a single asyncronous method as it's API: `request`
102
+
103
+ ```ts
104
+ class RequestManager {
105
+ request<T>(req: RequestInfo): Future<T>;
106
+ }
107
+ ```
108
+
109
+ `manager.request(<RequestInfo>)` accepts an object containing the information
110
+ necessary for the request to be handled successfully.
111
+
112
+ These options extend the [options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) provided to `fetch`, and can accept a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). All properties accepted by Request options and fetch options are valid.
113
+
114
+ ```ts
115
+ interface RequestInfo extends FetchOptions {
116
+ op?: string;
117
+ store?: Store;
118
+
119
+ url: string;
120
+ // data that a handler should convert into
121
+ // the query (GET) or body (POST)
122
+ data?: Record<string, unknown>;
123
+
124
+ // options specifically intended for handlers
125
+ // to utilize to process the request
126
+ options?: Record<string, unknown>;
127
+ }
128
+ ```
129
+
130
+ > **note**
131
+ > providing a `signal` is unnecessary as an `AbortController` is automatically provided if none is present.
132
+
133
+ ---
134
+
135
+ #### Using the Response
136
+
137
+ `manager.request` returns a `Future`, which allows access to limited information about the request while it is still pending and fulfills with the final state when the request completes and the response has been read.
138
+
139
+ ```ts
140
+ const usersFuture = manager.request({
141
+ url: `/api/v1/users.list`
142
+ });
143
+ ```
144
+
145
+ A `Future` is cancellable via `abort`.
146
+
147
+ ```ts
148
+ usersFuture.abort();
149
+ ```
150
+
151
+ Handlers may *optionally* expose a ReadableStream to the `Future` for streaming data; however, when doing so the handler should not resolve until it has fully read the response stream itself.
152
+
153
+ ```ts
154
+ interface Future<T> extends Promise<StructuredDocument<T>> {
155
+ abort(): void;
156
+
157
+ async getStream(): ReadableStream | null;
158
+ }
159
+ ```
160
+
161
+ A Future resolves or rejects with a `StructuredDocument`.
162
+
163
+ ```ts
164
+ interface StructuredDocument<T> {
165
+ request: RequestInfo;
166
+ response: ResponseInfo | null;
167
+ content?: T;
168
+ error?: Error;
169
+ }
170
+ ```
171
+
172
+ The `RequestInfo` specified by `document.request` is the same as originally provided to `manager.request`. If any handler fulfilled this request using different request info it is not represented here. This contract helps to ensure that `retry` and `caching` are possible since the original arguments are correctly preserved. This also allows handlers to "fork" the request or fulfill from multiple sources without the details of fulfillment muddying the original request.
173
+
174
+ The `ResponseInfo` is a serializable fulfilled subset of a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) if set via `setResponse`. If no response was ever set this will be `null`.
175
+
176
+ ```ts
177
+ interface ResponseInfo {
178
+ headers?: Record<string, string>;
179
+ ok?: boolean;
180
+ redirected?: boolean;
181
+ status?: HTTPStatusCode;
182
+ statusText?: string;
183
+ type?: 'basic' | 'cors';
184
+ url?: string;
185
+ }
186
+ ```
187
+
188
+ ---
189
+
190
+ ### Request Handlers
191
+
192
+ Requests are fulfilled by handlers. A handler receives the request context
193
+ as well as a `next` function with which to pass along a request to the next
194
+ handler if it so chooses.
195
+
196
+ A handler may be any object with a `request` method. This allows both stateful and non-stateful
197
+ handlers to be utilized.
198
+
199
+ If a handler calls `next`, it receives a `Future` which resolves to a `StructuredDocument`
200
+ that it can then compose how it sees fit with its own response.
201
+
202
+ ```ts
203
+
204
+ type NextFn<P> = (req: RequestInfo) => Future<P>;
205
+
206
+ interface Handler {
207
+ async request<T>(context: RequestContext, next: NextFn<P>): T;
208
+ }
209
+ ```
210
+
211
+ `RequestContext` contains a readonly version of the RequestInfo as well as a few methods for building up the `StructuredDocument` and `Future` that will be part of the response.
212
+
213
+ ```ts
214
+ interface RequestContext<T> {
215
+ readonly request: RequestInfo;
216
+
217
+ setStream(stream: ReadableStream | Promise<ReadableStream>): void;
218
+ setResponse(response: Response | ResponseInfo): void;
219
+ }
220
+ ```
221
+
222
+ A basic `fetch` handler with support for streaming content updates while
223
+ the download is still underway might look like the following, where we use
224
+ [`response.clone()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/clone) to `tee` the `ReadableStream` into two streams.
225
+
226
+ A more efficient handler might read from the response stream, building up the
227
+ response content before passing along the chunk downstream.
228
+
229
+ ```ts
230
+ const FetchHandler = {
231
+ async request(context) {
232
+ const response = await fetch(context.request);
233
+ context.setResponse(reponse);
234
+ context.setStream(response.clone().body);
235
+
236
+ return response.json();
237
+ }
238
+ }
239
+ ```
240
+
241
+ Request handlers are registered by configuring the manager via `use`
242
+
243
+ ```ts
244
+ manager.use([Handler1, Handler2])
245
+ ```
246
+
247
+ Handlers will be invoked in the order they are registered ("fifo", first-in first-out), and may only be registered up until the first request is made. It is recommended but not required to register all handlers at one time in order to ensure explicitly visible handler ordering.
248
+
249
+ ---
250
+
251
+ #### Handling Errors
252
+
253
+ Each handler in the chain can catch errors from upstream and choose to
254
+ either handle the error, re-throw the error, or throw a new error.
255
+
256
+ ```ts
257
+ const MAX_RETRIES = 5;
258
+
259
+ const Handler = {
260
+ async request(context, next) {
261
+ let attempts = 0;
262
+
263
+ while (attempts < MAX_RETRIES) {
264
+ attempts++;
265
+ try {
266
+ const response = await next(context.request);
267
+ return response;
268
+ } catch (e) {
269
+ if (isTimeoutError(e) && attempts < MAX_RETRIES) {
270
+ // retry request
271
+ continue;
272
+ }
273
+ // rethrow if it is not a timeout error
274
+ throw e;
275
+ }
276
+ }
277
+ }
278
+ }
279
+ ```
280
+
281
+ ---
282
+
283
+ #### Handling Abort
284
+
285
+ Aborting a request will reject the current handler in the chain. However,
286
+ every handler can potentially catch this error. If your handler needs to
287
+ separate AbortError from other Error types, it is recommended to check
288
+ `context.request.signal.aborted` (or if a custom controller was supplied `controller.signal.aborted`).
289
+
290
+ In this manner it is possible for a request to recover from an abort and
291
+ still proceed; however, as a best practice this should be used for necessary
292
+ cleanup only and the original AbortError rethrown if the abort signal comes
293
+ from the root controller.
294
+
295
+ **AbortControllers are Always Present and Always Entangled**
296
+
297
+ If the initial request does not supply an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController), one will be generated.
298
+
299
+ The [signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for this controller is automatically added to the request passed into the first handler.
300
+
301
+ Each handler has the option to supply a new controller to the request when calling `next`. If a new controller is provided it will be automatically
302
+ entangled with the root controller. If the root controller aborts, so will
303
+ any entangled controllers.
304
+
305
+ If an entangled controller aborts, the root controller will not abort. This
306
+ allows for advanced request-flow scenarios to abort subsections of the request tree without aborting the entire request.
307
+
308
+ ---
309
+
310
+ #### Stream Currying
311
+
312
+ `RequestManager.request` and `next` differ from `fetch` in one **crucial detail** in that the outer Promise resolves only once the response stream has been processed.
313
+
314
+ For context, it helps to understand a few of the use-cases that RequestManager
315
+ is intended to allow.
316
+
317
+ - to manage and return streaming content (such as video files)
318
+ - to fulfill a request from multiple sources or by splitting one request into multiple requests
319
+ - for instance one API call for a user and another for the user's friends
320
+ - or e.g. fulfilling part of the request from one source (one API, in-memory, localStorage, IndexedDB
321
+ etc.) and the rest from another source (a different API, a WebWorker, etc.)
322
+ - to coalesce multiple requests
323
+ - to decorate a request with additional info
324
+ - e.g. an Auth handler that ensures the correct tokens or headers or cookies are attached.
325
+
326
+
327
+ `await fetch(<req>)` resolves at the moment headers are received. This allows for the body of the request to be processed as a stream by application
328
+ code *while chunks are still being received by the browser*.
329
+
330
+ When an app chooses to `await response.json()` what occurs is the browser reads the stream to completion and then returns the result. Additionally, this stream may only be read **once**.
331
+
332
+ The `RequestManager` preserves this ability to subscribe to and utilize the stream by either the application or the handler – thereby delivering the full power and flexibility of native APIs – without restricting developers in ways that lead to complicated workarounds.
333
+
334
+ Each handler may call `setStream` only once, but may do so *at any time* until the promise that the handler returns has resolved. The associated promise returned by calling `future.getStream` will resolve with the stream set by `setStream` if that method is called, or `null` if that method
335
+ has not been called by the time that the handler's request method has resolved.
336
+
337
+ Handlers that do not create a stream of their own, but which call `next`, should defensively pipe the stream forward. While this is not required (see automatic currying below) it is better to do so in most cases as otherwise the stream may not become available to downstream handlers or the application until the upstream handler has fully read it.
338
+
339
+ ```ts
340
+ context.setStream(future.getStream());
341
+ ```
342
+
343
+ Handlers that either call `next` multiple times or otherwise have reason to create multiple fetch requests should either choose to return no stream, meaningfully combine the streams, or select a single prioritized stream.
344
+
345
+ Of course, any handler may choose to read and handle the stream, and return either no stream or a different stream in the process.
346
+
347
+ ---
348
+
349
+ #### Automatic Currying of Stream and Response
350
+
351
+ In order to simplify the common case for handlers which decorate a request, if `next` is called only a single time and `setResponse` was never called by the handler, the response set by the next handler in the chain will be applied to that handler's outcome. For instance, this makes the following pattern possible `return (await next(<req>)).content;`.
352
+
353
+ Similarly, if `next` is called only a single time and neither `setStream` nor `getStream` was called, we automatically curry the stream from the future returned by `next` onto the future returned by the handler.
354
+
355
+ Finally, if the return value of a handler is a `Future`, we curry `content` and `errors` as well, thus enabling the simplest form `return next(<req>)`.
356
+
357
+ In the case of the `Future` being returned, `Stream` proxying is automatic and immediate and does not wait for the `Future` to resolve.
358
+
359
+ ---
360
+
361
+ ### Using as a Service
362
+
363
+ Most applications will desire to have a single `RequestManager` instance, which can be achieved using module-state patterns for singletons, or for [Ember](https://emberjs.com) applications by exporting the manager as a [service](https://guides.emberjs.com/release/services/).
364
+
365
+ *services/request.ts*
366
+ ```ts
367
+ import RequestManager from '@ember-data-mirror/request';
368
+ import Fetch from '@ember-data-mirror/request/fetch';
369
+ import Auth from 'ember-simple-auth/ember-data-handler';
370
+
371
+ export default class extends RequestManager {
372
+ constructor(createArgs) {
373
+ super(createArgs);
374
+ this.use([Auth, Fetch]);
375
+ }
376
+ }
377
+ ```
378
+
379
+ ---
380
+
381
+ #### Using with `@ember-data-mirror/store`
382
+
383
+ To have a request service unique to a Store:
384
+
385
+ ```ts
386
+ import Store, { CacheHandler } from '@ember-data-mirror/store';
387
+ import RequestManager from '@ember-data-mirror/request';
388
+ import Fetch from '@ember-data-mirror/request/fetch';
389
+
390
+ class extends Store {
391
+ requestManager = new RequestManager();
392
+
393
+ constructor(args) {
394
+ super(args);
395
+ this.requestManager.use([Fetch]);
396
+ this.requestManager.useCache(CacheHandler);
397
+ }
398
+ }
399
+ ```
400
+
401
+ ---
402
+
403
+ #### Using with `ember-data`
404
+
405
+ If using the package [ember-data](https://github.com/emberjs/data/tree/main/packages/-ember-data),
406
+ the following configuration will automatically be done in order to preserve the
407
+ legacy [Adapter](https://github.com/emberjs/data/tree/main/packages/adapter) and
408
+ [Serializer](https://github.com/emberjs/data/tree/main/packages/serializer) behavior.
409
+ Additional handlers or a service injection like the above would need to be done by the
410
+ consuming application in order to make broader use of `RequestManager`.
411
+
412
+ ```ts
413
+ import Store, { CacheHandler } from 'ember-data-mirror/store';
414
+ import RequestManager from '@ember-data-mirror/request';
415
+ import Fetch from '@ember-data-mirror/request/fetch';
416
+ import { LegacyNetworkHandler } from '@ember-data-mirror/legacy-compat';
417
+
418
+ export default class extends Store {
419
+ requestManager = new RequestManager();
420
+
421
+ constructor(args) {
422
+ super(args);
423
+ this.requestManager.use([LegacyNetworkHandler, Fetch]);
424
+ this.requestManager.useCache(CacheHandler);
425
+ }
426
+ }
427
+ ```
428
+
429
+ To provide a different configuration, import and extend `ember-data/store`. The
430
+ default configuration will be ignored if the `requestManager` property is set,
431
+ though the store will still register the CacheHandler.
432
+
433
+ For usage of the store's `requestManager` via `store.request(<req>)` see the
434
+ [Store](https://api.emberjs.com/ember-data/release/modules/@ember-data%2Fstore) documentation.
435
+
436
+ *
437
+ * @module @ember-data-mirror/request
438
+ * @main @ember-data-mirror/request
439
+ */
440
+
441
+ /**
442
+ * ```js
443
+ * import RequestManager from '@ember-data-mirror/request';
444
+ * ```
445
+ *
446
+ * A RequestManager provides a request/response flow in which configured
447
+ * handlers are successively given the opportunity to handle, modify, or
448
+ * pass-along a request.
449
+ *
450
+ * ```ts
451
+ * interface RequestManager {
452
+ * request<T>(req: RequestInfo): Future<T>;
453
+ * }
454
+ * ```
455
+ *
456
+ * For example:
457
+ *
458
+ * ```ts
459
+ * import RequestManager from '@ember-data-mirror/request';
460
+ * import Fetch from '@ember-data-mirror/request/fetch';
461
+ * import Auth from 'ember-simple-auth/ember-data-handler';
462
+ * import Config from './config';
463
+ *
464
+ * const { apiUrl } = Config;
465
+ *
466
+ * // ... create manager
467
+ * const manager = new RequestManager().use([Auth, Fetch]);
468
+ *
469
+ * // ... execute a request
470
+ * const response = await manager.request({
471
+ * url: `${apiUrl}/users`
472
+ * });
473
+ * ```
474
+ *
475
+ * ### Futures
476
+ *
477
+ * The return value of `manager.request` is a `Future`, which allows
478
+ * access to limited information about the request while it is still
479
+ * pending and fulfills with the final state when the request completes.
480
+ *
481
+ * A `Future` is cancellable via `abort`.
482
+ *
483
+ * Handlers may optionally expose a `ReadableStream` to the `Future` for
484
+ * streaming data; however, when doing so the future should not resolve
485
+ * until the response stream is fully read.
486
+ *
487
+ * ```ts
488
+ * interface Future<T> extends Promise<StructuredDocument<T>> {
489
+ * abort(): void;
490
+ *
491
+ * async getStream(): ReadableStream | null;
492
+ * }
493
+ * ```
494
+ *
495
+ * ### StructuredDocuments
496
+ *
497
+ * A Future resolves with a `StructuredDataDocument` or rejects with a `StructuredErrorDocument`.
498
+ *
499
+ * ```ts
500
+ * interface StructuredDataDocument<T> {
501
+ * request: ImmutableRequestInfo;
502
+ * response: ImmutableResponseInfo;
503
+ * content: T;
504
+ * }
505
+ * interface StructuredErrorDocument extends Error {
506
+ * request: ImmutableRequestInfo;
507
+ * response: ImmutableResponseInfo;
508
+ * error: string | object;
509
+ * }
510
+ * type StructuredDocument<T> = StructuredDataDocument<T> | StructuredErrorDocument;
511
+ * ```
512
+ *
513
+ * @class RequestManager
514
+ * @public
515
+ */
516
+ class RequestManager {
517
+ #handlers = [];
518
+
519
+ /**
520
+ * A map of pending requests from request.id to their
521
+ * associated CacheHandler promise.
522
+ *
523
+ * This queue is managed by the CacheHandler
524
+ *
525
+ * @internal
526
+ */
527
+
528
+ constructor(options) {
529
+ Object.assign(this, options);
530
+ this._pending = new Map();
531
+ this._deduped = new Map();
532
+ }
533
+
534
+ /**
535
+ * Register a handler to use for primary cache intercept.
536
+ *
537
+ * Only one such handler may exist. If using the same
538
+ * RequestManager as the Store instance the Store
539
+ * registers itself as a Cache handler.
540
+ *
541
+ * @method useCache
542
+ * @public
543
+ * @param {Handler[]} cacheHandler
544
+ * @return {ThisType}
545
+ */
546
+ useCache(cacheHandler) {
547
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
548
+ if (this._hasCacheHandler) {
549
+ throw new Error(`\`RequestManager.useCache(<handler>)\` May only be invoked once.`);
550
+ }
551
+ if (Object.isFrozen(this.#handlers)) {
552
+ throw new Error(`\`RequestManager.useCache(<handler>)\` May only be invoked prior to any request having been made.`);
553
+ }
554
+ this._hasCacheHandler = true;
555
+ }
556
+ cacheHandler[IS_CACHE_HANDLER] = true;
557
+ this.#handlers.unshift(cacheHandler);
558
+ return this;
559
+ }
560
+
561
+ /**
562
+ * Register handler(s) to use when a request is issued.
563
+ *
564
+ * Handlers will be invoked in the order they are registered.
565
+ * Each Handler is given the opportunity to handle the request,
566
+ * curry the request, or pass along a modified request.
567
+ *
568
+ * @method use
569
+ * @public
570
+ * @param {Handler[]} newHandlers
571
+ * @return {ThisType}
572
+ */
573
+ use(newHandlers) {
574
+ const handlers = this.#handlers;
575
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
576
+ if (Object.isFrozen(handlers)) {
577
+ throw new Error(`Cannot add a Handler to a RequestManager after a request has been made`);
578
+ }
579
+ if (!Array.isArray(newHandlers)) {
580
+ throw new Error(`\`RequestManager.use(<Handler[]>)\` expects an array of handlers, but was called with \`${typeof newHandlers}\``);
581
+ }
582
+ newHandlers.forEach((handler, index) => {
583
+ if (!handler || typeof handler !== 'object' || typeof handler.request !== 'function') {
584
+ throw new Error(`\`RequestManager.use(<Handler[]>)\` expected to receive an array of handler objects with request methods, by the handler at index ${index} does not conform.`);
585
+ }
586
+ });
587
+ }
588
+ handlers.push(...newHandlers);
589
+ return this;
590
+ }
591
+
592
+ /**
593
+ * Issue a Request.
594
+ *
595
+ * Returns a Future that fulfills with a StructuredDocument
596
+ *
597
+ * @method request
598
+ * @public
599
+ * @param {RequestInfo} request
600
+ * @return {Future}
601
+ */
602
+ request(request) {
603
+ const handlers = this.#handlers;
604
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
605
+ if (!Object.isFrozen(handlers)) {
606
+ Object.freeze(handlers);
607
+ }
608
+ assertValidRequest(request, true);
609
+ }
610
+ const controller = request.controller || new AbortController();
611
+ if (request.controller) {
612
+ delete request.controller;
613
+ }
614
+ const requestId = peekUniversalTransient('REQ_ID') ?? 0;
615
+ setUniversalTransient('REQ_ID', requestId + 1);
616
+ const context = {
617
+ controller,
618
+ response: null,
619
+ stream: null,
620
+ hasRequestedStream: false,
621
+ id: requestId,
622
+ identifier: null
623
+ };
624
+ const promise = executeNextHandler(handlers, request, 0, context);
625
+
626
+ // the cache handler will set the result of the request synchronously
627
+ // if it is able to fulfill the request from the cache
628
+ const cacheResult = getRequestResult(requestId);
629
+ if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
630
+ if (!request.disableTestWaiter) {
631
+ const {
632
+ waitForPromise
633
+ } = importSync('@ember/test-waiters');
634
+ const newPromise = waitForPromise(promise);
635
+ const finalPromise = upgradePromise(newPromise.then(result => {
636
+ setPromiseResult(finalPromise, {
637
+ isError: false,
638
+ result
639
+ });
640
+ clearRequestResult(requestId);
641
+ return result;
642
+ }, error => {
643
+ setPromiseResult(finalPromise, {
644
+ isError: true,
645
+ result: error
646
+ });
647
+ clearRequestResult(requestId);
648
+ throw error;
649
+ }), promise);
650
+ if (cacheResult) {
651
+ setPromiseResult(finalPromise, cacheResult);
652
+ }
653
+ return finalPromise;
654
+ }
655
+ }
656
+
657
+ // const promise1 = store.request(myRequest);
658
+ // const promise2 = store.request(myRequest);
659
+ // promise1 === promise2; // false
660
+ // either we need to make promise1 === promise2, or we need to make sure that
661
+ // we need to have a way to key from request to result
662
+ // such that we can lookup the result here and return it if it exists
663
+ const finalPromise = upgradePromise(promise.then(result => {
664
+ setPromiseResult(finalPromise, {
665
+ isError: false,
666
+ result
667
+ });
668
+ clearRequestResult(requestId);
669
+ return result;
670
+ }, error => {
671
+ setPromiseResult(finalPromise, {
672
+ isError: true,
673
+ result: error
674
+ });
675
+ clearRequestResult(requestId);
676
+ throw error;
677
+ }), promise);
678
+ if (cacheResult) {
679
+ setPromiseResult(finalPromise, cacheResult);
680
+ }
681
+ return finalPromise;
682
+ }
683
+ static create(options) {
684
+ return new this(options);
685
+ }
686
+ }
687
+ export { RequestManager as default, setPromiseResult };