vigor-fetch 4.1.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -70,6 +70,14 @@ var VigorStatus = class {
70
70
  };
71
71
  return merge(source, target, strategy);
72
72
  }
73
+ /**
74
+ * Snapshots a runtime context for a timeline entry: a `_merge` deep clone
75
+ * of everything but `timeline`, so later changes to `ctx` don't reach it.
76
+ */
77
+ _snapshot(ctx) {
78
+ const { timeline: _, ...rest } = ctx;
79
+ return this._merge(rest, {});
80
+ }
73
81
  /** The default/base config this builder was constructed with. */
74
82
  get base() {
75
83
  return this._base;
@@ -83,6 +91,7 @@ var VigorStatus = class {
83
91
  // src/all/settings.ts
84
92
  var VigorAllPolicySettingsBase = {
85
93
  __brand: createBrand("All", "Policy<Settings<Schema"),
94
+ debug: false,
86
95
  concurrency: 5,
87
96
  onlySuccess: false,
88
97
  timeout: VigorEmpty,
@@ -111,6 +120,14 @@ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
111
120
  failFast(bool) {
112
121
  return this._next({ policy: { settings: { failFast: bool } } });
113
122
  }
123
+ /**
124
+ * Turns timeline recording on or off (off by default). Off, the
125
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
126
+ * are taken, so it costs nothing unless you're debugging.
127
+ */
128
+ debug(bool) {
129
+ return this._next({ policy: { settings: { debug: bool } } });
130
+ }
114
131
  };
115
132
 
116
133
  // src/all/middlewares.ts
@@ -167,7 +184,8 @@ var VigorAllContextBase = {
167
184
  __brand: createBrand("All", "Context<Schema"),
168
185
  result: VigorDefault,
169
186
  policy: VigorAllPolicyBase,
170
- record: {}
187
+ record: {},
188
+ timeline: []
171
189
  };
172
190
  var VigorAllEachContextBase = {
173
191
  __brand: createBrand("All", "EachContext<Schema"),
@@ -185,6 +203,7 @@ var VigorError = class extends Error {
185
203
  code;
186
204
  data;
187
205
  method;
206
+ /** The run context when the error was raised; its presence depends on the code (see {@link VigorErrorContext}). */
188
207
  context;
189
208
  /**
190
209
  * @param code - Machine-readable error code.
@@ -219,9 +238,64 @@ var VigorAllError = class extends VigorError {
219
238
  super(code, messageFn(options.data), options);
220
239
  }
221
240
  };
222
- var isVigorAllError = (error) => error instanceof VigorAllError;
241
+ function isVigorAllError(error, ...codes) {
242
+ return error instanceof VigorAllError && (codes.length === 0 || codes.includes(error.code));
243
+ }
244
+
245
+ // src/core/timeline.ts
246
+ var internalMiddlewares = /* @__PURE__ */ new WeakSet();
247
+ function markVigorInternal(func) {
248
+ internalMiddlewares.add(func);
249
+ return func;
250
+ }
251
+ function isVigorInternalMiddleware(middleware) {
252
+ const func = typeof middleware === "function" ? middleware : middleware?.func;
253
+ return typeof func === "function" && internalMiddlewares.has(func);
254
+ }
255
+ function createVigorTimelineRecorder(timeline, snapshot, enabled) {
256
+ const add = (action, content) => {
257
+ if (!enabled) return;
258
+ timeline.push({ action, content, now: Date.now(), ctx: snapshot() });
259
+ };
260
+ const record = add;
261
+ const stage = async (stage2, middlewares, run) => {
262
+ if (middlewares.length === 0) return;
263
+ if (!enabled) {
264
+ for (const middleware of middlewares) await run(middleware, (api) => api);
265
+ return;
266
+ }
267
+ record("MIDDLEWARE_LOOP_STARTED", { stage: stage2, middlewares });
268
+ const started = performance.now();
269
+ try {
270
+ for (const [index, middleware] of middlewares.entries()) {
271
+ const internal = isVigorInternalMiddleware(middleware);
272
+ const ranAt = performance.now();
273
+ try {
274
+ await run(middleware, (api) => {
275
+ const traced = {};
276
+ for (const [method, func] of Object.entries(api)) {
277
+ traced[method] = (...args) => {
278
+ record("MIDDLEWARE_API_CALLED", { stage: stage2, index, middleware, internal, method, args });
279
+ return func(...args);
280
+ };
281
+ }
282
+ return traced;
283
+ });
284
+ } catch (error) {
285
+ record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: true, error });
286
+ throw error;
287
+ }
288
+ record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: false, error: null });
289
+ }
290
+ } finally {
291
+ record("MIDDLEWARE_LOOP_ENDED", { stage: stage2, middlewares, took: performance.now() - started });
292
+ }
293
+ };
294
+ return { add, stage };
295
+ }
223
296
 
224
297
  // src/all/main.ts
298
+ var MAX_TIMEOUT = 2 ** 31 - 1;
225
299
  var VigorAllBase = {
226
300
  __brand: createBrand("All", "Schema"),
227
301
  policy: VigorAllPolicyBase,
@@ -244,7 +318,7 @@ var VigorAll = class _VigorAll extends VigorStatus {
244
318
  }
245
319
  settings(input) {
246
320
  if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
247
- const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
321
+ const result = typeof input === "function" ? input(new VigorAllPolicySettings(this.config)) : input;
248
322
  return this._next({
249
323
  policy: { settings: result.config.policy.settings }
250
324
  });
@@ -261,21 +335,28 @@ var VigorAll = class _VigorAll extends VigorStatus {
261
335
  return this._next({ policy: { middlewares: input } });
262
336
  }
263
337
  /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
264
- async _runTask(task, index, policy, batchSignal) {
338
+ async _runTask(task, index, policy, batchSignal, timeline, debug) {
265
339
  let ctx = this._merge(VigorAllEachContextBase, { index });
340
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._merge(ctx, {}), debug);
266
341
  const timeoutController = new AbortController();
267
342
  const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
268
343
  let timeoutId;
269
344
  let onAbort;
345
+ add("TASK_STARTED", { index });
346
+ const started = performance.now();
347
+ const settle = (res) => {
348
+ add("TASK_ENDED", { index, success: res.success, took: performance.now() - started });
349
+ return res;
350
+ };
270
351
  try {
271
- for (const beforeEach of policy.middlewares.beforeEach) await beforeEach(ctx);
352
+ await stage("beforeEach", policy.middlewares.beforeEach, (beforeEach) => beforeEach(ctx));
272
353
  signal.throwIfAborted();
273
354
  const limit = policy.settings.timeout;
274
- if (!isVigorEmpty(limit)) {
355
+ if (!isVigorEmpty(limit) && Number.isFinite(limit) && limit > 0) {
275
356
  timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
276
357
  method: "request",
277
358
  data: { limit, index }
278
- })), limit);
359
+ })), Math.min(limit, MAX_TIMEOUT));
279
360
  }
280
361
  ctx.result = await Promise.race([
281
362
  task(signal),
@@ -284,17 +365,18 @@ var VigorAll = class _VigorAll extends VigorStatus {
284
365
  signal.addEventListener("abort", onAbort);
285
366
  })
286
367
  ]);
287
- for (const afterEach of policy.middlewares.afterEach) await afterEach(ctx);
288
- return { success: true, value: ctx.result };
368
+ await stage("afterEach", policy.middlewares.afterEach, (afterEach) => afterEach(ctx));
369
+ return settle({ success: true, value: ctx.result });
289
370
  } catch (error) {
290
371
  ctx.error = error;
372
+ add("TASK_ERROR", { index, error });
291
373
  const setResult = (r) => {
292
374
  ctx.flags.overridden = true;
293
375
  ctx.result = r;
294
376
  };
295
- for (const onErrorEach of policy.middlewares.onErrorEach) await onErrorEach(ctx, { setResult });
296
- if (ctx.flags.overridden) return { success: true, value: ctx.result };
297
- return { success: false, value: error };
377
+ await stage("onErrorEach", policy.middlewares.onErrorEach, (onErrorEach, trace) => onErrorEach(ctx, trace({ setResult })));
378
+ if (ctx.flags.overridden) return settle({ success: true, value: ctx.result });
379
+ return settle({ success: false, value: error });
298
380
  } finally {
299
381
  clearTimeout(timeoutId);
300
382
  if (onAbort) signal.removeEventListener("abort", onAbort);
@@ -312,43 +394,63 @@ var VigorAll = class _VigorAll extends VigorStatus {
312
394
  { cast: "replace" }
313
395
  );
314
396
  }
315
- /** Runs all tasks and returns the results array directly, throwing on final failure. */
397
+ /**
398
+ * Runs all tasks and returns the results array directly, throwing on final failure.
399
+ *
400
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
401
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
402
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
403
+ */
316
404
  async request() {
317
405
  const res = await this.requestVerbose();
318
406
  if (res.success) return res.data;
319
407
  throw res.error;
320
408
  }
321
- /** Runs all tasks and returns a result/error envelope instead of throwing. */
409
+ /**
410
+ * Runs all tasks and returns a result/error envelope instead of throwing,
411
+ * along with the `timeline` of everything the batch went through.
412
+ */
322
413
  async requestVerbose() {
323
414
  return await this.requestRuntime();
324
415
  }
325
416
  /** Internal execution loop implementing the bounded-concurrency worker pool and the batch-level before/after/onResult pipeline. */
326
- async requestRuntime() {
417
+ async requestRuntime(timeline = []) {
327
418
  const config = this._merge(this.config, {});
328
419
  const policy = config.policy;
329
420
  let ctx = this._merge(VigorAllContextBase, {
330
421
  policy
331
422
  }, void 0, "replace");
423
+ ctx.timeline = timeline;
424
+ const startedAt = performance.now();
425
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
426
+ const end = (success, error) => add("REQUEST_END", {
427
+ success,
428
+ outcome: success ? "result" : "failed",
429
+ error,
430
+ took: performance.now() - startedAt,
431
+ restarts: 0
432
+ });
332
433
  const setResult = (r) => {
333
434
  ctx.result = r;
334
435
  };
335
436
  const throwError = (err) => {
336
437
  throw err;
337
438
  };
439
+ const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
440
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { tasks: policy.target.length, concurrency } });
338
441
  try {
339
442
  if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
340
443
  method: "request",
341
444
  data: {},
342
445
  context: ctx
343
446
  });
344
- for (const mw of policy.middlewares.before) {
447
+ await stage("before", policy.middlewares.before, async (mw, trace) => {
345
448
  if (mw._mode === "fluent") {
346
449
  await mw.func(ctx);
347
450
  } else {
348
- ctx = await mw.func(ctx, { throwError }) ?? ctx;
451
+ ctx = await mw.func(ctx, trace({ throwError })) ?? ctx;
349
452
  }
350
- }
351
- const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
453
+ });
352
454
  const results = new Array(policy.target.length);
353
455
  const batchController = new AbortController();
354
456
  const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
@@ -358,7 +460,7 @@ var VigorAll = class _VigorAll extends VigorStatus {
358
460
  const i = cursor++;
359
461
  if (i >= policy.target.length) return;
360
462
  try {
361
- results[i] = await this._runTask(policy.target[i], i, policy, batchSignal);
463
+ results[i] = await this._runTask(policy.target[i], i, policy, batchSignal, timeline, policy.settings.debug);
362
464
  } catch (error) {
363
465
  batchController.abort(error);
364
466
  return;
@@ -372,31 +474,36 @@ var VigorAll = class _VigorAll extends VigorStatus {
372
474
  Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
373
475
  );
374
476
  batchSignal.throwIfAborted();
375
- ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
376
- for (const mw of policy.middlewares.after) {
477
+ 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 });
478
+ await stage("after", policy.middlewares.after, async (mw, trace) => {
377
479
  if (mw._mode === "fluent") {
378
480
  await mw.func(ctx);
379
481
  } else {
380
- ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
482
+ ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
381
483
  }
382
- }
383
- for (const mw of policy.middlewares.onResult) {
484
+ });
485
+ await stage("onResult", policy.middlewares.onResult, async (mw, trace) => {
384
486
  if (mw._mode === "fluent") {
385
487
  ctx.result = await mw.func(ctx.result);
386
488
  } else {
387
- ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
489
+ ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
388
490
  }
389
- }
491
+ });
492
+ end(true, null);
390
493
  return {
391
494
  success: true,
392
495
  data: ctx.result,
393
- error: null
496
+ error: null,
497
+ timeline
394
498
  };
395
499
  } catch (error) {
500
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
501
+ end(false, error);
396
502
  return {
397
503
  success: false,
398
504
  data: null,
399
- error
505
+ error,
506
+ timeline
400
507
  };
401
508
  }
402
509
  }
@@ -405,9 +512,46 @@ var VigorAll = class _VigorAll extends VigorStatus {
405
512
  // src/fetch/settings.ts
406
513
  var VigorFetchPolicySettingsBase = {
407
514
  __brand: createBrand("Fetch", "Policy<Settings<Schema"),
515
+ debug: false,
408
516
  retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
409
- unretryStatus: [400, 401, 403, 404, 405, 413, 422],
410
- redirect: true,
517
+ // Statuses a retry of the same request won't change. Left retryable on
518
+ // purpose: 408 (timeout), 421 (misdirected — another connection may
519
+ // work), 423 (locked), 425 (too early), 429 (rate limit), and 5xx
520
+ // outages (500, 502, 503, 504, 507).
521
+ unretryStatus: [
522
+ 400,
523
+ 401,
524
+ 402,
525
+ 403,
526
+ 404,
527
+ 405,
528
+ 406,
529
+ 407,
530
+ 409,
531
+ 410,
532
+ 411,
533
+ 412,
534
+ 413,
535
+ 414,
536
+ 415,
537
+ 416,
538
+ 417,
539
+ 422,
540
+ 424,
541
+ 426,
542
+ 428,
543
+ 431,
544
+ 451,
545
+ 501,
546
+ 505,
547
+ 506,
548
+ 508,
549
+ 510,
550
+ 511
551
+ ],
552
+ maxRetryAfter: 5 * 60 * 1e3,
553
+ redirect: false,
554
+ confinePath: true,
411
555
  maxRestarts: 3,
412
556
  default: VigorEmpty
413
557
  };
@@ -426,11 +570,24 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
426
570
  unretryStatus(...nums) {
427
571
  return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
428
572
  }
573
+ /** Sets the upper bound, in milliseconds, on a server-suggested retry delay. */
574
+ maxRetryAfter(num) {
575
+ return this._next({ policy: { settings: { maxRetryAfter: num } } });
576
+ }
577
+ /**
578
+ * When enabled, a redirected response (or a readable `3xx` with a
579
+ * `Location` header) navigates the page to its target
580
+ * (`window.location.href`). Without `window.location` — e.g. in Node —
581
+ * this behaves like `false`.
582
+ */
429
583
  /**
430
- * When enabled, a `3xx` response with a `Location` header navigates the
431
- * page to that URL (`window.location.href`). Without `window.location`
432
- * — e.g. in Node — this behaves like `false`.
584
+ * When enabled (the default), a request whose URL would leave its
585
+ * origin's domain or path (e.g. through a `".."` path segment) fails with
586
+ * `PATH_ESCAPED` instead of being sent.
433
587
  */
588
+ confinePath(bool) {
589
+ return this._next({ policy: { settings: { confinePath: bool } } });
590
+ }
434
591
  redirect(bool) {
435
592
  return this._next({ policy: { settings: { redirect: bool } } });
436
593
  }
@@ -442,6 +599,15 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
442
599
  default(func) {
443
600
  return this._next({ policy: { settings: { default: func } } });
444
601
  }
602
+ /**
603
+ * Turns timeline recording on or off (off by default). Off, the
604
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
605
+ * are taken, so it costs nothing unless you're debugging. With it on,
606
+ * the nested retry/parse engines record theirs too.
607
+ */
608
+ debug(bool) {
609
+ return this._next({ policy: { settings: { debug: bool } } });
610
+ }
445
611
  };
446
612
 
447
613
  // src/fetch/middlewares.ts
@@ -476,6 +642,7 @@ var VigorFetchPolicyMiddlewares = class _VigorFetchPolicyMiddlewares extends Vig
476
642
  // src/retry/settings.ts
477
643
  var VigorRetryPolicySettingsBase = {
478
644
  __brand: createBrand("Retry", "Policy<Settings<Schema"),
645
+ debug: false,
479
646
  default: VigorEmpty,
480
647
  maxAttempts: 5,
481
648
  maxRestarts: 3,
@@ -512,6 +679,14 @@ var VigorRetryPolicySettings = class _VigorRetryPolicySettings extends VigorStat
512
679
  policy: { settings: { timeout: num } }
513
680
  });
514
681
  }
682
+ /**
683
+ * Turns timeline recording on or off (off by default). Off, the
684
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
685
+ * are taken, so it costs nothing unless you're debugging.
686
+ */
687
+ debug(bool) {
688
+ return this._next({ policy: { settings: { debug: bool } } });
689
+ }
515
690
  };
516
691
 
517
692
  // src/retry/middlewares.ts
@@ -580,7 +755,9 @@ var VigorRetryError = class extends VigorError {
580
755
  super(code, messageFn(options.data), options);
581
756
  }
582
757
  };
583
- var isVigorRetryError = (error) => error instanceof VigorRetryError;
758
+ function isVigorRetryError(error, ...codes) {
759
+ return error instanceof VigorRetryError && (codes.length === 0 || codes.includes(error.code));
760
+ }
584
761
 
585
762
  // src/retry/algorithms.ts
586
763
  function VigorJitter(jitter) {
@@ -826,14 +1003,17 @@ var VigorRetryContextBase = {
826
1003
  doRetry: true,
827
1004
  doRestart: false,
828
1005
  brokeRetry: false,
1006
+ aborted: false,
1007
+ timedOut: false,
829
1008
  overridden: false
830
1009
  },
831
1010
  record: {},
1011
+ timeline: [],
832
1012
  policy: VigorRetryPolicyBase
833
1013
  };
834
1014
 
835
1015
  // src/retry/main.ts
836
- var MAX_TIMEOUT = 2 ** 31 - 1;
1016
+ var MAX_TIMEOUT2 = 2 ** 31 - 1;
837
1017
  var VigorRetryBase = {
838
1018
  __brand: createBrand("Retry", "Schema"),
839
1019
  policy: VigorRetryPolicyBase,
@@ -860,7 +1040,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
860
1040
  }
861
1041
  settings(input) {
862
1042
  if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
863
- const result = typeof input === "function" ? input(new VigorRetryPolicySettings()) : input;
1043
+ const result = typeof input === "function" ? input(new VigorRetryPolicySettings(this.config)) : input;
864
1044
  return this._next({
865
1045
  policy: { settings: result.config.policy.settings }
866
1046
  });
@@ -904,33 +1084,63 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
904
1084
  { cast: "replace" }
905
1085
  );
906
1086
  }
907
- /** Runs the target and returns its result directly, throwing on final failure. */
1087
+ /**
1088
+ * Runs the target and returns its result directly, throwing on final failure.
1089
+ *
1090
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1091
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
1092
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1093
+ */
908
1094
  async request() {
909
1095
  const res = await this.requestVerbose();
910
1096
  if (res.success) return res.data;
911
1097
  throw res.error;
912
1098
  }
913
- /** Runs the target and returns a result/error envelope instead of throwing. */
1099
+ /**
1100
+ * Runs the target and returns a result/error envelope instead of throwing,
1101
+ * along with the `timeline` of everything the run went through.
1102
+ */
914
1103
  async requestVerbose() {
915
- try {
916
- return await this.requestRuntime();
917
- } catch (error) {
918
- return { success: false, data: null, error };
919
- }
1104
+ return await this.requestRuntime();
920
1105
  }
921
- /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
922
- async requestRuntime(restartAttempt = 1) {
1106
+ /**
1107
+ * Internal execution loop implementing the attempt/retry/restart lifecycle.
1108
+ * Never throws: every failure, including one from `onError` or `default`,
1109
+ * comes back as an envelope carrying the timeline. A restart passes the
1110
+ * same `timeline` on, so it keeps growing across runs; `startedAt` is the
1111
+ * first run's start, for `REQUEST_END`'s `took`.
1112
+ */
1113
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
923
1114
  const config = this._merge(this.config, {});
924
1115
  let ctx = this._merge(VigorRetryContextBase, {
925
1116
  policy: config.policy
926
1117
  }, void 0, "replace");
927
- if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
1118
+ ctx.timeline = timeline;
1119
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1120
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1121
+ const end = (success, outcome, error) => add("REQUEST_END", {
1122
+ success,
1123
+ outcome,
1124
+ error,
1125
+ took: performance.now() - startedAt,
1126
+ restarts: restartAttempt - 1
1127
+ });
1128
+ const succeed = (data, outcome) => {
1129
+ end(true, outcome, null);
1130
+ return { success: true, data, error: null, timeline };
1131
+ };
1132
+ const fail = (error) => {
1133
+ end(false, "failed", error);
1134
+ return { success: false, data: null, error, timeline };
1135
+ };
1136
+ const decide = (retry, reason) => add("RETRY_DECISION", { attempt: ctx.system.attempt, retry, reason });
1137
+ if (isVigorEmpty(ctx.policy.target)) return fail(new VigorRetryError("VALUE_REQUIRED", {
928
1138
  method: "request",
929
1139
  data: {
930
1140
  key: "target"
931
1141
  },
932
1142
  context: ctx
933
- });
1143
+ }));
934
1144
  const target = ctx.policy.target;
935
1145
  const throwError = (err) => {
936
1146
  throw err;
@@ -939,6 +1149,9 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
939
1149
  try {
940
1150
  while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
941
1151
  ctx.system.attempt++;
1152
+ add("ATTEMPT_INCREASED", { attempt: ctx.system.attempt });
1153
+ add("PROCESS_HANDLING", { type: "RETRY_START", data: { attempt: ctx.system.attempt } });
1154
+ ctx.flags.timedOut = false;
942
1155
  try {
943
1156
  const breakRetry = (err) => {
944
1157
  ctx.flags.brokeRetry = true;
@@ -957,28 +1170,34 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
957
1170
  let onAbort;
958
1171
  let timeoutId;
959
1172
  try {
960
- for (const middleware of ctx.policy.middlewares.before) {
1173
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
961
1174
  if (middleware._mode === "fluent") {
962
1175
  await middleware.func(ctx);
963
1176
  } else {
964
- ctx = await middleware.func(ctx, {
1177
+ ctx = await middleware.func(ctx, trace({
965
1178
  abort: (reason) => userController.abort(reason),
966
1179
  throwError,
967
1180
  breakRetry
968
- }) ?? ctx;
1181
+ })) ?? ctx;
969
1182
  }
970
- }
1183
+ });
971
1184
  mergedSignals.throwIfAborted();
972
1185
  const limit = ctx.policy.settings.timeout;
973
1186
  if (Number.isFinite(limit) && limit > 0) {
974
- timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
975
- method: "request",
976
- data: {
977
- limit
978
- },
979
- context: ctx
980
- })), Math.min(limit, MAX_TIMEOUT));
1187
+ timeoutId = setTimeout(() => {
1188
+ ctx.flags.timedOut = true;
1189
+ timeoutController.abort(new VigorRetryError("TIMED_OUT", {
1190
+ method: "request",
1191
+ data: {
1192
+ limit
1193
+ },
1194
+ context: ctx
1195
+ }));
1196
+ }, Math.min(limit, MAX_TIMEOUT2));
981
1197
  }
1198
+ const attempt = ctx.system.attempt;
1199
+ add("TARGET_REQUEST_STARTED", { attempt });
1200
+ const started = performance.now();
982
1201
  ctx.result = await Promise.race([
983
1202
  target(mergedSignals),
984
1203
  new Promise((_, rej) => {
@@ -986,78 +1205,97 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
986
1205
  mergedSignals.addEventListener("abort", onAbort);
987
1206
  })
988
1207
  ]);
989
- for (const middleware of ctx.policy.middlewares.after) {
1208
+ add("TARGET_REQUEST_ENDED", { attempt, took: performance.now() - started });
1209
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
990
1210
  if (middleware._mode === "fluent") {
991
1211
  await middleware.func(ctx);
992
1212
  } else {
993
- ctx = await middleware.func(ctx, {
1213
+ ctx = await middleware.func(ctx, trace({
994
1214
  throwError
995
- }) ?? ctx;
1215
+ })) ?? ctx;
996
1216
  }
997
- }
1217
+ });
998
1218
  const setResult = (res) => {
999
1219
  ctx.result = res;
1000
1220
  };
1001
- for (const middleware of ctx.policy.middlewares.onResult) {
1221
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1002
1222
  if (middleware._mode === "fluent") {
1003
1223
  ctx.result = await middleware.func(ctx.result);
1004
1224
  } else {
1005
- ctx = await middleware.func(ctx, {
1225
+ ctx = await middleware.func(ctx, trace({
1006
1226
  setResult,
1007
1227
  throwError
1008
- }) ?? ctx;
1228
+ })) ?? ctx;
1009
1229
  }
1010
- }
1011
- return {
1012
- success: true,
1013
- data: ctx.result,
1014
- error: null
1015
- };
1230
+ });
1231
+ return succeed(ctx.result, "result");
1016
1232
  } finally {
1017
1233
  clearTimeout(timeoutId);
1018
1234
  if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
1019
1235
  }
1020
1236
  } catch (error) {
1021
1237
  ctx.error = error;
1022
- if (outerSignals.aborted) ctx.flags.brokeRetry = true;
1023
- if (ctx.flags.brokeRetry) throw ctx.error;
1238
+ if (outerSignals.aborted) ctx.flags.aborted = true;
1239
+ add("PROCESS_HANDLING", { type: "RETRY_ERROR", data: {
1240
+ attempt: ctx.system.attempt,
1241
+ error,
1242
+ timedOut: ctx.flags.timedOut,
1243
+ aborted: ctx.flags.aborted
1244
+ } });
1245
+ if (ctx.flags.aborted) {
1246
+ decide(false, "aborted");
1247
+ throw ctx.error;
1248
+ }
1249
+ if (ctx.flags.brokeRetry) {
1250
+ decide(false, "breakRetry");
1251
+ throw ctx.error;
1252
+ }
1024
1253
  ctx.flags.doRetry = true;
1025
1254
  const proceedRetry = () => ctx.flags.doRetry = true;
1026
1255
  const cancelRetry = () => ctx.flags.doRetry = false;
1027
- for (const middleware of ctx.policy.middlewares.retryIf) {
1256
+ await stage("retryIf", ctx.policy.middlewares.retryIf, async (middleware, trace) => {
1028
1257
  if (middleware._mode === "fluent") {
1029
1258
  ctx.flags.doRetry = await middleware.func(ctx.error);
1030
1259
  } else {
1031
- ctx = await middleware.func(ctx, {
1260
+ ctx = await middleware.func(ctx, trace({
1032
1261
  proceedRetry,
1033
1262
  cancelRetry
1034
- }) ?? ctx;
1263
+ })) ?? ctx;
1035
1264
  }
1265
+ });
1266
+ if (!ctx.flags.doRetry) {
1267
+ decide(false, "cancelled");
1268
+ throw ctx.error;
1036
1269
  }
1037
- if (!ctx.flags.doRetry) throw ctx.error;
1270
+ if (ctx.system.attempt >= ctx.policy.settings.maxAttempts) {
1271
+ decide(false, "exhausted");
1272
+ break;
1273
+ }
1274
+ decide(true, "retry");
1038
1275
  ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
1039
1276
  const setDelay = (num) => {
1040
1277
  ctx.system.delay = num;
1041
1278
  };
1042
- for (const middleware of ctx.policy.middlewares.onRetry) {
1279
+ await stage("onRetry", ctx.policy.middlewares.onRetry, async (middleware, trace) => {
1043
1280
  if (middleware._mode === "fluent") {
1044
1281
  await middleware.func(ctx.error);
1045
1282
  } else {
1046
- ctx = await middleware.func(ctx, {
1283
+ ctx = await middleware.func(ctx, trace({
1047
1284
  throwError,
1048
1285
  setDelay
1049
- }) ?? ctx;
1286
+ })) ?? ctx;
1050
1287
  }
1051
- }
1052
- const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT);
1288
+ });
1289
+ const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT2);
1290
+ add("RETRY_DELAY", { attempt: ctx.system.attempt, delay });
1053
1291
  await new Promise((res, rej) => {
1054
1292
  if (outerSignals.aborted) {
1055
- ctx.flags.brokeRetry = true;
1293
+ ctx.flags.aborted = true;
1056
1294
  return rej(outerSignals.reason);
1057
1295
  }
1058
1296
  const onAbort = () => {
1059
1297
  clearTimeout(id);
1060
- ctx.flags.brokeRetry = true;
1298
+ ctx.flags.aborted = true;
1061
1299
  rej(outerSignals.reason);
1062
1300
  };
1063
1301
  const id = setTimeout(() => {
@@ -1079,6 +1317,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1079
1317
  });
1080
1318
  } catch (error) {
1081
1319
  ctx.error = error;
1320
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1082
1321
  ctx.flags.doRestart = false;
1083
1322
  ctx.flags.overridden = false;
1084
1323
  const setResult = (res) => {
@@ -1087,20 +1326,24 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1087
1326
  };
1088
1327
  const proceedRestart = () => ctx.flags.doRestart = true;
1089
1328
  const cancelRestart = () => ctx.flags.doRestart = false;
1090
- for (const middleware of ctx.policy.middlewares.onError) {
1091
- if (middleware._mode === "fluent") {
1092
- await middleware.func(ctx.error);
1093
- } else {
1094
- ctx = await middleware.func(ctx, {
1095
- setResult,
1096
- throwError,
1097
- proceedRestart,
1098
- cancelRestart
1099
- }) ?? ctx;
1100
- }
1329
+ try {
1330
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1331
+ if (middleware._mode === "fluent") {
1332
+ await middleware.func(ctx.error);
1333
+ } else {
1334
+ ctx = await middleware.func(ctx, trace({
1335
+ setResult,
1336
+ throwError,
1337
+ proceedRestart,
1338
+ cancelRestart
1339
+ })) ?? ctx;
1340
+ }
1341
+ });
1342
+ } catch (err) {
1343
+ return fail(err);
1101
1344
  }
1102
1345
  if (ctx.flags.doRestart) {
1103
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1346
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorRetryError("RESTART_EXHAUSTED", {
1104
1347
  method: "request",
1105
1348
  cause: ctx.error,
1106
1349
  data: {
@@ -1108,27 +1351,19 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1108
1351
  error: ctx.error
1109
1352
  },
1110
1353
  context: ctx
1111
- });
1112
- return await this.requestRuntime(restartAttempt + 1);
1354
+ }));
1355
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
1356
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
1113
1357
  }
1114
- if (ctx.flags.overridden) return {
1115
- success: true,
1116
- data: ctx.result,
1117
- error: null
1118
- };
1358
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
1119
1359
  if (!isVigorEmpty(ctx.policy.settings.default)) {
1120
- const data = await ctx.policy.settings.default(ctx);
1121
- return {
1122
- success: true,
1123
- data,
1124
- error: null
1125
- };
1360
+ try {
1361
+ return succeed(await ctx.policy.settings.default(ctx), "default");
1362
+ } catch (err) {
1363
+ return fail(err);
1364
+ }
1126
1365
  }
1127
- return {
1128
- success: false,
1129
- data: null,
1130
- error: ctx.error
1131
- };
1366
+ return fail(ctx.error);
1132
1367
  }
1133
1368
  }
1134
1369
  };
@@ -1136,6 +1371,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1136
1371
  // src/parse/settings.ts
1137
1372
  var VigorParsePolicySettingsBase = {
1138
1373
  __brand: createBrand("Parse", "Policy<Settings<Schema"),
1374
+ debug: false,
1139
1375
  raw: false,
1140
1376
  default: VigorEmpty,
1141
1377
  maxRestarts: 3
@@ -1165,6 +1401,14 @@ var VigorParsePolicySettings = class _VigorParsePolicySettings extends VigorStat
1165
1401
  policy: { settings: { maxRestarts: num } }
1166
1402
  });
1167
1403
  }
1404
+ /**
1405
+ * Turns timeline recording on or off (off by default). Off, the
1406
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
1407
+ * are taken, so it costs nothing unless you're debugging.
1408
+ */
1409
+ debug(bool) {
1410
+ return this._next({ policy: { settings: { debug: bool } } });
1411
+ }
1168
1412
  };
1169
1413
 
1170
1414
  // src/parse/middlewares.ts
@@ -1197,11 +1441,12 @@ var VigorParsePolicyMiddlewares = class _VigorParsePolicyMiddlewares extends Vig
1197
1441
  };
1198
1442
 
1199
1443
  // src/parse/error.ts
1444
+ var describeVigorParseFailure = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1200
1445
  var VigorParseErrorMessageFuncs = {
1201
1446
  VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1202
1447
  INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1203
1448
  PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1204
- PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1449
+ PARSER_ALL_FAILED: ({ tried, errors }) => `All parsers failed: ${tried.map((name, i) => `${name} (${describeVigorParseFailure(errors[i])})`).join(", ")}`,
1205
1450
  RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1206
1451
  };
1207
1452
  var VigorParseError = class extends VigorError {
@@ -1214,63 +1459,141 @@ var VigorParseError = class extends VigorError {
1214
1459
  super(code, messageFn(options.data), options);
1215
1460
  }
1216
1461
  };
1217
- var isVigorParseError = (error) => error instanceof VigorParseError;
1462
+ function isVigorParseError(error, ...codes) {
1463
+ return error instanceof VigorParseError && (codes.length === 0 || codes.includes(error.code));
1464
+ }
1218
1465
 
1219
1466
  // src/parse/strategies.ts
1220
1467
  var VigorParsePolicyStrategiesBase = {
1221
1468
  __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1222
1469
  funcs: []
1223
1470
  };
1224
- var parseJsonOrNull = async (res) => {
1225
- const text = await res.text();
1471
+ var bodyCache = /* @__PURE__ */ new WeakMap();
1472
+ async function readVigorParseBody(source) {
1473
+ let bytes = bodyCache.get(source);
1474
+ if (!bytes) {
1475
+ bytes = source.body === null ? Promise.resolve(new Uint8Array(0)) : source.arrayBuffer().then((buf) => new Uint8Array(buf));
1476
+ bodyCache.set(source, bytes);
1477
+ }
1478
+ return {
1479
+ bytes: await bytes,
1480
+ contentType: source.headers.get("content-type"),
1481
+ status: source instanceof Response ? source.status : null,
1482
+ headers: source.headers,
1483
+ source
1484
+ };
1485
+ }
1486
+ var utf8 = new TextDecoder("utf-8");
1487
+ var getCharset = (contentType) => /;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(contentType ?? "")?.[1] ?? "utf-8";
1488
+ var getMimeType = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
1489
+ var decodeText = (body, fatal = false) => {
1490
+ let decoder;
1491
+ try {
1492
+ decoder = new TextDecoder(getCharset(body.contentType), { fatal });
1493
+ } catch {
1494
+ decoder = new TextDecoder("utf-8", { fatal });
1495
+ }
1496
+ return decoder.decode(body.bytes);
1497
+ };
1498
+ var parseJson = (body) => JSON.parse(utf8.decode(body.bytes));
1499
+ var parseJsonOrNull = (body) => {
1500
+ const text = utf8.decode(body.bytes);
1226
1501
  return text.trim() === "" ? null : JSON.parse(text);
1227
1502
  };
1503
+ var hexValue = (b) => {
1504
+ if (b >= 48 && b <= 57) return b - 48;
1505
+ if (b >= 65 && b <= 70) return b - 65 + 10;
1506
+ if (b >= 97 && b <= 102) return b - 97 + 10;
1507
+ return -1;
1508
+ };
1509
+ var decodeFormComponent = (input) => {
1510
+ const out = new Uint8Array(input.length);
1511
+ let n = 0;
1512
+ for (let i = 0; i < input.length; i++) {
1513
+ const b = input[i];
1514
+ if (b === 43) {
1515
+ out[n++] = 32;
1516
+ continue;
1517
+ }
1518
+ if (b === 37 && i + 2 < input.length) {
1519
+ const hi = hexValue(input[i + 1]);
1520
+ const lo = hexValue(input[i + 2]);
1521
+ if (hi >= 0 && lo >= 0) {
1522
+ out[n++] = hi * 16 + lo;
1523
+ i += 2;
1524
+ continue;
1525
+ }
1526
+ }
1527
+ out[n++] = b;
1528
+ }
1529
+ return utf8.decode(out.subarray(0, n));
1530
+ };
1531
+ var parseUrlEncoded = (body) => {
1532
+ const form = new FormData();
1533
+ const { bytes } = body;
1534
+ let start = 0;
1535
+ for (let i = 0; i <= bytes.length; i++) {
1536
+ if (i < bytes.length && bytes[i] !== 38) continue;
1537
+ const pair = bytes.subarray(start, i);
1538
+ start = i + 1;
1539
+ if (pair.length === 0) continue;
1540
+ const eq = pair.indexOf(61);
1541
+ const name = eq === -1 ? pair : pair.subarray(0, eq);
1542
+ const value = eq === -1 ? new Uint8Array(0) : pair.subarray(eq + 1);
1543
+ form.append(decodeFormComponent(name), decodeFormComponent(value));
1544
+ }
1545
+ return form;
1546
+ };
1547
+ var parseMultipart = (body) => new Response(body.bytes, { headers: { "content-type": body.contentType ?? "" } }).formData();
1548
+ var parseFormData = (body) => {
1549
+ const mime = getMimeType(body.contentType);
1550
+ if (mime === "application/x-www-form-urlencoded") return parseUrlEncoded(body);
1551
+ if (mime === "multipart/form-data") return parseMultipart(body);
1552
+ throw new VigorParseError("INVALID_CONTENT_TYPE", {
1553
+ method: "parseFormData",
1554
+ data: { received: body.contentType }
1555
+ });
1556
+ };
1557
+ var toArrayBuffer = (body) => body.bytes.slice().buffer;
1558
+ var toBlob = (body) => new Blob([body.bytes], { type: body.contentType ?? "" });
1228
1559
  var NoBodyStatus = [204, 205, 304];
1229
1560
  var ContentTypeParsers = [
1230
1561
  { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
1231
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1232
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1233
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1234
- { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1235
- { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1236
- { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1237
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1238
- { header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() }
1562
+ { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (body) => decodeText(body) },
1563
+ { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: parseUrlEncoded },
1564
+ { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: toArrayBuffer },
1565
+ { header: "image/*", regExp: /^image\/.+/i, method: toBlob },
1566
+ { header: "audio/*", regExp: /^audio\/.+/i, method: toBlob },
1567
+ { header: "video/*", regExp: /^video\/.+/i, method: toBlob },
1568
+ { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: parseMultipart },
1569
+ { header: "text/*", regExp: /^text\/.+/i, method: (body) => decodeText(body) }
1239
1570
  ];
1240
1571
  var SniffMethods = [
1241
- { title: "json", method: (res) => res.json() },
1242
- { title: "formData", method: (res) => res.formData() },
1243
- { title: "text", method: (res) => res.text() },
1244
- { title: "blob", method: (res) => res.blob() }
1572
+ { title: "json", method: parseJson },
1573
+ { title: "formData", method: parseFormData },
1574
+ { title: "text", method: (body) => decodeText(body, true) },
1575
+ { title: "blob", method: toBlob }
1245
1576
  ];
1246
- var VigorParseContentTypeStrategy = async (response) => {
1247
- if (response.body === null || NoBodyStatus.includes(response.status)) return null;
1248
- const contentTypeHeader = response.headers.get("content-type");
1249
- if (!contentTypeHeader) {
1250
- const text = await response.text();
1251
- return text === "" ? null : text;
1252
- }
1253
- const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
1254
- if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
1255
- method: "VigorParseContentTypeStrategy",
1256
- data: {
1257
- expected: ContentTypeParsers.map((p) => p.header),
1258
- received: contentTypeHeader
1259
- }
1260
- });
1261
- return await toDo.method(response);
1577
+ var VigorParseContentTypeStrategy = async (body) => {
1578
+ if (body.bytes.length === 0 || body.status !== null && NoBodyStatus.includes(body.status)) return null;
1579
+ if (!body.contentType) return decodeText(body);
1580
+ const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(body.contentType));
1581
+ if (!toDo) return toBlob(body);
1582
+ return await toDo.method(body);
1262
1583
  };
1263
- var VigorParseSniffStrategy = async (response) => {
1264
- for (const [i, parser] of SniffMethods.entries()) {
1265
- const cloned = i === SniffMethods.length - 1 ? response : response.clone();
1584
+ var VigorParseSniffStrategy = async (body) => {
1585
+ const errors = [];
1586
+ for (const parser of SniffMethods) {
1266
1587
  try {
1267
- return await parser.method(cloned);
1268
- } catch {
1588
+ return await parser.method(body);
1589
+ } catch (error) {
1590
+ errors.push(error);
1269
1591
  }
1270
1592
  }
1271
1593
  throw new VigorParseError("PARSER_ALL_FAILED", {
1272
1594
  method: "VigorParseSniffStrategy",
1273
- data: { tried: SniffMethods.map((p) => p.title) }
1595
+ cause: errors.at(-1),
1596
+ data: { tried: SniffMethods.map((p) => p.title), errors }
1274
1597
  });
1275
1598
  };
1276
1599
  var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends VigorStatus {
@@ -1297,35 +1620,35 @@ var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends Vigor
1297
1620
  contentType(replace) {
1298
1621
  return this._set([VigorParseContentTypeStrategy], replace);
1299
1622
  }
1300
- /** Adds the sniffing (try-each-method) parsing strategy. */
1623
+ /** Adds the sniffing (try-each-format) parsing strategy. */
1301
1624
  sniff(replace) {
1302
1625
  return this._set([VigorParseSniffStrategy], replace);
1303
1626
  }
1304
- /** Adds a strategy that always parses the response as JSON. */
1627
+ /** Adds a strategy that always parses the body as JSON. */
1305
1628
  json(replace) {
1306
- return this._set([(res) => res.json()], replace);
1629
+ return this._set([parseJson], replace);
1307
1630
  }
1308
- /** Adds a strategy that always parses the response as text. */
1631
+ /** Adds a strategy that always parses the body as text, in its declared `charset`. */
1309
1632
  text(replace) {
1310
- return this._set([(res) => res.text()], replace);
1633
+ return this._set([(body) => decodeText(body)], replace);
1311
1634
  }
1312
- /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1635
+ /** Adds a strategy that always parses the body as an `ArrayBuffer`. */
1313
1636
  arrayBuffer(replace) {
1314
- return this._set([(res) => res.arrayBuffer()], replace);
1637
+ return this._set([toArrayBuffer], replace);
1315
1638
  }
1316
- /** Adds a strategy that always parses the response as a `Blob`. */
1639
+ /** Adds a strategy that always parses the body as a `Blob`. */
1317
1640
  blob(replace) {
1318
- return this._set([(res) => res.blob()], replace);
1641
+ return this._set([toBlob], replace);
1319
1642
  }
1320
- /** Adds a strategy that always parses the response as a `Uint8Array`. */
1643
+ /** Adds a strategy that always parses the body as a `Uint8Array`. */
1321
1644
  bytes(replace) {
1322
- return this._set([(res) => res.arrayBuffer().then((b) => new Uint8Array(b))], replace);
1645
+ return this._set([(body) => body.bytes.slice()], replace);
1323
1646
  }
1324
- /** Adds a strategy that always parses the response as `FormData`. */
1647
+ /** Adds a strategy that always parses the body as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`). */
1325
1648
  formData(replace) {
1326
- return this._set([(res) => res.formData()], replace);
1649
+ return this._set([parseFormData], replace);
1327
1650
  }
1328
- /** Adds a user-supplied custom parsing strategy. */
1651
+ /** Adds a user-supplied custom parsing strategy. It receives the body already read into bytes. */
1329
1652
  custom(func, replace) {
1330
1653
  return this._set([func], replace);
1331
1654
  }
@@ -1351,6 +1674,7 @@ var VigorParseContextBase = {
1351
1674
  restarted: false
1352
1675
  },
1353
1676
  record: {},
1677
+ timeline: [],
1354
1678
  policy: VigorParsePolicyBase
1355
1679
  };
1356
1680
 
@@ -1373,7 +1697,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1373
1697
  }
1374
1698
  settings(input) {
1375
1699
  if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
1376
- const result = typeof input === "function" ? input(new VigorParsePolicySettings()) : input;
1700
+ const result = typeof input === "function" ? input(new VigorParsePolicySettings(this.config)) : input;
1377
1701
  return this._next({
1378
1702
  policy: { settings: result.config.policy.settings }
1379
1703
  });
@@ -1410,88 +1734,121 @@ var VigorParse = class _VigorParse extends VigorStatus {
1410
1734
  { cast: "replace" }
1411
1735
  );
1412
1736
  }
1413
- /** Runs parsing and returns the result directly, throwing on final failure. */
1737
+ /**
1738
+ * Runs parsing and returns the result directly, throwing on final failure.
1739
+ *
1740
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1741
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
1742
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1743
+ */
1414
1744
  async request() {
1415
1745
  const res = await this.requestVerbose();
1416
1746
  if (res.success) return res.data;
1417
1747
  throw res.error;
1418
1748
  }
1419
- /** Runs parsing and returns a result/error envelope instead of throwing. */
1749
+ /**
1750
+ * Runs parsing and returns a result/error envelope instead of throwing,
1751
+ * along with the `timeline` of everything the run went through.
1752
+ */
1420
1753
  async requestVerbose() {
1421
- try {
1422
- return await this.requestRuntime();
1423
- } catch (error) {
1424
- return { success: false, data: null, error };
1425
- }
1754
+ return await this.requestRuntime();
1426
1755
  }
1427
- /** Internal execution loop implementing the strategy fallback and restart handling. */
1428
- async requestRuntime(restartAttempt = 1) {
1756
+ /**
1757
+ * Internal execution loop implementing the strategy fallback and restart
1758
+ * handling. Never throws: every failure, including one from `onError` or
1759
+ * `default`, comes back as an envelope carrying the timeline. A restart
1760
+ * passes the same `timeline` on, so it keeps growing across runs.
1761
+ */
1762
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1429
1763
  const config = this._merge(this.config, {});
1430
1764
  let ctx = this._merge(VigorParseContextBase, {
1431
1765
  policy: config.policy
1432
1766
  }, void 0, "replace");
1433
- if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1767
+ ctx.timeline = timeline;
1768
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1769
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1770
+ const end = (success, outcome, error) => add("REQUEST_END", {
1771
+ success,
1772
+ outcome,
1773
+ error,
1774
+ took: performance.now() - startedAt,
1775
+ restarts: restartAttempt - 1
1776
+ });
1777
+ const succeed = (data, outcome) => {
1778
+ end(true, outcome, null);
1779
+ return { success: true, data, error: null, timeline };
1780
+ };
1781
+ const fail = (error) => {
1782
+ end(false, "failed", error);
1783
+ return { success: false, data: null, error, timeline };
1784
+ };
1785
+ if (isVigorDefault(ctx.policy.target)) return fail(new VigorParseError("VALUE_REQUIRED", {
1434
1786
  method: "request",
1435
1787
  data: { key: "target" },
1436
1788
  context: ctx
1437
- });
1789
+ }));
1438
1790
  ctx.response = ctx.policy.target;
1439
1791
  const throwError = (err) => {
1440
1792
  throw err;
1441
1793
  };
1442
1794
  try {
1443
- for (const middleware of ctx.policy.middlewares.before) {
1795
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1444
1796
  if (middleware._mode === "fluent") {
1445
1797
  await middleware.func(ctx);
1446
1798
  } else {
1447
- ctx = await middleware.func(ctx, { throwError }) ?? ctx;
1799
+ ctx = await middleware.func(ctx, trace({ throwError })) ?? ctx;
1448
1800
  }
1449
- }
1801
+ });
1450
1802
  if (ctx.policy.settings.raw) {
1451
1803
  ctx.result = ctx.response;
1452
1804
  } else {
1453
- const response = ctx.response;
1805
+ const readStarted = performance.now();
1806
+ const body = await readVigorParseBody(ctx.response);
1807
+ add("BODY_READ", { size: body.bytes.byteLength, took: performance.now() - readStarted });
1454
1808
  const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
1455
1809
  let parsed = false;
1456
- for (const [i, func] of funcs.entries()) {
1457
- const cloned = i === funcs.length - 1 ? response : response.clone();
1810
+ const errors = [];
1811
+ for (const [index, func] of funcs.entries()) {
1812
+ add("STRATEGY_STARTED", { index });
1813
+ const started = performance.now();
1458
1814
  try {
1459
- ctx.result = await func(cloned);
1815
+ ctx.result = await func(body);
1816
+ add("STRATEGY_SUCCEEDED", { index, took: performance.now() - started });
1460
1817
  parsed = true;
1461
1818
  break;
1462
- } catch {
1819
+ } catch (error) {
1820
+ errors.push(error);
1821
+ add("STRATEGY_FAILED", { index, error, took: performance.now() - started });
1463
1822
  }
1464
1823
  }
1465
1824
  if (!parsed) throw new VigorParseError("PARSER_ALL_FAILED", {
1466
1825
  method: "request",
1467
- data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1826
+ cause: errors.at(-1),
1827
+ data: { tried: funcs.map((_, i) => `strategy#${i}`), errors },
1468
1828
  context: ctx
1469
1829
  });
1470
1830
  }
1471
1831
  const setResult = (res) => {
1472
1832
  ctx.result = res;
1473
1833
  };
1474
- for (const middleware of ctx.policy.middlewares.after) {
1834
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1475
1835
  if (middleware._mode === "fluent") {
1476
1836
  await middleware.func(ctx);
1477
1837
  } else {
1478
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1838
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1479
1839
  }
1480
- }
1481
- for (const middleware of ctx.policy.middlewares.onResult) {
1840
+ });
1841
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1482
1842
  if (middleware._mode === "fluent") {
1483
1843
  ctx.result = await middleware.func(ctx.result);
1484
1844
  } else {
1485
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1845
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1486
1846
  }
1487
- }
1488
- return {
1489
- success: true,
1490
- data: ctx.result,
1491
- error: null
1492
- };
1847
+ });
1848
+ return succeed(ctx.result, "result");
1493
1849
  } catch (error) {
1494
1850
  ctx.error = error;
1851
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1495
1852
  ctx.flags.overridden = false;
1496
1853
  ctx.flags.restarted = false;
1497
1854
  const setResult = (res) => {
@@ -1500,15 +1857,19 @@ var VigorParse = class _VigorParse extends VigorStatus {
1500
1857
  };
1501
1858
  const proceedRestart = () => ctx.flags.restarted = true;
1502
1859
  const cancelRestart = () => ctx.flags.restarted = false;
1503
- for (const middleware of ctx.policy.middlewares.onError) {
1504
- if (middleware._mode === "fluent") {
1505
- await middleware.func(ctx.error);
1506
- } else {
1507
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1508
- }
1860
+ try {
1861
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1862
+ if (middleware._mode === "fluent") {
1863
+ await middleware.func(ctx.error);
1864
+ } else {
1865
+ ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
1866
+ }
1867
+ });
1868
+ } catch (err) {
1869
+ return fail(err);
1509
1870
  }
1510
1871
  if (ctx.flags.restarted) {
1511
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1872
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorParseError("RESTART_EXHAUSTED", {
1512
1873
  method: "request",
1513
1874
  cause: ctx.error,
1514
1875
  data: {
@@ -1516,27 +1877,19 @@ var VigorParse = class _VigorParse extends VigorStatus {
1516
1877
  error: ctx.error
1517
1878
  },
1518
1879
  context: ctx
1519
- });
1520
- return await this.requestRuntime(restartAttempt + 1);
1880
+ }));
1881
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
1882
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
1521
1883
  }
1522
- if (ctx.flags.overridden) return {
1523
- success: true,
1524
- data: ctx.result,
1525
- error: null
1526
- };
1884
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
1527
1885
  if (!isVigorEmpty(ctx.policy.settings.default)) {
1528
- const data = await ctx.policy.settings.default(ctx);
1529
- return {
1530
- success: true,
1531
- data,
1532
- error: null
1533
- };
1886
+ try {
1887
+ return succeed(await ctx.policy.settings.default(ctx), "default");
1888
+ } catch (err) {
1889
+ return fail(err);
1890
+ }
1534
1891
  }
1535
- return {
1536
- success: false,
1537
- data: null,
1538
- error: ctx.error
1539
- };
1892
+ return fail(ctx.error);
1540
1893
  }
1541
1894
  }
1542
1895
  };
@@ -1571,16 +1924,21 @@ var VigorFetchContextBase = {
1571
1924
  restarted: false
1572
1925
  },
1573
1926
  record: {},
1927
+ timeline: [],
1574
1928
  policy: VigorFetchPolicyBase
1575
1929
  };
1576
1930
 
1577
1931
  // src/fetch/error.ts
1578
1932
  var VigorFetchErrorMessageFuncs = {
1933
+ ...VigorRetryErrorMessageFuncs,
1934
+ ...VigorParseErrorMessageFuncs,
1579
1935
  VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1580
1936
  INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1937
+ BODY_NOT_ALLOWED: ({ method }) => `A ${method} request cannot have a body`,
1581
1938
  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`,
1582
1939
  FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1583
1940
  RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1941
+ PATH_ESCAPED: ({ url, base }) => `Path escapes "${base}": the request would go to "${url}" (settings.confinePath)`,
1584
1942
  REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
1585
1943
  };
1586
1944
  var VigorFetchError = class extends VigorError {
@@ -1593,13 +1951,27 @@ var VigorFetchError = class extends VigorError {
1593
1951
  super(code, messageFn(options.data), options);
1594
1952
  }
1595
1953
  };
1596
- var isVigorFetchError = (error) => error instanceof VigorFetchError;
1954
+ function isVigorFetchError(error, ...codes) {
1955
+ return error instanceof VigorFetchError && (codes.length === 0 || codes.includes(error.code));
1956
+ }
1957
+ function adoptVigorFetchError(error, context) {
1958
+ if (!(error instanceof VigorRetryError) && !(error instanceof VigorParseError)) return error;
1959
+ const data = error.data;
1960
+ const adopted = data !== null && typeof data === "object" && "error" in data ? { ...data, error: adoptVigorFetchError(data.error, context) } : data;
1961
+ return new VigorFetchError(error.code, {
1962
+ method: error.method,
1963
+ cause: error,
1964
+ data: adopted,
1965
+ context
1966
+ });
1967
+ }
1597
1968
 
1598
1969
  // src/fetch/main.ts
1599
1970
  var VigorFetchBase = {
1600
1971
  __brand: createBrand("Fetch", "Schema"),
1601
1972
  policy: VigorFetchPolicyBase,
1602
- cast: VigorEmpty
1973
+ cast: VigorEmpty,
1974
+ apiMap: VigorEmpty
1603
1975
  };
1604
1976
  var VigorFetch = class _VigorFetch extends VigorStatus {
1605
1977
  constructor(config = VigorFetchBase) {
@@ -1628,43 +2000,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1628
2000
  hash(str) {
1629
2001
  return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } });
1630
2002
  }
1631
- /**
1632
- * Sets request headers.
1633
- *
1634
- * @param mode - `"overwrite"` discards all previously configured headers
1635
- * and keeps only the ones passed here. `"merge"` behaves like
1636
- * `Object.assign`, overwriting only the keys that overlap and keeping
1637
- * the rest.
1638
- */
1639
2003
  headers(mode, obj) {
1640
2004
  if (mode === "overwrite") return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1641
2005
  return this._next({ policy: { headers: obj } });
1642
2006
  }
1643
- /**
1644
- * Sets the request body.
1645
- *
1646
- * @param mode - `"overwrite"` discards the previous body and fully
1647
- * replaces it with this value. `"merge"` shallow-merges (via
1648
- * `Object.assign`) when both the previous and new body are plain
1649
- * objects; for any other body type (string/Blob/FormData/etc) it is
1650
- * simply replaced.
1651
- */
1652
2007
  body(mode, obj) {
1653
- if (mode === "overwrite") return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1654
- return this._next({ policy: { body: obj } });
2008
+ const prev = this.config.policy.body;
2009
+ const body = mode === "merge" && this._isPlainObject(prev) && this._isPlainObject(obj) ? { ...prev, ...obj } : obj;
2010
+ return this._next({ policy: { body } }, { policy: { body: "replace" } });
1655
2011
  }
1656
- /**
1657
- * Sets additional `RequestInit` options other than headers/body/method/signal
1658
- * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1659
- * `referrerPolicy`, `keepalive`, `integrity`).
1660
- *
1661
- * @param mode - `"overwrite"` discards all previously configured options
1662
- * and replaces them with this value. `"merge"` shallow-merges this
1663
- * value onto the previous options.
1664
- */
1665
2012
  options(mode, obj) {
1666
- if (mode === "overwrite") return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1667
- return this._next({ policy: { extra: obj } });
2013
+ const extra = mode === "merge" ? { ...this.config.policy.extra, ...obj } : obj;
2014
+ return this._next({ policy: { extra } }, { policy: { extra: "replace" } });
1668
2015
  }
1669
2016
  settings(input) {
1670
2017
  const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
@@ -1691,14 +2038,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1691
2038
  const result = typeof input === "function" ? input(new VigorRetry()) : input;
1692
2039
  return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1693
2040
  }
1694
- return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
2041
+ return this._next({ policy: { retry: this._merge(VigorRetryBase, input) } }, { policy: { retry: "replace" } });
1695
2042
  }
1696
2043
  parse(input) {
1697
2044
  if (typeof input === "function" || input instanceof VigorParse) {
1698
2045
  const result = typeof input === "function" ? input(new VigorParse()) : input;
1699
2046
  return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1700
2047
  }
1701
- return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
2048
+ return this._next({ policy: { parse: this._merge(VigorParseBase, input) } }, { policy: { parse: "replace" } });
2049
+ }
2050
+ /** Whether `v` is a plain object literal (not an array, `FormData`, `Blob`, ...). */
2051
+ _isPlainObject(v) {
2052
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
1702
2053
  }
1703
2054
  /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1704
2055
  _stringifyList(unkList) {
@@ -1720,9 +2071,11 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1720
2071
  * Builds the final request URL from the configured origin, path
1721
2072
  * segments, query parameters, and hash. An absolute `origin` ignores
1722
2073
  * the resolved base (per the `URL` spec); a relative `origin` is
1723
- * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
2074
+ * resolved against it. Throws `INVALID_PROTOCOL` (with `context`) if
2075
+ * neither is possible, and with `settings.confinePath` on, `PATH_ESCAPED`
2076
+ * if the result leaves the origin's domain or path.
1724
2077
  */
1725
- _buildUrl(origin, path, query, hash) {
2078
+ _buildUrl(origin, path, query, hash, context) {
1726
2079
  const base = this._resolveBase();
1727
2080
  let originObj;
1728
2081
  try {
@@ -1730,7 +2083,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1730
2083
  } catch {
1731
2084
  throw new VigorFetchError("INVALID_PROTOCOL", {
1732
2085
  method: "_buildUrl",
1733
- data: { origin, base }
2086
+ data: { origin, base },
2087
+ context
1734
2088
  });
1735
2089
  }
1736
2090
  const baseStr = originObj.origin;
@@ -1751,10 +2105,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1751
2105
  }
1752
2106
  }
1753
2107
  mainObj.hash = hash || originObj.hash;
2108
+ if (context.policy.settings.confinePath) {
2109
+ const basePath = "/" + originObj.pathname.replace(/^\/+|\/+$/g, "");
2110
+ const inside = basePath === "/" || mainObj.pathname === basePath || mainObj.pathname.startsWith(basePath + "/");
2111
+ if (mainObj.origin !== originObj.origin || !inside) throw new VigorFetchError("PATH_ESCAPED", {
2112
+ method: "_buildUrl",
2113
+ data: { url: mainObj.href, base: originObj.origin + (basePath === "/" ? "" : basePath) },
2114
+ context
2115
+ });
2116
+ }
1754
2117
  return mainObj.href;
1755
2118
  }
1756
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1757
- _normalizeBody(body) {
2119
+ /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. Throws `INVALID_BODY` (with `context`) for anything else. */
2120
+ _normalizeBody(body, context) {
1758
2121
  if (body == null) return { headers: {}, body };
1759
2122
  if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1760
2123
  if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
@@ -1765,15 +2128,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1765
2128
  if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1766
2129
  throw new VigorFetchError("INVALID_BODY", {
1767
2130
  method: "_normalizeBody",
1768
- data: { received: body }
2131
+ data: { received: body },
2132
+ context
1769
2133
  });
1770
2134
  }
1771
2135
  /**
1772
- * Returns the absolute URL a `3xx` response points at, or `null` when the
1773
- * response isn't a redirect or carries no usable `Location` header. A
1774
- * relative `Location` is resolved against the responding URL.
2136
+ * Returns the absolute URL a redirect points at, or `null` when the
2137
+ * response isn't a redirect. A response `fetch` already followed
2138
+ * (`redirect: "follow"`, the default) yields its final URL; a readable
2139
+ * `3xx` (`redirect: "manual"` outside browsers) yields its `Location`,
2140
+ * resolved against the responding URL.
1775
2141
  */
1776
2142
  _resolveRedirect(response, href) {
2143
+ if (response.redirected && response.url) return response.url;
1777
2144
  if (response.status < 300 || response.status >= 400) return null;
1778
2145
  const location = response.headers.get("location");
1779
2146
  if (!location) return null;
@@ -1825,32 +2192,137 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1825
2192
  * any other configuration method); whichever `.cast<T>()` call happens
1826
2193
  * last wins.
1827
2194
  */
2195
+ /**
2196
+ * Attaches a type-level API map: a request whose method and path match a
2197
+ * route resolves to that route's success `responses` (see `VigorApiRoute`
2198
+ * for `responses`/`params`/`query`/`body`). Keys are
2199
+ * `"<METHOD> /<path>"`, where a `:name` segment matches any one segment.
2200
+ * Routes are relative to the path set so far, so a base path can be set
2201
+ * first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. Purely a type —
2202
+ * nothing changes at runtime. `.cast<T>()` and a `raw` parse still win.
2203
+ *
2204
+ * @example
2205
+ * type Api = {
2206
+ * "GET /users": { response: User[] }
2207
+ * "GET /users/:id": { response: User }
2208
+ * }
2209
+ * const api = vigor.fetch("https://api.example.com").apiMap<Api>()
2210
+ * const user = await api.path("users", id).request() // User
2211
+ */
2212
+ apiMap() {
2213
+ return this._next(
2214
+ { apiMap: VigorCastPlaceholder },
2215
+ { apiMap: "replace" }
2216
+ );
2217
+ }
2218
+ route(key, ...params) {
2219
+ const route = key;
2220
+ const space = route.indexOf(" ");
2221
+ const method = route.slice(0, space);
2222
+ const values = params[0] ?? {};
2223
+ const segments = route.slice(space + 1).split("/").filter(Boolean).map((segment) => {
2224
+ if (!segment.startsWith(":")) return segment;
2225
+ const name = segment.slice(1);
2226
+ const value = values[name];
2227
+ if (value === null || value === void 0) throw new VigorFetchError("VALUE_REQUIRED", {
2228
+ method: "route",
2229
+ data: { key: `params.${name}` }
2230
+ });
2231
+ return value;
2232
+ });
2233
+ return this.method(method).path(...segments);
2234
+ }
1828
2235
  cast() {
1829
2236
  return this._next(
1830
2237
  { cast: VigorCastPlaceholder },
1831
2238
  { cast: "replace" }
1832
2239
  );
1833
2240
  }
1834
- /** Runs the request and returns its parsed result directly, throwing on final failure. */
2241
+ /**
2242
+ * Runs the request and returns its parsed result directly, throwing on final failure.
2243
+ *
2244
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
2245
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
2246
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
2247
+ *
2248
+ * With an API map, the request's `body`/`query` must match its route's
2249
+ * (see {@link VigorFetchRequestThis}), or the call doesn't compile.
2250
+ */
1835
2251
  async request() {
1836
- const res = await this.requestVerbose();
2252
+ const res = await this.requestRuntime();
1837
2253
  if (res.success) return res.data;
1838
2254
  throw res.error;
1839
2255
  }
1840
- /** Runs the request and returns a result/error envelope instead of throwing. */
2256
+ /**
2257
+ * Runs the request and returns a result/error envelope instead of throwing,
2258
+ * along with the `timeline` of everything the run went through. The
2259
+ * nested retry/parse engines' full timelines are kept inside it, on their
2260
+ * `RETRY_ENDED`/`PARSE_ENDED` entries.
2261
+ *
2262
+ * A success carries the `status` and `response` its result was parsed
2263
+ * from; with an API map, narrowing `status` narrows `data` (see
2264
+ * {@link VigorFetchVerboseResult}). Passing `R` types every success's
2265
+ * `data` as `R`, unchecked.
2266
+ */
1841
2267
  async requestVerbose() {
1842
- try {
1843
- return await this.requestRuntime();
1844
- } catch (error) {
1845
- return { success: false, data: null, error };
1846
- }
2268
+ return await this.requestRuntime();
1847
2269
  }
1848
- /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1849
- async requestRuntime(restartAttempt = 1) {
2270
+ /**
2271
+ * Internal execution loop implementing URL building, retry, parsing, and
2272
+ * restart handling. Never throws: every failure, including one from
2273
+ * `onError` or `default`, comes back as an envelope carrying the timeline.
2274
+ * A restart passes the same `timeline` on, so it keeps growing across runs.
2275
+ */
2276
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1850
2277
  const config = this._merge(this.config, {});
1851
2278
  let ctx = this._merge(VigorFetchContextBase, {
1852
2279
  policy: config.policy
1853
2280
  }, void 0, "replace");
2281
+ ctx.timeline = timeline;
2282
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
2283
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
2284
+ const end = (success, outcome, error) => add("REQUEST_END", {
2285
+ success,
2286
+ outcome,
2287
+ error,
2288
+ took: performance.now() - startedAt,
2289
+ restarts: restartAttempt - 1
2290
+ });
2291
+ const succeed = (data, outcome, response = null) => {
2292
+ end(true, outcome, null);
2293
+ return { success: true, data, error: null, status: response?.status ?? null, response, timeline };
2294
+ };
2295
+ const fail = (error) => {
2296
+ end(false, "failed", error);
2297
+ return { success: false, data: null, error, status: null, response: null, timeline };
2298
+ };
2299
+ let lastAttempt = 0;
2300
+ const runRetry = async (engine) => {
2301
+ add("RETRY_STARTED", { engine });
2302
+ const started = performance.now();
2303
+ const res = await engine.requestVerbose();
2304
+ add("RETRY_ENDED", {
2305
+ engine,
2306
+ timeline: res.timeline,
2307
+ took: performance.now() - started,
2308
+ response: res.success ? res.data : VigorDefault
2309
+ });
2310
+ return res;
2311
+ };
2312
+ const runParse = async (source, attempt, engine) => {
2313
+ add("PARSE_STARTED", { engine, source, attempt });
2314
+ const started = performance.now();
2315
+ const res = await engine.requestVerbose();
2316
+ add("PARSE_ENDED", {
2317
+ engine,
2318
+ source,
2319
+ attempt,
2320
+ timeline: res.timeline,
2321
+ took: performance.now() - started,
2322
+ result: res.success ? res.data : VigorDefault
2323
+ });
2324
+ return res;
2325
+ };
1854
2326
  const throwError = (err) => {
1855
2327
  throw err;
1856
2328
  };
@@ -1860,7 +2332,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1860
2332
  data: { key: "origin" },
1861
2333
  context: ctx
1862
2334
  });
1863
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
2335
+ ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash, ctx);
2336
+ add("BUILT_URL", { url: ctx.href });
1864
2337
  const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
1865
2338
  const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
1866
2339
  const options = {
@@ -1869,17 +2342,17 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1869
2342
  headers: {}
1870
2343
  };
1871
2344
  if (hasBody) {
1872
- const normalized = this._normalizeBody(ctx.policy.body);
2345
+ const normalized = this._normalizeBody(ctx.policy.body, ctx);
1873
2346
  if (normalized.body !== void 0) options.body = normalized.body;
1874
2347
  Object.assign(options.headers, normalized.headers);
1875
2348
  }
1876
2349
  this._assignHeaders(options.headers, ctx.policy.headers);
1877
2350
  ctx.options = options;
1878
- for (const middleware of ctx.policy.middlewares.before) {
2351
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1879
2352
  if (middleware._mode === "fluent") {
1880
2353
  await middleware.func(ctx);
1881
2354
  } else {
1882
- ctx = await middleware.func(ctx, {
2355
+ ctx = await middleware.func(ctx, trace({
1883
2356
  throwError,
1884
2357
  setOptions: (o) => {
1885
2358
  ctx.options = o;
@@ -1890,19 +2363,38 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1890
2363
  setBody: (b) => {
1891
2364
  ctx.options.body = b;
1892
2365
  }
1893
- }) ?? ctx;
2366
+ })) ?? ctx;
1894
2367
  }
1895
- }
2368
+ });
1896
2369
  const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
1897
2370
  ctx.options = finalOptions;
1898
- if (typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream) {
2371
+ add("SET_OPTIONS", { options: finalOptions });
2372
+ const finalMethod = (finalOptions.method ?? "GET").toUpperCase();
2373
+ if (finalOptions.body != null && (finalMethod === "GET" || finalMethod === "HEAD")) throw new VigorFetchError("BODY_NOT_ALLOWED", {
2374
+ method: "request",
2375
+ data: { method: finalMethod },
2376
+ context: ctx
2377
+ });
2378
+ const isStreamBody = typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream;
2379
+ if (isStreamBody) {
1899
2380
  finalOptions.duplex ??= "half";
1900
2381
  }
1901
- const retryEngine = new VigorRetry(ctx.policy.retry).target(async (signal) => {
2382
+ const nestedDebug = { policy: { settings: { debug: true } } };
2383
+ const parseEngine = new VigorParse(config.policy.settings.debug ? this._merge(ctx.policy.parse, nestedDebug) : ctx.policy.parse);
2384
+ const retryEngine = new VigorRetry(config.policy.settings.debug ? this._merge(ctx.policy.retry, nestedDebug) : ctx.policy.retry).target(async (signal) => {
1902
2385
  return await fetch(ctx.href, { ...finalOptions, signal });
1903
2386
  }).middlewares(
1904
2387
  (m) => m.after("intercept", async (rctx, api) => {
1905
2388
  const response = rctx.result;
2389
+ lastAttempt = rctx.system.attempt;
2390
+ add("RESPONSE_RECEIVED", {
2391
+ attempt: rctx.system.attempt,
2392
+ status: response.status,
2393
+ statusText: response.statusText,
2394
+ ok: response.ok,
2395
+ redirected: response.redirected,
2396
+ url: response.url
2397
+ });
1906
2398
  if (ctx.policy.settings.redirect) {
1907
2399
  const target = this._resolveRedirect(response, ctx.href);
1908
2400
  const location = this._browserLocation();
@@ -1915,12 +2407,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1915
2407
  }));
1916
2408
  }
1917
2409
  }
1918
- if (!response.ok) {
1919
- let parsed = void 0;
1920
- try {
1921
- parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
1922
- } catch {
1923
- }
2410
+ if (!response.ok && response.status !== 304) {
2411
+ const parseRes2 = await runParse("failedResponse", rctx.system.attempt, parseEngine.target(response.clone()));
2412
+ const parsed = parseRes2.success ? parseRes2.data : void 0;
1924
2413
  api.throwError(new VigorFetchError("FETCH_FAILED", {
1925
2414
  method: "request",
1926
2415
  data: {
@@ -1929,13 +2418,17 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1929
2418
  response,
1930
2419
  url: response.url,
1931
2420
  parsed
1932
- }
2421
+ },
2422
+ context: ctx
1933
2423
  }));
1934
2424
  }
2425
+ if (!ctx.policy.parse.policy.settings.raw) await readVigorParseBody(response);
1935
2426
  return rctx;
1936
2427
  }).retryIf("intercept", async (rctx, api) => {
1937
2428
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1938
2429
  if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
2430
+ else if (isStreamBody) api.cancelRetry();
2431
+ else if (response && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) api.cancelRetry();
1939
2432
  else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1940
2433
  return rctx;
1941
2434
  }).onRetry("intercept", async (rctx, api) => {
@@ -1944,7 +2437,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1944
2437
  for (const header of ctx.policy.settings.retryHeaders) {
1945
2438
  const delay = this._parseRetryHeader(response.headers.get(header));
1946
2439
  if (delay !== null) {
1947
- api.setDelay(delay);
2440
+ api.setDelay(Math.min(delay, ctx.policy.settings.maxRetryAfter));
1948
2441
  break;
1949
2442
  }
1950
2443
  }
@@ -1952,35 +2445,40 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1952
2445
  return rctx;
1953
2446
  })
1954
2447
  );
1955
- ctx.response = await retryEngine.request();
1956
- const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
1957
- ctx.result = await parseEngine.request();
1958
- for (const middleware of ctx.policy.middlewares.after) {
2448
+ for (const name of ["after", "retryIf", "onRetry"]) {
2449
+ const list = retryEngine.config.policy.middlewares[name];
2450
+ markVigorInternal(list[list.length - 1].func);
2451
+ }
2452
+ add("ENGINE_CREATED", { retryEngine, parseEngine });
2453
+ const retryRes = await runRetry(retryEngine);
2454
+ if (!retryRes.success) throw adoptVigorFetchError(retryRes.error, ctx);
2455
+ ctx.response = retryRes.data;
2456
+ const parseRes = await runParse("response", lastAttempt, parseEngine.target(ctx.response));
2457
+ if (!parseRes.success) throw adoptVigorFetchError(parseRes.error, ctx);
2458
+ ctx.result = parseRes.data;
2459
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1959
2460
  if (middleware._mode === "fluent") {
1960
2461
  await middleware.func(ctx);
1961
2462
  } else {
1962
- ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
2463
+ ctx = await middleware.func(ctx, trace({ throwError, setResult: (r) => {
1963
2464
  ctx.result = r;
1964
- } }) ?? ctx;
2465
+ } })) ?? ctx;
1965
2466
  }
1966
- }
2467
+ });
1967
2468
  const setResult = (r) => {
1968
2469
  ctx.result = r;
1969
2470
  };
1970
- for (const middleware of ctx.policy.middlewares.onResult) {
2471
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1971
2472
  if (middleware._mode === "fluent") {
1972
2473
  ctx.result = await middleware.func(ctx.result);
1973
2474
  } else {
1974
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
2475
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1975
2476
  }
1976
- }
1977
- return {
1978
- success: true,
1979
- data: ctx.result,
1980
- error: null
1981
- };
2477
+ });
2478
+ return succeed(ctx.result, "result", ctx.response);
1982
2479
  } catch (error) {
1983
2480
  ctx.error = error;
2481
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1984
2482
  ctx.flags.overridden = false;
1985
2483
  ctx.flags.restarted = false;
1986
2484
  const setResult = (r) => {
@@ -1989,15 +2487,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1989
2487
  };
1990
2488
  const proceedRestart = () => ctx.flags.restarted = true;
1991
2489
  const cancelRestart = () => ctx.flags.restarted = false;
1992
- for (const middleware of ctx.policy.middlewares.onError) {
1993
- if (middleware._mode === "fluent") {
1994
- await middleware.func(ctx.error);
1995
- } else {
1996
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1997
- }
2490
+ try {
2491
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
2492
+ if (middleware._mode === "fluent") {
2493
+ await middleware.func(ctx.error);
2494
+ } else {
2495
+ ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
2496
+ }
2497
+ });
2498
+ } catch (err) {
2499
+ return fail(err);
1998
2500
  }
1999
2501
  if (ctx.flags.restarted) {
2000
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
2502
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorFetchError("RESTART_EXHAUSTED", {
2001
2503
  method: "request",
2002
2504
  cause: ctx.error,
2003
2505
  data: {
@@ -2005,27 +2507,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2005
2507
  error: ctx.error
2006
2508
  },
2007
2509
  context: ctx
2008
- });
2009
- return await this.requestRuntime(restartAttempt + 1);
2510
+ }));
2511
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
2512
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
2010
2513
  }
2011
- if (ctx.flags.overridden) return {
2012
- success: true,
2013
- data: ctx.result,
2014
- error: null
2015
- };
2514
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
2016
2515
  if (!isVigorEmpty(ctx.policy.settings.default)) {
2017
- const data = await ctx.policy.settings.default(ctx);
2018
- return {
2019
- success: true,
2020
- data,
2021
- error: null
2022
- };
2516
+ try {
2517
+ return succeed(await ctx.policy.settings.default(ctx), "default");
2518
+ } catch (err) {
2519
+ return fail(err);
2520
+ }
2023
2521
  }
2024
- return {
2025
- success: false,
2026
- data: null,
2027
- error
2028
- };
2522
+ return fail(error);
2029
2523
  }
2030
2524
  }
2031
2525
  };
@@ -2073,6 +2567,12 @@ var vigorBase = {
2073
2567
  settings: () => new VigorAllPolicySettings(),
2074
2568
  middlewares: () => new VigorAllPolicyMiddlewares()
2075
2569
  }
2570
+ },
2571
+ guards: {
2572
+ retry: isVigorRetryError,
2573
+ parse: isVigorParseError,
2574
+ fetch: isVigorFetchError,
2575
+ all: isVigorAllError
2076
2576
  }
2077
2577
  };
2078
2578
  var cloneVigor = (v) => ({
@@ -2082,13 +2582,14 @@ var cloneVigor = (v) => ({
2082
2582
  retry: { ...v.builders.retry, algorithm: { ...v.builders.retry.algorithm } },
2083
2583
  parse: { ...v.builders.parse },
2084
2584
  all: { ...v.builders.all }
2085
- }
2585
+ },
2586
+ guards: { ...v.guards }
2086
2587
  });
2087
2588
  var createVigor = (fields) => {
2088
2589
  const instance = {
2089
2590
  ...fields,
2090
2591
  use: (plugin, options) => {
2091
- const ext = plugin.func(instance, options);
2592
+ const ext = plugin.func(instance, { ...plugin.options, ...options });
2092
2593
  const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
2093
2594
  return createVigor(rest);
2094
2595
  }
@@ -2102,6 +2603,8 @@ var index_default = vigor;
2102
2603
  export {
2103
2604
  VigorAll,
2104
2605
  VigorAllBase,
2606
+ VigorAllContextBase,
2607
+ VigorAllEachContextBase,
2105
2608
  VigorAllError,
2106
2609
  VigorAllErrorMessageFuncs,
2107
2610
  VigorAllPolicyBase,
@@ -2109,9 +2612,13 @@ export {
2109
2612
  VigorAllPolicyMiddlewaresBase,
2110
2613
  VigorAllPolicySettings,
2111
2614
  VigorAllPolicySettingsBase,
2615
+ VigorCastPlaceholder,
2616
+ VigorDefault,
2617
+ VigorEmpty,
2112
2618
  VigorError,
2113
2619
  VigorFetch,
2114
2620
  VigorFetchBase,
2621
+ VigorFetchContextBase,
2115
2622
  VigorFetchError,
2116
2623
  VigorFetchErrorMessageFuncs,
2117
2624
  VigorFetchPolicyBase,
@@ -2123,6 +2630,7 @@ export {
2123
2630
  VigorParse,
2124
2631
  VigorParseBase,
2125
2632
  VigorParseContentTypeStrategy,
2633
+ VigorParseContextBase,
2126
2634
  VigorParseError,
2127
2635
  VigorParseErrorMessageFuncs,
2128
2636
  VigorParsePolicyBase,
@@ -2135,6 +2643,7 @@ export {
2135
2643
  VigorParseSniffStrategy,
2136
2644
  VigorRetry,
2137
2645
  VigorRetryBase,
2646
+ VigorRetryContextBase,
2138
2647
  VigorRetryError,
2139
2648
  VigorRetryErrorMessageFuncs,
2140
2649
  VigorRetryPolicyAlgorithms,
@@ -2153,10 +2662,18 @@ export {
2153
2662
  VigorRetryPolicySettings,
2154
2663
  VigorRetryPolicySettingsBase,
2155
2664
  VigorStatus,
2665
+ adoptVigorFetchError,
2666
+ createBrand,
2667
+ createVigorTimelineRecorder,
2156
2668
  index_default as default,
2157
2669
  isVigorAllError,
2670
+ isVigorDefault,
2671
+ isVigorEmpty,
2158
2672
  isVigorFetchError,
2673
+ isVigorInternalMiddleware,
2159
2674
  isVigorParseError,
2160
2675
  isVigorRetryError,
2676
+ markVigorInternal,
2677
+ readVigorParseBody,
2161
2678
  vigor
2162
2679
  };