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