vigor-fetch 5.2.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2822 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- VigorAll: () => VigorAll,
24
- VigorAllBase: () => VigorAllBase,
25
- VigorAllContextBase: () => VigorAllContextBase,
26
- VigorAllEachContextBase: () => VigorAllEachContextBase,
27
- VigorAllError: () => VigorAllError,
28
- VigorAllErrorMessageFuncs: () => VigorAllErrorMessageFuncs,
29
- VigorAllPolicyBase: () => VigorAllPolicyBase,
30
- VigorAllPolicyMiddlewares: () => VigorAllPolicyMiddlewares,
31
- VigorAllPolicyMiddlewaresBase: () => VigorAllPolicyMiddlewaresBase,
32
- VigorAllPolicySettings: () => VigorAllPolicySettings,
33
- VigorAllPolicySettingsBase: () => VigorAllPolicySettingsBase,
34
- VigorCastPlaceholder: () => VigorCastPlaceholder,
35
- VigorDefault: () => VigorDefault,
36
- VigorEmpty: () => VigorEmpty,
37
- VigorError: () => VigorError,
38
- VigorFetch: () => VigorFetch,
39
- VigorFetchBase: () => VigorFetchBase,
40
- VigorFetchContextBase: () => VigorFetchContextBase,
41
- VigorFetchError: () => VigorFetchError,
42
- VigorFetchErrorMessageFuncs: () => VigorFetchErrorMessageFuncs,
43
- VigorFetchPolicyBase: () => VigorFetchPolicyBase,
44
- VigorFetchPolicyMiddlewares: () => VigorFetchPolicyMiddlewares,
45
- VigorFetchPolicyMiddlewaresBase: () => VigorFetchPolicyMiddlewaresBase,
46
- VigorFetchPolicySettings: () => VigorFetchPolicySettings,
47
- VigorFetchPolicySettingsBase: () => VigorFetchPolicySettingsBase,
48
- VigorJitter: () => VigorJitter,
49
- VigorParse: () => VigorParse,
50
- VigorParseBase: () => VigorParseBase,
51
- VigorParseContentTypeStrategy: () => VigorParseContentTypeStrategy,
52
- VigorParseContextBase: () => VigorParseContextBase,
53
- VigorParseError: () => VigorParseError,
54
- VigorParseErrorMessageFuncs: () => VigorParseErrorMessageFuncs,
55
- VigorParsePolicyBase: () => VigorParsePolicyBase,
56
- VigorParsePolicyMiddlewares: () => VigorParsePolicyMiddlewares,
57
- VigorParsePolicyMiddlewaresBase: () => VigorParsePolicyMiddlewaresBase,
58
- VigorParsePolicySettings: () => VigorParsePolicySettings,
59
- VigorParsePolicySettingsBase: () => VigorParsePolicySettingsBase,
60
- VigorParsePolicyStrategies: () => VigorParsePolicyStrategies,
61
- VigorParsePolicyStrategiesBase: () => VigorParsePolicyStrategiesBase,
62
- VigorParseSniffStrategy: () => VigorParseSniffStrategy,
63
- VigorRetry: () => VigorRetry,
64
- VigorRetryBase: () => VigorRetryBase,
65
- VigorRetryContextBase: () => VigorRetryContextBase,
66
- VigorRetryError: () => VigorRetryError,
67
- VigorRetryErrorMessageFuncs: () => VigorRetryErrorMessageFuncs,
68
- VigorRetryPolicyAlgorithms: () => VigorRetryPolicyAlgorithms,
69
- VigorRetryPolicyAlgorithmsBackoff: () => VigorRetryPolicyAlgorithmsBackoff,
70
- VigorRetryPolicyAlgorithmsBackoffBase: () => VigorRetryPolicyAlgorithmsBackoffBase,
71
- VigorRetryPolicyAlgorithmsBase: () => VigorRetryPolicyAlgorithmsBase,
72
- VigorRetryPolicyAlgorithmsConstant: () => VigorRetryPolicyAlgorithmsConstant,
73
- VigorRetryPolicyAlgorithmsConstantBase: () => VigorRetryPolicyAlgorithmsConstantBase,
74
- VigorRetryPolicyAlgorithmsCustom: () => VigorRetryPolicyAlgorithmsCustom,
75
- VigorRetryPolicyAlgorithmsCustomBase: () => VigorRetryPolicyAlgorithmsCustomBase,
76
- VigorRetryPolicyAlgorithmsLinear: () => VigorRetryPolicyAlgorithmsLinear,
77
- VigorRetryPolicyAlgorithmsLinearBase: () => VigorRetryPolicyAlgorithmsLinearBase,
78
- VigorRetryPolicyBase: () => VigorRetryPolicyBase,
79
- VigorRetryPolicyMiddlewares: () => VigorRetryPolicyMiddlewares,
80
- VigorRetryPolicyMiddlewaresBase: () => VigorRetryPolicyMiddlewaresBase,
81
- VigorRetryPolicySettings: () => VigorRetryPolicySettings,
82
- VigorRetryPolicySettingsBase: () => VigorRetryPolicySettingsBase,
83
- VigorStatus: () => VigorStatus,
84
- adoptVigorFetchError: () => adoptVigorFetchError,
85
- createBrand: () => createBrand,
86
- createVigorTimelineRecorder: () => createVigorTimelineRecorder,
87
- default: () => index_default,
88
- findInVigorErrorChain: () => findInVigorErrorChain,
89
- findVigorAllError: () => findVigorAllError,
90
- findVigorFetchError: () => findVigorFetchError,
91
- findVigorParseError: () => findVigorParseError,
92
- findVigorRetryError: () => findVigorRetryError,
93
- isVigorAllError: () => isVigorAllError,
94
- isVigorDefault: () => isVigorDefault,
95
- isVigorEmpty: () => isVigorEmpty,
96
- isVigorFetchError: () => isVigorFetchError,
97
- isVigorInternalMiddleware: () => isVigorInternalMiddleware,
98
- isVigorParseError: () => isVigorParseError,
99
- isVigorRetryError: () => isVigorRetryError,
100
- markVigorInternal: () => markVigorInternal,
101
- readVigorParseBody: () => readVigorParseBody,
102
- vigor: () => vigor
103
- });
104
- module.exports = __toCommonJS(index_exports);
105
-
106
- // src/core/symbol.ts
107
- function createBrand(b, n) {
108
- return `@vigor-fetch:::${b} <- ${n}`;
109
- }
110
- var VigorDefault = /* @__PURE__ */ Symbol("VigorDefault");
111
- var isVigorDefault = (v) => v === VigorDefault;
112
- var VigorEmpty = /* @__PURE__ */ Symbol("VigorEmpty");
113
- var isVigorEmpty = (v) => v === VigorEmpty;
114
- var VigorCastPlaceholder = /* @__PURE__ */ Symbol("VigorCastPlaceholder");
115
-
116
- // src/core/status.ts
117
- var VigorStatus = class {
118
- _base;
119
- _config;
120
- /**
121
- * @param base - The default/base config for this builder.
122
- * @param config - The (possibly partial) config to merge onto `base`.
123
- */
124
- constructor(base, config) {
125
- this._base = base;
126
- this._config = this._merge(base, config, void 0, "replace");
127
- }
128
- /**
129
- * Derives a new instance by merging `patch` onto the current config.
130
- *
131
- * @param patch - Values to overwrite/merge in for this step.
132
- * @param strategy - Optional tree mirroring the shape of `patch`, whose
133
- * leaves may be `"replace" | "concat" | "merge"` to force the merge
134
- * behavior at that path. Paths without a strategy fall back to the
135
- * default behavior (deep merge for objects, concat for arrays).
136
- */
137
- _next(patch, strategy) {
138
- const merged = this._merge(this._config, patch, strategy);
139
- return this._create(merged);
140
- }
141
- /**
142
- * Deep-merges `target` onto `source`, honoring an optional per-path
143
- * `strategy` tree. Objects merge key by key, arrays concatenate (unless
144
- * `"replace"` is specified, or `arrayMode` is `"replace"`), and any other
145
- * value — including `null` — is overwritten. Only `undefined` keeps the
146
- * source value.
147
- */
148
- _merge(source, target, strategy, arrayMode = "concat") {
149
- const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
150
- const deepClone = (v) => {
151
- if (Array.isArray(v)) return v.map(deepClone);
152
- if (isObj(v)) {
153
- const r = {};
154
- for (const k of Object.keys(v)) r[k] = deepClone(v[k]);
155
- return r;
156
- }
157
- return v;
158
- };
159
- const merge = (a, b, s) => {
160
- if (b === void 0) return deepClone(a);
161
- if (s === "replace") return b;
162
- if (Array.isArray(a) && Array.isArray(b)) {
163
- return arrayMode === "replace" ? deepClone(b) : [...a, ...b];
164
- }
165
- if (isObj(a) && isObj(b)) {
166
- const r = {};
167
- const sObj = isObj(s) ? s : void 0;
168
- const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
169
- for (const k of keys) {
170
- r[k] = merge(a[k], b[k], sObj?.[k]);
171
- }
172
- return r;
173
- }
174
- return b;
175
- };
176
- return merge(source, target, strategy);
177
- }
178
- /**
179
- * Snapshots a runtime context for a timeline entry: a `_merge` deep clone
180
- * of everything but `timeline`, so later changes to `ctx` don't reach it.
181
- */
182
- _snapshot(ctx) {
183
- const { timeline: _, ...rest } = ctx;
184
- return this._merge(rest, {});
185
- }
186
- /** The default/base config this builder was constructed with. */
187
- get base() {
188
- return this._base;
189
- }
190
- /** The current, merged config for this builder instance. */
191
- get config() {
192
- return this._config;
193
- }
194
- };
195
-
196
- // src/all/settings.ts
197
- var VigorAllPolicySettingsBase = {
198
- __brand: createBrand("All", "Policy<Settings<Schema"),
199
- debug: false,
200
- concurrency: 5,
201
- onlySuccess: false,
202
- timeout: VigorEmpty,
203
- failFast: false
204
- };
205
- var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
206
- constructor(config = VigorAllBase) {
207
- super(VigorAllBase, config);
208
- }
209
- _create(config) {
210
- return new _VigorAllPolicySettings(config);
211
- }
212
- /** Sets the maximum number of tasks run concurrently. */
213
- concurrency(num) {
214
- return this._next({ policy: { settings: { concurrency: num } } });
215
- }
216
- /** When enabled, filters the final result down to only the tasks that succeeded. */
217
- onlySuccess(bool) {
218
- return this._next({ policy: { settings: { onlySuccess: bool } } });
219
- }
220
- /** Sets the per-task timeout, in milliseconds. A task exceeding it fails with `TIMED_OUT`. */
221
- timeout(num) {
222
- return this._next({ policy: { settings: { timeout: num } } });
223
- }
224
- /** When enabled, the first unrecovered task failure aborts the remaining tasks and fails the batch with that error. */
225
- failFast(bool) {
226
- return this._next({ policy: { settings: { failFast: bool } } });
227
- }
228
- /**
229
- * Turns timeline recording on or off (off by default). Off, the
230
- * `timeline` of `requestVerbose()` stays empty and no context snapshots
231
- * are taken, so it costs nothing unless you're debugging.
232
- */
233
- debug(bool) {
234
- return this._next({ policy: { settings: { debug: bool } } });
235
- }
236
- };
237
-
238
- // src/all/middlewares.ts
239
- var VigorAllPolicyMiddlewaresBase = {
240
- __brand: createBrand("All", "Policy<Middlewares<Schema"),
241
- before: [],
242
- after: [],
243
- onResult: [],
244
- beforeEach: [],
245
- afterEach: [],
246
- onErrorEach: []
247
- };
248
- var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorStatus {
249
- constructor(config = VigorAllBase) {
250
- super(VigorAllBase, config);
251
- }
252
- _create(config) {
253
- return new _VigorAllPolicyMiddlewares(config);
254
- }
255
- before(type, func) {
256
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
257
- }
258
- after(type, func) {
259
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
260
- }
261
- onResult(type, func) {
262
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
263
- }
264
- /** Registers a middleware that runs before each task is invoked. */
265
- beforeEach(func) {
266
- return this._next({ policy: { middlewares: { beforeEach: [func] } } });
267
- }
268
- /** Registers a middleware that runs after each task settles successfully. */
269
- afterEach(func) {
270
- return this._next({ policy: { middlewares: { afterEach: [func] } } });
271
- }
272
- /** Registers a middleware that runs when an individual task fails. */
273
- onErrorEach(func) {
274
- return this._next({ policy: { middlewares: { onErrorEach: [func] } } });
275
- }
276
- };
277
-
278
- // src/all/policy.ts
279
- var VigorAllPolicyBase = {
280
- __brand: createBrand("All", "Policy<Schema"),
281
- target: [],
282
- abortSignals: [],
283
- settings: VigorAllPolicySettingsBase,
284
- middlewares: VigorAllPolicyMiddlewaresBase
285
- };
286
-
287
- // src/all/context.ts
288
- var VigorAllContextBase = {
289
- __brand: createBrand("All", "Context<Schema"),
290
- result: VigorDefault,
291
- policy: VigorAllPolicyBase,
292
- record: {},
293
- timeline: []
294
- };
295
- var VigorAllEachContextBase = {
296
- __brand: createBrand("All", "EachContext<Schema"),
297
- index: 0,
298
- result: VigorDefault,
299
- error: VigorDefault,
300
- flags: { overridden: false },
301
- record: {}
302
- };
303
-
304
- // src/core/error.ts
305
- var VigorError = class extends Error {
306
- timestamp = /* @__PURE__ */ new Date();
307
- cause;
308
- code;
309
- data;
310
- method;
311
- /** The run context when the error was raised; its presence depends on the code (see {@link VigorErrorContext}). */
312
- context;
313
- /**
314
- * @param code - Machine-readable error code.
315
- * @param message - Human-readable message (rendered after the `[code]` prefix).
316
- * @param options - Additional error metadata (cause, data, method, context).
317
- */
318
- constructor(code, message, options) {
319
- super(`[${code}] ${message}`);
320
- this.name = new.target.name;
321
- this.code = code;
322
- this.cause = options.cause;
323
- this.data = options.data;
324
- this.method = options.method;
325
- this.context = options.context;
326
- Object.setPrototypeOf(this, new.target.prototype);
327
- Error.captureStackTrace?.(this, new.target);
328
- }
329
- };
330
- function findInVigorErrorChain(error, match) {
331
- const seen = /* @__PURE__ */ new Set();
332
- const visit = (current) => {
333
- if (current === null || current === void 0 || seen.has(current)) return void 0;
334
- seen.add(current);
335
- if (match(current)) return current;
336
- if (typeof current !== "object") return void 0;
337
- const data = current.data;
338
- if (current instanceof VigorError && data !== null && typeof data === "object" && "error" in data) {
339
- const found = visit(data.error);
340
- if (found !== void 0) return found;
341
- }
342
- return visit(current.cause);
343
- };
344
- return visit(error);
345
- }
346
-
347
- // src/all/error.ts
348
- var VigorAllErrorMessageFuncs = {
349
- EMPTY_TARGET: (_) => `Empty target list`,
350
- TIMED_OUT: ({ limit, index }) => `Task #${index} timeout: exceeded ${limit}ms`
351
- };
352
- var VigorAllError = class extends VigorError {
353
- /**
354
- * @param code - One of the all module's error codes.
355
- * @param options - Error metadata, including the `data` payload for `code`.
356
- */
357
- constructor(code, options) {
358
- const messageFn = VigorAllErrorMessageFuncs[code];
359
- super(code, messageFn(options.data), options);
360
- }
361
- };
362
- function isVigorAllError(error, ...codes) {
363
- return error instanceof VigorAllError && (codes.length === 0 || codes.includes(error.code));
364
- }
365
- function findVigorAllError(error, ...codes) {
366
- const found = findInVigorErrorChain(error, (e) => isVigorAllError(e, ...codes));
367
- return found === void 0 ? null : found;
368
- }
369
-
370
- // src/core/timeline.ts
371
- var internalMiddlewares = /* @__PURE__ */ new WeakSet();
372
- function markVigorInternal(func) {
373
- internalMiddlewares.add(func);
374
- return func;
375
- }
376
- function isVigorInternalMiddleware(middleware) {
377
- const func = typeof middleware === "function" ? middleware : middleware?.func;
378
- return typeof func === "function" && internalMiddlewares.has(func);
379
- }
380
- function createVigorTimelineRecorder(timeline, snapshot, enabled) {
381
- const add = (action, content) => {
382
- if (!enabled) return;
383
- timeline.push({ action, content, now: Date.now(), ctx: snapshot() });
384
- };
385
- const record = add;
386
- const stage = async (stage2, middlewares, run) => {
387
- if (middlewares.length === 0) return;
388
- if (!enabled) {
389
- for (const middleware of middlewares) await run(middleware, (api) => api);
390
- return;
391
- }
392
- record("MIDDLEWARE_LOOP_STARTED", { stage: stage2, middlewares });
393
- const started = performance.now();
394
- try {
395
- for (const [index, middleware] of middlewares.entries()) {
396
- const internal = isVigorInternalMiddleware(middleware);
397
- const ranAt = performance.now();
398
- try {
399
- await run(middleware, (api) => {
400
- const traced = {};
401
- for (const [method, func] of Object.entries(api)) {
402
- traced[method] = (...args) => {
403
- record("MIDDLEWARE_API_CALLED", { stage: stage2, index, middleware, internal, method, args });
404
- return func(...args);
405
- };
406
- }
407
- return traced;
408
- });
409
- } catch (error) {
410
- record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: true, error });
411
- throw error;
412
- }
413
- record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: false, error: null });
414
- }
415
- } finally {
416
- record("MIDDLEWARE_LOOP_ENDED", { stage: stage2, middlewares, took: performance.now() - started });
417
- }
418
- };
419
- return { add, stage };
420
- }
421
-
422
- // src/all/main.ts
423
- var MAX_TIMEOUT = 2 ** 31 - 1;
424
- var VigorAllBase = {
425
- __brand: createBrand("All", "Schema"),
426
- policy: VigorAllPolicyBase,
427
- cast: VigorEmpty
428
- };
429
- var VigorAll = class _VigorAll extends VigorStatus {
430
- constructor(config = VigorAllBase) {
431
- super(VigorAllBase, config);
432
- }
433
- _create(config) {
434
- return new _VigorAll(config);
435
- }
436
- /** Sets the list of tasks to run. */
437
- target(...funcs) {
438
- return this._next({ policy: { target: funcs } });
439
- }
440
- /** Sets external abort signals that, when aborted, cancel the remaining tasks and fail the batch. */
441
- abortSignals(...sig) {
442
- return this._next({ policy: { abortSignals: sig } });
443
- }
444
- settings(input) {
445
- if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
446
- const result = typeof input === "function" ? input(new VigorAllPolicySettings(this.config)) : input;
447
- return this._next({
448
- policy: { settings: result.config.policy.settings }
449
- });
450
- }
451
- return this._next({ policy: { settings: input } });
452
- }
453
- middlewares(input) {
454
- if (typeof input === "function" || input instanceof VigorAllPolicyMiddlewares) {
455
- const result = typeof input === "function" ? input(new VigorAllPolicyMiddlewares()) : input;
456
- return this._next({
457
- policy: { middlewares: result.config.policy.middlewares }
458
- });
459
- }
460
- return this._next({ policy: { middlewares: input } });
461
- }
462
- /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
463
- async _runTask(task, index, policy, batchSignal, timeline, debug) {
464
- let ctx = this._merge(VigorAllEachContextBase, { index });
465
- const { add, stage } = createVigorTimelineRecorder(timeline, () => this._merge(ctx, {}), debug);
466
- const timeoutController = new AbortController();
467
- const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
468
- let timeoutId;
469
- let onAbort;
470
- add("TASK_STARTED", { index });
471
- const started = performance.now();
472
- const settle = (res) => {
473
- add("TASK_ENDED", { index, success: res.success, took: performance.now() - started });
474
- return res;
475
- };
476
- try {
477
- await stage("beforeEach", policy.middlewares.beforeEach, (beforeEach) => beforeEach(ctx));
478
- signal.throwIfAborted();
479
- const limit = policy.settings.timeout;
480
- if (!isVigorEmpty(limit) && Number.isFinite(limit) && limit > 0) {
481
- timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
482
- method: "request",
483
- data: { limit, index }
484
- })), Math.min(limit, MAX_TIMEOUT));
485
- }
486
- ctx.result = await Promise.race([
487
- task(signal),
488
- new Promise((_, rej) => {
489
- onAbort = () => rej(signal.reason);
490
- signal.addEventListener("abort", onAbort);
491
- })
492
- ]);
493
- await stage("afterEach", policy.middlewares.afterEach, (afterEach) => afterEach(ctx));
494
- return settle({ success: true, value: ctx.result });
495
- } catch (error) {
496
- ctx.error = error;
497
- add("TASK_ERROR", { index, error });
498
- const setResult = (r) => {
499
- ctx.flags.overridden = true;
500
- ctx.result = r;
501
- };
502
- await stage("onErrorEach", policy.middlewares.onErrorEach, (onErrorEach, trace) => onErrorEach(ctx, trace({ setResult })));
503
- if (ctx.flags.overridden) return settle({ success: true, value: ctx.result });
504
- return settle({ success: false, value: error });
505
- } finally {
506
- clearTimeout(timeoutId);
507
- if (onAbort) signal.removeEventListener("abort", onAbort);
508
- }
509
- }
510
- /**
511
- * Overrides the resolved result type with `T`, taking priority over the
512
- * naturally-inferred `unknown[]`. Can be called before or after
513
- * `target()` (or any other configuration method); whichever `.cast<T>()`
514
- * call happens last wins.
515
- */
516
- cast() {
517
- return this._next(
518
- { cast: VigorCastPlaceholder },
519
- { cast: "replace" }
520
- );
521
- }
522
- /**
523
- * Runs all tasks and returns the results array directly, throwing on final failure.
524
- *
525
- * `R` defaults to the inferred result type. Passing one (`request<User>()`)
526
- * means "ignore the inference, it's this": it's taken as-is, unchecked.
527
- * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
528
- */
529
- async request() {
530
- const res = await this.requestVerbose();
531
- if (res.success) return res.data;
532
- throw res.error;
533
- }
534
- /**
535
- * Runs all tasks and returns a result/error envelope instead of throwing,
536
- * along with the `timeline` of everything the batch went through.
537
- */
538
- async requestVerbose() {
539
- return await this.requestRuntime();
540
- }
541
- /** Internal execution loop implementing the bounded-concurrency worker pool and the batch-level before/after/onResult pipeline. */
542
- async requestRuntime(timeline = []) {
543
- const config = this._merge(this.config, {});
544
- const policy = config.policy;
545
- let ctx = this._merge(VigorAllContextBase, {
546
- policy
547
- }, void 0, "replace");
548
- ctx.timeline = timeline;
549
- const startedAt = performance.now();
550
- const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
551
- const end = (success, error) => add("REQUEST_END", {
552
- success,
553
- outcome: success ? "result" : "failed",
554
- error,
555
- took: performance.now() - startedAt,
556
- restarts: 0
557
- });
558
- const setResult = (r) => {
559
- ctx.result = r;
560
- };
561
- const throwError = (err) => {
562
- throw err;
563
- };
564
- const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
565
- add("PROCESS_HANDLING", { type: "REQUEST_START", data: { tasks: policy.target.length, concurrency } });
566
- try {
567
- if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
568
- method: "request",
569
- data: {},
570
- context: ctx
571
- });
572
- await stage("before", policy.middlewares.before, async (mw, trace) => {
573
- if (mw._mode === "fluent") {
574
- await mw.func(ctx);
575
- } else {
576
- ctx = await mw.func(ctx, trace({ throwError })) ?? ctx;
577
- }
578
- });
579
- const results = new Array(policy.target.length);
580
- const batchController = new AbortController();
581
- const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
582
- let cursor = 0;
583
- const worker = async () => {
584
- while (!batchSignal.aborted) {
585
- const i = cursor++;
586
- if (i >= policy.target.length) return;
587
- try {
588
- results[i] = await this._runTask(policy.target[i], i, policy, batchSignal, timeline, policy.settings.debug);
589
- } catch (error) {
590
- batchController.abort(error);
591
- return;
592
- }
593
- if (!results[i].success && policy.settings.failFast) {
594
- batchController.abort(results[i].value);
595
- }
596
- }
597
- };
598
- await Promise.all(
599
- Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
600
- );
601
- batchSignal.throwIfAborted();
602
- ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.success ? { success: true, data: r.value, error: null } : { success: false, data: null, error: r.value });
603
- await stage("after", policy.middlewares.after, async (mw, trace) => {
604
- if (mw._mode === "fluent") {
605
- await mw.func(ctx);
606
- } else {
607
- ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
608
- }
609
- });
610
- await stage("onResult", policy.middlewares.onResult, async (mw, trace) => {
611
- if (mw._mode === "fluent") {
612
- ctx.result = await mw.func(ctx.result);
613
- } else {
614
- ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
615
- }
616
- });
617
- end(true, null);
618
- return {
619
- success: true,
620
- data: ctx.result,
621
- error: null,
622
- timeline
623
- };
624
- } catch (error) {
625
- add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
626
- end(false, error);
627
- return {
628
- success: false,
629
- data: null,
630
- error,
631
- timeline
632
- };
633
- }
634
- }
635
- };
636
-
637
- // src/fetch/settings.ts
638
- var VigorFetchPolicySettingsBase = {
639
- __brand: createBrand("Fetch", "Policy<Settings<Schema"),
640
- debug: false,
641
- retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
642
- // Statuses a retry of the same request won't change. Left retryable on
643
- // purpose: 408 (timeout), 421 (misdirected — another connection may
644
- // work), 423 (locked), 425 (too early), 429 (rate limit), and 5xx
645
- // outages (500, 502, 503, 504, 507).
646
- unretryStatus: [
647
- 400,
648
- 401,
649
- 402,
650
- 403,
651
- 404,
652
- 405,
653
- 406,
654
- 407,
655
- 409,
656
- 410,
657
- 411,
658
- 412,
659
- 413,
660
- 414,
661
- 415,
662
- 416,
663
- 417,
664
- 422,
665
- 424,
666
- 426,
667
- 428,
668
- 431,
669
- 451,
670
- 501,
671
- 505,
672
- 506,
673
- 508,
674
- 510,
675
- 511
676
- ],
677
- maxRetryAfter: 5 * 60 * 1e3,
678
- redirect: false,
679
- confinePath: true,
680
- maxRestarts: 3,
681
- default: VigorEmpty
682
- };
683
- var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStatus {
684
- constructor(config = VigorFetchBase) {
685
- super(VigorFetchBase, config);
686
- }
687
- _create(config) {
688
- return new _VigorFetchPolicySettings(config);
689
- }
690
- /** Sets (replaces) the response headers consulted to compute a server-suggested retry delay. */
691
- retryHeaders(...strs) {
692
- return this._next({ policy: { settings: { retryHeaders: strs } } }, { policy: { settings: { retryHeaders: "replace" } } });
693
- }
694
- /** Sets (replaces) the HTTP status codes that should never be retried. */
695
- unretryStatus(...nums) {
696
- return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
697
- }
698
- /** Sets the upper bound, in milliseconds, on a server-suggested retry delay. */
699
- maxRetryAfter(num) {
700
- return this._next({ policy: { settings: { maxRetryAfter: num } } });
701
- }
702
- /**
703
- * When enabled, a redirected response (or a readable `3xx` with a
704
- * `Location` header) navigates the page to its target
705
- * (`window.location.href`). Without `window.location` — e.g. in Node —
706
- * this behaves like `false`.
707
- */
708
- /**
709
- * When enabled (the default), a request whose URL would leave its
710
- * origin's domain or path (e.g. through a `".."` path segment) fails with
711
- * `PATH_ESCAPED` instead of being sent.
712
- */
713
- confinePath(bool) {
714
- return this._next({ policy: { settings: { confinePath: bool } } });
715
- }
716
- redirect(bool) {
717
- return this._next({ policy: { settings: { redirect: bool } } });
718
- }
719
- /** Sets the maximum number of full restarts allowed. */
720
- maxRestarts(num) {
721
- return this._next({ policy: { settings: { maxRestarts: num } } });
722
- }
723
- /** Sets the fallback value/factory used when the request ultimately fails. */
724
- default(func) {
725
- return this._next({ policy: { settings: { default: func } } });
726
- }
727
- /**
728
- * Turns timeline recording on or off (off by default). Off, the
729
- * `timeline` of `requestVerbose()` stays empty and no context snapshots
730
- * are taken, so it costs nothing unless you're debugging. With it on,
731
- * the nested retry/parse engines record theirs too.
732
- */
733
- debug(bool) {
734
- return this._next({ policy: { settings: { debug: bool } } });
735
- }
736
- };
737
-
738
- // src/fetch/middlewares.ts
739
- var VigorFetchPolicyMiddlewaresBase = {
740
- __brand: createBrand("Fetch", "Policy<Middlewares<Schema"),
741
- before: [],
742
- after: [],
743
- onResult: [],
744
- onError: []
745
- };
746
- var VigorFetchPolicyMiddlewares = class _VigorFetchPolicyMiddlewares extends VigorStatus {
747
- constructor(config = VigorFetchBase) {
748
- super(VigorFetchBase, config);
749
- }
750
- _create(config) {
751
- return new _VigorFetchPolicyMiddlewares(config);
752
- }
753
- before(type, func) {
754
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
755
- }
756
- after(type, func) {
757
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
758
- }
759
- onResult(type, func) {
760
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
761
- }
762
- onError(type, func) {
763
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
764
- }
765
- };
766
-
767
- // src/retry/settings.ts
768
- var VigorRetryPolicySettingsBase = {
769
- __brand: createBrand("Retry", "Policy<Settings<Schema"),
770
- debug: false,
771
- default: VigorEmpty,
772
- maxAttempts: 5,
773
- maxRestarts: 3,
774
- timeout: 2e4
775
- };
776
- var VigorRetryPolicySettings = class _VigorRetryPolicySettings extends VigorStatus {
777
- constructor(config = VigorRetryBase) {
778
- super(VigorRetryBase, config);
779
- }
780
- _create(config) {
781
- return new _VigorRetryPolicySettings(config);
782
- }
783
- /** Sets the fallback value/factory used when the target ultimately fails. */
784
- default(func) {
785
- return this._next({
786
- policy: { settings: { default: func } }
787
- });
788
- }
789
- /** Sets the maximum number of retry attempts before giving up. */
790
- maxAttempts(num) {
791
- return this._next({
792
- policy: { settings: { maxAttempts: num } }
793
- });
794
- }
795
- /** Sets the maximum number of full restarts allowed. */
796
- maxRestarts(num) {
797
- return this._next({
798
- policy: { settings: { maxRestarts: num } }
799
- });
800
- }
801
- /** Sets the timeout, in milliseconds, for a single attempt. */
802
- timeout(num) {
803
- return this._next({
804
- policy: { settings: { timeout: num } }
805
- });
806
- }
807
- /**
808
- * Turns timeline recording on or off (off by default). Off, the
809
- * `timeline` of `requestVerbose()` stays empty and no context snapshots
810
- * are taken, so it costs nothing unless you're debugging.
811
- */
812
- debug(bool) {
813
- return this._next({ policy: { settings: { debug: bool } } });
814
- }
815
- };
816
-
817
- // src/retry/middlewares.ts
818
- var VigorRetryPolicyMiddlewaresBase = {
819
- __brand: createBrand("Retry", "Policy<Middlewares<Schema"),
820
- before: [],
821
- after: [],
822
- onResult: [],
823
- retryIf: [],
824
- onRetry: [],
825
- onError: []
826
- };
827
- var VigorRetryPolicyMiddlewares = class _VigorRetryPolicyMiddlewares extends VigorStatus {
828
- constructor(config = VigorRetryBase) {
829
- super(VigorRetryBase, config);
830
- }
831
- _create(config) {
832
- return new _VigorRetryPolicyMiddlewares(config);
833
- }
834
- before(type, func) {
835
- return this._next({
836
- policy: { middlewares: { before: [{ _mode: type, func }] } }
837
- });
838
- }
839
- after(type, func) {
840
- return this._next({
841
- policy: { middlewares: { after: [{ _mode: type, func }] } }
842
- });
843
- }
844
- onResult(type, func) {
845
- return this._next({
846
- policy: { middlewares: { onResult: [{ _mode: type, func }] } }
847
- });
848
- }
849
- retryIf(type, func) {
850
- return this._next({
851
- policy: { middlewares: { retryIf: [{ _mode: type, func }] } }
852
- });
853
- }
854
- onRetry(type, func) {
855
- return this._next({
856
- policy: { middlewares: { onRetry: [{ _mode: type, func }] } }
857
- });
858
- }
859
- onError(type, func) {
860
- return this._next({
861
- policy: { middlewares: { onError: [{ _mode: type, func }] } }
862
- });
863
- }
864
- };
865
-
866
- // src/retry/error.ts
867
- var VigorRetryErrorMessageFuncs = {
868
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
869
- RETRY_EXHAUSTED: ({ maxAttempts }) => `Retry exhausted, (max ${maxAttempts})`,
870
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
871
- TIMED_OUT: ({ limit }) => `Timeout: exceeded ${limit}ms`
872
- };
873
- var VigorRetryError = class extends VigorError {
874
- /**
875
- * @param code - One of the retry module's error codes.
876
- * @param options - Error metadata, including the `data` payload for `code`.
877
- */
878
- constructor(code, options) {
879
- const messageFn = VigorRetryErrorMessageFuncs[code];
880
- super(code, messageFn(options.data), options);
881
- }
882
- };
883
- function isVigorRetryError(error, ...codes) {
884
- return error instanceof VigorRetryError && (codes.length === 0 || codes.includes(error.code));
885
- }
886
- function findVigorRetryError(error, ...codes) {
887
- const found = findInVigorErrorChain(error, (e) => isVigorRetryError(e, ...codes));
888
- return found === void 0 ? null : found;
889
- }
890
-
891
- // src/retry/algorithms.ts
892
- function VigorJitter(jitter) {
893
- return (Math.random() * 2 - 1) * jitter;
894
- }
895
- var VigorRetryPolicyAlgorithmsConstantBase = {
896
- __brand: createBrand("Retry", "Policy<Algorithms<Constant<Schema"),
897
- _tag: "constant",
898
- jitter: 1e3,
899
- interval: 2e3,
900
- _calculateDelay: (att, config) => {
901
- const { interval, jitter } = config;
902
- const min = jitter;
903
- let delay = Math.max(min, interval);
904
- delay += VigorJitter(jitter);
905
- return delay;
906
- }
907
- };
908
- var VigorRetryPolicyAlgorithmsConstant = class _VigorRetryPolicyAlgorithmsConstant extends VigorStatus {
909
- constructor(config = VigorRetryPolicyAlgorithmsConstantBase) {
910
- super(VigorRetryPolicyAlgorithmsConstantBase, config);
911
- }
912
- _create(config) {
913
- return new _VigorRetryPolicyAlgorithmsConstant(config);
914
- }
915
- /** Sets the amount of random jitter added to the computed delay. */
916
- jitter(num) {
917
- return this._next({ jitter: num });
918
- }
919
- /** Sets the fixed delay interval, in milliseconds. */
920
- interval(num) {
921
- return this._next({ interval: num });
922
- }
923
- };
924
- var VigorRetryPolicyAlgorithmsLinearBase = {
925
- __brand: createBrand("Retry", "Policy<Algorithms<Linear<Schema"),
926
- _tag: "linear",
927
- jitter: 1e3,
928
- initial: 500,
929
- increment: 1e3,
930
- minDelay: 0,
931
- maxDelay: 1e4,
932
- _calculateDelay: (att, config) => {
933
- const { initial, jitter, increment, minDelay, maxDelay } = config;
934
- const range = maxDelay - minDelay;
935
- const j = Math.min(jitter, range / 2);
936
- const min = minDelay + j;
937
- const max = maxDelay - j;
938
- let delay = initial + increment * att;
939
- delay = Math.max(min, Math.min(max, delay));
940
- delay += VigorJitter(j);
941
- return delay;
942
- }
943
- };
944
- var VigorRetryPolicyAlgorithmsLinear = class _VigorRetryPolicyAlgorithmsLinear extends VigorStatus {
945
- constructor(config = VigorRetryPolicyAlgorithmsLinearBase) {
946
- super(VigorRetryPolicyAlgorithmsLinearBase, config);
947
- }
948
- _create(config) {
949
- return new _VigorRetryPolicyAlgorithmsLinear(config);
950
- }
951
- /** Sets the amount of random jitter added to the computed delay. */
952
- jitter(num) {
953
- return this._next({ jitter: num });
954
- }
955
- /** Sets the initial delay, in milliseconds, before the first retry. */
956
- initial(num) {
957
- return this._next({ initial: num });
958
- }
959
- /** Sets how much the delay grows, in milliseconds, per attempt. */
960
- increment(num) {
961
- return this._next({ increment: num });
962
- }
963
- /** Sets the minimum allowed delay, in milliseconds. */
964
- minDelay(num) {
965
- return this._next({ minDelay: num });
966
- }
967
- /** Sets the maximum allowed delay, in milliseconds. */
968
- maxDelay(num) {
969
- return this._next({ maxDelay: num });
970
- }
971
- };
972
- var VigorRetryPolicyAlgorithmsBackoffBase = {
973
- __brand: createBrand("Retry", "Policy<Algorithms<Backoff<Schema"),
974
- _tag: "backoff",
975
- jitter: 800,
976
- initial: 0,
977
- multiplier: 1.7,
978
- unit: 1e3,
979
- minDelay: 500,
980
- maxDelay: 1e4,
981
- _calculateDelay: (att, config) => {
982
- const { jitter, initial, multiplier, unit, minDelay, maxDelay } = config;
983
- const range = maxDelay - minDelay;
984
- const j = Math.min(jitter, range / 2);
985
- const min = minDelay + j;
986
- const max = maxDelay - j;
987
- let delay = initial + unit * Math.pow(multiplier, att);
988
- delay = Math.max(min, Math.min(max, delay));
989
- delay += VigorJitter(j);
990
- return delay;
991
- }
992
- };
993
- var VigorRetryPolicyAlgorithmsBackoff = class _VigorRetryPolicyAlgorithmsBackoff extends VigorStatus {
994
- constructor(config = VigorRetryPolicyAlgorithmsBackoffBase) {
995
- super(VigorRetryPolicyAlgorithmsBackoffBase, config);
996
- }
997
- _create(config) {
998
- return new _VigorRetryPolicyAlgorithmsBackoff(config);
999
- }
1000
- /** Sets the amount of random jitter added to the computed delay. */
1001
- jitter(num) {
1002
- return this._next({ jitter: num });
1003
- }
1004
- /** Sets the initial delay, in milliseconds, before backoff growth is applied. */
1005
- initial(num) {
1006
- return this._next({ initial: num });
1007
- }
1008
- /** Sets the exponential growth factor applied per attempt. */
1009
- multiplier(num) {
1010
- return this._next({ multiplier: num });
1011
- }
1012
- /** Sets the base unit, in milliseconds, the multiplier is scaled by. */
1013
- unit(num) {
1014
- return this._next({ unit: num });
1015
- }
1016
- /** Sets the minimum allowed delay, in milliseconds. */
1017
- minDelay(num) {
1018
- return this._next({ minDelay: num });
1019
- }
1020
- /** Sets the maximum allowed delay, in milliseconds. */
1021
- maxDelay(num) {
1022
- return this._next({ maxDelay: num });
1023
- }
1024
- };
1025
- var VigorRetryPolicyAlgorithmsCustomBase = {
1026
- __brand: createBrand("Retry", "Policy<Algorithms<Custom<Schema"),
1027
- _tag: "custom",
1028
- jitter: 800,
1029
- minDelay: 500,
1030
- maxDelay: 1e4,
1031
- target: VigorEmpty,
1032
- _calculateDelay: (att, config) => {
1033
- const { jitter, minDelay, maxDelay, target } = config;
1034
- if (isVigorEmpty(target)) throw new VigorRetryError("VALUE_REQUIRED", {
1035
- method: "_calculateDelay",
1036
- data: {
1037
- key: "target"
1038
- }
1039
- });
1040
- const range = maxDelay - minDelay;
1041
- const j = Math.min(jitter, range / 2);
1042
- const min = minDelay + j;
1043
- const max = maxDelay - j;
1044
- let delay = target(att);
1045
- delay = Math.max(min, Math.min(max, delay));
1046
- delay += VigorJitter(j);
1047
- return delay;
1048
- }
1049
- };
1050
- var VigorRetryPolicyAlgorithmsCustom = class _VigorRetryPolicyAlgorithmsCustom extends VigorStatus {
1051
- constructor(config = VigorRetryPolicyAlgorithmsCustomBase) {
1052
- super(VigorRetryPolicyAlgorithmsCustomBase, config);
1053
- }
1054
- _create(config) {
1055
- return new _VigorRetryPolicyAlgorithmsCustom(config);
1056
- }
1057
- /** Sets the amount of random jitter added to the computed delay. */
1058
- jitter(num) {
1059
- return this._next({ jitter: num });
1060
- }
1061
- /** Sets the minimum allowed delay, in milliseconds. */
1062
- minDelay(num) {
1063
- return this._next({ minDelay: num });
1064
- }
1065
- /** Sets the maximum allowed delay, in milliseconds. */
1066
- maxDelay(num) {
1067
- return this._next({ maxDelay: num });
1068
- }
1069
- /** Sets the user-supplied function computing the raw delay for an attempt. */
1070
- target(func) {
1071
- return this._next({ target: func });
1072
- }
1073
- };
1074
- var VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsConstantBase;
1075
- var VigorRetryPolicyAlgorithms = class _VigorRetryPolicyAlgorithms extends VigorStatus {
1076
- constructor(config = VigorRetryBase) {
1077
- super(VigorRetryBase, config);
1078
- }
1079
- _create(config) {
1080
- return new _VigorRetryPolicyAlgorithms(config);
1081
- }
1082
- /** Switches to the constant-interval delay algorithm. */
1083
- constant(input) {
1084
- const leaf = this._merge(VigorRetryPolicyAlgorithmsConstantBase, input ?? {});
1085
- return this._next({
1086
- policy: { algorithms: leaf }
1087
- }, { policy: { algorithms: "replace" } });
1088
- }
1089
- /** Switches to the linearly-increasing delay algorithm. */
1090
- linear(input) {
1091
- const leaf = this._merge(VigorRetryPolicyAlgorithmsLinearBase, input ?? {});
1092
- return this._next({
1093
- policy: { algorithms: leaf }
1094
- }, { policy: { algorithms: "replace" } });
1095
- }
1096
- /** Switches to the exponential-backoff delay algorithm. */
1097
- backoff(input) {
1098
- const leaf = this._merge(VigorRetryPolicyAlgorithmsBackoffBase, input ?? {});
1099
- return this._next({
1100
- policy: { algorithms: leaf }
1101
- }, { policy: { algorithms: "replace" } });
1102
- }
1103
- /** Switches to a user-supplied custom delay algorithm. */
1104
- custom(input) {
1105
- const leaf = this._merge(VigorRetryPolicyAlgorithmsCustomBase, input ?? {});
1106
- return this._next({
1107
- policy: { algorithms: leaf }
1108
- }, { policy: { algorithms: "replace" } });
1109
- }
1110
- };
1111
-
1112
- // src/retry/policy.ts
1113
- var VigorRetryPolicyBase = {
1114
- __brand: createBrand("Retry", "Policy<Schema"),
1115
- target: VigorEmpty,
1116
- abortSignals: [],
1117
- settings: VigorRetryPolicySettingsBase,
1118
- middlewares: VigorRetryPolicyMiddlewaresBase,
1119
- algorithms: VigorRetryPolicyAlgorithmsBase
1120
- };
1121
-
1122
- // src/retry/context.ts
1123
- var VigorRetryContextBase = {
1124
- __brand: createBrand("Retry", "Context<Schema"),
1125
- result: VigorDefault,
1126
- error: VigorDefault,
1127
- system: {
1128
- delay: VigorDefault,
1129
- attempt: 0
1130
- },
1131
- flags: {
1132
- doRetry: true,
1133
- doRestart: false,
1134
- brokeRetry: false,
1135
- aborted: false,
1136
- timedOut: false,
1137
- overridden: false
1138
- },
1139
- record: {},
1140
- timeline: [],
1141
- policy: VigorRetryPolicyBase
1142
- };
1143
-
1144
- // src/retry/main.ts
1145
- var MAX_TIMEOUT2 = 2 ** 31 - 1;
1146
- var VigorRetryBase = {
1147
- __brand: createBrand("Retry", "Schema"),
1148
- policy: VigorRetryPolicyBase,
1149
- cast: VigorEmpty
1150
- };
1151
- var VigorRetry = class _VigorRetry extends VigorStatus {
1152
- constructor(config = VigorRetryBase) {
1153
- super(VigorRetryBase, config);
1154
- }
1155
- _create(config) {
1156
- return new _VigorRetry(config);
1157
- }
1158
- /** Sets the target function to invoke, with retry/timeout applied. */
1159
- target(func) {
1160
- return this._next({
1161
- policy: { target: func }
1162
- });
1163
- }
1164
- /** Sets external abort signals that, when aborted, stop retrying. */
1165
- abortSignals(...sig) {
1166
- return this._next({
1167
- policy: { abortSignals: sig }
1168
- });
1169
- }
1170
- settings(input) {
1171
- if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
1172
- const result = typeof input === "function" ? input(new VigorRetryPolicySettings(this.config)) : input;
1173
- return this._next({
1174
- policy: { settings: result.config.policy.settings }
1175
- });
1176
- }
1177
- return this._next({
1178
- policy: { settings: input }
1179
- });
1180
- }
1181
- middlewares(input) {
1182
- if (typeof input === "function" || input instanceof VigorRetryPolicyMiddlewares) {
1183
- const result = typeof input === "function" ? input(new VigorRetryPolicyMiddlewares()) : input;
1184
- return this._next({
1185
- policy: { middlewares: result.config.policy.middlewares }
1186
- });
1187
- }
1188
- return this._next({
1189
- policy: { middlewares: input }
1190
- });
1191
- }
1192
- algorithms(input) {
1193
- if (typeof input === "function") {
1194
- const result = input(new VigorRetryPolicyAlgorithms());
1195
- const algoSlice = result.config.policy.algorithms;
1196
- return this._next({
1197
- policy: { algorithms: algoSlice }
1198
- }, { policy: { algorithms: "replace" } });
1199
- }
1200
- return this._next({
1201
- policy: { algorithms: input }
1202
- }, { policy: { algorithms: "replace" } });
1203
- }
1204
- /**
1205
- * Overrides the resolved result type with `T`, taking priority over the
1206
- * type naturally inferred from `target()`. Can be called before or after
1207
- * `target()` (or any other configuration method); whichever `.cast<T>()`
1208
- * call happens last wins.
1209
- */
1210
- cast() {
1211
- return this._next(
1212
- { cast: VigorCastPlaceholder },
1213
- { cast: "replace" }
1214
- );
1215
- }
1216
- /**
1217
- * Runs the target and returns its result directly, throwing on final failure.
1218
- *
1219
- * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1220
- * means "ignore the inference, it's this": it's taken as-is, unchecked.
1221
- * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1222
- */
1223
- async request() {
1224
- const res = await this.requestVerbose();
1225
- if (res.success) return res.data;
1226
- throw res.error;
1227
- }
1228
- /**
1229
- * Runs the target and returns a result/error envelope instead of throwing,
1230
- * along with the `timeline` of everything the run went through.
1231
- */
1232
- async requestVerbose() {
1233
- return await this.requestRuntime();
1234
- }
1235
- /**
1236
- * Internal execution loop implementing the attempt/retry/restart lifecycle.
1237
- * Never throws: every failure, including one from `onError` or `default`,
1238
- * comes back as an envelope carrying the timeline. A restart passes the
1239
- * same `timeline` on, so it keeps growing across runs; `startedAt` is the
1240
- * first run's start, for `REQUEST_END`'s `took`.
1241
- */
1242
- async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1243
- const config = this._merge(this.config, {});
1244
- let ctx = this._merge(VigorRetryContextBase, {
1245
- policy: config.policy
1246
- }, void 0, "replace");
1247
- ctx.timeline = timeline;
1248
- const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1249
- add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1250
- const end = (success, outcome, error) => add("REQUEST_END", {
1251
- success,
1252
- outcome,
1253
- error,
1254
- took: performance.now() - startedAt,
1255
- restarts: restartAttempt - 1
1256
- });
1257
- const succeed = (data, outcome) => {
1258
- end(true, outcome, null);
1259
- return { success: true, data, error: null, timeline };
1260
- };
1261
- const fail = (error) => {
1262
- end(false, "failed", error);
1263
- return { success: false, data: null, error, timeline };
1264
- };
1265
- const decide = (retry, reason) => add("RETRY_DECISION", { attempt: ctx.system.attempt, retry, reason });
1266
- if (isVigorEmpty(ctx.policy.target)) return fail(new VigorRetryError("VALUE_REQUIRED", {
1267
- method: "request",
1268
- data: {
1269
- key: "target"
1270
- },
1271
- context: ctx
1272
- }));
1273
- const target = ctx.policy.target;
1274
- const throwError = (err) => {
1275
- throw err;
1276
- };
1277
- const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
1278
- try {
1279
- while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
1280
- ctx.system.attempt++;
1281
- add("ATTEMPT_INCREASED", { attempt: ctx.system.attempt });
1282
- add("PROCESS_HANDLING", { type: "RETRY_START", data: { attempt: ctx.system.attempt } });
1283
- ctx.flags.timedOut = false;
1284
- try {
1285
- const breakRetry = (err) => {
1286
- ctx.flags.brokeRetry = true;
1287
- throw err;
1288
- };
1289
- const userController = new AbortController();
1290
- const timeoutController = new AbortController();
1291
- const innerSignals = AbortSignal.any([
1292
- userController.signal,
1293
- timeoutController.signal
1294
- ]);
1295
- const mergedSignals = AbortSignal.any([
1296
- innerSignals,
1297
- outerSignals
1298
- ]);
1299
- let onAbort;
1300
- let timeoutId;
1301
- try {
1302
- await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1303
- if (middleware._mode === "fluent") {
1304
- await middleware.func(ctx);
1305
- } else {
1306
- ctx = await middleware.func(ctx, trace({
1307
- abort: (reason) => userController.abort(reason),
1308
- throwError,
1309
- breakRetry
1310
- })) ?? ctx;
1311
- }
1312
- });
1313
- mergedSignals.throwIfAborted();
1314
- const limit = ctx.policy.settings.timeout;
1315
- if (Number.isFinite(limit) && limit > 0) {
1316
- timeoutId = setTimeout(() => {
1317
- ctx.flags.timedOut = true;
1318
- timeoutController.abort(new VigorRetryError("TIMED_OUT", {
1319
- method: "request",
1320
- data: {
1321
- limit
1322
- },
1323
- context: ctx
1324
- }));
1325
- }, Math.min(limit, MAX_TIMEOUT2));
1326
- }
1327
- const attempt = ctx.system.attempt;
1328
- add("TARGET_REQUEST_STARTED", { attempt });
1329
- const started = performance.now();
1330
- ctx.result = await Promise.race([
1331
- target(mergedSignals),
1332
- new Promise((_, rej) => {
1333
- onAbort = () => rej(mergedSignals.reason);
1334
- mergedSignals.addEventListener("abort", onAbort);
1335
- })
1336
- ]);
1337
- add("TARGET_REQUEST_ENDED", { attempt, took: performance.now() - started });
1338
- await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1339
- if (middleware._mode === "fluent") {
1340
- await middleware.func(ctx);
1341
- } else {
1342
- ctx = await middleware.func(ctx, trace({
1343
- throwError
1344
- })) ?? ctx;
1345
- }
1346
- });
1347
- const setResult = (res) => {
1348
- ctx.result = res;
1349
- };
1350
- await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1351
- if (middleware._mode === "fluent") {
1352
- ctx.result = await middleware.func(ctx.result);
1353
- } else {
1354
- ctx = await middleware.func(ctx, trace({
1355
- setResult,
1356
- throwError
1357
- })) ?? ctx;
1358
- }
1359
- });
1360
- return succeed(ctx.result, "result");
1361
- } finally {
1362
- clearTimeout(timeoutId);
1363
- if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
1364
- }
1365
- } catch (error) {
1366
- ctx.error = error;
1367
- if (outerSignals.aborted) ctx.flags.aborted = true;
1368
- add("PROCESS_HANDLING", { type: "RETRY_ERROR", data: {
1369
- attempt: ctx.system.attempt,
1370
- error,
1371
- timedOut: ctx.flags.timedOut,
1372
- aborted: ctx.flags.aborted
1373
- } });
1374
- if (ctx.flags.aborted) {
1375
- decide(false, "aborted");
1376
- throw ctx.error;
1377
- }
1378
- if (ctx.flags.brokeRetry) {
1379
- decide(false, "breakRetry");
1380
- throw ctx.error;
1381
- }
1382
- ctx.flags.doRetry = true;
1383
- const proceedRetry = () => ctx.flags.doRetry = true;
1384
- const cancelRetry = () => ctx.flags.doRetry = false;
1385
- await stage("retryIf", ctx.policy.middlewares.retryIf, async (middleware, trace) => {
1386
- if (middleware._mode === "fluent") {
1387
- ctx.flags.doRetry = await middleware.func(ctx.error);
1388
- } else {
1389
- ctx = await middleware.func(ctx, trace({
1390
- proceedRetry,
1391
- cancelRetry
1392
- })) ?? ctx;
1393
- }
1394
- });
1395
- if (!ctx.flags.doRetry) {
1396
- decide(false, "cancelled");
1397
- throw ctx.error;
1398
- }
1399
- if (ctx.system.attempt >= ctx.policy.settings.maxAttempts) {
1400
- decide(false, "exhausted");
1401
- break;
1402
- }
1403
- decide(true, "retry");
1404
- ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
1405
- const setDelay = (num) => {
1406
- ctx.system.delay = num;
1407
- };
1408
- await stage("onRetry", ctx.policy.middlewares.onRetry, async (middleware, trace) => {
1409
- if (middleware._mode === "fluent") {
1410
- await middleware.func(ctx.error);
1411
- } else {
1412
- ctx = await middleware.func(ctx, trace({
1413
- throwError,
1414
- setDelay
1415
- })) ?? ctx;
1416
- }
1417
- });
1418
- const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT2);
1419
- add("RETRY_DELAY", { attempt: ctx.system.attempt, delay });
1420
- await new Promise((res, rej) => {
1421
- if (outerSignals.aborted) {
1422
- ctx.flags.aborted = true;
1423
- return rej(outerSignals.reason);
1424
- }
1425
- const onAbort = () => {
1426
- clearTimeout(id);
1427
- ctx.flags.aborted = true;
1428
- rej(outerSignals.reason);
1429
- };
1430
- const id = setTimeout(() => {
1431
- outerSignals.removeEventListener("abort", onAbort);
1432
- res();
1433
- }, delay);
1434
- outerSignals.addEventListener("abort", onAbort, { once: true });
1435
- });
1436
- }
1437
- }
1438
- throw new VigorRetryError("RETRY_EXHAUSTED", {
1439
- method: "request",
1440
- cause: ctx.error,
1441
- data: {
1442
- maxAttempts: ctx.policy.settings.maxAttempts,
1443
- error: ctx.error
1444
- },
1445
- context: ctx
1446
- });
1447
- } catch (error) {
1448
- ctx.error = error;
1449
- add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1450
- ctx.flags.doRestart = false;
1451
- ctx.flags.overridden = false;
1452
- const setResult = (res) => {
1453
- ctx.flags.overridden = true;
1454
- ctx.result = res;
1455
- };
1456
- const proceedRestart = () => ctx.flags.doRestart = true;
1457
- const cancelRestart = () => ctx.flags.doRestart = false;
1458
- try {
1459
- await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1460
- if (middleware._mode === "fluent") {
1461
- await middleware.func(ctx.error);
1462
- } else {
1463
- ctx = await middleware.func(ctx, trace({
1464
- setResult,
1465
- throwError,
1466
- proceedRestart,
1467
- cancelRestart
1468
- })) ?? ctx;
1469
- }
1470
- });
1471
- } catch (err) {
1472
- return fail(err);
1473
- }
1474
- if (ctx.flags.doRestart) {
1475
- if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorRetryError("RESTART_EXHAUSTED", {
1476
- method: "request",
1477
- cause: ctx.error,
1478
- data: {
1479
- maxAttempts: ctx.policy.settings.maxRestarts,
1480
- error: ctx.error
1481
- },
1482
- context: ctx
1483
- }));
1484
- add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
1485
- return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
1486
- }
1487
- if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
1488
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1489
- try {
1490
- return succeed(await ctx.policy.settings.default(ctx), "default");
1491
- } catch (err) {
1492
- return fail(err);
1493
- }
1494
- }
1495
- return fail(ctx.error);
1496
- }
1497
- }
1498
- };
1499
-
1500
- // src/parse/settings.ts
1501
- var VigorParsePolicySettingsBase = {
1502
- __brand: createBrand("Parse", "Policy<Settings<Schema"),
1503
- debug: false,
1504
- raw: false,
1505
- default: VigorEmpty,
1506
- maxRestarts: 3
1507
- };
1508
- var VigorParsePolicySettings = class _VigorParsePolicySettings extends VigorStatus {
1509
- constructor(config = VigorParseBase) {
1510
- super(VigorParseBase, config);
1511
- }
1512
- _create(config) {
1513
- return new _VigorParsePolicySettings(config);
1514
- }
1515
- /** When enabled, skips content-type based parsing and returns the raw response. */
1516
- raw(bool) {
1517
- return this._next({
1518
- policy: { settings: { raw: bool } }
1519
- });
1520
- }
1521
- /** Sets the fallback value/factory used when parsing ultimately fails. */
1522
- default(func) {
1523
- return this._next({
1524
- policy: { settings: { default: func } }
1525
- });
1526
- }
1527
- /** Sets the maximum number of full restarts allowed. */
1528
- maxRestarts(num) {
1529
- return this._next({
1530
- policy: { settings: { maxRestarts: num } }
1531
- });
1532
- }
1533
- /**
1534
- * Turns timeline recording on or off (off by default). Off, the
1535
- * `timeline` of `requestVerbose()` stays empty and no context snapshots
1536
- * are taken, so it costs nothing unless you're debugging.
1537
- */
1538
- debug(bool) {
1539
- return this._next({ policy: { settings: { debug: bool } } });
1540
- }
1541
- };
1542
-
1543
- // src/parse/middlewares.ts
1544
- var VigorParsePolicyMiddlewaresBase = {
1545
- __brand: createBrand("Parse", "Policy<Middlewares<Schema"),
1546
- before: [],
1547
- after: [],
1548
- onResult: [],
1549
- onError: []
1550
- };
1551
- var VigorParsePolicyMiddlewares = class _VigorParsePolicyMiddlewares extends VigorStatus {
1552
- constructor(config = VigorParseBase) {
1553
- super(VigorParseBase, config);
1554
- }
1555
- _create(config) {
1556
- return new _VigorParsePolicyMiddlewares(config);
1557
- }
1558
- before(type, func) {
1559
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
1560
- }
1561
- after(type, func) {
1562
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
1563
- }
1564
- onResult(type, func) {
1565
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
1566
- }
1567
- onError(type, func) {
1568
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
1569
- }
1570
- };
1571
-
1572
- // src/parse/error.ts
1573
- var describeVigorParseFailure = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1574
- var VigorParseErrorMessageFuncs = {
1575
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1576
- INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1577
- PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1578
- PARSER_ALL_FAILED: ({ tried, errors }) => `All parsers failed: ${tried.map((name, i) => `${name} (${describeVigorParseFailure(errors[i])})`).join(", ")}`,
1579
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1580
- };
1581
- var VigorParseError = class extends VigorError {
1582
- /**
1583
- * @param code - One of the parse module's error codes.
1584
- * @param options - Error metadata, including the `data` payload for `code`.
1585
- */
1586
- constructor(code, options) {
1587
- const messageFn = VigorParseErrorMessageFuncs[code];
1588
- super(code, messageFn(options.data), options);
1589
- }
1590
- };
1591
- function isVigorParseError(error, ...codes) {
1592
- return error instanceof VigorParseError && (codes.length === 0 || codes.includes(error.code));
1593
- }
1594
- function findVigorParseError(error, ...codes) {
1595
- const found = findInVigorErrorChain(error, (e) => isVigorParseError(e, ...codes));
1596
- return found === void 0 ? null : found;
1597
- }
1598
-
1599
- // src/parse/strategies.ts
1600
- var VigorParsePolicyStrategiesBase = {
1601
- __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1602
- funcs: []
1603
- };
1604
- var bodyCache = /* @__PURE__ */ new WeakMap();
1605
- async function readVigorParseBody(source) {
1606
- let bytes = bodyCache.get(source);
1607
- if (!bytes) {
1608
- bytes = source.body === null ? Promise.resolve(new Uint8Array(0)) : source.arrayBuffer().then((buf) => new Uint8Array(buf));
1609
- bodyCache.set(source, bytes);
1610
- }
1611
- return {
1612
- bytes: await bytes,
1613
- contentType: source.headers.get("content-type"),
1614
- status: source instanceof Response ? source.status : null,
1615
- headers: source.headers,
1616
- source
1617
- };
1618
- }
1619
- var utf8 = new TextDecoder("utf-8");
1620
- var getCharset = (contentType) => /;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(contentType ?? "")?.[1] ?? "utf-8";
1621
- var getMimeType = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
1622
- var decodeText = (body, fatal = false) => {
1623
- let decoder;
1624
- try {
1625
- decoder = new TextDecoder(getCharset(body.contentType), { fatal });
1626
- } catch {
1627
- decoder = new TextDecoder("utf-8", { fatal });
1628
- }
1629
- return decoder.decode(body.bytes);
1630
- };
1631
- var parseJson = (body) => JSON.parse(utf8.decode(body.bytes));
1632
- var parseJsonOrNull = (body) => {
1633
- const text = utf8.decode(body.bytes);
1634
- return text.trim() === "" ? null : JSON.parse(text);
1635
- };
1636
- var hexValue = (b) => {
1637
- if (b >= 48 && b <= 57) return b - 48;
1638
- if (b >= 65 && b <= 70) return b - 65 + 10;
1639
- if (b >= 97 && b <= 102) return b - 97 + 10;
1640
- return -1;
1641
- };
1642
- var decodeFormComponent = (input) => {
1643
- const out = new Uint8Array(input.length);
1644
- let n = 0;
1645
- for (let i = 0; i < input.length; i++) {
1646
- const b = input[i];
1647
- if (b === 43) {
1648
- out[n++] = 32;
1649
- continue;
1650
- }
1651
- if (b === 37 && i + 2 < input.length) {
1652
- const hi = hexValue(input[i + 1]);
1653
- const lo = hexValue(input[i + 2]);
1654
- if (hi >= 0 && lo >= 0) {
1655
- out[n++] = hi * 16 + lo;
1656
- i += 2;
1657
- continue;
1658
- }
1659
- }
1660
- out[n++] = b;
1661
- }
1662
- return utf8.decode(out.subarray(0, n));
1663
- };
1664
- var parseUrlEncoded = (body) => {
1665
- const form = new FormData();
1666
- const { bytes } = body;
1667
- let start = 0;
1668
- for (let i = 0; i <= bytes.length; i++) {
1669
- if (i < bytes.length && bytes[i] !== 38) continue;
1670
- const pair = bytes.subarray(start, i);
1671
- start = i + 1;
1672
- if (pair.length === 0) continue;
1673
- const eq = pair.indexOf(61);
1674
- const name = eq === -1 ? pair : pair.subarray(0, eq);
1675
- const value = eq === -1 ? new Uint8Array(0) : pair.subarray(eq + 1);
1676
- form.append(decodeFormComponent(name), decodeFormComponent(value));
1677
- }
1678
- return form;
1679
- };
1680
- var parseMultipart = (body) => new Response(body.bytes, { headers: { "content-type": body.contentType ?? "" } }).formData();
1681
- var parseFormData = (body) => {
1682
- const mime = getMimeType(body.contentType);
1683
- if (mime === "application/x-www-form-urlencoded") return parseUrlEncoded(body);
1684
- if (mime === "multipart/form-data") return parseMultipart(body);
1685
- throw new VigorParseError("INVALID_CONTENT_TYPE", {
1686
- method: "parseFormData",
1687
- data: { received: body.contentType }
1688
- });
1689
- };
1690
- var toArrayBuffer = (body) => body.bytes.slice().buffer;
1691
- var toBlob = (body) => new Blob([body.bytes], { type: body.contentType ?? "" });
1692
- var NoBodyStatus = [204, 205, 304];
1693
- var ContentTypeParsers = [
1694
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
1695
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (body) => decodeText(body) },
1696
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: parseUrlEncoded },
1697
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: toArrayBuffer },
1698
- { header: "image/*", regExp: /^image\/.+/i, method: toBlob },
1699
- { header: "audio/*", regExp: /^audio\/.+/i, method: toBlob },
1700
- { header: "video/*", regExp: /^video\/.+/i, method: toBlob },
1701
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: parseMultipart },
1702
- { header: "text/*", regExp: /^text\/.+/i, method: (body) => decodeText(body) }
1703
- ];
1704
- var SniffMethods = [
1705
- { title: "json", method: parseJson },
1706
- { title: "formData", method: parseFormData },
1707
- { title: "text", method: (body) => decodeText(body, true) },
1708
- { title: "blob", method: toBlob }
1709
- ];
1710
- var VigorParseContentTypeStrategy = async (body) => {
1711
- if (body.bytes.length === 0 || body.status !== null && NoBodyStatus.includes(body.status)) return null;
1712
- if (!body.contentType) return decodeText(body);
1713
- const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(body.contentType));
1714
- if (!toDo) return toBlob(body);
1715
- return await toDo.method(body);
1716
- };
1717
- var VigorParseSniffStrategy = async (body) => {
1718
- const errors = [];
1719
- for (const parser of SniffMethods) {
1720
- try {
1721
- return await parser.method(body);
1722
- } catch (error) {
1723
- errors.push(error);
1724
- }
1725
- }
1726
- throw new VigorParseError("PARSER_ALL_FAILED", {
1727
- method: "VigorParseSniffStrategy",
1728
- cause: errors.at(-1),
1729
- data: { tried: SniffMethods.map((p) => p.title), errors }
1730
- });
1731
- };
1732
- var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends VigorStatus {
1733
- constructor(config = VigorParseBase) {
1734
- super(VigorParseBase, config);
1735
- }
1736
- _create(config) {
1737
- return new _VigorParsePolicyStrategies(config);
1738
- }
1739
- /**
1740
- * Adds strategy functions to the fallback chain.
1741
- *
1742
- * @param replace - When `true`, replaces the existing chain instead of
1743
- * appending to it (the default is to concat, since strategies are
1744
- * tried in sequence as a fallback chain).
1745
- */
1746
- _set(funcs, replace) {
1747
- return this._next(
1748
- { policy: { strategies: { funcs } } },
1749
- replace ? { policy: { strategies: { funcs: "replace" } } } : void 0
1750
- );
1751
- }
1752
- /** Adds the content-type based parsing strategy. */
1753
- contentType(replace) {
1754
- return this._set([VigorParseContentTypeStrategy], replace);
1755
- }
1756
- /** Adds the sniffing (try-each-format) parsing strategy. */
1757
- sniff(replace) {
1758
- return this._set([VigorParseSniffStrategy], replace);
1759
- }
1760
- /** Adds a strategy that always parses the body as JSON. */
1761
- json(replace) {
1762
- return this._set([parseJson], replace);
1763
- }
1764
- /** Adds a strategy that always parses the body as text, in its declared `charset`. */
1765
- text(replace) {
1766
- return this._set([(body) => decodeText(body)], replace);
1767
- }
1768
- /** Adds a strategy that always parses the body as an `ArrayBuffer`. */
1769
- arrayBuffer(replace) {
1770
- return this._set([toArrayBuffer], replace);
1771
- }
1772
- /** Adds a strategy that always parses the body as a `Blob`. */
1773
- blob(replace) {
1774
- return this._set([toBlob], replace);
1775
- }
1776
- /** Adds a strategy that always parses the body as a `Uint8Array`. */
1777
- bytes(replace) {
1778
- return this._set([(body) => body.bytes.slice()], replace);
1779
- }
1780
- /** Adds a strategy that always parses the body as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`). */
1781
- formData(replace) {
1782
- return this._set([parseFormData], replace);
1783
- }
1784
- /** Adds a user-supplied custom parsing strategy. It receives the body already read into bytes. */
1785
- custom(func, replace) {
1786
- return this._set([func], replace);
1787
- }
1788
- };
1789
-
1790
- // src/parse/policy.ts
1791
- var VigorParsePolicyBase = {
1792
- __brand: createBrand("Parse", "Policy<Schema"),
1793
- target: VigorDefault,
1794
- settings: VigorParsePolicySettingsBase,
1795
- middlewares: VigorParsePolicyMiddlewaresBase,
1796
- strategies: VigorParsePolicyStrategiesBase
1797
- };
1798
-
1799
- // src/parse/context.ts
1800
- var VigorParseContextBase = {
1801
- __brand: createBrand("Parse", "Context<Schema"),
1802
- result: VigorDefault,
1803
- error: VigorDefault,
1804
- response: VigorDefault,
1805
- flags: {
1806
- overridden: false,
1807
- restarted: false
1808
- },
1809
- record: {},
1810
- timeline: [],
1811
- policy: VigorParsePolicyBase
1812
- };
1813
-
1814
- // src/parse/main.ts
1815
- var VigorParseBase = {
1816
- __brand: createBrand("Parse", "Schema"),
1817
- policy: VigorParsePolicyBase,
1818
- cast: VigorEmpty
1819
- };
1820
- var VigorParse = class _VigorParse extends VigorStatus {
1821
- constructor(config = VigorParseBase) {
1822
- super(VigorParseBase, config);
1823
- }
1824
- _create(config) {
1825
- return new _VigorParse(config);
1826
- }
1827
- /** Sets the `Response` object to parse. */
1828
- target(response) {
1829
- return this._next({ policy: { target: response } });
1830
- }
1831
- settings(input) {
1832
- if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
1833
- const result = typeof input === "function" ? input(new VigorParsePolicySettings(this.config)) : input;
1834
- return this._next({
1835
- policy: { settings: result.config.policy.settings }
1836
- });
1837
- }
1838
- return this._next({ policy: { settings: input } });
1839
- }
1840
- middlewares(input) {
1841
- if (typeof input === "function" || input instanceof VigorParsePolicyMiddlewares) {
1842
- const result = typeof input === "function" ? input(new VigorParsePolicyMiddlewares()) : input;
1843
- return this._next({
1844
- policy: { middlewares: result.config.policy.middlewares }
1845
- });
1846
- }
1847
- return this._next({ policy: { middlewares: input } });
1848
- }
1849
- strategies(input) {
1850
- if (typeof input === "function" || input instanceof VigorParsePolicyStrategies) {
1851
- const result = typeof input === "function" ? input(new VigorParsePolicyStrategies()) : input;
1852
- return this._next({
1853
- policy: { strategies: result.config.policy.strategies }
1854
- });
1855
- }
1856
- return this._next({ policy: { strategies: input } });
1857
- }
1858
- /**
1859
- * Overrides the resolved result type with `T`, taking priority over the
1860
- * default `unknown` result. Can be called before or after `strategies()`
1861
- * (or any other configuration method); whichever `.cast<T>()` call
1862
- * happens last wins.
1863
- */
1864
- cast() {
1865
- return this._next(
1866
- { cast: VigorCastPlaceholder },
1867
- { cast: "replace" }
1868
- );
1869
- }
1870
- /**
1871
- * Runs parsing and returns the result directly, throwing on final failure.
1872
- *
1873
- * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1874
- * means "ignore the inference, it's this": it's taken as-is, unchecked.
1875
- * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1876
- */
1877
- async request() {
1878
- const res = await this.requestVerbose();
1879
- if (res.success) return res.data;
1880
- throw res.error;
1881
- }
1882
- /**
1883
- * Runs parsing and returns a result/error envelope instead of throwing,
1884
- * along with the `timeline` of everything the run went through.
1885
- */
1886
- async requestVerbose() {
1887
- return await this.requestRuntime();
1888
- }
1889
- /**
1890
- * Internal execution loop implementing the strategy fallback and restart
1891
- * handling. Never throws: every failure, including one from `onError` or
1892
- * `default`, comes back as an envelope carrying the timeline. A restart
1893
- * passes the same `timeline` on, so it keeps growing across runs.
1894
- */
1895
- async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1896
- const config = this._merge(this.config, {});
1897
- let ctx = this._merge(VigorParseContextBase, {
1898
- policy: config.policy
1899
- }, void 0, "replace");
1900
- ctx.timeline = timeline;
1901
- const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1902
- add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1903
- const end = (success, outcome, error) => add("REQUEST_END", {
1904
- success,
1905
- outcome,
1906
- error,
1907
- took: performance.now() - startedAt,
1908
- restarts: restartAttempt - 1
1909
- });
1910
- const succeed = (data, outcome) => {
1911
- end(true, outcome, null);
1912
- return { success: true, data, error: null, timeline };
1913
- };
1914
- const fail = (error) => {
1915
- end(false, "failed", error);
1916
- return { success: false, data: null, error, timeline };
1917
- };
1918
- if (isVigorDefault(ctx.policy.target)) return fail(new VigorParseError("VALUE_REQUIRED", {
1919
- method: "request",
1920
- data: { key: "target" },
1921
- context: ctx
1922
- }));
1923
- ctx.response = ctx.policy.target;
1924
- const throwError = (err) => {
1925
- throw err;
1926
- };
1927
- try {
1928
- await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1929
- if (middleware._mode === "fluent") {
1930
- await middleware.func(ctx);
1931
- } else {
1932
- ctx = await middleware.func(ctx, trace({ throwError })) ?? ctx;
1933
- }
1934
- });
1935
- if (ctx.policy.settings.raw) {
1936
- ctx.result = ctx.response;
1937
- } else {
1938
- const readStarted = performance.now();
1939
- const body = await readVigorParseBody(ctx.response);
1940
- add("BODY_READ", { size: body.bytes.byteLength, took: performance.now() - readStarted });
1941
- const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
1942
- let parsed = false;
1943
- const errors = [];
1944
- for (const [index, func] of funcs.entries()) {
1945
- add("STRATEGY_STARTED", { index });
1946
- const started = performance.now();
1947
- try {
1948
- ctx.result = await func(body);
1949
- add("STRATEGY_SUCCEEDED", { index, took: performance.now() - started });
1950
- parsed = true;
1951
- break;
1952
- } catch (error) {
1953
- errors.push(error);
1954
- add("STRATEGY_FAILED", { index, error, took: performance.now() - started });
1955
- }
1956
- }
1957
- if (!parsed) throw new VigorParseError("PARSER_ALL_FAILED", {
1958
- method: "request",
1959
- cause: errors.at(-1),
1960
- data: { tried: funcs.map((_, i) => `strategy#${i}`), errors },
1961
- context: ctx
1962
- });
1963
- }
1964
- const setResult = (res) => {
1965
- ctx.result = res;
1966
- };
1967
- await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1968
- if (middleware._mode === "fluent") {
1969
- await middleware.func(ctx);
1970
- } else {
1971
- ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1972
- }
1973
- });
1974
- await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1975
- if (middleware._mode === "fluent") {
1976
- ctx.result = await middleware.func(ctx.result);
1977
- } else {
1978
- ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1979
- }
1980
- });
1981
- return succeed(ctx.result, "result");
1982
- } catch (error) {
1983
- ctx.error = error;
1984
- add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1985
- ctx.flags.overridden = false;
1986
- ctx.flags.restarted = false;
1987
- const setResult = (res) => {
1988
- ctx.flags.overridden = true;
1989
- ctx.result = res;
1990
- };
1991
- const proceedRestart = () => ctx.flags.restarted = true;
1992
- const cancelRestart = () => ctx.flags.restarted = false;
1993
- try {
1994
- await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1995
- if (middleware._mode === "fluent") {
1996
- await middleware.func(ctx.error);
1997
- } else {
1998
- ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
1999
- }
2000
- });
2001
- } catch (err) {
2002
- return fail(err);
2003
- }
2004
- if (ctx.flags.restarted) {
2005
- if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorParseError("RESTART_EXHAUSTED", {
2006
- method: "request",
2007
- cause: ctx.error,
2008
- data: {
2009
- maxAttempts: ctx.policy.settings.maxRestarts,
2010
- error: ctx.error
2011
- },
2012
- context: ctx
2013
- }));
2014
- add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
2015
- return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
2016
- }
2017
- if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
2018
- if (!isVigorEmpty(ctx.policy.settings.default)) {
2019
- try {
2020
- return succeed(await ctx.policy.settings.default(ctx), "default");
2021
- } catch (err) {
2022
- return fail(err);
2023
- }
2024
- }
2025
- return fail(ctx.error);
2026
- }
2027
- }
2028
- };
2029
-
2030
- // src/fetch/policy.ts
2031
- var VigorFetchPolicyBase = {
2032
- __brand: createBrand("Fetch", "Policy<Schema"),
2033
- method: VigorEmpty,
2034
- origin: VigorEmpty,
2035
- path: [],
2036
- query: [],
2037
- hash: "",
2038
- headers: {},
2039
- body: VigorEmpty,
2040
- extra: {},
2041
- settings: VigorFetchPolicySettingsBase,
2042
- middlewares: VigorFetchPolicyMiddlewaresBase,
2043
- retry: VigorRetryBase,
2044
- parse: VigorParseBase
2045
- };
2046
-
2047
- // src/fetch/context.ts
2048
- var VigorFetchContextBase = {
2049
- __brand: createBrand("Fetch", "Context<Schema"),
2050
- href: "",
2051
- response: VigorDefault,
2052
- result: VigorDefault,
2053
- error: VigorDefault,
2054
- options: VigorDefault,
2055
- flags: {
2056
- overridden: false,
2057
- restarted: false
2058
- },
2059
- record: {},
2060
- timeline: [],
2061
- policy: VigorFetchPolicyBase
2062
- };
2063
-
2064
- // src/fetch/error.ts
2065
- var VigorFetchErrorMessageFuncs = {
2066
- ...VigorRetryErrorMessageFuncs,
2067
- ...VigorParseErrorMessageFuncs,
2068
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
2069
- INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
2070
- BODY_NOT_ALLOWED: ({ method }) => `A ${method} request cannot have a body`,
2071
- INVALID_PROTOCOL: ({ origin, base }) => base ? `Invalid URL: could not resolve "${origin}" against base "${base}"` : `Invalid URL: "${origin}" is not an absolute URL, and no base (window.location) is available to resolve it against \u2014 pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,
2072
- FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
2073
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
2074
- PATH_ESCAPED: ({ url, base }) => `Path escapes "${base}": the request would go to "${url}" (settings.confinePath)`,
2075
- REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
2076
- };
2077
- var VigorFetchError = class extends VigorError {
2078
- /**
2079
- * @param code - One of the fetch module's error codes.
2080
- * @param options - Error metadata, including the `data` payload for `code`.
2081
- */
2082
- constructor(code, options) {
2083
- const messageFn = VigorFetchErrorMessageFuncs[code];
2084
- super(code, messageFn(options.data), options);
2085
- }
2086
- };
2087
- function isVigorFetchError(error, ...codes) {
2088
- return error instanceof VigorFetchError && (codes.length === 0 || codes.includes(error.code));
2089
- }
2090
- function findVigorFetchError(error, ...codes) {
2091
- const found = findInVigorErrorChain(error, (e) => isVigorFetchError(e, ...codes));
2092
- return found === void 0 ? null : found;
2093
- }
2094
- function adoptVigorFetchError(error, context) {
2095
- if (!(error instanceof VigorRetryError) && !(error instanceof VigorParseError)) return error;
2096
- const data = error.data;
2097
- const adopted = data !== null && typeof data === "object" && "error" in data ? { ...data, error: adoptVigorFetchError(data.error, context) } : data;
2098
- return new VigorFetchError(error.code, {
2099
- method: error.method,
2100
- cause: error,
2101
- data: adopted,
2102
- context
2103
- });
2104
- }
2105
-
2106
- // src/fetch/main.ts
2107
- var VigorFetchBase = {
2108
- __brand: createBrand("Fetch", "Schema"),
2109
- policy: VigorFetchPolicyBase,
2110
- cast: VigorEmpty,
2111
- apiMap: VigorEmpty
2112
- };
2113
- var VigorFetch = class _VigorFetch extends VigorStatus {
2114
- constructor(config = VigorFetchBase) {
2115
- super(VigorFetchBase, config);
2116
- }
2117
- _create(config) {
2118
- return new _VigorFetch(config);
2119
- }
2120
- /** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
2121
- method(str) {
2122
- return this._next({ policy: { method: str } });
2123
- }
2124
- /** Sets the request origin, either an absolute URL or a path relative to the current page. */
2125
- origin(str) {
2126
- return this._next({ policy: { origin: str } });
2127
- }
2128
- /** Appends path segments to the request URL. */
2129
- path(...strs) {
2130
- return this._next({ policy: { path: this._stringifyList(strs) } });
2131
- }
2132
- /** Adds query-string parameter objects to the request URL. */
2133
- query(...objs) {
2134
- return this._next({ policy: { query: objs } });
2135
- }
2136
- /** Sets the URL fragment ("hash"), replacing any previous value. */
2137
- hash(str) {
2138
- return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } });
2139
- }
2140
- headers(mode, obj) {
2141
- if (mode === "overwrite") return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
2142
- return this._next({ policy: { headers: obj } });
2143
- }
2144
- body(mode, obj) {
2145
- const prev = this.config.policy.body;
2146
- const body = mode === "merge" && this._isPlainObject(prev) && this._isPlainObject(obj) ? { ...prev, ...obj } : obj;
2147
- return this._next({ policy: { body } }, { policy: { body: "replace" } });
2148
- }
2149
- options(mode, obj) {
2150
- const extra = mode === "merge" ? { ...this.config.policy.extra, ...obj } : obj;
2151
- return this._next({ policy: { extra } }, { policy: { extra: "replace" } });
2152
- }
2153
- settings(input) {
2154
- const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
2155
- if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
2156
- const result = typeof input === "function" ? input(new VigorFetchPolicySettings(this.config)) : input;
2157
- return this._next(
2158
- { policy: { settings: result.config.policy.settings } },
2159
- strategy
2160
- );
2161
- }
2162
- return this._next({ policy: { settings: input } }, strategy);
2163
- }
2164
- middlewares(input) {
2165
- if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
2166
- const result = typeof input === "function" ? input(new VigorFetchPolicyMiddlewares()) : input;
2167
- return this._next(
2168
- { policy: { middlewares: result.config.policy.middlewares } }
2169
- );
2170
- }
2171
- return this._next({ policy: { middlewares: input } });
2172
- }
2173
- retry(input) {
2174
- if (typeof input === "function" || input instanceof VigorRetry) {
2175
- const result = typeof input === "function" ? input(new VigorRetry()) : input;
2176
- return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
2177
- }
2178
- return this._next({ policy: { retry: this._merge(VigorRetryBase, input) } }, { policy: { retry: "replace" } });
2179
- }
2180
- parse(input) {
2181
- if (typeof input === "function" || input instanceof VigorParse) {
2182
- const result = typeof input === "function" ? input(new VigorParse()) : input;
2183
- return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
2184
- }
2185
- return this._next({ policy: { parse: this._merge(VigorParseBase, input) } }, { policy: { parse: "replace" } });
2186
- }
2187
- /** Whether `v` is a plain object literal (not an array, `FormData`, `Blob`, ...). */
2188
- _isPlainObject(v) {
2189
- return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
2190
- }
2191
- /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
2192
- _stringifyList(unkList) {
2193
- return unkList.filter((unk) => unk !== null && unk !== void 0).map((unk) => unk instanceof Date ? unk.toISOString() : String(unk));
2194
- }
2195
- /**
2196
- * Resolves the base URL used to interpret a relative `origin`. In a
2197
- * browser environment this is the current page location; in
2198
- * environments without `location` (e.g. Node), no base is available and
2199
- * `origin` must be an absolute URL.
2200
- */
2201
- _resolveBase() {
2202
- if (typeof globalThis !== "undefined" && globalThis.location?.href) {
2203
- return globalThis.location.href;
2204
- }
2205
- return void 0;
2206
- }
2207
- /**
2208
- * Builds the final request URL from the configured origin, path
2209
- * segments, query parameters, and hash. An absolute `origin` ignores
2210
- * the resolved base (per the `URL` spec); a relative `origin` is
2211
- * resolved against it. Throws `INVALID_PROTOCOL` (with `context`) if
2212
- * neither is possible, and with `settings.confinePath` on, `PATH_ESCAPED`
2213
- * if the result leaves the origin's domain or path.
2214
- */
2215
- _buildUrl(origin, path, query, hash, context) {
2216
- const base = this._resolveBase();
2217
- let originObj;
2218
- try {
2219
- originObj = new URL(origin, base);
2220
- } catch {
2221
- throw new VigorFetchError("INVALID_PROTOCOL", {
2222
- method: "_buildUrl",
2223
- data: { origin, base },
2224
- context
2225
- });
2226
- }
2227
- const baseStr = originObj.origin;
2228
- const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, "")];
2229
- for (const p of path) {
2230
- for (const part of p.split("/")) pathParts.push(encodeURIComponent(part));
2231
- }
2232
- const pathStr = pathParts.filter(Boolean).join("/");
2233
- const mainObj = new URL(pathStr, baseStr);
2234
- const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
2235
- const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap((q) => Object.entries(q))];
2236
- for (const [key, val] of queryEntries) {
2237
- if (val === void 0 || val === null) continue;
2238
- if (Array.isArray(val)) {
2239
- for (const e of val) mainObj.searchParams.append(key, parseVal(e));
2240
- } else {
2241
- mainObj.searchParams.append(key, parseVal(val));
2242
- }
2243
- }
2244
- mainObj.hash = hash || originObj.hash;
2245
- if (context.policy.settings.confinePath) {
2246
- const basePath = "/" + originObj.pathname.replace(/^\/+|\/+$/g, "");
2247
- const inside = basePath === "/" || mainObj.pathname === basePath || mainObj.pathname.startsWith(basePath + "/");
2248
- if (mainObj.origin !== originObj.origin || !inside) throw new VigorFetchError("PATH_ESCAPED", {
2249
- method: "_buildUrl",
2250
- data: { url: mainObj.href, base: originObj.origin + (basePath === "/" ? "" : basePath) },
2251
- context
2252
- });
2253
- }
2254
- return mainObj.href;
2255
- }
2256
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. Throws `INVALID_BODY` (with `context`) for anything else. */
2257
- _normalizeBody(body, context) {
2258
- if (body == null) return { headers: {}, body };
2259
- if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
2260
- if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
2261
- if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { headers: { "Content-Type": "application/octet-stream" }, body };
2262
- if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return { headers: { "Content-Type": "application/octet-stream" }, body };
2263
- if (body instanceof URLSearchParams) return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
2264
- if (body instanceof FormData) return { headers: {}, body };
2265
- if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
2266
- throw new VigorFetchError("INVALID_BODY", {
2267
- method: "_normalizeBody",
2268
- data: { received: body },
2269
- context
2270
- });
2271
- }
2272
- /**
2273
- * Returns the absolute URL a redirect points at, or `null` when the
2274
- * response isn't a redirect. A response `fetch` already followed
2275
- * (`redirect: "follow"`, the default) yields its final URL; a readable
2276
- * `3xx` (`redirect: "manual"` outside browsers) yields its `Location`,
2277
- * resolved against the responding URL.
2278
- */
2279
- _resolveRedirect(response, href) {
2280
- if (response.redirected && response.url) return response.url;
2281
- if (response.status < 300 || response.status >= 400) return null;
2282
- const location = response.headers.get("location");
2283
- if (!location) return null;
2284
- try {
2285
- return new URL(location, response.url || href).href;
2286
- } catch {
2287
- return null;
2288
- }
2289
- }
2290
- /** The browser's `location`, or `null` in environments without one (e.g. Node). */
2291
- _browserLocation() {
2292
- const win = globalThis.window;
2293
- return win?.location?.href !== void 0 ? win.location : null;
2294
- }
2295
- /** Assigns `source` headers onto `target`, replacing any existing key that differs only in case. */
2296
- _assignHeaders(target, source) {
2297
- for (const [key, value] of Object.entries(source)) {
2298
- const lower = key.toLowerCase();
2299
- for (const existing of Object.keys(target)) {
2300
- if (existing.toLowerCase() === lower) delete target[existing];
2301
- }
2302
- target[key] = value;
2303
- }
2304
- }
2305
- /**
2306
- * Converts a rate-limit header value into a delay in milliseconds, or
2307
- * `null` if it can't be used. Accepts delta seconds (`Retry-After: 120`),
2308
- * Unix epoch seconds or milliseconds (`X-RateLimit-Reset: 1735689600`),
2309
- * and HTTP dates.
2310
- */
2311
- _parseRetryHeader(value) {
2312
- if (!value) return null;
2313
- const num = Number(value);
2314
- let delay;
2315
- if (value.trim() !== "" && !isNaN(num)) {
2316
- if (num >= 1e12) delay = num - Date.now();
2317
- else if (num >= 1e9) delay = num * 1e3 - Date.now();
2318
- else delay = num * 1e3;
2319
- } else {
2320
- const date = new Date(value).getTime();
2321
- if (isNaN(date)) return null;
2322
- delay = date - Date.now();
2323
- }
2324
- return delay > 0 ? delay : null;
2325
- }
2326
- /**
2327
- * Overrides the resolved result type with `T`, taking priority over the
2328
- * default `unknown` result. Can be called before or after `parse()` (or
2329
- * any other configuration method); whichever `.cast<T>()` call happens
2330
- * last wins.
2331
- */
2332
- /**
2333
- * Attaches a type-level API map: a request whose method and path match a
2334
- * route resolves to that route's success `responses` (see `VigorApiRoute`
2335
- * for `responses`/`params`/`query`/`body`). Keys are
2336
- * `"<METHOD> /<path>"`, where a `:name` segment matches any one segment.
2337
- * Routes are relative to the path set so far, so a base path can be set
2338
- * first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. Purely a type —
2339
- * nothing changes at runtime. `.cast<T>()` and a `raw` parse still win.
2340
- *
2341
- * @example
2342
- * type Api = {
2343
- * "GET /users": { response: User[] }
2344
- * "GET /users/:id": { response: User }
2345
- * }
2346
- * const api = vigor.fetch("https://api.example.com").apiMap<Api>()
2347
- * const user = await api.path("users", id).request() // User
2348
- */
2349
- apiMap() {
2350
- return this._next(
2351
- { apiMap: VigorCastPlaceholder },
2352
- { apiMap: "replace" }
2353
- );
2354
- }
2355
- route(key, ...params) {
2356
- const route = key;
2357
- const space = route.indexOf(" ");
2358
- const method = route.slice(0, space);
2359
- const values = params[0] ?? {};
2360
- const segments = route.slice(space + 1).split("/").filter(Boolean).map((segment) => {
2361
- if (!segment.startsWith(":")) return segment;
2362
- const name = segment.slice(1);
2363
- const value = values[name];
2364
- if (value === null || value === void 0) throw new VigorFetchError("VALUE_REQUIRED", {
2365
- method: "route",
2366
- data: { key: `params.${name}` }
2367
- });
2368
- return value;
2369
- });
2370
- return this.method(method).path(...segments);
2371
- }
2372
- cast() {
2373
- return this._next(
2374
- { cast: VigorCastPlaceholder },
2375
- { cast: "replace" }
2376
- );
2377
- }
2378
- /**
2379
- * Runs the request and returns its parsed result directly, throwing on final failure.
2380
- *
2381
- * `R` defaults to the inferred result type. Passing one (`request<User>()`)
2382
- * means "ignore the inference, it's this": it's taken as-is, unchecked.
2383
- * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
2384
- *
2385
- * With an API map, the request's `body`/`query` must match its route's
2386
- * (see {@link VigorFetchRequestThis}), or the call doesn't compile.
2387
- */
2388
- async request() {
2389
- const res = await this.requestRuntime();
2390
- if (res.success) return res.data;
2391
- throw res.error;
2392
- }
2393
- /**
2394
- * Runs the request and returns a result/error envelope instead of throwing,
2395
- * along with the `timeline` of everything the run went through. The
2396
- * nested retry/parse engines' full timelines are kept inside it, on their
2397
- * `RETRY_ENDED`/`PARSE_ENDED` entries.
2398
- *
2399
- * A success carries the `status` and `response` its result was parsed
2400
- * from; with an API map, narrowing `status` narrows `data` (see
2401
- * {@link VigorFetchVerboseResult}). Passing `R` types every success's
2402
- * `data` as `R`, unchecked.
2403
- */
2404
- async requestVerbose() {
2405
- return await this.requestRuntime();
2406
- }
2407
- /**
2408
- * Internal execution loop implementing URL building, retry, parsing, and
2409
- * restart handling. Never throws: every failure, including one from
2410
- * `onError` or `default`, comes back as an envelope carrying the timeline.
2411
- * A restart passes the same `timeline` on, so it keeps growing across runs.
2412
- */
2413
- async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
2414
- const config = this._merge(this.config, {});
2415
- let ctx = this._merge(VigorFetchContextBase, {
2416
- policy: config.policy
2417
- }, void 0, "replace");
2418
- ctx.timeline = timeline;
2419
- const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
2420
- add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
2421
- const end = (success, outcome, error) => add("REQUEST_END", {
2422
- success,
2423
- outcome,
2424
- error,
2425
- took: performance.now() - startedAt,
2426
- restarts: restartAttempt - 1
2427
- });
2428
- const succeed = (data, outcome, response = null) => {
2429
- end(true, outcome, null);
2430
- return { success: true, data, error: null, status: response?.status ?? null, response, timeline };
2431
- };
2432
- const fail = (error) => {
2433
- end(false, "failed", error);
2434
- return { success: false, data: null, error, status: null, response: null, timeline };
2435
- };
2436
- let lastAttempt = 0;
2437
- const runRetry = async (engine) => {
2438
- add("RETRY_STARTED", { engine });
2439
- const started = performance.now();
2440
- const res = await engine.requestVerbose();
2441
- add("RETRY_ENDED", {
2442
- engine,
2443
- timeline: res.timeline,
2444
- took: performance.now() - started,
2445
- response: res.success ? res.data : VigorDefault
2446
- });
2447
- return res;
2448
- };
2449
- const runParse = async (source, attempt, engine) => {
2450
- add("PARSE_STARTED", { engine, source, attempt });
2451
- const started = performance.now();
2452
- const res = await engine.requestVerbose();
2453
- add("PARSE_ENDED", {
2454
- engine,
2455
- source,
2456
- attempt,
2457
- timeline: res.timeline,
2458
- took: performance.now() - started,
2459
- result: res.success ? res.data : VigorDefault
2460
- });
2461
- return res;
2462
- };
2463
- const throwError = (err) => {
2464
- throw err;
2465
- };
2466
- try {
2467
- if (isVigorEmpty(ctx.policy.origin)) throw new VigorFetchError("VALUE_REQUIRED", {
2468
- method: "request",
2469
- data: { key: "origin" },
2470
- context: ctx
2471
- });
2472
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash, ctx);
2473
- add("BUILT_URL", { url: ctx.href });
2474
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
2475
- const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
2476
- const options = {
2477
- ...ctx.policy.extra,
2478
- method,
2479
- headers: {}
2480
- };
2481
- if (hasBody) {
2482
- const normalized = this._normalizeBody(ctx.policy.body, ctx);
2483
- if (normalized.body !== void 0) options.body = normalized.body;
2484
- Object.assign(options.headers, normalized.headers);
2485
- }
2486
- this._assignHeaders(options.headers, ctx.policy.headers);
2487
- ctx.options = options;
2488
- await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
2489
- if (middleware._mode === "fluent") {
2490
- await middleware.func(ctx);
2491
- } else {
2492
- ctx = await middleware.func(ctx, trace({
2493
- throwError,
2494
- setOptions: (o) => {
2495
- ctx.options = o;
2496
- },
2497
- setHeaders: (h) => {
2498
- ctx.options.headers = h;
2499
- },
2500
- setBody: (b) => {
2501
- ctx.options.body = b;
2502
- }
2503
- })) ?? ctx;
2504
- }
2505
- });
2506
- const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
2507
- ctx.options = finalOptions;
2508
- add("SET_OPTIONS", { options: finalOptions });
2509
- const finalMethod = (finalOptions.method ?? "GET").toUpperCase();
2510
- if (finalOptions.body != null && (finalMethod === "GET" || finalMethod === "HEAD")) throw new VigorFetchError("BODY_NOT_ALLOWED", {
2511
- method: "request",
2512
- data: { method: finalMethod },
2513
- context: ctx
2514
- });
2515
- const isStreamBody = typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream;
2516
- if (isStreamBody) {
2517
- finalOptions.duplex ??= "half";
2518
- }
2519
- const nestedDebug = { policy: { settings: { debug: true } } };
2520
- const parseEngine = new VigorParse(config.policy.settings.debug ? this._merge(ctx.policy.parse, nestedDebug) : ctx.policy.parse);
2521
- const retryEngine = new VigorRetry(config.policy.settings.debug ? this._merge(ctx.policy.retry, nestedDebug) : ctx.policy.retry).target(async (signal) => {
2522
- return await fetch(ctx.href, { ...finalOptions, signal });
2523
- }).middlewares(
2524
- (m) => m.after("intercept", async (rctx, api) => {
2525
- const response = rctx.result;
2526
- lastAttempt = rctx.system.attempt;
2527
- add("RESPONSE_RECEIVED", {
2528
- attempt: rctx.system.attempt,
2529
- status: response.status,
2530
- statusText: response.statusText,
2531
- ok: response.ok,
2532
- redirected: response.redirected,
2533
- url: response.url
2534
- });
2535
- if (ctx.policy.settings.redirect) {
2536
- const target = this._resolveRedirect(response, ctx.href);
2537
- const location = this._browserLocation();
2538
- if (target && location) {
2539
- location.href = target;
2540
- api.throwError(new VigorFetchError("REDIRECTED", {
2541
- method: "request",
2542
- data: { url: target, status: response.status, response },
2543
- context: ctx
2544
- }));
2545
- }
2546
- }
2547
- if (!response.ok && response.status !== 304) {
2548
- const parseRes2 = await runParse("failedResponse", rctx.system.attempt, parseEngine.target(response.clone()));
2549
- const parsed = parseRes2.success ? parseRes2.data : void 0;
2550
- api.throwError(new VigorFetchError("FETCH_FAILED", {
2551
- method: "request",
2552
- data: {
2553
- status: response.status,
2554
- statusText: response.statusText,
2555
- response,
2556
- url: response.url,
2557
- parsed
2558
- },
2559
- context: ctx
2560
- }));
2561
- }
2562
- if (!ctx.policy.parse.policy.settings.raw) await readVigorParseBody(response);
2563
- return rctx;
2564
- }).retryIf("intercept", async (rctx, api) => {
2565
- const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
2566
- if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
2567
- else if (isStreamBody) api.cancelRetry();
2568
- else if (response && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) api.cancelRetry();
2569
- else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
2570
- return rctx;
2571
- }).onRetry("intercept", async (rctx, api) => {
2572
- const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
2573
- if (response?.status === 429 || response?.status === 503) {
2574
- for (const header of ctx.policy.settings.retryHeaders) {
2575
- const delay = this._parseRetryHeader(response.headers.get(header));
2576
- if (delay !== null) {
2577
- api.setDelay(Math.min(delay, ctx.policy.settings.maxRetryAfter));
2578
- break;
2579
- }
2580
- }
2581
- }
2582
- return rctx;
2583
- })
2584
- );
2585
- for (const name of ["after", "retryIf", "onRetry"]) {
2586
- const list = retryEngine.config.policy.middlewares[name];
2587
- markVigorInternal(list[list.length - 1].func);
2588
- }
2589
- add("ENGINE_CREATED", { retryEngine, parseEngine });
2590
- const retryRes = await runRetry(retryEngine);
2591
- if (!retryRes.success) throw adoptVigorFetchError(retryRes.error, ctx);
2592
- ctx.response = retryRes.data;
2593
- const parseRes = await runParse("response", lastAttempt, parseEngine.target(ctx.response));
2594
- if (!parseRes.success) throw adoptVigorFetchError(parseRes.error, ctx);
2595
- ctx.result = parseRes.data;
2596
- await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
2597
- if (middleware._mode === "fluent") {
2598
- await middleware.func(ctx);
2599
- } else {
2600
- ctx = await middleware.func(ctx, trace({ throwError, setResult: (r) => {
2601
- ctx.result = r;
2602
- } })) ?? ctx;
2603
- }
2604
- });
2605
- const setResult = (r) => {
2606
- ctx.result = r;
2607
- };
2608
- await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
2609
- if (middleware._mode === "fluent") {
2610
- ctx.result = await middleware.func(ctx.result);
2611
- } else {
2612
- ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
2613
- }
2614
- });
2615
- return succeed(ctx.result, "result", ctx.response);
2616
- } catch (error) {
2617
- ctx.error = error;
2618
- add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
2619
- ctx.flags.overridden = false;
2620
- ctx.flags.restarted = false;
2621
- const setResult = (r) => {
2622
- ctx.flags.overridden = true;
2623
- ctx.result = r;
2624
- };
2625
- const proceedRestart = () => ctx.flags.restarted = true;
2626
- const cancelRestart = () => ctx.flags.restarted = false;
2627
- try {
2628
- await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
2629
- if (middleware._mode === "fluent") {
2630
- await middleware.func(ctx.error);
2631
- } else {
2632
- ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
2633
- }
2634
- });
2635
- } catch (err) {
2636
- return fail(err);
2637
- }
2638
- if (ctx.flags.restarted) {
2639
- if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorFetchError("RESTART_EXHAUSTED", {
2640
- method: "request",
2641
- cause: ctx.error,
2642
- data: {
2643
- maxAttempts: ctx.policy.settings.maxRestarts,
2644
- error: ctx.error
2645
- },
2646
- context: ctx
2647
- }));
2648
- add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
2649
- return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
2650
- }
2651
- if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
2652
- if (!isVigorEmpty(ctx.policy.settings.default)) {
2653
- try {
2654
- return succeed(await ctx.policy.settings.default(ctx), "default");
2655
- } catch (err) {
2656
- return fail(err);
2657
- }
2658
- }
2659
- return fail(error);
2660
- }
2661
- }
2662
- };
2663
-
2664
- // src/entry/main.ts
2665
- var guardWithFind = (guard, find) => Object.assign(((...args) => guard(...args)), { find });
2666
- function retryWithTarget(task) {
2667
- return new VigorRetry().target(task);
2668
- }
2669
- function parseWithTarget(response) {
2670
- return new VigorParse().target(response);
2671
- }
2672
- function fetchWithOrigin(origin) {
2673
- return new VigorFetch().origin(origin);
2674
- }
2675
- function allWithTargets(tasks) {
2676
- return new VigorAll().target(...tasks);
2677
- }
2678
- var vigorBase = {
2679
- retry: ((task) => task !== void 0 ? retryWithTarget(task) : new VigorRetry()),
2680
- parse: ((response) => response !== void 0 ? parseWithTarget(response) : new VigorParse()),
2681
- fetch: ((origin) => origin !== void 0 ? fetchWithOrigin(origin) : new VigorFetch()),
2682
- all: ((...tasks) => tasks.length > 0 ? allWithTargets(tasks) : new VigorAll()),
2683
- builders: {
2684
- fetch: {
2685
- settings: () => new VigorFetchPolicySettings(),
2686
- middlewares: () => new VigorFetchPolicyMiddlewares()
2687
- },
2688
- retry: {
2689
- settings: () => new VigorRetryPolicySettings(),
2690
- middlewares: () => new VigorRetryPolicyMiddlewares(),
2691
- algorithms: () => new VigorRetryPolicyAlgorithms(),
2692
- algorithm: {
2693
- constant: () => new VigorRetryPolicyAlgorithmsConstant(),
2694
- linear: () => new VigorRetryPolicyAlgorithmsLinear(),
2695
- backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
2696
- custom: () => new VigorRetryPolicyAlgorithmsCustom()
2697
- }
2698
- },
2699
- parse: {
2700
- settings: () => new VigorParsePolicySettings(),
2701
- middlewares: () => new VigorParsePolicyMiddlewares(),
2702
- strategies: () => new VigorParsePolicyStrategies()
2703
- },
2704
- all: {
2705
- settings: () => new VigorAllPolicySettings(),
2706
- middlewares: () => new VigorAllPolicyMiddlewares()
2707
- }
2708
- },
2709
- guards: {
2710
- retry: guardWithFind(isVigorRetryError, findVigorRetryError),
2711
- parse: guardWithFind(isVigorParseError, findVigorParseError),
2712
- fetch: guardWithFind(isVigorFetchError, findVigorFetchError),
2713
- all: guardWithFind(isVigorAllError, findVigorAllError)
2714
- }
2715
- };
2716
- var cloneVigor = (v) => ({
2717
- ...v,
2718
- builders: {
2719
- fetch: { ...v.builders.fetch },
2720
- retry: { ...v.builders.retry, algorithm: { ...v.builders.retry.algorithm } },
2721
- parse: { ...v.builders.parse },
2722
- all: { ...v.builders.all }
2723
- },
2724
- guards: { ...v.guards }
2725
- });
2726
- var createVigor = (fields) => {
2727
- const instance = {
2728
- ...fields,
2729
- use: (plugin, options) => {
2730
- const ext = plugin.func(instance, { ...plugin.options, ...options });
2731
- const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
2732
- return createVigor(rest);
2733
- }
2734
- };
2735
- return instance;
2736
- };
2737
- var vigor = createVigor(vigorBase);
2738
-
2739
- // src/index.ts
2740
- var index_default = vigor;
2741
- // Annotate the CommonJS export names for ESM import in node:
2742
- 0 && (module.exports = {
2743
- VigorAll,
2744
- VigorAllBase,
2745
- VigorAllContextBase,
2746
- VigorAllEachContextBase,
2747
- VigorAllError,
2748
- VigorAllErrorMessageFuncs,
2749
- VigorAllPolicyBase,
2750
- VigorAllPolicyMiddlewares,
2751
- VigorAllPolicyMiddlewaresBase,
2752
- VigorAllPolicySettings,
2753
- VigorAllPolicySettingsBase,
2754
- VigorCastPlaceholder,
2755
- VigorDefault,
2756
- VigorEmpty,
2757
- VigorError,
2758
- VigorFetch,
2759
- VigorFetchBase,
2760
- VigorFetchContextBase,
2761
- VigorFetchError,
2762
- VigorFetchErrorMessageFuncs,
2763
- VigorFetchPolicyBase,
2764
- VigorFetchPolicyMiddlewares,
2765
- VigorFetchPolicyMiddlewaresBase,
2766
- VigorFetchPolicySettings,
2767
- VigorFetchPolicySettingsBase,
2768
- VigorJitter,
2769
- VigorParse,
2770
- VigorParseBase,
2771
- VigorParseContentTypeStrategy,
2772
- VigorParseContextBase,
2773
- VigorParseError,
2774
- VigorParseErrorMessageFuncs,
2775
- VigorParsePolicyBase,
2776
- VigorParsePolicyMiddlewares,
2777
- VigorParsePolicyMiddlewaresBase,
2778
- VigorParsePolicySettings,
2779
- VigorParsePolicySettingsBase,
2780
- VigorParsePolicyStrategies,
2781
- VigorParsePolicyStrategiesBase,
2782
- VigorParseSniffStrategy,
2783
- VigorRetry,
2784
- VigorRetryBase,
2785
- VigorRetryContextBase,
2786
- VigorRetryError,
2787
- VigorRetryErrorMessageFuncs,
2788
- VigorRetryPolicyAlgorithms,
2789
- VigorRetryPolicyAlgorithmsBackoff,
2790
- VigorRetryPolicyAlgorithmsBackoffBase,
2791
- VigorRetryPolicyAlgorithmsBase,
2792
- VigorRetryPolicyAlgorithmsConstant,
2793
- VigorRetryPolicyAlgorithmsConstantBase,
2794
- VigorRetryPolicyAlgorithmsCustom,
2795
- VigorRetryPolicyAlgorithmsCustomBase,
2796
- VigorRetryPolicyAlgorithmsLinear,
2797
- VigorRetryPolicyAlgorithmsLinearBase,
2798
- VigorRetryPolicyBase,
2799
- VigorRetryPolicyMiddlewares,
2800
- VigorRetryPolicyMiddlewaresBase,
2801
- VigorRetryPolicySettings,
2802
- VigorRetryPolicySettingsBase,
2803
- VigorStatus,
2804
- adoptVigorFetchError,
2805
- createBrand,
2806
- createVigorTimelineRecorder,
2807
- findInVigorErrorChain,
2808
- findVigorAllError,
2809
- findVigorFetchError,
2810
- findVigorParseError,
2811
- findVigorRetryError,
2812
- isVigorAllError,
2813
- isVigorDefault,
2814
- isVigorEmpty,
2815
- isVigorFetchError,
2816
- isVigorInternalMiddleware,
2817
- isVigorParseError,
2818
- isVigorRetryError,
2819
- markVigorInternal,
2820
- readVigorParseBody,
2821
- vigor
2822
- });
1
+ "use strict";function createBrand(e,r){return`@vigor-fetch:::${e} <- ${r}`}Object.defineProperty(exports,"__esModule",{value:!0});var VigorDefault=Symbol("VigorDefault"),isVigorDefault=e=>e===VigorDefault,VigorEmpty=Symbol("VigorEmpty"),isVigorEmpty=e=>e===VigorEmpty,VigorCastPlaceholder=Symbol("VigorCastPlaceholder"),VigorStatus=class{_base;_config;constructor(e,r){this._base=e,this._config=this._merge(e,r,void 0,"replace")}_next(e,r){const t=this._merge(this._config,e,r);return this._create(t)}_merge(e,r,t,o="concat"){const i=e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype,s=e=>{if(Array.isArray(e))return e.map(s);if(i(e)){const r={};for(const t of Object.keys(e))r[t]=s(e[t]);return r}return e},a=(e,r,t)=>{if(void 0===r)return s(e);if("replace"===t)return r;if(Array.isArray(e)&&Array.isArray(r))return"replace"===o?s(r):[...e,...r];if(i(e)&&i(r)){const o={},s=i(t)?t:void 0,n=new Set([...Object.keys(e),...Object.keys(r)]);for(const t of n)o[t]=a(e[t],r[t],s?.[t]);return o}return r};return a(e,r,t)}_snapshot(e){const{timeline:r,...t}=e;return this._merge(t,{})}get base(){return this._base}get config(){return this._config}},VigorAllPolicySettingsBase={__brand:createBrand("All","Policy<Settings<Schema"),debug:!1,concurrency:5,onlySuccess:!1,timeout:VigorEmpty,failFast:!1},VigorAllPolicySettings=class _VigorAllPolicySettings extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicySettings(e)}concurrency(e){return this._next({policy:{settings:{concurrency:e}}})}onlySuccess(e){return this._next({policy:{settings:{onlySuccess:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}failFast(e){return this._next({policy:{settings:{failFast:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorAllPolicyMiddlewaresBase={__brand:createBrand("All","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],beforeEach:[],afterEach:[],onErrorEach:[]},VigorAllPolicyMiddlewares=class _VigorAllPolicyMiddlewares extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}beforeEach(e){return this._next({policy:{middlewares:{beforeEach:[e]}}})}afterEach(e){return this._next({policy:{middlewares:{afterEach:[e]}}})}onErrorEach(e){return this._next({policy:{middlewares:{onErrorEach:[e]}}})}},VigorAllPolicyBase={__brand:createBrand("All","Policy<Schema"),target:[],abortSignals:[],settings:VigorAllPolicySettingsBase,middlewares:VigorAllPolicyMiddlewaresBase},VigorAllContextBase={__brand:createBrand("All","Context<Schema"),result:VigorDefault,policy:VigorAllPolicyBase,record:{},timeline:[]},VigorAllEachContextBase={__brand:createBrand("All","EachContext<Schema"),index:0,result:VigorDefault,error:VigorDefault,flags:{overridden:!1},record:{}},VigorError=class extends Error{timestamp=new Date;cause;code;data;method;context;constructor(e,r,t){super(`[${e}] ${r}`),this.name=new.target.name,this.code=e,this.cause=t.cause,this.data=t.data,this.method=t.method,this.context=t.context,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,new.target)}};function findInVigorErrorChain(e,r){const t=new Set,o=e=>{if(null==e||t.has(e))return;if(t.add(e),r(e))return e;if("object"!=typeof e)return;const i=e.data;if(e instanceof VigorError&&null!==i&&"object"==typeof i&&"error"in i){const e=o(i.error);if(void 0!==e)return e}return o(e.cause)};return o(e)}function runVigorGuard(e,r,t){const o=r[r.length-1];if("function"!=typeof o)return t(e,r);const i=Array.isArray(r[0])?r[0]:[r[0]],s=findInVigorErrorChain(e,e=>t(e,i));return void 0===s?void 0:o(s)}var VigorAllErrorMessageFuncs={EMPTY_TARGET:e=>"Empty target list",TIMED_OUT:({limit:e,index:r})=>`Task #${r} timeout: exceeded ${e}ms`},VigorAllError=class extends VigorError{constructor(e,r){super(e,(0,VigorAllErrorMessageFuncs[e])(r.data),r)}};function isVigorAllError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorAllError&&(0===r.length||r.includes(e.code)))}var internalMiddlewares=new WeakSet;function markVigorInternal(e){return internalMiddlewares.add(e),e}function isVigorInternalMiddleware(e){const r="function"==typeof e?e:e?.func;return"function"==typeof r&&internalMiddlewares.has(r)}function createVigorTimelineRecorder(e,r,t){const o=(o,i)=>{t&&e.push({action:o,content:i,now:Date.now(),ctx:r()})},i=o;return{add:o,stage:async(e,r,o)=>{if(0===r.length)return;if(!t){for(const e of r)await o(e,e=>e);return}i("MIDDLEWARE_LOOP_STARTED",{stage:e,middlewares:r});const s=performance.now();try{for(const[t,s]of r.entries()){const r=isVigorInternalMiddleware(s),a=performance.now();try{await o(s,o=>{const a={};for(const[n,l]of Object.entries(o))a[n]=(...o)=>(i("MIDDLEWARE_API_CALLED",{stage:e,index:t,middleware:s,internal:r,method:n,args:o}),l(...o));return a})}catch(o){throw i("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!0,error:o}),o}i("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!1,error:null})}}finally{i("MIDDLEWARE_LOOP_ENDED",{stage:e,middlewares:r,took:performance.now()-s})}}}}var MAX_TIMEOUT=2**31-1,VigorAllBase={__brand:createBrand("All","Schema"),policy:VigorAllPolicyBase,cast:VigorEmpty},VigorAll=class _VigorAll extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAll(e)}target(...e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorAllPolicySettings){const r="function"==typeof e?e(new VigorAllPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorAllPolicyMiddlewares){const r="function"==typeof e?e(new VigorAllPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}async _runTask(e,r,t,o,i,s){let a=this._merge(VigorAllEachContextBase,{index:r});const{add:n,stage:l}=createVigorTimelineRecorder(i,()=>this._merge(a,{}),s),c=new AbortController,g=AbortSignal.any([o,c.signal]);let u,y;n("TASK_STARTED",{index:r});const d=performance.now(),p=e=>(n("TASK_ENDED",{index:r,success:e.success,took:performance.now()-d}),e);try{await l("beforeEach",t.middlewares.beforeEach,e=>e(a)),g.throwIfAborted();const o=t.settings.timeout;return!isVigorEmpty(o)&&Number.isFinite(o)&&o>0&&(u=setTimeout(()=>c.abort(new VigorAllError("TIMED_OUT",{method:"request",data:{limit:o,index:r}})),Math.min(o,MAX_TIMEOUT))),a.result=await Promise.race([e(g),new Promise((e,r)=>{y=()=>r(g.reason),g.addEventListener("abort",y)})]),await l("afterEach",t.middlewares.afterEach,e=>e(a)),p({success:!0,value:a.result})}catch(e){a.error=e,n("TASK_ERROR",{index:r,error:e});const o=e=>{a.flags.overridden=!0,a.result=e};return await l("onErrorEach",t.middlewares.onErrorEach,(e,r)=>e(a,r({setResult:o}))),a.flags.overridden?p({success:!0,value:a.result}):p({success:!1,value:e})}finally{clearTimeout(u),y&&g.removeEventListener("abort",y)}}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=[]){const r=this._merge(this.config,{}),t=r.policy;let o=this._merge(VigorAllContextBase,{policy:t},void 0,"replace");o.timeline=e;const i=performance.now(),{add:s,stage:a}=createVigorTimelineRecorder(e,()=>this._snapshot(o),r.policy.settings.debug),n=(e,r)=>s("REQUEST_END",{success:e,outcome:e?"result":"failed",error:r,took:performance.now()-i,restarts:0}),l=e=>{o.result=e},c=e=>{throw e},g=Number.isNaN(t.settings.concurrency)?1:Math.max(1,Math.floor(t.settings.concurrency));s("PROCESS_HANDLING",{type:"REQUEST_START",data:{tasks:t.target.length,concurrency:g}});try{if(0===t.target.length)throw new VigorAllError("EMPTY_TARGET",{method:"request",data:{},context:o});await a("before",t.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:c}))??o});const r=new Array(t.target.length),i=new AbortController,s=AbortSignal.any([...t.abortSignals,i.signal]);let u=0;const y=async()=>{for(;!s.aborted;){const o=u++;if(o>=t.target.length)return;try{r[o]=await this._runTask(t.target[o],o,t,s,e,t.settings.debug)}catch(e){return void i.abort(e)}!r[o].success&&t.settings.failFast&&i.abort(r[o].value)}};return await Promise.all(Array.from({length:Math.min(g,t.target.length)},()=>y())),s.throwIfAborted(),o.result=t.settings.onlySuccess?r.filter(e=>e.success).map(e=>e.value):r.map(e=>e.success?{success:!0,data:e.value,error:null}:{success:!1,data:null,error:e.value}),await a("after",t.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({setResult:l,throwError:c}))??o}),await a("onResult",t.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?o.result=await e.func(o.result):o=await e.func(o,r({setResult:l,throwError:c}))??o}),n(!0,null),{success:!0,data:o.result,error:null,timeline:e}}catch(r){return s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:r}}),n(!1,r),{success:!1,data:null,error:r,timeline:e}}}},VigorFetchPolicySettingsBase={__brand:createBrand("Fetch","Policy<Settings<Schema"),debug:!1,retryHeaders:["retry-after","ratelimit-reset","x-ratelimit-reset","x-retry-after","x-amz-retry-after"],unretryStatus:[400,401,402,403,404,405,406,407,409,410,411,412,413,414,415,416,417,422,424,426,428,431,451,501,505,506,508,510,511],maxRetryAfter:3e5,redirect:!1,confinePath:!0,maxRestarts:3,default:VigorEmpty},VigorFetchPolicySettings=class _VigorFetchPolicySettings extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicySettings(e)}retryHeaders(...e){return this._next({policy:{settings:{retryHeaders:e}}},{policy:{settings:{retryHeaders:"replace"}}})}unretryStatus(...e){return this._next({policy:{settings:{unretryStatus:e}}},{policy:{settings:{unretryStatus:"replace"}}})}maxRetryAfter(e){return this._next({policy:{settings:{maxRetryAfter:e}}})}confinePath(e){return this._next({policy:{settings:{confinePath:e}}})}redirect(e){return this._next({policy:{settings:{redirect:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorFetchPolicyMiddlewaresBase={__brand:createBrand("Fetch","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorFetchPolicyMiddlewares=class _VigorFetchPolicyMiddlewares extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryPolicySettingsBase={__brand:createBrand("Retry","Policy<Settings<Schema"),debug:!1,default:VigorEmpty,maxAttempts:5,maxRestarts:3,timeout:2e4},VigorRetryPolicySettings=class _VigorRetryPolicySettings extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicySettings(e)}default(e){return this._next({policy:{settings:{default:e}}})}maxAttempts(e){return this._next({policy:{settings:{maxAttempts:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorRetryPolicyMiddlewaresBase={__brand:createBrand("Retry","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],retryIf:[],onRetry:[],onError:[]},VigorRetryPolicyMiddlewares=class _VigorRetryPolicyMiddlewares extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}retryIf(e,r){return this._next({policy:{middlewares:{retryIf:[{_mode:e,func:r}]}}})}onRetry(e,r){return this._next({policy:{middlewares:{onRetry:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,RETRY_EXHAUSTED:({maxAttempts:e})=>`Retry exhausted, (max ${e})`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,TIMED_OUT:({limit:e})=>`Timeout: exceeded ${e}ms`},VigorRetryError=class extends VigorError{constructor(e,r){super(e,(0,VigorRetryErrorMessageFuncs[e])(r.data),r)}};function isVigorRetryError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorRetryError&&(0===r.length||r.includes(e.code)))}function VigorJitter(e){return(2*Math.random()-1)*e}var VigorRetryPolicyAlgorithmsConstantBase={__brand:createBrand("Retry","Policy<Algorithms<Constant<Schema"),_tag:"constant",jitter:1e3,interval:2e3,_calculateDelay:(e,r)=>{const{interval:t,jitter:o}=r,i=o;let s=Math.max(i,t);return s+=VigorJitter(o),s}},VigorRetryPolicyAlgorithmsConstant=class _VigorRetryPolicyAlgorithmsConstant extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsConstantBase){super(VigorRetryPolicyAlgorithmsConstantBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsConstant(e)}jitter(e){return this._next({jitter:e})}interval(e){return this._next({interval:e})}},VigorRetryPolicyAlgorithmsLinearBase={__brand:createBrand("Retry","Policy<Algorithms<Linear<Schema"),_tag:"linear",jitter:1e3,initial:500,increment:1e3,minDelay:0,maxDelay:1e4,_calculateDelay:(e,r)=>{const{initial:t,jitter:o,increment:i,minDelay:s,maxDelay:a}=r,n=a-s,l=Math.min(o,n/2),c=s+l,g=a-l;let u=t+i*e;return u=Math.max(c,Math.min(g,u)),u+=VigorJitter(l),u}},VigorRetryPolicyAlgorithmsLinear=class _VigorRetryPolicyAlgorithmsLinear extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsLinearBase){super(VigorRetryPolicyAlgorithmsLinearBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsLinear(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}increment(e){return this._next({increment:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsBackoffBase={__brand:createBrand("Retry","Policy<Algorithms<Backoff<Schema"),_tag:"backoff",jitter:800,initial:0,multiplier:1.7,unit:1e3,minDelay:500,maxDelay:1e4,_calculateDelay:(e,r)=>{const{jitter:t,initial:o,multiplier:i,unit:s,minDelay:a,maxDelay:n}=r,l=n-a,c=Math.min(t,l/2),g=a+c,u=n-c;let y=o+s*Math.pow(i,e);return y=Math.max(g,Math.min(u,y)),y+=VigorJitter(c),y}},VigorRetryPolicyAlgorithmsBackoff=class _VigorRetryPolicyAlgorithmsBackoff extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsBackoffBase){super(VigorRetryPolicyAlgorithmsBackoffBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsBackoff(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}multiplier(e){return this._next({multiplier:e})}unit(e){return this._next({unit:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsCustomBase={__brand:createBrand("Retry","Policy<Algorithms<Custom<Schema"),_tag:"custom",jitter:800,minDelay:500,maxDelay:1e4,target:VigorEmpty,_calculateDelay:(e,r)=>{const{jitter:t,minDelay:o,maxDelay:i,target:s}=r;if(isVigorEmpty(s))throw new VigorRetryError("VALUE_REQUIRED",{method:"_calculateDelay",data:{key:"target"}});const a=i-o,n=Math.min(t,a/2),l=o+n,c=i-n;let g=s(e);return g=Math.max(l,Math.min(c,g)),g+=VigorJitter(n),g}},VigorRetryPolicyAlgorithmsCustom=class _VigorRetryPolicyAlgorithmsCustom extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsCustomBase){super(VigorRetryPolicyAlgorithmsCustomBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsCustom(e)}jitter(e){return this._next({jitter:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}target(e){return this._next({target:e})}},VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsConstantBase,VigorRetryPolicyAlgorithms=class _VigorRetryPolicyAlgorithms extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyAlgorithms(e)}constant(e){const r=this._merge(VigorRetryPolicyAlgorithmsConstantBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}linear(e){const r=this._merge(VigorRetryPolicyAlgorithmsLinearBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}backoff(e){const r=this._merge(VigorRetryPolicyAlgorithmsBackoffBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}custom(e){const r=this._merge(VigorRetryPolicyAlgorithmsCustomBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}},VigorRetryPolicyBase={__brand:createBrand("Retry","Policy<Schema"),target:VigorEmpty,abortSignals:[],settings:VigorRetryPolicySettingsBase,middlewares:VigorRetryPolicyMiddlewaresBase,algorithms:VigorRetryPolicyAlgorithmsBase},VigorRetryContextBase={__brand:createBrand("Retry","Context<Schema"),result:VigorDefault,error:VigorDefault,system:{delay:VigorDefault,attempt:0},flags:{doRetry:!0,doRestart:!1,brokeRetry:!1,aborted:!1,timedOut:!1,overridden:!1},record:{},timeline:[],policy:VigorRetryPolicyBase},MAX_TIMEOUT2=2**31-1,VigorRetryBase={__brand:createBrand("Retry","Schema"),policy:VigorRetryPolicyBase,cast:VigorEmpty},VigorRetry=class _VigorRetry extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetry(e)}target(e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorRetryPolicySettings){const r="function"==typeof e?e(new VigorRetryPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorRetryPolicyMiddlewares){const r="function"==typeof e?e(new VigorRetryPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}algorithms(e){if("function"==typeof e){const r=e(new VigorRetryPolicyAlgorithms).config.policy.algorithms;return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}return this._next({policy:{algorithms:e}},{policy:{algorithms:"replace"}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorRetryContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r}),g=(e,r)=>s("RETRY_DECISION",{attempt:i.system.attempt,retry:e,reason:r});if(isVigorEmpty(i.policy.target))return c(new VigorRetryError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:i}));const u=i.policy.target,y=e=>{throw e},d=AbortSignal.any(i.policy.abortSignals);try{for(;i.system.attempt<i.policy.settings.maxAttempts;){i.system.attempt++,s("ATTEMPT_INCREASED",{attempt:i.system.attempt}),s("PROCESS_HANDLING",{type:"RETRY_START",data:{attempt:i.system.attempt}}),i.flags.timedOut=!1;try{const e=e=>{throw i.flags.brokeRetry=!0,e},r=new AbortController,t=new AbortController,o=AbortSignal.any([r.signal,t.signal]),n=AbortSignal.any([o,d]);let c,g;try{await a("before",i.policy.middlewares.before,async(t,o)=>{"fluent"===t._mode?await t.func(i):i=await t.func(i,o({abort:e=>r.abort(e),throwError:y,breakRetry:e}))??i}),n.throwIfAborted();const o=i.policy.settings.timeout;Number.isFinite(o)&&o>0&&(g=setTimeout(()=>{i.flags.timedOut=!0,t.abort(new VigorRetryError("TIMED_OUT",{method:"request",data:{limit:o},context:i}))},Math.min(o,MAX_TIMEOUT2)));const d=i.system.attempt;s("TARGET_REQUEST_STARTED",{attempt:d});const p=performance.now();i.result=await Promise.race([u(n),new Promise((e,r)=>{c=()=>r(n.reason),n.addEventListener("abort",c)})]),s("TARGET_REQUEST_ENDED",{attempt:d,took:performance.now()-p}),await a("after",i.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y}))??i});const h=e=>{i.result=e};return await a("onResult",i.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?i.result=await e.func(i.result):i=await e.func(i,r({setResult:h,throwError:y}))??i}),l(i.result,"result")}finally{clearTimeout(g),c&&n.removeEventListener("abort",c)}}catch(e){if(i.error=e,d.aborted&&(i.flags.aborted=!0),s("PROCESS_HANDLING",{type:"RETRY_ERROR",data:{attempt:i.system.attempt,error:e,timedOut:i.flags.timedOut,aborted:i.flags.aborted}}),i.flags.aborted)throw g(!1,"aborted"),i.error;if(i.flags.brokeRetry)throw g(!1,"breakRetry"),i.error;i.flags.doRetry=!0;const r=()=>i.flags.doRetry=!0,t=()=>i.flags.doRetry=!1;if(await a("retryIf",i.policy.middlewares.retryIf,async(e,o)=>{"fluent"===e._mode?i.flags.doRetry=await e.func(i.error):i=await e.func(i,o({proceedRetry:r,cancelRetry:t}))??i}),!i.flags.doRetry)throw g(!1,"cancelled"),i.error;if(i.system.attempt>=i.policy.settings.maxAttempts){g(!1,"exhausted");break}g(!0,"retry"),i.system.delay=i.policy.algorithms._calculateDelay(i.system.attempt,i.policy.algorithms);const o=e=>{i.system.delay=e};await a("onRetry",i.policy.middlewares.onRetry,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({throwError:y,setDelay:o}))??i});const n=Math.min(Math.max(0,Number(i.system.delay)||0),MAX_TIMEOUT2);s("RETRY_DELAY",{attempt:i.system.attempt,delay:n}),await new Promise((e,r)=>{if(d.aborted)return i.flags.aborted=!0,r(d.reason);const t=()=>{clearTimeout(o),i.flags.aborted=!0,r(d.reason)},o=setTimeout(()=>{d.removeEventListener("abort",t),e()},n);d.addEventListener("abort",t,{once:!0})})}}throw new VigorRetryError("RETRY_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxAttempts,error:i.error},context:i})}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.doRestart=!1,i.flags.overridden=!1;const n=e=>{i.flags.overridden=!0,i.result=e},g=()=>i.flags.doRestart=!0,u=()=>i.flags.doRestart=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:y,proceedRestart:g,cancelRestart:u}))??i})}catch(e){return c(e)}if(i.flags.doRestart)return e>i.policy.settings.maxRestarts?c(new VigorRetryError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(i.error)}}},VigorParsePolicySettingsBase={__brand:createBrand("Parse","Policy<Settings<Schema"),debug:!1,raw:!1,default:VigorEmpty,maxRestarts:3},VigorParsePolicySettings=class _VigorParsePolicySettings extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicySettings(e)}raw(e){return this._next({policy:{settings:{raw:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorParsePolicyMiddlewaresBase={__brand:createBrand("Parse","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorParsePolicyMiddlewares=class _VigorParsePolicyMiddlewares extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},describeVigorParseFailure=e=>e instanceof Error?`${e.name}: ${e.message}`:String(e),VigorParseErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,INVALID_CONTENT_TYPE:({received:e})=>`Invalid Content-Type header: ${String(e)}`,PARSER_NOT_FOUND:({received:e,expected:r})=>`Parser not found for Content-Type "${String(e)}" (known: ${r.join(", ")})`,PARSER_ALL_FAILED:({tried:e,errors:r})=>`All parsers failed: ${e.map((e,t)=>`${e} (${describeVigorParseFailure(r[t])})`).join(", ")}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`},VigorParseError=class extends VigorError{constructor(e,r){super(e,(0,VigorParseErrorMessageFuncs[e])(r.data),r)}};function isVigorParseError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorParseError&&(0===r.length||r.includes(e.code)))}var VigorParsePolicyStrategiesBase={__brand:createBrand("Parse","Policy<Strategies<Schema"),funcs:[]},bodyCache=new WeakMap;async function readVigorParseBody(e){let r=bodyCache.get(e);return r||(r=null===e.body?Promise.resolve(new Uint8Array(0)):e.arrayBuffer().then(e=>new Uint8Array(e)),bodyCache.set(e,r)),{bytes:await r,contentType:e.headers.get("content-type"),status:e instanceof Response?e.status:null,headers:e.headers,source:e}}var utf8=new TextDecoder("utf-8"),getCharset=e=>/;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(e??"")?.[1]??"utf-8",getMimeType=e=>(e??"").split(";")[0].trim().toLowerCase(),decodeText=(e,r=!1)=>{let t;try{t=new TextDecoder(getCharset(e.contentType),{fatal:r})}catch{t=new TextDecoder("utf-8",{fatal:r})}return t.decode(e.bytes)},parseJson=e=>JSON.parse(utf8.decode(e.bytes)),parseJsonOrNull=e=>{const r=utf8.decode(e.bytes);return""===r.trim()?null:JSON.parse(r)},hexValue=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1,decodeFormComponent=e=>{const r=new Uint8Array(e.length);let t=0;for(let o=0;o<e.length;o++){const i=e[o];if(43!==i){if(37===i&&o+2<e.length){const i=hexValue(e[o+1]),s=hexValue(e[o+2]);if(i>=0&&s>=0){r[t++]=16*i+s,o+=2;continue}}r[t++]=i}else r[t++]=32}return utf8.decode(r.subarray(0,t))},parseUrlEncoded=e=>{const r=new FormData,{bytes:t}=e;let o=0;for(let e=0;e<=t.length;e++){if(e<t.length&&38!==t[e])continue;const i=t.subarray(o,e);if(o=e+1,0===i.length)continue;const s=i.indexOf(61),a=-1===s?i:i.subarray(0,s),n=-1===s?new Uint8Array(0):i.subarray(s+1);r.append(decodeFormComponent(a),decodeFormComponent(n))}return r},parseMultipart=e=>new Response(e.bytes,{headers:{"content-type":e.contentType??""}}).formData(),parseFormData=e=>{const r=getMimeType(e.contentType);if("application/x-www-form-urlencoded"===r)return parseUrlEncoded(e);if("multipart/form-data"===r)return parseMultipart(e);throw new VigorParseError("INVALID_CONTENT_TYPE",{method:"parseFormData",data:{received:e.contentType}})},toArrayBuffer=e=>e.bytes.slice().buffer,toBlob=e=>new Blob([e.bytes],{type:e.contentType??""}),NoBodyStatus=[204,205,304],ContentTypeParsers=[{header:"application/json",regExp:/application\/(.+\+)?json(.+\+)?/i,method:parseJsonOrNull},{header:"application/xml",regExp:/application\/(.+\+)?xml(.+\+)?/i,method:e=>decodeText(e)},{header:"application/x-www-form-urlencoded",regExp:/application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i,method:parseUrlEncoded},{header:"application/octet-stream",regExp:/application\/(.+\+)?octet-stream(.+\+)?/i,method:toArrayBuffer},{header:"image/*",regExp:/^image\/.+/i,method:toBlob},{header:"audio/*",regExp:/^audio\/.+/i,method:toBlob},{header:"video/*",regExp:/^video\/.+/i,method:toBlob},{header:"multipart/form-data",regExp:/multipart\/(.+\+)?form-data(.+\+)?/i,method:parseMultipart},{header:"text/*",regExp:/^text\/.+/i,method:e=>decodeText(e)}],SniffMethods=[{title:"json",method:parseJson},{title:"formData",method:parseFormData},{title:"text",method:e=>decodeText(e,!0)},{title:"blob",method:toBlob}],VigorParseContentTypeStrategy=async e=>{if(0===e.bytes.length||null!==e.status&&NoBodyStatus.includes(e.status))return null;if(!e.contentType)return decodeText(e);const r=ContentTypeParsers.find(r=>r.regExp.test(e.contentType));return r?await r.method(e):toBlob(e)},VigorParseSniffStrategy=async e=>{const r=[];for(const t of SniffMethods)try{return await t.method(e)}catch(e){r.push(e)}throw new VigorParseError("PARSER_ALL_FAILED",{method:"VigorParseSniffStrategy",cause:r.at(-1),data:{tried:SniffMethods.map(e=>e.title),errors:r}})},VigorParsePolicyStrategies=class _VigorParsePolicyStrategies extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyStrategies(e)}_set(e,r){return this._next({policy:{strategies:{funcs:e}}},r?{policy:{strategies:{funcs:"replace"}}}:void 0)}contentType(e){return this._set([VigorParseContentTypeStrategy],e)}sniff(e){return this._set([VigorParseSniffStrategy],e)}json(e){return this._set([parseJson],e)}text(e){return this._set([e=>decodeText(e)],e)}arrayBuffer(e){return this._set([toArrayBuffer],e)}blob(e){return this._set([toBlob],e)}bytes(e){return this._set([e=>e.bytes.slice()],e)}formData(e){return this._set([parseFormData],e)}custom(e,r){return this._set([e],r)}},VigorParsePolicyBase={__brand:createBrand("Parse","Policy<Schema"),target:VigorDefault,settings:VigorParsePolicySettingsBase,middlewares:VigorParsePolicyMiddlewaresBase,strategies:VigorParsePolicyStrategiesBase},VigorParseContextBase={__brand:createBrand("Parse","Context<Schema"),result:VigorDefault,error:VigorDefault,response:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorParsePolicyBase},VigorParseBase={__brand:createBrand("Parse","Schema"),policy:VigorParsePolicyBase,cast:VigorEmpty},VigorParse=class _VigorParse extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParse(e)}target(e){return this._next({policy:{target:e}})}settings(e){if("function"==typeof e||e instanceof VigorParsePolicySettings){const r="function"==typeof e?e(new VigorParsePolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorParsePolicyMiddlewares){const r="function"==typeof e?e(new VigorParsePolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}strategies(e){if("function"==typeof e||e instanceof VigorParsePolicyStrategies){const r="function"==typeof e?e(new VigorParsePolicyStrategies):e;return this._next({policy:{strategies:r.config.policy.strategies}})}return this._next({policy:{strategies:e}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorParseContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r});if(isVigorDefault(i.policy.target))return c(new VigorParseError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:i}));i.response=i.policy.target;const g=e=>{throw e};try{if(await a("before",i.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:g}))??i}),i.policy.settings.raw)i.result=i.response;else{const e=performance.now(),r=await readVigorParseBody(i.response);s("BODY_READ",{size:r.bytes.byteLength,took:performance.now()-e});const t=i.policy.strategies.funcs.length>0?i.policy.strategies.funcs:[VigorParseContentTypeStrategy];let o=!1;const a=[];for(const[e,n]of t.entries()){s("STRATEGY_STARTED",{index:e});const t=performance.now();try{i.result=await n(r),s("STRATEGY_SUCCEEDED",{index:e,took:performance.now()-t}),o=!0;break}catch(r){a.push(r),s("STRATEGY_FAILED",{index:e,error:r,took:performance.now()-t})}}if(!o)throw new VigorParseError("PARSER_ALL_FAILED",{method:"request",cause:a.at(-1),data:{tried:t.map((e,r)=>`strategy#${r}`),errors:a},context:i})}const e=e=>{i.result=e};return await a("after",i.policy.middlewares.after,async(r,t)=>{"fluent"===r._mode?await r.func(i):i=await r.func(i,t({setResult:e,throwError:g}))??i}),await a("onResult",i.policy.middlewares.onResult,async(r,t)=>{"fluent"===r._mode?i.result=await r.func(i.result):i=await r.func(i,t({setResult:e,throwError:g}))??i}),l(i.result,"result")}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.overridden=!1,i.flags.restarted=!1;const n=e=>{i.flags.overridden=!0,i.result=e},u=()=>i.flags.restarted=!0,y=()=>i.flags.restarted=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:g,proceedRestart:u,cancelRestart:y}))??i})}catch(e){return c(e)}if(i.flags.restarted)return e>i.policy.settings.maxRestarts?c(new VigorParseError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(i.error)}}},VigorFetchPolicyBase={__brand:createBrand("Fetch","Policy<Schema"),method:VigorEmpty,origin:VigorEmpty,path:[],query:[],hash:"",headers:{},body:VigorEmpty,extra:{},settings:VigorFetchPolicySettingsBase,middlewares:VigorFetchPolicyMiddlewaresBase,retry:VigorRetryBase,parse:VigorParseBase},VigorFetchContextBase={__brand:createBrand("Fetch","Context<Schema"),href:"",response:VigorDefault,result:VigorDefault,error:VigorDefault,options:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorFetchPolicyBase},VigorFetchErrorMessageFuncs={...VigorRetryErrorMessageFuncs,...VigorParseErrorMessageFuncs,VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,INVALID_BODY:({received:e})=>"Invalid Body type: "+typeof e,BODY_NOT_ALLOWED:({method:e})=>`A ${e} request cannot have a body`,INVALID_PROTOCOL:({origin:e,base:r})=>r?`Invalid URL: could not resolve "${e}" against base "${r}"`:`Invalid URL: "${e}" is not an absolute URL, and no base (window.location) is available to resolve it against — pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,FETCH_FAILED:({status:e,statusText:r})=>`Fetch Failed: ${e} ${r}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,PATH_ESCAPED:({url:e,base:r})=>`Path escapes "${r}": the request would go to "${e}" (settings.confinePath)`,REDIRECTED:({url:e,status:r})=>`Redirected (${r}) to "${e}" — navigating away`},VigorFetchError=class extends VigorError{constructor(e,r){super(e,(0,VigorFetchErrorMessageFuncs[e])(r.data),r)}};function isVigorFetchError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorFetchError&&(0===r.length||r.includes(e.code)))}function adoptVigorFetchError(e,r){if(!(e instanceof VigorRetryError||e instanceof VigorParseError))return e;const t=e.data,o=null!==t&&"object"==typeof t&&"error"in t?{...t,error:adoptVigorFetchError(t.error,r)}:t;return new VigorFetchError(e.code,{method:e.method,cause:e,data:o,context:r})}var VigorFetchBase={__brand:createBrand("Fetch","Schema"),policy:VigorFetchPolicyBase,cast:VigorEmpty,apiMap:VigorEmpty},VigorFetch=class _VigorFetch extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetch(e)}method(e){return this._next({policy:{method:e}})}origin(e){return this._next({policy:{origin:e}})}path(...e){return this._next({policy:{path:this._stringifyList(e)}})}query(...e){return this._next({policy:{query:e}})}hash(e){return this._next({policy:{hash:e}},{policy:{hash:"replace"}})}headers(e,r){return"overwrite"===e?this._next({policy:{headers:r}},{policy:{headers:"replace"}}):this._next({policy:{headers:r}})}body(e,r){const t=this.config.policy.body,o="merge"===e&&this._isPlainObject(t)&&this._isPlainObject(r)?{...t,...r}:r;return this._next({policy:{body:o}},{policy:{body:"replace"}})}options(e,r){const t="merge"===e?{...this.config.policy.extra,...r}:r;return this._next({policy:{extra:t}},{policy:{extra:"replace"}})}settings(e){const r={policy:{settings:{retryHeaders:"replace",unretryStatus:"replace"}}};if("function"==typeof e||e instanceof VigorFetchPolicySettings){const t="function"==typeof e?e(new VigorFetchPolicySettings(this.config)):e;return this._next({policy:{settings:t.config.policy.settings}},r)}return this._next({policy:{settings:e}},r)}middlewares(e){if("function"==typeof e||e instanceof VigorFetchPolicyMiddlewares){const r="function"==typeof e?e(new VigorFetchPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}retry(e){if("function"==typeof e||e instanceof VigorRetry){const r="function"==typeof e?e(new VigorRetry):e;return this._next({policy:{retry:r.config}},{policy:{retry:"replace"}})}return this._next({policy:{retry:this._merge(VigorRetryBase,e)}},{policy:{retry:"replace"}})}parse(e){if("function"==typeof e||e instanceof VigorParse){const r="function"==typeof e?e(new VigorParse):e;return this._next({policy:{parse:r.config}},{policy:{parse:"replace"}})}return this._next({policy:{parse:this._merge(VigorParseBase,e)}},{policy:{parse:"replace"}})}_isPlainObject(e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}_stringifyList(e){return e.filter(e=>null!=e).map(e=>e instanceof Date?e.toISOString():String(e))}_resolveBase(){if("undefined"!=typeof globalThis&&globalThis.location?.href)return globalThis.location.href}_buildUrl(e,r,t,o,i){const s=this._resolveBase();let a;try{a=new URL(e,s)}catch{throw new VigorFetchError("INVALID_PROTOCOL",{method:"_buildUrl",data:{origin:e,base:s},context:i})}const n=a.origin,l=[a.pathname.replace(/^\/+|\/+$/g,"")];for(const e of r)for(const r of e.split("/"))l.push(encodeURIComponent(r));const c=l.filter(Boolean).join("/"),g=new URL(c,n),u=e=>e instanceof Date?e.toISOString():String(e),y=[...a.searchParams.entries(),...t.flatMap(e=>Object.entries(e))];for(const[e,r]of y)if(null!=r)if(Array.isArray(r))for(const t of r)g.searchParams.append(e,u(t));else g.searchParams.append(e,u(r));if(g.hash=o||a.hash,i.policy.settings.confinePath){const e="/"+a.pathname.replace(/^\/+|\/+$/g,""),r="/"===e||g.pathname===e||g.pathname.startsWith(e+"/");if(g.origin!==a.origin||!r)throw new VigorFetchError("PATH_ESCAPED",{method:"_buildUrl",data:{url:g.href,base:a.origin+("/"===e?"":e)},context:i})}return g.href}_normalizeBody(e,r){if(null==e)return{headers:{},body:e};if("string"==typeof e)return{headers:{"Content-Type":"text/plain;charset=UTF-8"},body:e};if(e instanceof Blob)return{headers:e.type?{"Content-Type":e.type}:{},body:e};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{headers:{"Content-Type":"application/octet-stream"},body:e};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{headers:{"Content-Type":"application/octet-stream"},body:e};if(e instanceof URLSearchParams)return{headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:e};if(e instanceof FormData)return{headers:{},body:e};if("object"==typeof e)return{headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};throw new VigorFetchError("INVALID_BODY",{method:"_normalizeBody",data:{received:e},context:r})}_resolveRedirect(e,r){if(e.redirected&&e.url)return e.url;if(e.status<300||e.status>=400)return null;const t=e.headers.get("location");if(!t)return null;try{return new URL(t,e.url||r).href}catch{return null}}_browserLocation(){const e=globalThis.window;return void 0!==e?.location?.href?e.location:null}_assignHeaders(e,r){for(const[t,o]of Object.entries(r)){const r=t.toLowerCase();for(const t of Object.keys(e))t.toLowerCase()===r&&delete e[t];e[t]=o}}_parseRetryHeader(e){if(!e)return null;const r=Number(e);let t;if(""===e.trim()||isNaN(r)){const r=new Date(e).getTime();if(isNaN(r))return null;t=r-Date.now()}else t=r>=1e12?r-Date.now():r>=1e9?1e3*r-Date.now():1e3*r;return t>0?t:null}apiMap(){return this._next({apiMap:VigorCastPlaceholder},{apiMap:"replace"})}route(e,...r){const t=e,o=t.indexOf(" "),i=t.slice(0,o),s=r[0]??{},a=t.slice(o+1).split("/").filter(Boolean).map(e=>{if(!e.startsWith(":"))return e;const r=e.slice(1),t=s[r];if(null==t)throw new VigorFetchError("VALUE_REQUIRED",{method:"route",data:{key:`params.${r}`}});return t});return this.method(i).path(...a)}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestRuntime();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorFetchContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t,o=null)=>(n(!0,t,null),{success:!0,data:e,error:null,status:o?.status??null,response:o,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,status:null,response:null,timeline:r});let g=0;const u=async(e,r,t)=>{s("PARSE_STARTED",{engine:t,source:e,attempt:r});const o=performance.now(),i=await t.requestVerbose();return s("PARSE_ENDED",{engine:t,source:e,attempt:r,timeline:i.timeline,took:performance.now()-o,result:i.success?i.data:VigorDefault}),i},y=e=>{throw e};try{if(isVigorEmpty(i.policy.origin))throw new VigorFetchError("VALUE_REQUIRED",{method:"request",data:{key:"origin"},context:i});i.href=this._buildUrl(i.policy.origin,i.policy.path,i.policy.query,i.policy.hash,i),s("BUILT_URL",{url:i.href});const e=!isVigorEmpty(i.policy.body)&&null!=i.policy.body,r=isVigorEmpty(i.policy.method)?e?"POST":"GET":i.policy.method,t={...i.policy.extra,method:r,headers:{}};if(e){const e=this._normalizeBody(i.policy.body,i);void 0!==e.body&&(t.body=e.body),Object.assign(t.headers,e.headers)}this._assignHeaders(t.headers,i.policy.headers),i.options=t,await a("before",i.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y,setOptions:e=>{i.options=e},setHeaders:e=>{i.options.headers=e},setBody:e=>{i.options.body=e}}))??i});const n=isVigorDefault(i.options)?t:i.options;i.options=n,s("SET_OPTIONS",{options:n});const c=(n.method??"GET").toUpperCase();if(null!=n.body&&("GET"===c||"HEAD"===c))throw new VigorFetchError("BODY_NOT_ALLOWED",{method:"request",data:{method:c},context:i});const d="undefined"!=typeof ReadableStream&&n.body instanceof ReadableStream;d&&(n.duplex??="half");const p={policy:{settings:{debug:!0}}},h=new VigorParse(o.policy.settings.debug?this._merge(i.policy.parse,p):i.policy.parse),m=new VigorRetry(o.policy.settings.debug?this._merge(i.policy.retry,p):i.policy.retry).target(async e=>await fetch(i.href,{...n,signal:e})).middlewares(e=>e.after("intercept",async(e,r)=>{const t=e.result;if(g=e.system.attempt,s("RESPONSE_RECEIVED",{attempt:e.system.attempt,status:t.status,statusText:t.statusText,ok:t.ok,redirected:t.redirected,url:t.url}),i.policy.settings.redirect){const e=this._resolveRedirect(t,i.href),o=this._browserLocation();e&&o&&(o.href=e,r.throwError(new VigorFetchError("REDIRECTED",{method:"request",data:{url:e,status:t.status,response:t},context:i})))}if(!t.ok&&304!==t.status){const o=await u("failedResponse",e.system.attempt,h.target(t.clone())),s=o.success?o.data:void 0;r.throwError(new VigorFetchError("FETCH_FAILED",{method:"request",data:{status:t.status,statusText:t.statusText,response:t,url:t.url,parsed:s},context:i}))}return i.policy.parse.policy.settings.raw||await readVigorParseBody(t),e}).retryIf("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;return(e.error instanceof VigorFetchError&&"REDIRECTED"===e.error.code||d||t&&("opaqueredirect"===t.type||t.status>=300&&t.status<400)||t&&i.policy.settings.unretryStatus.includes(t.status))&&r.cancelRetry(),e}).onRetry("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;if(429===t?.status||503===t?.status)for(const e of i.policy.settings.retryHeaders){const o=this._parseRetryHeader(t.headers.get(e));if(null!==o){r.setDelay(Math.min(o,i.policy.settings.maxRetryAfter));break}}return e}));for(const e of["after","retryIf","onRetry"]){const r=m.config.policy.middlewares[e];markVigorInternal(r[r.length-1].func)}s("ENGINE_CREATED",{retryEngine:m,parseEngine:h});const f=await(async e=>{s("RETRY_STARTED",{engine:e});const r=performance.now(),t=await e.requestVerbose();return s("RETRY_ENDED",{engine:e,timeline:t.timeline,took:performance.now()-r,response:t.success?t.data:VigorDefault}),t})(m);if(!f.success)throw adoptVigorFetchError(f.error,i);i.response=f.data;const V=await u("response",g,h.target(i.response));if(!V.success)throw adoptVigorFetchError(V.error,i);i.result=V.data,await a("after",i.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y,setResult:e=>{i.result=e}}))??i});const _=e=>{i.result=e};return await a("onResult",i.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?i.result=await e.func(i.result):i=await e.func(i,r({setResult:_,throwError:y}))??i}),l(i.result,"result",i.response)}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.overridden=!1,i.flags.restarted=!1;const n=e=>{i.flags.overridden=!0,i.result=e},g=()=>i.flags.restarted=!0,u=()=>i.flags.restarted=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:y,proceedRestart:g,cancelRestart:u}))??i})}catch(e){return c(e)}if(i.flags.restarted)return e>i.policy.settings.maxRestarts?c(new VigorFetchError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(o)}}};function retryWithTarget(e){return(new VigorRetry).target(e)}function parseWithTarget(e){return(new VigorParse).target(e)}function fetchWithOrigin(e){return(new VigorFetch).origin(e)}function allWithTargets(e){return(new VigorAll).target(...e)}var vigorBase={retry:e=>void 0!==e?retryWithTarget(e):new VigorRetry,parse:e=>void 0!==e?parseWithTarget(e):new VigorParse,fetch:e=>void 0!==e?fetchWithOrigin(e):new VigorFetch,all:(...e)=>e.length>0?allWithTargets(e):new VigorAll,builders:{fetch:{settings:()=>new VigorFetchPolicySettings,middlewares:()=>new VigorFetchPolicyMiddlewares},retry:{settings:()=>new VigorRetryPolicySettings,middlewares:()=>new VigorRetryPolicyMiddlewares,algorithms:()=>new VigorRetryPolicyAlgorithms,algorithm:{constant:()=>new VigorRetryPolicyAlgorithmsConstant,linear:()=>new VigorRetryPolicyAlgorithmsLinear,backoff:()=>new VigorRetryPolicyAlgorithmsBackoff,custom:()=>new VigorRetryPolicyAlgorithmsCustom}},parse:{settings:()=>new VigorParsePolicySettings,middlewares:()=>new VigorParsePolicyMiddlewares,strategies:()=>new VigorParsePolicyStrategies},all:{settings:()=>new VigorAllPolicySettings,middlewares:()=>new VigorAllPolicyMiddlewares}},guards:{retry:isVigorRetryError,parse:isVigorParseError,fetch:isVigorFetchError,all:isVigorAllError}},cloneVigor=e=>({...e,builders:{fetch:{...e.builders.fetch},retry:{...e.builders.retry,algorithm:{...e.builders.retry.algorithm}},parse:{...e.builders.parse},all:{...e.builders.all}},guards:{...e.guards}}),createVigor=e=>{const r={...e,use:(e,t)=>{const o=e.func(r,{...e.options,...t}),{use:i,...s}={...cloneVigor(r),...o};return createVigor(s)}};return r},vigor=createVigor(vigorBase),index_default=vigor;exports.VigorAll=VigorAll,exports.VigorAllBase=VigorAllBase,exports.VigorAllContextBase=VigorAllContextBase,exports.VigorAllEachContextBase=VigorAllEachContextBase,exports.VigorAllError=VigorAllError,exports.VigorAllErrorMessageFuncs=VigorAllErrorMessageFuncs,exports.VigorAllPolicyBase=VigorAllPolicyBase,exports.VigorAllPolicyMiddlewares=VigorAllPolicyMiddlewares,exports.VigorAllPolicyMiddlewaresBase=VigorAllPolicyMiddlewaresBase,exports.VigorAllPolicySettings=VigorAllPolicySettings,exports.VigorAllPolicySettingsBase=VigorAllPolicySettingsBase,exports.VigorCastPlaceholder=VigorCastPlaceholder,exports.VigorDefault=VigorDefault,exports.VigorEmpty=VigorEmpty,exports.VigorError=VigorError,exports.VigorFetch=VigorFetch,exports.VigorFetchBase=VigorFetchBase,exports.VigorFetchContextBase=VigorFetchContextBase,exports.VigorFetchError=VigorFetchError,exports.VigorFetchErrorMessageFuncs=VigorFetchErrorMessageFuncs,exports.VigorFetchPolicyBase=VigorFetchPolicyBase,exports.VigorFetchPolicyMiddlewares=VigorFetchPolicyMiddlewares,exports.VigorFetchPolicyMiddlewaresBase=VigorFetchPolicyMiddlewaresBase,exports.VigorFetchPolicySettings=VigorFetchPolicySettings,exports.VigorFetchPolicySettingsBase=VigorFetchPolicySettingsBase,exports.VigorJitter=VigorJitter,exports.VigorParse=VigorParse,exports.VigorParseBase=VigorParseBase,exports.VigorParseContentTypeStrategy=VigorParseContentTypeStrategy,exports.VigorParseContextBase=VigorParseContextBase,exports.VigorParseError=VigorParseError,exports.VigorParseErrorMessageFuncs=VigorParseErrorMessageFuncs,exports.VigorParsePolicyBase=VigorParsePolicyBase,exports.VigorParsePolicyMiddlewares=VigorParsePolicyMiddlewares,exports.VigorParsePolicyMiddlewaresBase=VigorParsePolicyMiddlewaresBase,exports.VigorParsePolicySettings=VigorParsePolicySettings,exports.VigorParsePolicySettingsBase=VigorParsePolicySettingsBase,exports.VigorParsePolicyStrategies=VigorParsePolicyStrategies,exports.VigorParsePolicyStrategiesBase=VigorParsePolicyStrategiesBase,exports.VigorParseSniffStrategy=VigorParseSniffStrategy,exports.VigorRetry=VigorRetry,exports.VigorRetryBase=VigorRetryBase,exports.VigorRetryContextBase=VigorRetryContextBase,exports.VigorRetryError=VigorRetryError,exports.VigorRetryErrorMessageFuncs=VigorRetryErrorMessageFuncs,exports.VigorRetryPolicyAlgorithms=VigorRetryPolicyAlgorithms,exports.VigorRetryPolicyAlgorithmsBackoff=VigorRetryPolicyAlgorithmsBackoff,exports.VigorRetryPolicyAlgorithmsBackoffBase=VigorRetryPolicyAlgorithmsBackoffBase,exports.VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsBase,exports.VigorRetryPolicyAlgorithmsConstant=VigorRetryPolicyAlgorithmsConstant,exports.VigorRetryPolicyAlgorithmsConstantBase=VigorRetryPolicyAlgorithmsConstantBase,exports.VigorRetryPolicyAlgorithmsCustom=VigorRetryPolicyAlgorithmsCustom,exports.VigorRetryPolicyAlgorithmsCustomBase=VigorRetryPolicyAlgorithmsCustomBase,exports.VigorRetryPolicyAlgorithmsLinear=VigorRetryPolicyAlgorithmsLinear,exports.VigorRetryPolicyAlgorithmsLinearBase=VigorRetryPolicyAlgorithmsLinearBase,exports.VigorRetryPolicyBase=VigorRetryPolicyBase,exports.VigorRetryPolicyMiddlewares=VigorRetryPolicyMiddlewares,exports.VigorRetryPolicyMiddlewaresBase=VigorRetryPolicyMiddlewaresBase,exports.VigorRetryPolicySettings=VigorRetryPolicySettings,exports.VigorRetryPolicySettingsBase=VigorRetryPolicySettingsBase,exports.VigorStatus=VigorStatus,exports.adoptVigorFetchError=adoptVigorFetchError,exports.createBrand=createBrand,exports.createVigorTimelineRecorder=createVigorTimelineRecorder,exports.default=index_default,exports.findInVigorErrorChain=findInVigorErrorChain,exports.isVigorAllError=isVigorAllError,exports.isVigorDefault=isVigorDefault,exports.isVigorEmpty=isVigorEmpty,exports.isVigorFetchError=isVigorFetchError,exports.isVigorInternalMiddleware=isVigorInternalMiddleware,exports.isVigorParseError=isVigorParseError,exports.isVigorRetryError=isVigorRetryError,exports.markVigorInternal=markVigorInternal,exports.readVigorParseBody=readVigorParseBody,exports.runVigorGuard=runVigorGuard,exports.vigor=vigor;