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