vigor-fetch 4.0.4 → 4.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1993 +1,1883 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- /**
6
- * Builds the literal brand string used by {@link VigorBrand}, preserving the
7
- * `Branch`/`Name` literal types for use as a `__brand` value.
8
- */
1
+ // src/core/symbol.ts
9
2
  function createBrand(b, n) {
10
- return `@vigor-fetch:::${b} <- ${n}`;
3
+ return `@vigor-fetch:::${b} <- ${n}`;
11
4
  }
12
- const VigorDefault = Symbol("VigorDefault");
13
- /** Type guard checking whether a value is the {@link VigorDefault} sentinel. */
14
- const isVigorDefault = (v) => v === VigorDefault;
15
- const VigorEmpty = Symbol("VigorEmpty");
16
- /** Type guard checking whether a value is the {@link VigorEmpty} sentinel. */
17
- const isVigorEmpty = (v) => v === VigorEmpty;
5
+ var VigorDefault = /* @__PURE__ */ Symbol("VigorDefault");
6
+ var isVigorDefault = (v) => v === VigorDefault;
7
+ var VigorEmpty = /* @__PURE__ */ Symbol("VigorEmpty");
8
+ var isVigorEmpty = (v) => v === VigorEmpty;
18
9
 
19
- /**
20
- * Base class for Vigor's immutable, chainable builder objects.
21
- *
22
- * Each subclass holds a `base` config and a current `config`, and exposes
23
- * `_next()` to derive a new instance with a patch merged in. Subclasses
24
- * implement `_create()` to construct the concrete instance type, and the
25
- * return type of `_next()` is computed through the `TL` type lambda so
26
- * chained calls stay precisely typed.
27
- *
28
- * @typeParam Base - Shape of the full config for this builder.
29
- * @typeParam Config - Concrete config type held by this instance (extends `Base`).
30
- * @typeParam TL - Type lambda mapping a config type to the concrete instance type.
31
- */
32
- class VigorStatus {
33
- _base;
34
- _config;
35
- /**
36
- * @param base - The default/base config for this builder.
37
- * @param config - The (possibly partial) config to merge onto `base`.
38
- */
39
- constructor(base, config) {
40
- this._base = base;
41
- this._config = this._merge(base, config);
42
- }
43
- /**
44
- * Derives a new instance by merging `patch` onto the current config.
45
- *
46
- * @param patch - Values to overwrite/merge in for this step.
47
- * @param strategy - Optional tree mirroring the shape of `patch`, whose
48
- * leaves may be `"replace" | "concat" | "merge"` to force the merge
49
- * behavior at that path. Paths without a strategy fall back to the
50
- * default behavior (deep merge for objects, concat for arrays).
51
- */
52
- _next(patch, strategy) {
53
- const merged = this._merge(this._config, patch, strategy);
54
- return this._create(merged);
55
- }
56
- /**
57
- * Deep-merges `target` onto `source`, honoring an optional per-path
58
- * `strategy` tree. Objects merge key by key, arrays concatenate (unless
59
- * `"replace"` is specified), and any other value is overwritten.
60
- */
61
- _merge(source, target, strategy) {
62
- const isObj = (v) => v !== null &&
63
- typeof v === "object" &&
64
- Object.getPrototypeOf(v) === Object.prototype;
65
- const merge = (a, b, s) => {
66
- if (b === undefined || b === null)
67
- return a;
68
- if (s === "replace")
69
- return b;
70
- if (Array.isArray(a) && Array.isArray(b)) {
71
- return s === "replace" ? b : [...a, ...b];
72
- }
73
- if (isObj(a) && isObj(b)) {
74
- const r = { ...a };
75
- const sObj = isObj(s) ? s : undefined;
76
- for (const k of Object.keys(b)) {
77
- r[k] = merge(a[k], b[k], sObj?.[k]);
78
- }
79
- return r;
80
- }
81
- return b;
82
- };
83
- return merge(source, target, strategy);
84
- }
85
- /** The default/base config this builder was constructed with. */
86
- get base() {
87
- return this._base;
88
- }
89
- /** The current, merged config for this builder instance. */
90
- get config() {
91
- return this._config;
92
- }
93
- }
10
+ // src/core/status.ts
11
+ var VigorStatus = class {
12
+ _base;
13
+ _config;
14
+ /**
15
+ * @param base - The default/base config for this builder.
16
+ * @param config - The (possibly partial) config to merge onto `base`.
17
+ */
18
+ constructor(base, config) {
19
+ this._base = base;
20
+ this._config = this._merge(base, config);
21
+ }
22
+ /**
23
+ * Derives a new instance by merging `patch` onto the current config.
24
+ *
25
+ * @param patch - Values to overwrite/merge in for this step.
26
+ * @param strategy - Optional tree mirroring the shape of `patch`, whose
27
+ * leaves may be `"replace" | "concat" | "merge"` to force the merge
28
+ * behavior at that path. Paths without a strategy fall back to the
29
+ * default behavior (deep merge for objects, concat for arrays).
30
+ */
31
+ _next(patch, strategy) {
32
+ const merged = this._merge(this._config, patch, strategy);
33
+ return this._create(merged);
34
+ }
35
+ /**
36
+ * Deep-merges `target` onto `source`, honoring an optional per-path
37
+ * `strategy` tree. Objects merge key by key, arrays concatenate (unless
38
+ * `"replace"` is specified), and any other value is overwritten.
39
+ */
40
+ _merge(source, target, strategy) {
41
+ const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
42
+ const merge = (a, b, s) => {
43
+ if (b === void 0 || b === null) return a;
44
+ if (s === "replace") return b;
45
+ if (Array.isArray(a) && Array.isArray(b)) {
46
+ return s === "replace" ? b : [...a, ...b];
47
+ }
48
+ if (isObj(a) && isObj(b)) {
49
+ const r = { ...a };
50
+ const sObj = isObj(s) ? s : void 0;
51
+ for (const k of Object.keys(b)) {
52
+ r[k] = merge(a[k], b[k], sObj?.[k]);
53
+ }
54
+ return r;
55
+ }
56
+ return b;
57
+ };
58
+ return merge(source, target, strategy);
59
+ }
60
+ /** The default/base config this builder was constructed with. */
61
+ get base() {
62
+ return this._base;
63
+ }
64
+ /** The current, merged config for this builder instance. */
65
+ get config() {
66
+ return this._config;
67
+ }
68
+ };
94
69
 
95
- const VigorAllPolicySettingsBase = {
96
- __brand: createBrand("All", "Policy<Settings<Schema"),
97
- concurrency: 5,
98
- onlySuccess: false
70
+ // src/all/settings.ts
71
+ var VigorAllPolicySettingsBase = {
72
+ __brand: createBrand("All", "Policy<Settings<Schema"),
73
+ concurrency: 5,
74
+ onlySuccess: false
75
+ };
76
+ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
77
+ constructor(config = VigorAllBase) {
78
+ super(VigorAllBase, config);
79
+ }
80
+ _create(config) {
81
+ return new _VigorAllPolicySettings(config);
82
+ }
83
+ /** Sets the maximum number of tasks run concurrently. */
84
+ concurrency(num) {
85
+ return this._next({ policy: { settings: { concurrency: num } } });
86
+ }
87
+ /** When enabled, filters the final result down to only the tasks that succeeded. */
88
+ onlySuccess(bool) {
89
+ return this._next({ policy: { settings: { onlySuccess: bool } } });
90
+ }
99
91
  };
100
- /** Immutable builder for an all-policy's general settings. */
101
- class VigorAllPolicySettings extends VigorStatus {
102
- constructor(config = VigorAllBase) {
103
- super(VigorAllBase, config);
104
- }
105
- _create(config) {
106
- return new VigorAllPolicySettings(config);
107
- }
108
- /** Sets the maximum number of tasks run concurrently. */
109
- concurrency(num) {
110
- return this._next({ policy: { settings: { concurrency: num } } });
111
- }
112
- /** When enabled, filters the final result down to only the tasks that succeeded. */
113
- onlySuccess(bool) {
114
- return this._next({ policy: { settings: { onlySuccess: bool } } });
115
- }
116
- }
117
92
 
118
- const VigorAllPolicyMiddlewaresBase = {
119
- __brand: createBrand("All", "Policy<Middlewares<Schema"),
120
- before: [],
121
- after: [],
122
- onError: []
93
+ // src/all/middlewares.ts
94
+ var VigorAllPolicyMiddlewaresBase = {
95
+ __brand: createBrand("All", "Policy<Middlewares<Schema"),
96
+ before: [],
97
+ after: [],
98
+ onError: []
99
+ };
100
+ var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorStatus {
101
+ constructor(config = VigorAllBase) {
102
+ super(VigorAllBase, config);
103
+ }
104
+ _create(config) {
105
+ return new _VigorAllPolicyMiddlewares(config);
106
+ }
107
+ /** Registers a middleware that runs before each task is invoked. */
108
+ before(func) {
109
+ return this._next({ policy: { middlewares: { before: [func] } } });
110
+ }
111
+ /** Registers a middleware that runs after each task settles successfully. */
112
+ after(func) {
113
+ return this._next({ policy: { middlewares: { after: [func] } } });
114
+ }
115
+ /** Registers a middleware that runs when an individual task fails. */
116
+ onError(func) {
117
+ return this._next({ policy: { middlewares: { onError: [func] } } });
118
+ }
123
119
  };
124
- /** Immutable builder for an all-policy's per-task middleware pipeline (`before`, `after`, `onError`). */
125
- class VigorAllPolicyMiddlewares extends VigorStatus {
126
- constructor(config = VigorAllBase) {
127
- super(VigorAllBase, config);
128
- }
129
- _create(config) {
130
- return new VigorAllPolicyMiddlewares(config);
131
- }
132
- /** Registers a middleware that runs before each task is invoked. */
133
- before(func) {
134
- return this._next({ policy: { middlewares: { before: [func] } } });
135
- }
136
- /** Registers a middleware that runs after each task settles successfully. */
137
- after(func) {
138
- return this._next({ policy: { middlewares: { after: [func] } } });
139
- }
140
- /** Registers a middleware that runs when an individual task fails. */
141
- onError(func) {
142
- return this._next({ policy: { middlewares: { onError: [func] } } });
143
- }
144
- }
145
120
 
146
- const VigorAllPolicyBase = {
147
- __brand: createBrand("All", "Policy<Schema"),
148
- target: [],
149
- settings: VigorAllPolicySettingsBase,
150
- middlewares: VigorAllPolicyMiddlewaresBase
121
+ // src/all/policy.ts
122
+ var VigorAllPolicyBase = {
123
+ __brand: createBrand("All", "Policy<Schema"),
124
+ target: [],
125
+ settings: VigorAllPolicySettingsBase,
126
+ middlewares: VigorAllPolicyMiddlewaresBase
151
127
  };
152
128
 
153
- const VigorAllContextBase = {
154
- __brand: createBrand("All", "Context<Schema"),
155
- result: VigorDefault,
156
- policy: VigorAllPolicyBase,
157
- record: {}
129
+ // src/all/context.ts
130
+ var VigorAllContextBase = {
131
+ __brand: createBrand("All", "Context<Schema"),
132
+ result: VigorDefault,
133
+ policy: VigorAllPolicyBase,
134
+ record: {}
158
135
  };
159
- const VigorAllEachContextBase = {
160
- __brand: createBrand("All", "EachContext<Schema"),
161
- result: VigorDefault,
162
- error: VigorDefault,
163
- flags: { overrided: false },
164
- record: {}
136
+ var VigorAllEachContextBase = {
137
+ __brand: createBrand("All", "EachContext<Schema"),
138
+ result: VigorDefault,
139
+ error: VigorDefault,
140
+ flags: { overrided: false },
141
+ record: {}
165
142
  };
166
143
 
167
- /**
168
- * Base class for all Vigor error types. Subclasses (`VigorRetryError`,
169
- * `VigorFetchError`, `VigorParseError`, `VigorAllError`) fix `C`, `D`, and
170
- * `T` to their own error-code union, data shape, and context shape.
171
- *
172
- * @typeParam C - Union of error codes for the subclass.
173
- * @typeParam D - Shape of the structured error data.
174
- * @typeParam T - Shape of the domain context.
175
- */
176
- class VigorError extends Error {
177
- timestamp = new Date();
178
- cause;
179
- code;
180
- data;
181
- method;
182
- context;
183
- /**
184
- * @param code - Machine-readable error code.
185
- * @param message - Human-readable message (rendered after the `[code]` prefix).
186
- * @param options - Additional error metadata (cause, data, method, context).
187
- */
188
- constructor(code, message, options) {
189
- super(`[${code}] ${message}`);
190
- this.name = new.target.name;
191
- this.code = code;
192
- this.cause = options.cause;
193
- this.data = options.data;
194
- this.method = options.method;
195
- this.context = options.context;
196
- Object.setPrototypeOf(this, new.target.prototype);
197
- Error.captureStackTrace?.(this, new.target);
198
- }
199
- }
144
+ // src/core/error.ts
145
+ var VigorError = class extends Error {
146
+ timestamp = /* @__PURE__ */ new Date();
147
+ cause;
148
+ code;
149
+ data;
150
+ method;
151
+ context;
152
+ /**
153
+ * @param code - Machine-readable error code.
154
+ * @param message - Human-readable message (rendered after the `[code]` prefix).
155
+ * @param options - Additional error metadata (cause, data, method, context).
156
+ */
157
+ constructor(code, message, options) {
158
+ super(`[${code}] ${message}`);
159
+ this.name = new.target.name;
160
+ this.code = code;
161
+ this.cause = options.cause;
162
+ this.data = options.data;
163
+ this.method = options.method;
164
+ this.context = options.context;
165
+ Object.setPrototypeOf(this, new.target.prototype);
166
+ Error.captureStackTrace?.(this, new.target);
167
+ }
168
+ };
200
169
 
201
- const VigorAllErrorMessageFuncs = {
202
- EMPTY_TARGET: (_) => `Empty target list`,
170
+ // src/all/error.ts
171
+ var VigorAllErrorMessageFuncs = {
172
+ EMPTY_TARGET: (_) => `Empty target list`
173
+ };
174
+ var VigorAllError = class extends VigorError {
175
+ /**
176
+ * @param code - One of the all module's error codes.
177
+ * @param options - Error metadata, including the `data` payload for `code`.
178
+ */
179
+ constructor(code, options) {
180
+ const messageFn = VigorAllErrorMessageFuncs[code];
181
+ super(code, messageFn(options.data), options);
182
+ }
203
183
  };
204
- /** Error type thrown by the all module. */
205
- class VigorAllError extends VigorError {
206
- /**
207
- * @param code - One of the all module's error codes.
208
- * @param options - Error metadata, including the `data` payload for `code`.
209
- */
210
- constructor(code, options) {
211
- const messageFn = VigorAllErrorMessageFuncs[code];
212
- super(code, messageFn(options.data), options);
213
- }
214
- }
215
184
 
216
- const VigorAllBase = {
217
- __brand: createBrand("All", "Schema"),
218
- policy: VigorAllPolicyBase,
219
- context: VigorAllContextBase
185
+ // src/all/main.ts
186
+ var VigorAllBase = {
187
+ __brand: createBrand("All", "Schema"),
188
+ policy: VigorAllPolicyBase,
189
+ context: VigorAllContextBase
220
190
  };
221
- /**
222
- * Immutable builder that runs a list of independent tasks with bounded
223
- * concurrency, per-task middleware, and either an all-results or
224
- * only-successes result mode.
225
- */
226
- class VigorAll extends VigorStatus {
227
- constructor(config = VigorAllBase) {
228
- super(VigorAllBase, config);
229
- }
230
- _create(config) {
231
- return new VigorAll(config);
232
- }
233
- /** Sets the list of tasks to run. */
234
- target(...funcs) {
235
- return this._next({ policy: { target: funcs } });
236
- }
237
- /** Configures the all-policy's general settings (concurrency, onlySuccess). */
238
- settings(input) {
239
- if (typeof input === 'function' || input instanceof VigorAllPolicySettings) {
240
- const result = typeof input === 'function'
241
- ? input(new VigorAllPolicySettings())
242
- : input;
243
- return this._next({
244
- policy: { settings: result.config.policy.settings }
245
- });
246
- }
247
- return this._next({ policy: { settings: input } });
248
- }
249
- /** Configures the all-policy's per-task middleware pipeline. */
250
- middlewares(input) {
251
- if (typeof input === 'function' || input instanceof VigorAllPolicyMiddlewares) {
252
- const result = typeof input === 'function'
253
- ? input(new VigorAllPolicyMiddlewares())
254
- : input;
255
- return this._next({
256
- policy: { middlewares: result.config.policy.middlewares }
257
- });
258
- }
259
- return this._next({ policy: { middlewares: input } });
260
- }
261
- /** Runs a single task through the before/after/onError middleware pipeline. */
262
- async _runTask(task, policy) {
263
- let ctx = { ...VigorAllEachContextBase };
264
- try {
265
- for (const before of policy.middlewares.before)
266
- await before(ctx);
267
- ctx.result = await task();
268
- for (const after of policy.middlewares.after)
269
- await after(ctx);
270
- return { success: true, value: ctx.result };
271
- }
272
- catch (error) {
273
- ctx.error = error;
274
- const setResult = (r) => { ctx.flags.overrided = true; ctx.result = r; };
275
- for (const onError of policy.middlewares.onError)
276
- await onError(ctx, { setResult });
277
- if (ctx.flags.overrided)
278
- return { success: true, value: ctx.result };
279
- return { success: false, value: error };
191
+ var VigorAll = class _VigorAll extends VigorStatus {
192
+ constructor(config = VigorAllBase) {
193
+ super(VigorAllBase, config);
194
+ }
195
+ _create(config) {
196
+ return new _VigorAll(config);
197
+ }
198
+ /** Sets the list of tasks to run. */
199
+ target(...funcs) {
200
+ return this._next({ policy: { target: funcs } });
201
+ }
202
+ /** Configures the all-policy's general settings (concurrency, onlySuccess). */
203
+ settings(input) {
204
+ if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
205
+ const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
206
+ return this._next({
207
+ policy: { settings: result.config.policy.settings }
208
+ });
209
+ }
210
+ return this._next({ policy: { settings: input } });
211
+ }
212
+ /** Configures the all-policy's per-task middleware pipeline. */
213
+ middlewares(input) {
214
+ if (typeof input === "function" || input instanceof VigorAllPolicyMiddlewares) {
215
+ const result = typeof input === "function" ? input(new VigorAllPolicyMiddlewares()) : input;
216
+ return this._next({
217
+ policy: { middlewares: result.config.policy.middlewares }
218
+ });
219
+ }
220
+ return this._next({ policy: { middlewares: input } });
221
+ }
222
+ /** Runs a single task through the before/after/onError middleware pipeline. */
223
+ async _runTask(task, policy) {
224
+ let ctx = { ...VigorAllEachContextBase };
225
+ try {
226
+ for (const before of policy.middlewares.before) await before(ctx);
227
+ ctx.result = await task();
228
+ for (const after of policy.middlewares.after) await after(ctx);
229
+ return { success: true, value: ctx.result };
230
+ } catch (error) {
231
+ ctx.error = error;
232
+ const setResult = (r) => {
233
+ ctx.flags.overrided = true;
234
+ ctx.result = r;
235
+ };
236
+ for (const onError of policy.middlewares.onError) await onError(ctx, { setResult });
237
+ if (ctx.flags.overrided) return { success: true, value: ctx.result };
238
+ return { success: false, value: error };
239
+ }
240
+ }
241
+ /** Runs all tasks and returns the results array directly, throwing on final failure. */
242
+ async request() {
243
+ const res = await this.requestVerbose();
244
+ if (res.success) return res.data;
245
+ throw res.error;
246
+ }
247
+ /** Runs all tasks and returns a result/error envelope instead of throwing. */
248
+ async requestVerbose() {
249
+ return await this.requestRuntime();
250
+ }
251
+ /** Internal execution loop implementing the bounded-concurrency worker pool. */
252
+ async requestRuntime(restartAttempt = 1) {
253
+ const config = this._merge(this.config, {});
254
+ const policy = config.policy;
255
+ try {
256
+ if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
257
+ method: "request",
258
+ data: {}
259
+ });
260
+ const concurrency = Math.max(1, policy.settings.concurrency);
261
+ const results = new Array(policy.target.length);
262
+ let cursor = 0;
263
+ const worker = async () => {
264
+ while (true) {
265
+ const i = cursor++;
266
+ if (i >= policy.target.length) return;
267
+ results[i] = await this._runTask(policy.target[i], policy);
280
268
  }
281
- }
282
- /** Runs all tasks and returns the results array directly, throwing on final failure. */
283
- async request() {
284
- const res = await this.requestVerbose();
285
- if (res.success)
286
- return res.data;
287
- throw res.error;
288
- }
289
- /** Runs all tasks and returns a result/error envelope instead of throwing. */
290
- async requestVerbose() {
291
- return await this.requestRuntime();
292
- }
293
- /** Internal execution loop implementing the bounded-concurrency worker pool. */
294
- async requestRuntime(restartAttempt = 1) {
295
- const config = this._merge(this.config, {});
296
- const policy = config.policy;
297
- try {
298
- if (policy.target.length === 0)
299
- throw new VigorAllError("EMPTY_TARGET", {
300
- method: "request",
301
- data: {}
302
- });
303
- const concurrency = Math.max(1, policy.settings.concurrency);
304
- const results = new Array(policy.target.length);
305
- let cursor = 0;
306
- const worker = async () => {
307
- while (true) {
308
- const i = cursor++;
309
- if (i >= policy.target.length)
310
- return;
311
- results[i] = await this._runTask(policy.target[i], policy);
312
- }
313
- };
314
- await Promise.all(Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker()));
315
- const result = policy.settings.onlySuccess
316
- ? results.filter(r => r.success).map(r => r.value)
317
- : results.map(r => r.value);
318
- return {
319
- success: true,
320
- data: result,
321
- error: null
322
- };
323
- }
324
- catch (error) {
325
- return {
326
- success: false,
327
- data: null,
328
- error
329
- };
330
- }
331
- }
332
- }
269
+ };
270
+ await Promise.all(
271
+ Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
272
+ );
273
+ const result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
274
+ return {
275
+ success: true,
276
+ data: result,
277
+ error: null
278
+ };
279
+ } catch (error) {
280
+ return {
281
+ success: false,
282
+ data: null,
283
+ error
284
+ };
285
+ }
286
+ }
287
+ };
333
288
 
334
- const VigorFetchPolicySettingsBase = {
335
- __brand: createBrand("Fetch", "Policy<Settings<Schema"),
336
- retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
337
- unretryStatus: [400, 401, 403, 404, 405, 413, 422],
338
- maxRestarts: 3,
339
- default: VigorEmpty
289
+ // src/fetch/settings.ts
290
+ var VigorFetchPolicySettingsBase = {
291
+ __brand: createBrand("Fetch", "Policy<Settings<Schema"),
292
+ retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
293
+ unretryStatus: [400, 401, 403, 404, 405, 413, 422],
294
+ maxRestarts: 3,
295
+ default: VigorEmpty
296
+ };
297
+ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStatus {
298
+ constructor(config = VigorFetchBase) {
299
+ super(VigorFetchBase, config);
300
+ }
301
+ _create(config) {
302
+ return new _VigorFetchPolicySettings(config);
303
+ }
304
+ /** Sets response headers consulted to compute a server-suggested retry delay. */
305
+ retryHeaders(...strs) {
306
+ return this._next({ policy: { settings: { retryHeaders: strs } } });
307
+ }
308
+ /** Sets HTTP status codes that should never be retried. */
309
+ unretryStatus(...nums) {
310
+ return this._next({ policy: { settings: { unretryStatus: nums } } });
311
+ }
312
+ /** Sets the maximum number of full restarts allowed. */
313
+ maxRestarts(num) {
314
+ return this._next({ policy: { settings: { maxRestarts: num } } });
315
+ }
316
+ /** Sets the fallback value/factory used when the request ultimately fails. */
317
+ default(func) {
318
+ return this._next({ policy: { settings: { default: func } } });
319
+ }
340
320
  };
341
- /** Immutable builder for a fetch policy's general settings. */
342
- class VigorFetchPolicySettings extends VigorStatus {
343
- constructor(config = VigorFetchBase) {
344
- super(VigorFetchBase, config);
345
- }
346
- _create(config) {
347
- return new VigorFetchPolicySettings(config);
348
- }
349
- /** Sets response headers consulted to compute a server-suggested retry delay. */
350
- retryHeaders(...strs) {
351
- return this._next({ policy: { settings: { retryHeaders: strs } } });
352
- }
353
- /** Sets HTTP status codes that should never be retried. */
354
- unretryStatus(...nums) {
355
- return this._next({ policy: { settings: { unretryStatus: nums } } });
356
- }
357
- /** Sets the maximum number of full restarts allowed. */
358
- maxRestarts(num) {
359
- return this._next({ policy: { settings: { maxRestarts: num } } });
360
- }
361
- /** Sets the fallback value/factory used when the request ultimately fails. */
362
- default(func) {
363
- return this._next({ policy: { settings: { default: func } } });
364
- }
365
- }
366
321
 
367
- const VigorFetchPolicyMiddlewaresBase = {
368
- __brand: createBrand("Fetch", "Policy<Middlewares<Schema"),
369
- before: [],
370
- after: [],
371
- onResult: [],
372
- onError: []
322
+ // src/fetch/middlewares.ts
323
+ var VigorFetchPolicyMiddlewaresBase = {
324
+ __brand: createBrand("Fetch", "Policy<Middlewares<Schema"),
325
+ before: [],
326
+ after: [],
327
+ onResult: [],
328
+ onError: []
329
+ };
330
+ var VigorFetchPolicyMiddlewares = class _VigorFetchPolicyMiddlewares extends VigorStatus {
331
+ constructor(config = VigorFetchBase) {
332
+ super(VigorFetchBase, config);
333
+ }
334
+ _create(config) {
335
+ return new _VigorFetchPolicyMiddlewares(config);
336
+ }
337
+ before(type, func) {
338
+ return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
339
+ }
340
+ after(type, func) {
341
+ return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
342
+ }
343
+ onResult(type, func) {
344
+ return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
345
+ }
346
+ onError(type, func) {
347
+ return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
348
+ }
373
349
  };
374
- /**
375
- * Immutable builder for a fetch policy's middleware pipeline (`before`,
376
- * `after`, `onResult`, `onError`). Each stage accepts either "fluent"
377
- * middleware (returns a plain value merged into the context) or
378
- * "intercept" middleware (receives an explicit API to mutate control flow).
379
- */
380
- class VigorFetchPolicyMiddlewares extends VigorStatus {
381
- constructor(config = VigorFetchBase) {
382
- super(VigorFetchBase, config);
383
- }
384
- _create(config) {
385
- return new VigorFetchPolicyMiddlewares(config);
386
- }
387
- before(type, func) {
388
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
389
- }
390
- after(type, func) {
391
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
392
- }
393
- onResult(type, func) {
394
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
395
- }
396
- onError(type, func) {
397
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
398
- }
399
- }
400
350
 
401
- const VigorRetryPolicySettingsBase = {
402
- __brand: createBrand("Retry", "Policy<Settings<Schema"),
403
- default: VigorEmpty,
404
- maxAttempts: 5,
405
- maxRestarts: 3,
406
- timeout: 20000
351
+ // src/retry/settings.ts
352
+ var VigorRetryPolicySettingsBase = {
353
+ __brand: createBrand("Retry", "Policy<Settings<Schema"),
354
+ default: VigorEmpty,
355
+ maxAttempts: 5,
356
+ maxRestarts: 3,
357
+ timeout: 2e4
358
+ };
359
+ var VigorRetryPolicySettings = class _VigorRetryPolicySettings extends VigorStatus {
360
+ constructor(config = VigorRetryBase) {
361
+ super(VigorRetryBase, config);
362
+ }
363
+ _create(config) {
364
+ return new _VigorRetryPolicySettings(config);
365
+ }
366
+ /** Sets the fallback value/factory used when the target ultimately fails. */
367
+ default(func) {
368
+ return this._next({
369
+ policy: { settings: { default: func } }
370
+ });
371
+ }
372
+ /** Sets the maximum number of retry attempts before giving up. */
373
+ maxAttempts(num) {
374
+ return this._next({
375
+ policy: { settings: { maxAttempts: num } }
376
+ });
377
+ }
378
+ /** Sets the maximum number of full restarts allowed. */
379
+ maxRestarts(num) {
380
+ return this._next({
381
+ policy: { settings: { maxRestarts: num } }
382
+ });
383
+ }
384
+ /** Sets the timeout, in milliseconds, for a single attempt. */
385
+ timeout(num) {
386
+ return this._next({
387
+ policy: { settings: { timeout: num } }
388
+ });
389
+ }
407
390
  };
408
- /** Immutable builder for a retry policy's general settings. */
409
- class VigorRetryPolicySettings extends VigorStatus {
410
- constructor(config = VigorRetryBase) {
411
- super(VigorRetryBase, config);
412
- }
413
- _create(config) {
414
- return new VigorRetryPolicySettings(config);
415
- }
416
- /** Sets the fallback value/factory used when the target ultimately fails. */
417
- default(func) {
418
- return this._next({
419
- policy: { settings: { default: func } }
420
- });
421
- }
422
- /** Sets the maximum number of retry attempts before giving up. */
423
- maxAttempts(num) {
424
- return this._next({
425
- policy: { settings: { maxAttempts: num } }
426
- });
427
- }
428
- /** Sets the maximum number of full restarts allowed. */
429
- maxRestarts(num) {
430
- return this._next({
431
- policy: { settings: { maxRestarts: num } }
432
- });
433
- }
434
- /** Sets the timeout, in milliseconds, for a single attempt. */
435
- timeout(num) {
436
- return this._next({
437
- policy: { settings: { timeout: num } }
438
- });
439
- }
440
- }
441
391
 
442
- const VigorRetryPolicyMiddlewaresBase = {
443
- __brand: createBrand("Retry", "Policy<Middlewares<Schema"),
444
- before: [],
445
- after: [],
446
- onResult: [],
447
- retryIf: [],
448
- onRetry: [],
449
- onError: []
392
+ // src/retry/middlewares.ts
393
+ var VigorRetryPolicyMiddlewaresBase = {
394
+ __brand: createBrand("Retry", "Policy<Middlewares<Schema"),
395
+ before: [],
396
+ after: [],
397
+ onResult: [],
398
+ retryIf: [],
399
+ onRetry: [],
400
+ onError: []
401
+ };
402
+ var VigorRetryPolicyMiddlewares = class _VigorRetryPolicyMiddlewares extends VigorStatus {
403
+ constructor(config = VigorRetryBase) {
404
+ super(VigorRetryBase, config);
405
+ }
406
+ _create(config) {
407
+ return new _VigorRetryPolicyMiddlewares(config);
408
+ }
409
+ before(type, func) {
410
+ return this._next({
411
+ policy: { middlewares: { before: [{ _mode: type, func }] } }
412
+ });
413
+ }
414
+ after(type, func) {
415
+ return this._next({
416
+ policy: { middlewares: { after: [{ _mode: type, func }] } }
417
+ });
418
+ }
419
+ onResult(type, func) {
420
+ return this._next({
421
+ policy: { middlewares: { onResult: [{ _mode: type, func }] } }
422
+ });
423
+ }
424
+ retryIf(type, func) {
425
+ return this._next({
426
+ policy: { middlewares: { retryIf: [{ _mode: type, func }] } }
427
+ });
428
+ }
429
+ onRetry(type, func) {
430
+ return this._next({
431
+ policy: { middlewares: { onRetry: [{ _mode: type, func }] } }
432
+ });
433
+ }
434
+ onError(type, func) {
435
+ return this._next({
436
+ policy: { middlewares: { onError: [{ _mode: type, func }] } }
437
+ });
438
+ }
450
439
  };
451
- /**
452
- * Immutable builder for a retry policy's middleware pipeline (`before`,
453
- * `after`, `onResult`, `retryIf`, `onRetry`, `onError`). Each stage accepts
454
- * either "fluent" middleware (returns a plain value merged into the
455
- * context) or "intercept" middleware (receives an explicit API to mutate
456
- * control flow).
457
- */
458
- class VigorRetryPolicyMiddlewares extends VigorStatus {
459
- constructor(config = VigorRetryBase) {
460
- super(VigorRetryBase, config);
461
- }
462
- _create(config) {
463
- return new VigorRetryPolicyMiddlewares(config);
464
- }
465
- before(type, func) {
466
- return this._next({
467
- policy: { middlewares: { before: [{ _mode: type, func }] } }
468
- });
469
- }
470
- after(type, func) {
471
- return this._next({
472
- policy: { middlewares: { after: [{ _mode: type, func }] } }
473
- });
474
- }
475
- onResult(type, func) {
476
- return this._next({
477
- policy: { middlewares: { onResult: [{ _mode: type, func }] } }
478
- });
479
- }
480
- retryIf(type, func) {
481
- return this._next({
482
- policy: { middlewares: { retryIf: [{ _mode: type, func }] } }
483
- });
484
- }
485
- onRetry(type, func) {
486
- return this._next({
487
- policy: { middlewares: { onRetry: [{ _mode: type, func }] } }
488
- });
489
- }
490
- onError(type, func) {
491
- return this._next({
492
- policy: { middlewares: { onError: [{ _mode: type, func }] } }
493
- });
494
- }
495
- }
496
440
 
497
- const VigorRetryErrorMessageFuncs = {
498
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
499
- RETRY_EXHAUSTED: ({ maxAttempts }) => `Retry exhausted, (max ${maxAttempts})`,
500
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
501
- TIMED_OUT: ({ limit }) => `Timeout: exceeded ${limit}ms`,
441
+ // src/retry/error.ts
442
+ var VigorRetryErrorMessageFuncs = {
443
+ VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
444
+ RETRY_EXHAUSTED: ({ maxAttempts }) => `Retry exhausted, (max ${maxAttempts})`,
445
+ RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
446
+ TIMED_OUT: ({ limit }) => `Timeout: exceeded ${limit}ms`
447
+ };
448
+ var VigorRetryError = class extends VigorError {
449
+ /**
450
+ * @param code - One of the retry module's error codes.
451
+ * @param options - Error metadata, including the `data` payload for `code`.
452
+ */
453
+ constructor(code, options) {
454
+ const messageFn = VigorRetryErrorMessageFuncs[code];
455
+ super(code, messageFn(options.data), options);
456
+ }
502
457
  };
503
- /** Error type thrown by the retry module. */
504
- class VigorRetryError extends VigorError {
505
- /**
506
- * @param code - One of the retry module's error codes.
507
- * @param options - Error metadata, including the `data` payload for `code`.
508
- */
509
- constructor(code, options) {
510
- const messageFn = VigorRetryErrorMessageFuncs[code];
511
- super(code, messageFn(options.data), options);
512
- }
513
- }
514
458
 
515
- /** Returns a random offset in the range `[-jitter, +jitter]` to randomize a computed delay. */
459
+ // src/retry/algorithms.ts
516
460
  function VigorJitter(jitter) {
517
- return (Math.random() * 2 - 1) * jitter;
461
+ return (Math.random() * 2 - 1) * jitter;
518
462
  }
519
- const VigorRetryPolicyAlgorithmsConstantBase = {
520
- __brand: createBrand("Retry", "Policy<Algorithms<Constant<Schema"),
521
- _tag: "constant",
522
- jitter: 1000,
523
- interval: 2000,
524
- _calculateDelay: (att, config) => {
525
- const { interval, jitter } = config;
526
- const min = jitter;
527
- let delay = Math.max(min, interval);
528
- delay += VigorJitter(jitter);
529
- return delay;
530
- }
463
+ var VigorRetryPolicyAlgorithmsConstantBase = {
464
+ __brand: createBrand("Retry", "Policy<Algorithms<Constant<Schema"),
465
+ _tag: "constant",
466
+ jitter: 1e3,
467
+ interval: 2e3,
468
+ _calculateDelay: (att, config) => {
469
+ const { interval, jitter } = config;
470
+ const min = jitter;
471
+ let delay = Math.max(min, interval);
472
+ delay += VigorJitter(jitter);
473
+ return delay;
474
+ }
531
475
  };
532
- /** Immutable builder for the constant-interval retry delay algorithm. */
533
- class VigorRetryPolicyAlgorithmsConstant extends VigorStatus {
534
- constructor(config = VigorRetryPolicyAlgorithmsConstantBase) {
535
- super(VigorRetryPolicyAlgorithmsConstantBase, config);
536
- }
537
- _create(config) {
538
- return new VigorRetryPolicyAlgorithmsConstant(config);
539
- }
540
- /** Sets the amount of random jitter added to the computed delay. */
541
- jitter(num) {
542
- return this._next({ jitter: num });
543
- }
544
- /** Sets the fixed delay interval, in milliseconds. */
545
- interval(num) {
546
- return this._next({ interval: num });
547
- }
548
- }
549
- const VigorRetryPolicyAlgorithmsLinearBase = {
550
- __brand: createBrand("Retry", "Policy<Algorithms<Linear<Schema"),
551
- _tag: "linear",
552
- jitter: 1000,
553
- initial: 500,
554
- increment: 1000,
555
- minDelay: 0,
556
- maxDelay: 10000,
557
- _calculateDelay: (att, config) => {
558
- const { initial, jitter, increment, minDelay, maxDelay } = config;
559
- const range = maxDelay - minDelay;
560
- const j = Math.min(jitter, range / 2);
561
- const min = minDelay + j;
562
- const max = maxDelay - j;
563
- let delay = initial + increment * att;
564
- delay = Math.max(min, Math.min(max, delay));
565
- delay += VigorJitter(j);
566
- return delay;
567
- }
476
+ var VigorRetryPolicyAlgorithmsConstant = class _VigorRetryPolicyAlgorithmsConstant extends VigorStatus {
477
+ constructor(config = VigorRetryPolicyAlgorithmsConstantBase) {
478
+ super(VigorRetryPolicyAlgorithmsConstantBase, config);
479
+ }
480
+ _create(config) {
481
+ return new _VigorRetryPolicyAlgorithmsConstant(config);
482
+ }
483
+ /** Sets the amount of random jitter added to the computed delay. */
484
+ jitter(num) {
485
+ return this._next({ jitter: num });
486
+ }
487
+ /** Sets the fixed delay interval, in milliseconds. */
488
+ interval(num) {
489
+ return this._next({ interval: num });
490
+ }
568
491
  };
569
- /** Immutable builder for the linearly-increasing retry delay algorithm. */
570
- class VigorRetryPolicyAlgorithmsLinear extends VigorStatus {
571
- constructor(config = VigorRetryPolicyAlgorithmsLinearBase) {
572
- super(VigorRetryPolicyAlgorithmsLinearBase, config);
573
- }
574
- _create(config) {
575
- return new VigorRetryPolicyAlgorithmsLinear(config);
576
- }
577
- /** Sets the amount of random jitter added to the computed delay. */
578
- jitter(num) {
579
- return this._next({ jitter: num });
580
- }
581
- /** Sets the initial delay, in milliseconds, before the first retry. */
582
- initial(num) {
583
- return this._next({ initial: num });
584
- }
585
- /** Sets how much the delay grows, in milliseconds, per attempt. */
586
- increment(num) {
587
- return this._next({ increment: num });
588
- }
589
- /** Sets the minimum allowed delay, in milliseconds. */
590
- minDelay(num) {
591
- return this._next({ minDelay: num });
592
- }
593
- /** Sets the maximum allowed delay, in milliseconds. */
594
- maxDelay(num) {
595
- return this._next({ maxDelay: num });
596
- }
597
- }
598
- const VigorRetryPolicyAlgorithmsBackoffBase = {
599
- __brand: createBrand("Retry", "Policy<Algorithms<Backoff<Schema"),
600
- _tag: "backoff",
601
- jitter: 800,
602
- initial: 0,
603
- multiplier: 1.7,
604
- unit: 1000,
605
- minDelay: 500,
606
- maxDelay: 10000,
607
- _calculateDelay: (att, config) => {
608
- const { jitter, initial, multiplier, unit, minDelay, maxDelay } = config;
609
- const range = maxDelay - minDelay;
610
- const j = Math.min(jitter, range / 2);
611
- const min = minDelay + j;
612
- const max = maxDelay - j;
613
- let delay = initial + unit * Math.pow(multiplier, att);
614
- delay = Math.max(min, Math.min(max, delay));
615
- delay += VigorJitter(j);
616
- return delay;
617
- }
492
+ var VigorRetryPolicyAlgorithmsLinearBase = {
493
+ __brand: createBrand("Retry", "Policy<Algorithms<Linear<Schema"),
494
+ _tag: "linear",
495
+ jitter: 1e3,
496
+ initial: 500,
497
+ increment: 1e3,
498
+ minDelay: 0,
499
+ maxDelay: 1e4,
500
+ _calculateDelay: (att, config) => {
501
+ const { initial, jitter, increment, minDelay, maxDelay } = config;
502
+ const range = maxDelay - minDelay;
503
+ const j = Math.min(jitter, range / 2);
504
+ const min = minDelay + j;
505
+ const max = maxDelay - j;
506
+ let delay = initial + increment * att;
507
+ delay = Math.max(min, Math.min(max, delay));
508
+ delay += VigorJitter(j);
509
+ return delay;
510
+ }
618
511
  };
619
- /** Immutable builder for the exponential-backoff retry delay algorithm. */
620
- class VigorRetryPolicyAlgorithmsBackoff extends VigorStatus {
621
- constructor(config = VigorRetryPolicyAlgorithmsBackoffBase) {
622
- super(VigorRetryPolicyAlgorithmsBackoffBase, config);
623
- }
624
- _create(config) {
625
- return new VigorRetryPolicyAlgorithmsBackoff(config);
626
- }
627
- /** Sets the amount of random jitter added to the computed delay. */
628
- jitter(num) {
629
- return this._next({ jitter: num });
630
- }
631
- /** Sets the initial delay, in milliseconds, before backoff growth is applied. */
632
- initial(num) {
633
- return this._next({ initial: num });
634
- }
635
- /** Sets the exponential growth factor applied per attempt. */
636
- multiplier(num) {
637
- return this._next({ multiplier: num });
638
- }
639
- /** Sets the base unit, in milliseconds, the multiplier is scaled by. */
640
- unit(num) {
641
- return this._next({ unit: num });
642
- }
643
- /** Sets the minimum allowed delay, in milliseconds. */
644
- minDelay(num) {
645
- return this._next({ minDelay: num });
646
- }
647
- /** Sets the maximum allowed delay, in milliseconds. */
648
- maxDelay(num) {
649
- return this._next({ maxDelay: num });
650
- }
651
- }
652
- const VigorRetryPolicyAlgorithmsCustomBase = {
653
- __brand: createBrand("Retry", "Policy<Algorithms<Custom<Schema"),
654
- _tag: "custom",
655
- jitter: 800,
656
- minDelay: 500,
657
- maxDelay: 10000,
658
- target: VigorEmpty,
659
- _calculateDelay: (att, config) => {
660
- const { jitter, minDelay, maxDelay, target } = config;
661
- if (isVigorEmpty(target))
662
- throw new VigorRetryError("VALUE_REQUIRED", {
663
- method: "_calculateDelay",
664
- data: {
665
- key: "target"
666
- }
667
- });
668
- const range = maxDelay - minDelay;
669
- const j = Math.min(jitter, range / 2);
670
- const min = minDelay + j;
671
- const max = maxDelay - j;
672
- let delay = target(att);
673
- delay = Math.max(min, Math.min(max, delay));
674
- delay += VigorJitter(j);
675
- return delay;
676
- }
512
+ var VigorRetryPolicyAlgorithmsLinear = class _VigorRetryPolicyAlgorithmsLinear extends VigorStatus {
513
+ constructor(config = VigorRetryPolicyAlgorithmsLinearBase) {
514
+ super(VigorRetryPolicyAlgorithmsLinearBase, config);
515
+ }
516
+ _create(config) {
517
+ return new _VigorRetryPolicyAlgorithmsLinear(config);
518
+ }
519
+ /** Sets the amount of random jitter added to the computed delay. */
520
+ jitter(num) {
521
+ return this._next({ jitter: num });
522
+ }
523
+ /** Sets the initial delay, in milliseconds, before the first retry. */
524
+ initial(num) {
525
+ return this._next({ initial: num });
526
+ }
527
+ /** Sets how much the delay grows, in milliseconds, per attempt. */
528
+ increment(num) {
529
+ return this._next({ increment: num });
530
+ }
531
+ /** Sets the minimum allowed delay, in milliseconds. */
532
+ minDelay(num) {
533
+ return this._next({ minDelay: num });
534
+ }
535
+ /** Sets the maximum allowed delay, in milliseconds. */
536
+ maxDelay(num) {
537
+ return this._next({ maxDelay: num });
538
+ }
539
+ };
540
+ var VigorRetryPolicyAlgorithmsBackoffBase = {
541
+ __brand: createBrand("Retry", "Policy<Algorithms<Backoff<Schema"),
542
+ _tag: "backoff",
543
+ jitter: 800,
544
+ initial: 0,
545
+ multiplier: 1.7,
546
+ unit: 1e3,
547
+ minDelay: 500,
548
+ maxDelay: 1e4,
549
+ _calculateDelay: (att, config) => {
550
+ const { jitter, initial, multiplier, unit, minDelay, maxDelay } = config;
551
+ const range = maxDelay - minDelay;
552
+ const j = Math.min(jitter, range / 2);
553
+ const min = minDelay + j;
554
+ const max = maxDelay - j;
555
+ let delay = initial + unit * Math.pow(multiplier, att);
556
+ delay = Math.max(min, Math.min(max, delay));
557
+ delay += VigorJitter(j);
558
+ return delay;
559
+ }
560
+ };
561
+ var VigorRetryPolicyAlgorithmsBackoff = class _VigorRetryPolicyAlgorithmsBackoff extends VigorStatus {
562
+ constructor(config = VigorRetryPolicyAlgorithmsBackoffBase) {
563
+ super(VigorRetryPolicyAlgorithmsBackoffBase, config);
564
+ }
565
+ _create(config) {
566
+ return new _VigorRetryPolicyAlgorithmsBackoff(config);
567
+ }
568
+ /** Sets the amount of random jitter added to the computed delay. */
569
+ jitter(num) {
570
+ return this._next({ jitter: num });
571
+ }
572
+ /** Sets the initial delay, in milliseconds, before backoff growth is applied. */
573
+ initial(num) {
574
+ return this._next({ initial: num });
575
+ }
576
+ /** Sets the exponential growth factor applied per attempt. */
577
+ multiplier(num) {
578
+ return this._next({ multiplier: num });
579
+ }
580
+ /** Sets the base unit, in milliseconds, the multiplier is scaled by. */
581
+ unit(num) {
582
+ return this._next({ unit: num });
583
+ }
584
+ /** Sets the minimum allowed delay, in milliseconds. */
585
+ minDelay(num) {
586
+ return this._next({ minDelay: num });
587
+ }
588
+ /** Sets the maximum allowed delay, in milliseconds. */
589
+ maxDelay(num) {
590
+ return this._next({ maxDelay: num });
591
+ }
592
+ };
593
+ var VigorRetryPolicyAlgorithmsCustomBase = {
594
+ __brand: createBrand("Retry", "Policy<Algorithms<Custom<Schema"),
595
+ _tag: "custom",
596
+ jitter: 800,
597
+ minDelay: 500,
598
+ maxDelay: 1e4,
599
+ target: VigorEmpty,
600
+ _calculateDelay: (att, config) => {
601
+ const { jitter, minDelay, maxDelay, target } = config;
602
+ if (isVigorEmpty(target)) throw new VigorRetryError("VALUE_REQUIRED", {
603
+ method: "_calculateDelay",
604
+ data: {
605
+ key: "target"
606
+ }
607
+ });
608
+ const range = maxDelay - minDelay;
609
+ const j = Math.min(jitter, range / 2);
610
+ const min = minDelay + j;
611
+ const max = maxDelay - j;
612
+ let delay = target(att);
613
+ delay = Math.max(min, Math.min(max, delay));
614
+ delay += VigorJitter(j);
615
+ return delay;
616
+ }
617
+ };
618
+ var VigorRetryPolicyAlgorithmsCustom = class _VigorRetryPolicyAlgorithmsCustom extends VigorStatus {
619
+ constructor(config = VigorRetryPolicyAlgorithmsCustomBase) {
620
+ super(VigorRetryPolicyAlgorithmsCustomBase, config);
621
+ }
622
+ _create(config) {
623
+ return new _VigorRetryPolicyAlgorithmsCustom(config);
624
+ }
625
+ /** Sets the amount of random jitter added to the computed delay. */
626
+ jitter(num) {
627
+ return this._next({ jitter: num });
628
+ }
629
+ /** Sets the minimum allowed delay, in milliseconds. */
630
+ minDelay(num) {
631
+ return this._next({ minDelay: num });
632
+ }
633
+ /** Sets the maximum allowed delay, in milliseconds. */
634
+ maxDelay(num) {
635
+ return this._next({ maxDelay: num });
636
+ }
637
+ /** Sets the user-supplied function computing the raw delay for an attempt. */
638
+ target(func) {
639
+ return this._next({ target: func });
640
+ }
641
+ };
642
+ var VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsConstantBase;
643
+ var VigorRetryPolicyAlgorithms = class _VigorRetryPolicyAlgorithms extends VigorStatus {
644
+ constructor(config = VigorRetryBase) {
645
+ super(VigorRetryBase, config);
646
+ }
647
+ _create(config) {
648
+ return new _VigorRetryPolicyAlgorithms(config);
649
+ }
650
+ /** Switches to the constant-interval delay algorithm. */
651
+ constant(input) {
652
+ const leaf = this._merge(VigorRetryPolicyAlgorithmsConstantBase, input ?? {});
653
+ return this._next({
654
+ policy: { algorithms: leaf }
655
+ }, { policy: { algorithms: "replace" } });
656
+ }
657
+ /** Switches to the linearly-increasing delay algorithm. */
658
+ linear(input) {
659
+ const leaf = this._merge(VigorRetryPolicyAlgorithmsLinearBase, input ?? {});
660
+ return this._next({
661
+ policy: { algorithms: leaf }
662
+ }, { policy: { algorithms: "replace" } });
663
+ }
664
+ /** Switches to the exponential-backoff delay algorithm. */
665
+ backoff(input) {
666
+ const leaf = this._merge(VigorRetryPolicyAlgorithmsBackoffBase, input ?? {});
667
+ return this._next({
668
+ policy: { algorithms: leaf }
669
+ }, { policy: { algorithms: "replace" } });
670
+ }
671
+ /** Switches to a user-supplied custom delay algorithm. */
672
+ custom(input) {
673
+ const leaf = this._merge(VigorRetryPolicyAlgorithmsCustomBase, input ?? {});
674
+ return this._next({
675
+ policy: { algorithms: leaf }
676
+ }, { policy: { algorithms: "replace" } });
677
+ }
677
678
  };
678
- /** Immutable builder for a user-supplied custom retry delay algorithm. */
679
- class VigorRetryPolicyAlgorithmsCustom extends VigorStatus {
680
- constructor(config = VigorRetryPolicyAlgorithmsCustomBase) {
681
- super(VigorRetryPolicyAlgorithmsCustomBase, config);
682
- }
683
- _create(config) {
684
- return new VigorRetryPolicyAlgorithmsCustom(config);
685
- }
686
- /** Sets the amount of random jitter added to the computed delay. */
687
- jitter(num) {
688
- return this._next({ jitter: num });
689
- }
690
- /** Sets the minimum allowed delay, in milliseconds. */
691
- minDelay(num) {
692
- return this._next({ minDelay: num });
693
- }
694
- /** Sets the maximum allowed delay, in milliseconds. */
695
- maxDelay(num) {
696
- return this._next({ maxDelay: num });
697
- }
698
- /** Sets the user-supplied function computing the raw delay for an attempt. */
699
- target(func) {
700
- return this._next({ target: func });
701
- }
702
- }
703
- const VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsConstantBase;
704
- /**
705
- * Immutable builder for selecting a retry policy's delay algorithm.
706
- *
707
- * Switching algorithms (`constant`/`linear`/`backoff`/`custom`) always
708
- * replaces the previous algorithm's config wholesale via the `"replace"`
709
- * merge strategy, since the different algorithms' fields are not
710
- * compatible with one another.
711
- */
712
- class VigorRetryPolicyAlgorithms extends VigorStatus {
713
- constructor(config = VigorRetryBase) {
714
- super(VigorRetryBase, config);
715
- }
716
- _create(config) {
717
- return new VigorRetryPolicyAlgorithms(config);
718
- }
719
- /** Switches to the constant-interval delay algorithm. */
720
- constant(input) {
721
- const leaf = this._merge(VigorRetryPolicyAlgorithmsConstantBase, input ?? {});
722
- return this._next({
723
- policy: { algorithms: leaf }
724
- }, { policy: { algorithms: "replace" } });
725
- }
726
- /** Switches to the linearly-increasing delay algorithm. */
727
- linear(input) {
728
- const leaf = this._merge(VigorRetryPolicyAlgorithmsLinearBase, input ?? {});
729
- return this._next({
730
- policy: { algorithms: leaf }
731
- }, { policy: { algorithms: "replace" } });
732
- }
733
- /** Switches to the exponential-backoff delay algorithm. */
734
- backoff(input) {
735
- const leaf = this._merge(VigorRetryPolicyAlgorithmsBackoffBase, input ?? {});
736
- return this._next({
737
- policy: { algorithms: leaf }
738
- }, { policy: { algorithms: "replace" } });
739
- }
740
- /** Switches to a user-supplied custom delay algorithm. */
741
- custom(input) {
742
- const leaf = this._merge(VigorRetryPolicyAlgorithmsCustomBase, input ?? {});
743
- return this._next({
744
- policy: { algorithms: leaf }
745
- }, { policy: { algorithms: "replace" } });
746
- }
747
- }
748
679
 
749
- const VigorRetryPolicyBase = {
750
- __brand: createBrand("Retry", "Policy<Schema"),
751
- target: VigorEmpty,
752
- abortSignals: [],
753
- settings: VigorRetryPolicySettingsBase,
754
- middlewares: VigorRetryPolicyMiddlewaresBase,
755
- algorithms: VigorRetryPolicyAlgorithmsBase
680
+ // src/retry/policy.ts
681
+ var VigorRetryPolicyBase = {
682
+ __brand: createBrand("Retry", "Policy<Schema"),
683
+ target: VigorEmpty,
684
+ abortSignals: [],
685
+ settings: VigorRetryPolicySettingsBase,
686
+ middlewares: VigorRetryPolicyMiddlewaresBase,
687
+ algorithms: VigorRetryPolicyAlgorithmsBase
756
688
  };
757
689
 
758
- const VigorRetryContextBase = {
759
- __brand: createBrand("Retry", "Context<Schema"),
760
- result: VigorDefault,
761
- error: VigorDefault,
762
- system: {
763
- delay: VigorDefault,
764
- attempt: 0
765
- },
766
- flags: {
767
- doRetry: true,
768
- doRestart: false,
769
- brokeRetry: false,
770
- overridden: false
771
- },
772
- record: {},
773
- policy: VigorRetryPolicyBase
690
+ // src/retry/context.ts
691
+ var VigorRetryContextBase = {
692
+ __brand: createBrand("Retry", "Context<Schema"),
693
+ result: VigorDefault,
694
+ error: VigorDefault,
695
+ system: {
696
+ delay: VigorDefault,
697
+ attempt: 0
698
+ },
699
+ flags: {
700
+ doRetry: true,
701
+ doRestart: false,
702
+ brokeRetry: false,
703
+ overridden: false
704
+ },
705
+ record: {},
706
+ policy: VigorRetryPolicyBase
774
707
  };
775
708
 
776
- const VigorRetryBase = {
777
- __brand: createBrand("Retry", "Schema"),
778
- policy: VigorRetryPolicyBase,
779
- context: VigorRetryContextBase
709
+ // src/retry/main.ts
710
+ var VigorRetryBase = {
711
+ __brand: createBrand("Retry", "Schema"),
712
+ policy: VigorRetryPolicyBase,
713
+ context: VigorRetryContextBase
780
714
  };
781
- /**
782
- * Immutable builder that executes a target function with retry, restart,
783
- * timeout, and abort support, driven by a configurable delay algorithm and
784
- * middleware pipeline.
785
- */
786
- class VigorRetry extends VigorStatus {
787
- constructor(config = VigorRetryBase) {
788
- super(VigorRetryBase, config);
789
- }
790
- _create(config) {
791
- return new VigorRetry(config);
792
- }
793
- /** Sets the target function to invoke, with retry/timeout applied. */
794
- target(func) {
795
- return this._next({
796
- policy: { target: func }
797
- });
798
- }
799
- /** Sets external abort signals that, when aborted, stop retrying. */
800
- abortSignals(...sig) {
801
- return this._next({
802
- policy: { abortSignals: sig }
803
- });
804
- }
805
- /** Configures the retry policy's general settings (max attempts, timeout, etc). */
806
- settings(input) {
807
- if (typeof input === 'function' || input instanceof VigorRetryPolicySettings) {
808
- const result = typeof input === 'function'
809
- ? input(new VigorRetryPolicySettings())
810
- : input;
811
- return this._next({
812
- policy: { settings: result.config.policy.settings }
813
- });
814
- }
815
- return this._next({
816
- policy: { settings: input }
817
- });
818
- }
819
- /** Configures the retry policy's middleware pipeline. */
820
- middlewares(input) {
821
- if (typeof input === 'function' || input instanceof VigorRetryPolicyMiddlewares) {
822
- const result = typeof input === 'function'
823
- ? input(new VigorRetryPolicyMiddlewares())
824
- : input;
825
- return this._next({
826
- policy: { middlewares: result.config.policy.middlewares }
827
- });
828
- }
829
- return this._next({
830
- policy: { middlewares: input }
831
- });
832
- }
833
- /** Configures the retry policy's delay algorithm. */
834
- algorithms(input) {
835
- if (typeof input === 'function') {
836
- const result = input(new VigorRetryPolicyAlgorithms());
837
- const algoSlice = result.config.policy.algorithms;
838
- return this._next({
839
- policy: { algorithms: algoSlice }
840
- }, { policy: { algorithms: "replace" } });
841
- }
842
- return this._next({
843
- policy: { algorithms: input }
844
- }, { policy: { algorithms: "replace" } });
845
- }
846
- /** Runs the target and returns its result directly, throwing on final failure. */
847
- async request() {
848
- const res = await this.requestVerbose();
849
- if (res.success)
850
- return res.data;
851
- throw res.error;
852
- }
853
- /** Runs the target and returns a result/error envelope instead of throwing. */
854
- async requestVerbose() {
855
- return await this.requestRuntime();
856
- }
857
- /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
858
- async requestRuntime(restartAttempt = 1) {
859
- const config = this._merge(this.config, {});
860
- let ctx = {
861
- ...config.context,
862
- policy: config.policy
863
- };
864
- if (isVigorEmpty(ctx.policy.target))
865
- throw new VigorRetryError("VALUE_REQUIRED", {
866
- method: "request",
867
- data: {
868
- key: "target"
869
- },
870
- context: ctx
871
- });
872
- const target = ctx.policy.target;
873
- const throwError = (err) => {
874
- throw err;
875
- };
715
+ var VigorRetry = class _VigorRetry extends VigorStatus {
716
+ constructor(config = VigorRetryBase) {
717
+ super(VigorRetryBase, config);
718
+ }
719
+ _create(config) {
720
+ return new _VigorRetry(config);
721
+ }
722
+ /** Sets the target function to invoke, with retry/timeout applied. */
723
+ target(func) {
724
+ return this._next({
725
+ policy: { target: func }
726
+ });
727
+ }
728
+ /** Sets external abort signals that, when aborted, stop retrying. */
729
+ abortSignals(...sig) {
730
+ return this._next({
731
+ policy: { abortSignals: sig }
732
+ });
733
+ }
734
+ /** Configures the retry policy's general settings (max attempts, timeout, etc). */
735
+ settings(input) {
736
+ if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
737
+ const result = typeof input === "function" ? input(new VigorRetryPolicySettings()) : input;
738
+ return this._next({
739
+ policy: { settings: result.config.policy.settings }
740
+ });
741
+ }
742
+ return this._next({
743
+ policy: { settings: input }
744
+ });
745
+ }
746
+ /** Configures the retry policy's middleware pipeline. */
747
+ middlewares(input) {
748
+ if (typeof input === "function" || input instanceof VigorRetryPolicyMiddlewares) {
749
+ const result = typeof input === "function" ? input(new VigorRetryPolicyMiddlewares()) : input;
750
+ return this._next({
751
+ policy: { middlewares: result.config.policy.middlewares }
752
+ });
753
+ }
754
+ return this._next({
755
+ policy: { middlewares: input }
756
+ });
757
+ }
758
+ /** Configures the retry policy's delay algorithm. */
759
+ algorithms(input) {
760
+ if (typeof input === "function") {
761
+ const result = input(new VigorRetryPolicyAlgorithms());
762
+ const algoSlice = result.config.policy.algorithms;
763
+ return this._next({
764
+ policy: { algorithms: algoSlice }
765
+ }, { policy: { algorithms: "replace" } });
766
+ }
767
+ return this._next({
768
+ policy: { algorithms: input }
769
+ }, { policy: { algorithms: "replace" } });
770
+ }
771
+ /** Runs the target and returns its result directly, throwing on final failure. */
772
+ async request() {
773
+ const res = await this.requestVerbose();
774
+ if (res.success) return res.data;
775
+ throw res.error;
776
+ }
777
+ /** Runs the target and returns a result/error envelope instead of throwing. */
778
+ async requestVerbose() {
779
+ return await this.requestRuntime();
780
+ }
781
+ /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
782
+ async requestRuntime(restartAttempt = 1) {
783
+ const config = this._merge(this.config, {});
784
+ let ctx = {
785
+ ...config.context,
786
+ policy: config.policy
787
+ };
788
+ if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
789
+ method: "request",
790
+ data: {
791
+ key: "target"
792
+ },
793
+ context: ctx
794
+ });
795
+ const target = ctx.policy.target;
796
+ const throwError = (err) => {
797
+ throw err;
798
+ };
799
+ try {
800
+ while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
801
+ ctx.system.attempt++;
876
802
  try {
877
- while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
878
- ctx.system.attempt++;
879
- try {
880
- const breakRetry = (err) => {
881
- ctx.flags.brokeRetry = true;
882
- throw err;
883
- };
884
- const userController = new AbortController();
885
- const timeoutController = new AbortController();
886
- const innerSignals = AbortSignal.any([
887
- userController.signal,
888
- timeoutController.signal
889
- ]);
890
- const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
891
- const autoBreak = () => {
892
- ctx.flags.brokeRetry = true;
893
- };
894
- outerSignals.addEventListener("abort", autoBreak);
895
- const mergedSignals = AbortSignal.any([
896
- innerSignals,
897
- outerSignals
898
- ]);
899
- let onAbort;
900
- let timeoutId;
901
- try {
902
- for (const middleware of ctx.policy.middlewares.before) {
903
- if (middleware._mode === "fluent") {
904
- await middleware.func(ctx);
905
- }
906
- else {
907
- ctx = await middleware.func(ctx, {
908
- abort: (reason) => userController.abort(reason),
909
- throwError,
910
- breakRetry
911
- });
912
- }
913
- }
914
- mergedSignals.throwIfAborted();
915
- timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
916
- method: "request",
917
- data: {
918
- limit: ctx.policy.settings.timeout
919
- }
920
- })), ctx.policy.settings.timeout);
921
- ctx.result = await Promise.race([
922
- target(mergedSignals),
923
- new Promise((_, rej) => {
924
- onAbort = () => rej(mergedSignals.reason);
925
- mergedSignals.addEventListener("abort", onAbort);
926
- })
927
- ]);
928
- for (const middleware of ctx.policy.middlewares.after) {
929
- if (middleware._mode === "fluent") {
930
- await middleware.func(ctx);
931
- }
932
- else {
933
- ctx = await middleware.func(ctx, {
934
- throwError
935
- });
936
- }
937
- }
938
- const setResult = (res) => {
939
- ctx.result = res;
940
- };
941
- for (const middleware of ctx.policy.middlewares.onResult) {
942
- if (middleware._mode === "fluent") {
943
- ctx.result = await middleware.func(ctx.result);
944
- }
945
- else {
946
- ctx = await middleware.func(ctx, {
947
- setResult,
948
- throwError
949
- });
950
- }
951
- }
952
- return {
953
- success: true,
954
- data: ctx.result,
955
- error: null
956
- };
957
- }
958
- finally {
959
- clearTimeout(timeoutId);
960
- outerSignals.removeEventListener("abort", autoBreak);
961
- if (onAbort)
962
- mergedSignals.removeEventListener("abort", onAbort);
963
- }
964
- }
965
- catch (error) {
966
- ctx.error = error;
967
- if (ctx.flags.brokeRetry)
968
- throw ctx.error;
969
- ctx.flags.doRetry = true;
970
- const proceedRetry = () => ctx.flags.doRetry = true;
971
- const cancelRetry = () => ctx.flags.doRetry = false;
972
- for (const middleware of ctx.policy.middlewares.retryIf) {
973
- if (middleware._mode === "fluent") {
974
- ctx.flags.doRetry = await middleware.func(ctx.error);
975
- }
976
- else {
977
- ctx = await middleware.func(ctx, {
978
- proceedRetry,
979
- cancelRetry
980
- });
981
- }
982
- }
983
- if (!ctx.flags.doRetry)
984
- throw ctx.error;
985
- ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
986
- const setDelay = (num) => {
987
- ctx.system.delay = num;
988
- };
989
- for (const middleware of ctx.policy.middlewares.onRetry) {
990
- if (middleware._mode === "fluent") {
991
- await middleware.func(ctx.error);
992
- }
993
- else {
994
- ctx = await middleware.func(ctx, {
995
- throwError,
996
- setDelay
997
- });
998
- }
999
- }
1000
- const delay = ctx.system.delay;
1001
- await new Promise(res => setTimeout(res, delay));
1002
- }
803
+ const breakRetry = (err) => {
804
+ ctx.flags.brokeRetry = true;
805
+ throw err;
806
+ };
807
+ const userController = new AbortController();
808
+ const timeoutController = new AbortController();
809
+ const innerSignals = AbortSignal.any([
810
+ userController.signal,
811
+ timeoutController.signal
812
+ ]);
813
+ const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
814
+ const autoBreak = () => {
815
+ ctx.flags.brokeRetry = true;
816
+ };
817
+ outerSignals.addEventListener("abort", autoBreak);
818
+ const mergedSignals = AbortSignal.any([
819
+ innerSignals,
820
+ outerSignals
821
+ ]);
822
+ let onAbort;
823
+ let timeoutId;
824
+ try {
825
+ for (const middleware of ctx.policy.middlewares.before) {
826
+ if (middleware._mode === "fluent") {
827
+ await middleware.func(ctx);
828
+ } else {
829
+ ctx = await middleware.func(ctx, {
830
+ abort: (reason) => userController.abort(reason),
831
+ throwError,
832
+ breakRetry
833
+ });
834
+ }
835
+ }
836
+ mergedSignals.throwIfAborted();
837
+ timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
838
+ method: "request",
839
+ data: {
840
+ limit: ctx.policy.settings.timeout
841
+ }
842
+ })), ctx.policy.settings.timeout);
843
+ ctx.result = await Promise.race([
844
+ target(mergedSignals),
845
+ new Promise((_, rej) => {
846
+ onAbort = () => rej(mergedSignals.reason);
847
+ mergedSignals.addEventListener("abort", onAbort);
848
+ })
849
+ ]);
850
+ for (const middleware of ctx.policy.middlewares.after) {
851
+ if (middleware._mode === "fluent") {
852
+ await middleware.func(ctx);
853
+ } else {
854
+ ctx = await middleware.func(ctx, {
855
+ throwError
856
+ });
857
+ }
1003
858
  }
1004
- throw new VigorRetryError("RETRY_EXHAUSTED", {
1005
- method: "request",
1006
- cause: ctx.error,
1007
- data: {
1008
- maxAttempts: ctx.policy.settings.maxAttempts,
1009
- error: ctx.error
1010
- }
1011
- });
1012
- }
1013
- catch (error) {
1014
- ctx.error = error;
1015
- ctx.flags.doRestart = false;
1016
- ctx.flags.overridden = false;
1017
859
  const setResult = (res) => {
1018
- ctx.flags.overridden = true;
1019
- ctx.result = res;
860
+ ctx.result = res;
1020
861
  };
1021
- const proceedRestart = () => ctx.flags.doRestart = true;
1022
- const cancelRestart = () => ctx.flags.doRestart = false;
1023
- for (const middleware of ctx.policy.middlewares.onError) {
1024
- if (middleware._mode === "fluent") {
1025
- await middleware.func(ctx.error);
1026
- }
1027
- else {
1028
- ctx = await middleware.func(ctx, {
1029
- setResult,
1030
- throwError,
1031
- proceedRestart,
1032
- cancelRestart
1033
- });
1034
- }
1035
- }
1036
- if (ctx.flags.doRestart) {
1037
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1038
- throw new VigorRetryError("RESTART_EXHAUSTED", {
1039
- method: "request",
1040
- cause: ctx.error,
1041
- data: {
1042
- maxAttempts: ctx.policy.settings.maxRestarts,
1043
- error: ctx.error
1044
- }
1045
- });
1046
- return await this.requestRuntime(restartAttempt + 1);
1047
- }
1048
- if (ctx.flags.overridden)
1049
- return {
1050
- success: true,
1051
- data: ctx.result,
1052
- error: null
1053
- };
1054
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1055
- const data = await ctx.policy.settings.default(ctx);
1056
- return {
1057
- success: true,
1058
- data,
1059
- error: null
1060
- };
862
+ for (const middleware of ctx.policy.middlewares.onResult) {
863
+ if (middleware._mode === "fluent") {
864
+ ctx.result = await middleware.func(ctx.result);
865
+ } else {
866
+ ctx = await middleware.func(ctx, {
867
+ setResult,
868
+ throwError
869
+ });
870
+ }
1061
871
  }
1062
872
  return {
1063
- success: false,
1064
- data: null,
1065
- error: ctx.error
873
+ success: true,
874
+ data: ctx.result,
875
+ error: null
1066
876
  };
877
+ } finally {
878
+ clearTimeout(timeoutId);
879
+ outerSignals.removeEventListener("abort", autoBreak);
880
+ if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
881
+ }
882
+ } catch (error) {
883
+ ctx.error = error;
884
+ if (ctx.flags.brokeRetry) throw ctx.error;
885
+ ctx.flags.doRetry = true;
886
+ const proceedRetry = () => ctx.flags.doRetry = true;
887
+ const cancelRetry = () => ctx.flags.doRetry = false;
888
+ for (const middleware of ctx.policy.middlewares.retryIf) {
889
+ if (middleware._mode === "fluent") {
890
+ ctx.flags.doRetry = await middleware.func(ctx.error);
891
+ } else {
892
+ ctx = await middleware.func(ctx, {
893
+ proceedRetry,
894
+ cancelRetry
895
+ });
896
+ }
897
+ }
898
+ if (!ctx.flags.doRetry) throw ctx.error;
899
+ ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
900
+ const setDelay = (num) => {
901
+ ctx.system.delay = num;
902
+ };
903
+ for (const middleware of ctx.policy.middlewares.onRetry) {
904
+ if (middleware._mode === "fluent") {
905
+ await middleware.func(ctx.error);
906
+ } else {
907
+ ctx = await middleware.func(ctx, {
908
+ throwError,
909
+ setDelay
910
+ });
911
+ }
912
+ }
913
+ const delay = ctx.system.delay;
914
+ await new Promise((res) => setTimeout(res, delay));
1067
915
  }
1068
- }
1069
- }
916
+ }
917
+ throw new VigorRetryError("RETRY_EXHAUSTED", {
918
+ method: "request",
919
+ cause: ctx.error,
920
+ data: {
921
+ maxAttempts: ctx.policy.settings.maxAttempts,
922
+ error: ctx.error
923
+ }
924
+ });
925
+ } catch (error) {
926
+ ctx.error = error;
927
+ ctx.flags.doRestart = false;
928
+ ctx.flags.overridden = false;
929
+ const setResult = (res) => {
930
+ ctx.flags.overridden = true;
931
+ ctx.result = res;
932
+ };
933
+ const proceedRestart = () => ctx.flags.doRestart = true;
934
+ const cancelRestart = () => ctx.flags.doRestart = false;
935
+ for (const middleware of ctx.policy.middlewares.onError) {
936
+ if (middleware._mode === "fluent") {
937
+ await middleware.func(ctx.error);
938
+ } else {
939
+ ctx = await middleware.func(ctx, {
940
+ setResult,
941
+ throwError,
942
+ proceedRestart,
943
+ cancelRestart
944
+ });
945
+ }
946
+ }
947
+ if (ctx.flags.doRestart) {
948
+ if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
949
+ method: "request",
950
+ cause: ctx.error,
951
+ data: {
952
+ maxAttempts: ctx.policy.settings.maxRestarts,
953
+ error: ctx.error
954
+ }
955
+ });
956
+ return await this.requestRuntime(restartAttempt + 1);
957
+ }
958
+ if (ctx.flags.overridden) return {
959
+ success: true,
960
+ data: ctx.result,
961
+ error: null
962
+ };
963
+ if (!isVigorEmpty(ctx.policy.settings.default)) {
964
+ const data = await ctx.policy.settings.default(ctx);
965
+ return {
966
+ success: true,
967
+ data,
968
+ error: null
969
+ };
970
+ }
971
+ return {
972
+ success: false,
973
+ data: null,
974
+ error: ctx.error
975
+ };
976
+ }
977
+ }
978
+ };
1070
979
 
1071
- const VigorParsePolicySettingsBase = {
1072
- __brand: createBrand("Parse", "Policy<Settings<Schema"),
1073
- raw: false,
1074
- default: VigorEmpty,
1075
- maxRestarts: 3
980
+ // src/parse/settings.ts
981
+ var VigorParsePolicySettingsBase = {
982
+ __brand: createBrand("Parse", "Policy<Settings<Schema"),
983
+ raw: false,
984
+ default: VigorEmpty,
985
+ maxRestarts: 3
986
+ };
987
+ var VigorParsePolicySettings = class _VigorParsePolicySettings extends VigorStatus {
988
+ constructor(config = VigorParseBase) {
989
+ super(VigorParseBase, config);
990
+ }
991
+ _create(config) {
992
+ return new _VigorParsePolicySettings(config);
993
+ }
994
+ /** When enabled, skips content-type based parsing and returns the raw response. */
995
+ raw(bool) {
996
+ return this._next({
997
+ policy: { settings: { raw: bool } }
998
+ });
999
+ }
1000
+ /** Sets the fallback value/factory used when parsing ultimately fails. */
1001
+ default(func) {
1002
+ return this._next({
1003
+ policy: { settings: { default: func } }
1004
+ });
1005
+ }
1006
+ /** Sets the maximum number of full restarts allowed. */
1007
+ maxRestarts(num) {
1008
+ return this._next({
1009
+ policy: { settings: { maxRestarts: num } }
1010
+ });
1011
+ }
1076
1012
  };
1077
- /** Immutable builder for a parse policy's general settings. */
1078
- class VigorParsePolicySettings extends VigorStatus {
1079
- constructor(config = VigorParseBase) {
1080
- super(VigorParseBase, config);
1081
- }
1082
- _create(config) {
1083
- return new VigorParsePolicySettings(config);
1084
- }
1085
- /** When enabled, skips content-type based parsing and returns the raw response. */
1086
- raw(bool) {
1087
- return this._next({
1088
- policy: { settings: { raw: bool } }
1089
- });
1090
- }
1091
- /** Sets the fallback value/factory used when parsing ultimately fails. */
1092
- default(func) {
1093
- return this._next({
1094
- policy: { settings: { default: func } }
1095
- });
1096
- }
1097
- /** Sets the maximum number of full restarts allowed. */
1098
- maxRestarts(num) {
1099
- return this._next({
1100
- policy: { settings: { maxRestarts: num } }
1101
- });
1102
- }
1103
- }
1104
1013
 
1105
- const VigorParsePolicyMiddlewaresBase = {
1106
- __brand: createBrand("Parse", "Policy<Middlewares<Schema"),
1107
- before: [],
1108
- after: [],
1109
- onResult: [],
1110
- onError: []
1014
+ // src/parse/middlewares.ts
1015
+ var VigorParsePolicyMiddlewaresBase = {
1016
+ __brand: createBrand("Parse", "Policy<Middlewares<Schema"),
1017
+ before: [],
1018
+ after: [],
1019
+ onResult: [],
1020
+ onError: []
1021
+ };
1022
+ var VigorParsePolicyMiddlewares = class _VigorParsePolicyMiddlewares extends VigorStatus {
1023
+ constructor(config = VigorParseBase) {
1024
+ super(VigorParseBase, config);
1025
+ }
1026
+ _create(config) {
1027
+ return new _VigorParsePolicyMiddlewares(config);
1028
+ }
1029
+ before(type, func) {
1030
+ return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
1031
+ }
1032
+ after(type, func) {
1033
+ return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
1034
+ }
1035
+ onResult(type, func) {
1036
+ return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
1037
+ }
1038
+ onError(type, func) {
1039
+ return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
1040
+ }
1111
1041
  };
1112
- /**
1113
- * Immutable builder for a parse policy's middleware pipeline (`before`,
1114
- * `after`, `onResult`, `onError`). Each stage accepts either "fluent"
1115
- * middleware (returns a plain value merged into the context) or
1116
- * "intercept" middleware (receives an explicit API to mutate control flow).
1117
- */
1118
- class VigorParsePolicyMiddlewares extends VigorStatus {
1119
- constructor(config = VigorParseBase) {
1120
- super(VigorParseBase, config);
1121
- }
1122
- _create(config) {
1123
- return new VigorParsePolicyMiddlewares(config);
1124
- }
1125
- before(type, func) {
1126
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
1127
- }
1128
- after(type, func) {
1129
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
1130
- }
1131
- onResult(type, func) {
1132
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
1133
- }
1134
- onError(type, func) {
1135
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
1136
- }
1137
- }
1138
1042
 
1139
- const VigorParseErrorMessageFuncs = {
1140
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1141
- INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1142
- PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1143
- PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1144
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1043
+ // src/parse/error.ts
1044
+ var VigorParseErrorMessageFuncs = {
1045
+ VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1046
+ INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1047
+ PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1048
+ PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1049
+ RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1050
+ };
1051
+ var VigorParseError = class extends VigorError {
1052
+ /**
1053
+ * @param code - One of the parse module's error codes.
1054
+ * @param options - Error metadata, including the `data` payload for `code`.
1055
+ */
1056
+ constructor(code, options) {
1057
+ const messageFn = VigorParseErrorMessageFuncs[code];
1058
+ super(code, messageFn(options.data), options);
1059
+ }
1145
1060
  };
1146
- /** Error type thrown by the parse module. */
1147
- class VigorParseError extends VigorError {
1148
- /**
1149
- * @param code - One of the parse module's error codes.
1150
- * @param options - Error metadata, including the `data` payload for `code`.
1151
- */
1152
- constructor(code, options) {
1153
- const messageFn = VigorParseErrorMessageFuncs[code];
1154
- super(code, messageFn(options.data), options);
1155
- }
1156
- }
1157
1061
 
1158
- const VigorParsePolicyStrategiesBase = {
1159
- __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1160
- funcs: []
1062
+ // src/parse/strategies.ts
1063
+ var VigorParsePolicyStrategiesBase = {
1064
+ __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1065
+ funcs: []
1161
1066
  };
1162
- const ContentTypeParsers = [
1163
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1164
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1165
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1166
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1167
- { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1168
- { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1169
- { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1170
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1171
- { header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() },
1067
+ var ContentTypeParsers = [
1068
+ { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1069
+ { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1070
+ { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1071
+ { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1072
+ { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1073
+ { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1074
+ { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1075
+ { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1076
+ { header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() }
1172
1077
  ];
1173
- const SniffMethods = [
1174
- { title: "json", method: (res) => res.json() },
1175
- { title: "formData", method: (res) => res.formData() },
1176
- { title: "text", method: (res) => res.text() },
1177
- { title: "blob", method: (res) => res.blob() },
1078
+ var SniffMethods = [
1079
+ { title: "json", method: (res) => res.json() },
1080
+ { title: "formData", method: (res) => res.formData() },
1081
+ { title: "text", method: (res) => res.text() },
1082
+ { title: "blob", method: (res) => res.blob() }
1178
1083
  ];
1179
- /** Parses a response by matching its `Content-Type` header against a known parser table. */
1180
- const VigorParseContentTypeStrategy = async (response) => {
1181
- const contentTypeHeader = response.headers.get("content-type");
1182
- if (!contentTypeHeader)
1183
- throw new VigorParseError("INVALID_CONTENT_TYPE", {
1184
- method: "VigorParseContentTypeStrategy",
1185
- data: { received: contentTypeHeader }
1186
- });
1187
- const toDo = ContentTypeParsers.find(parser => parser.regExp.test(contentTypeHeader));
1188
- if (!toDo)
1189
- throw new VigorParseError("PARSER_NOT_FOUND", {
1190
- method: "VigorParseContentTypeStrategy",
1191
- data: {
1192
- expected: ContentTypeParsers.map(p => p.header),
1193
- received: contentTypeHeader
1194
- }
1195
- });
1196
- return await toDo.method(response);
1084
+ var VigorParseContentTypeStrategy = async (response) => {
1085
+ const contentTypeHeader = response.headers.get("content-type");
1086
+ if (!contentTypeHeader) throw new VigorParseError("INVALID_CONTENT_TYPE", {
1087
+ method: "VigorParseContentTypeStrategy",
1088
+ data: { received: contentTypeHeader }
1089
+ });
1090
+ const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
1091
+ if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
1092
+ method: "VigorParseContentTypeStrategy",
1093
+ data: {
1094
+ expected: ContentTypeParsers.map((p) => p.header),
1095
+ received: contentTypeHeader
1096
+ }
1097
+ });
1098
+ return await toDo.method(response);
1197
1099
  };
1198
- /** Parses a response by trying a sequence of body-reading methods until one succeeds. */
1199
- const VigorParseSniffStrategy = async (response) => {
1200
- for (const [i, parser] of SniffMethods.entries()) {
1201
- const cloned = (i === SniffMethods.length - 1) ? response : response.clone();
1202
- try {
1203
- return await parser.method(cloned);
1204
- }
1205
- catch { }
1206
- }
1207
- throw new VigorParseError("PARSER_ALL_FAILED", {
1208
- method: "VigorParseSniffStrategy",
1209
- data: { tried: SniffMethods.map(p => p.title) }
1210
- });
1100
+ var VigorParseSniffStrategy = async (response) => {
1101
+ for (const [i, parser] of SniffMethods.entries()) {
1102
+ const cloned = i === SniffMethods.length - 1 ? response : response.clone();
1103
+ try {
1104
+ return await parser.method(cloned);
1105
+ } catch {
1106
+ }
1107
+ }
1108
+ throw new VigorParseError("PARSER_ALL_FAILED", {
1109
+ method: "VigorParseSniffStrategy",
1110
+ data: { tried: SniffMethods.map((p) => p.title) }
1111
+ });
1112
+ };
1113
+ var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends VigorStatus {
1114
+ constructor(config = VigorParseBase) {
1115
+ super(VigorParseBase, config);
1116
+ }
1117
+ _create(config) {
1118
+ return new _VigorParsePolicyStrategies(config);
1119
+ }
1120
+ /**
1121
+ * Adds strategy functions to the fallback chain.
1122
+ *
1123
+ * @param replace - When `true`, replaces the existing chain instead of
1124
+ * appending to it (the default is to concat, since strategies are
1125
+ * tried in sequence as a fallback chain).
1126
+ */
1127
+ _set(funcs, replace) {
1128
+ return this._next(
1129
+ { policy: { strategies: { funcs } } },
1130
+ replace ? { policy: { strategies: { funcs: "replace" } } } : void 0
1131
+ );
1132
+ }
1133
+ /** Adds the content-type based parsing strategy. */
1134
+ contentType(replace) {
1135
+ return this._set([VigorParseContentTypeStrategy], replace);
1136
+ }
1137
+ /** Adds the sniffing (try-each-method) parsing strategy. */
1138
+ sniff(replace) {
1139
+ return this._set([VigorParseSniffStrategy], replace);
1140
+ }
1141
+ /** Adds a strategy that always parses the response as JSON. */
1142
+ json(replace) {
1143
+ return this._set([(res) => res.json()], replace);
1144
+ }
1145
+ /** Adds a strategy that always parses the response as text. */
1146
+ text(replace) {
1147
+ return this._set([(res) => res.text()], replace);
1148
+ }
1149
+ /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1150
+ arrayBuffer(replace) {
1151
+ return this._set([(res) => res.arrayBuffer()], replace);
1152
+ }
1153
+ /** Adds a strategy that always parses the response as a `Blob`. */
1154
+ blob(replace) {
1155
+ return this._set([(res) => res.blob()], replace);
1156
+ }
1157
+ /** Adds a strategy that always parses the response as a `Uint8Array`. */
1158
+ bytes(replace) {
1159
+ return this._set([(res) => res.arrayBuffer().then((b) => new Uint8Array(b))], replace);
1160
+ }
1161
+ /** Adds a strategy that always parses the response as `FormData`. */
1162
+ formData(replace) {
1163
+ return this._set([(res) => res.formData()], replace);
1164
+ }
1165
+ /** Adds a user-supplied custom parsing strategy. */
1166
+ custom(func, replace) {
1167
+ return this._set([func], replace);
1168
+ }
1211
1169
  };
1212
- /** Immutable builder for a parse policy's fallback chain of parsing strategies. */
1213
- class VigorParsePolicyStrategies extends VigorStatus {
1214
- constructor(config = VigorParseBase) {
1215
- super(VigorParseBase, config);
1216
- }
1217
- _create(config) {
1218
- return new VigorParsePolicyStrategies(config);
1219
- }
1220
- /**
1221
- * Adds strategy functions to the fallback chain.
1222
- *
1223
- * @param replace - When `true`, replaces the existing chain instead of
1224
- * appending to it (the default is to concat, since strategies are
1225
- * tried in sequence as a fallback chain).
1226
- */
1227
- _set(funcs, replace) {
1228
- return this._next({ policy: { strategies: { funcs } } }, replace ? { policy: { strategies: { funcs: "replace" } } } : undefined);
1229
- }
1230
- /** Adds the content-type based parsing strategy. */
1231
- contentType(replace) { return this._set([VigorParseContentTypeStrategy], replace); }
1232
- /** Adds the sniffing (try-each-method) parsing strategy. */
1233
- sniff(replace) { return this._set([VigorParseSniffStrategy], replace); }
1234
- /** Adds a strategy that always parses the response as JSON. */
1235
- json(replace) { return this._set([(res) => res.json()], replace); }
1236
- /** Adds a strategy that always parses the response as text. */
1237
- text(replace) { return this._set([(res) => res.text()], replace); }
1238
- /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1239
- arrayBuffer(replace) { return this._set([(res) => res.arrayBuffer()], replace); }
1240
- /** Adds a strategy that always parses the response as a `Blob`. */
1241
- blob(replace) { return this._set([(res) => res.blob()], replace); }
1242
- /** Adds a strategy that always parses the response as a `Uint8Array`. */
1243
- bytes(replace) { return this._set([(res) => res.arrayBuffer().then(b => new Uint8Array(b))], replace); }
1244
- /** Adds a strategy that always parses the response as `FormData`. */
1245
- formData(replace) { return this._set([(res) => res.formData()], replace); }
1246
- /** Adds a user-supplied custom parsing strategy. */
1247
- custom(func, replace) { return this._set([func], replace); }
1248
- }
1249
1170
 
1250
- const VigorParsePolicyBase = {
1251
- __brand: createBrand("Parse", "Policy<Schema"),
1252
- target: VigorDefault,
1253
- settings: VigorParsePolicySettingsBase,
1254
- middlewares: VigorParsePolicyMiddlewaresBase,
1255
- strategies: VigorParsePolicyStrategiesBase
1171
+ // src/parse/policy.ts
1172
+ var VigorParsePolicyBase = {
1173
+ __brand: createBrand("Parse", "Policy<Schema"),
1174
+ target: VigorDefault,
1175
+ settings: VigorParsePolicySettingsBase,
1176
+ middlewares: VigorParsePolicyMiddlewaresBase,
1177
+ strategies: VigorParsePolicyStrategiesBase
1256
1178
  };
1257
1179
 
1258
- const VigorParseContextBase = {
1259
- __brand: createBrand("Parse", "Context<Schema"),
1260
- result: VigorDefault,
1261
- error: VigorDefault,
1262
- response: VigorDefault,
1263
- flags: {
1264
- overrided: false,
1265
- restarted: false
1266
- },
1267
- record: {},
1268
- policy: VigorParsePolicyBase
1180
+ // src/parse/context.ts
1181
+ var VigorParseContextBase = {
1182
+ __brand: createBrand("Parse", "Context<Schema"),
1183
+ result: VigorDefault,
1184
+ error: VigorDefault,
1185
+ response: VigorDefault,
1186
+ flags: {
1187
+ overrided: false,
1188
+ restarted: false
1189
+ },
1190
+ record: {},
1191
+ policy: VigorParsePolicyBase
1269
1192
  };
1270
1193
 
1271
- const VigorParseBase = {
1272
- __brand: createBrand("Parse", "Schema"),
1273
- policy: VigorParsePolicyBase,
1274
- context: VigorParseContextBase
1194
+ // src/parse/main.ts
1195
+ var VigorParseBase = {
1196
+ __brand: createBrand("Parse", "Schema"),
1197
+ policy: VigorParsePolicyBase,
1198
+ context: VigorParseContextBase
1275
1199
  };
1276
- /**
1277
- * Immutable builder that parses an HTTP response into a result value,
1278
- * trying each configured strategy in sequence with an optional middleware
1279
- * pipeline and restart-on-failure support.
1280
- */
1281
- class VigorParse extends VigorStatus {
1282
- constructor(config = VigorParseBase) {
1283
- super(VigorParseBase, config);
1284
- }
1285
- _create(config) {
1286
- return new VigorParse(config);
1287
- }
1288
- /** Sets the `Response` object to parse. */
1289
- target(response) {
1290
- return this._next({ policy: { target: response } });
1291
- }
1292
- /** Configures the parse policy's general settings. */
1293
- settings(input) {
1294
- if (typeof input === 'function' || input instanceof VigorParsePolicySettings) {
1295
- const result = typeof input === 'function'
1296
- ? input(new VigorParsePolicySettings())
1297
- : input;
1298
- return this._next({
1299
- policy: { settings: result.config.policy.settings }
1300
- });
1200
+ var VigorParse = class _VigorParse extends VigorStatus {
1201
+ constructor(config = VigorParseBase) {
1202
+ super(VigorParseBase, config);
1203
+ }
1204
+ _create(config) {
1205
+ return new _VigorParse(config);
1206
+ }
1207
+ /** Sets the `Response` object to parse. */
1208
+ target(response) {
1209
+ return this._next({ policy: { target: response } });
1210
+ }
1211
+ /** Configures the parse policy's general settings. */
1212
+ settings(input) {
1213
+ if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
1214
+ const result = typeof input === "function" ? input(new VigorParsePolicySettings()) : input;
1215
+ return this._next({
1216
+ policy: { settings: result.config.policy.settings }
1217
+ });
1218
+ }
1219
+ return this._next({ policy: { settings: input } });
1220
+ }
1221
+ /** Configures the parse policy's middleware pipeline. */
1222
+ middlewares(input) {
1223
+ if (typeof input === "function" || input instanceof VigorParsePolicyMiddlewares) {
1224
+ const result = typeof input === "function" ? input(new VigorParsePolicyMiddlewares()) : input;
1225
+ return this._next({
1226
+ policy: { middlewares: result.config.policy.middlewares }
1227
+ });
1228
+ }
1229
+ return this._next({ policy: { middlewares: input } });
1230
+ }
1231
+ /** Configures the parse policy's fallback chain of parsing strategies. */
1232
+ strategies(input) {
1233
+ if (typeof input === "function" || input instanceof VigorParsePolicyStrategies) {
1234
+ const result = typeof input === "function" ? input(new VigorParsePolicyStrategies()) : input;
1235
+ return this._next({
1236
+ policy: { strategies: result.config.policy.strategies }
1237
+ });
1238
+ }
1239
+ return this._next({ policy: { strategies: input } });
1240
+ }
1241
+ /** Runs parsing and returns the result directly, throwing on final failure. */
1242
+ async request() {
1243
+ const res = await this.requestVerbose();
1244
+ if (res.success) return res.data;
1245
+ throw res.error;
1246
+ }
1247
+ /** Runs parsing and returns a result/error envelope instead of throwing. */
1248
+ async requestVerbose() {
1249
+ return await this.requestRuntime();
1250
+ }
1251
+ /** Internal execution loop implementing the strategy fallback and restart handling. */
1252
+ async requestRuntime(restartAttempt = 1) {
1253
+ const config = this._merge(this.config, {});
1254
+ let ctx = {
1255
+ ...config.context,
1256
+ policy: config.policy
1257
+ };
1258
+ if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1259
+ method: "request",
1260
+ data: { key: "target" },
1261
+ context: ctx
1262
+ });
1263
+ ctx.response = ctx.policy.target;
1264
+ const throwError = (err) => {
1265
+ throw err;
1266
+ };
1267
+ try {
1268
+ for (const middleware of ctx.policy.middlewares.before) {
1269
+ if (middleware._mode === "fluent") {
1270
+ await middleware.func(ctx);
1271
+ } else {
1272
+ ctx = await middleware.func(ctx, { throwError });
1301
1273
  }
1302
- return this._next({ policy: { settings: input } });
1303
- }
1304
- /** Configures the parse policy's middleware pipeline. */
1305
- middlewares(input) {
1306
- if (typeof input === 'function' || input instanceof VigorParsePolicyMiddlewares) {
1307
- const result = typeof input === 'function'
1308
- ? input(new VigorParsePolicyMiddlewares())
1309
- : input;
1310
- return this._next({
1311
- policy: { middlewares: result.config.policy.middlewares }
1312
- });
1274
+ }
1275
+ const response = ctx.response;
1276
+ if (ctx.policy.settings.raw) {
1277
+ ctx.result = response;
1278
+ } else {
1279
+ const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
1280
+ let parsed = false;
1281
+ for (const [i, func] of funcs.entries()) {
1282
+ const cloned = i === funcs.length - 1 ? response : response.clone();
1283
+ try {
1284
+ ctx.result = await func(cloned);
1285
+ parsed = true;
1286
+ break;
1287
+ } catch {
1288
+ }
1313
1289
  }
1314
- return this._next({ policy: { middlewares: input } });
1315
- }
1316
- /** Configures the parse policy's fallback chain of parsing strategies. */
1317
- strategies(input) {
1318
- if (typeof input === 'function' || input instanceof VigorParsePolicyStrategies) {
1319
- const result = typeof input === 'function'
1320
- ? input(new VigorParsePolicyStrategies())
1321
- : input;
1322
- return this._next({
1323
- policy: { strategies: result.config.policy.strategies }
1324
- });
1290
+ if (!parsed) throw new VigorParseError("PARSER_ALL_FAILED", {
1291
+ method: "request",
1292
+ data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1293
+ context: ctx
1294
+ });
1295
+ }
1296
+ const setResult = (res) => {
1297
+ ctx.result = res;
1298
+ };
1299
+ for (const middleware of ctx.policy.middlewares.after) {
1300
+ if (middleware._mode === "fluent") {
1301
+ await middleware.func(ctx);
1302
+ } else {
1303
+ ctx = await middleware.func(ctx, { setResult, throwError });
1325
1304
  }
1326
- return this._next({ policy: { strategies: input } });
1327
- }
1328
- /** Runs parsing and returns the result directly, throwing on final failure. */
1329
- async request() {
1330
- const res = await this.requestVerbose();
1331
- if (res.success)
1332
- return res.data;
1333
- throw res.error;
1334
- }
1335
- /** Runs parsing and returns a result/error envelope instead of throwing. */
1336
- async requestVerbose() {
1337
- return await this.requestRuntime();
1338
- }
1339
- /** Internal execution loop implementing the strategy fallback and restart handling. */
1340
- async requestRuntime(restartAttempt = 1) {
1341
- const config = this._merge(this.config, {});
1342
- let ctx = {
1343
- ...config.context,
1344
- policy: config.policy
1345
- };
1346
- if (isVigorDefault(ctx.policy.target))
1347
- throw new VigorParseError("VALUE_REQUIRED", {
1348
- method: "request",
1349
- data: { key: "target" },
1350
- context: ctx
1351
- });
1352
- ctx.response = ctx.policy.target;
1353
- const throwError = (err) => { throw err; };
1354
- try {
1355
- for (const middleware of ctx.policy.middlewares.before) {
1356
- if (middleware._mode === "fluent") {
1357
- await middleware.func(ctx);
1358
- }
1359
- else {
1360
- ctx = await middleware.func(ctx, { throwError });
1361
- }
1362
- }
1363
- const response = ctx.response;
1364
- if (ctx.policy.settings.raw) {
1365
- ctx.result = response;
1366
- }
1367
- else {
1368
- const funcs = ctx.policy.strategies.funcs.length > 0
1369
- ? ctx.policy.strategies.funcs
1370
- : [VigorParseContentTypeStrategy];
1371
- let parsed = false;
1372
- for (const [i, func] of funcs.entries()) {
1373
- const cloned = (i === funcs.length - 1) ? response : response.clone();
1374
- try {
1375
- ctx.result = await func(cloned);
1376
- parsed = true;
1377
- break;
1378
- }
1379
- catch { }
1380
- }
1381
- if (!parsed)
1382
- throw new VigorParseError("PARSER_ALL_FAILED", {
1383
- method: "request",
1384
- data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1385
- context: ctx
1386
- });
1387
- }
1388
- const setResult = (res) => { ctx.result = res; };
1389
- for (const middleware of ctx.policy.middlewares.after) {
1390
- if (middleware._mode === "fluent") {
1391
- await middleware.func(ctx);
1392
- }
1393
- else {
1394
- ctx = await middleware.func(ctx, { setResult, throwError });
1395
- }
1396
- }
1397
- for (const middleware of ctx.policy.middlewares.onResult) {
1398
- if (middleware._mode === "fluent") {
1399
- ctx.result = await middleware.func(ctx.result);
1400
- }
1401
- else {
1402
- ctx = await middleware.func(ctx, { setResult, throwError });
1403
- }
1404
- }
1405
- return {
1406
- success: true,
1407
- data: ctx.result,
1408
- error: null
1409
- };
1305
+ }
1306
+ for (const middleware of ctx.policy.middlewares.onResult) {
1307
+ if (middleware._mode === "fluent") {
1308
+ ctx.result = await middleware.func(ctx.result);
1309
+ } else {
1310
+ ctx = await middleware.func(ctx, { setResult, throwError });
1410
1311
  }
1411
- catch (error) {
1412
- ctx.error = error;
1413
- ctx.flags.overrided = false;
1414
- ctx.flags.restarted = false;
1415
- const setResult = (res) => {
1416
- ctx.flags.overrided = true;
1417
- ctx.result = res;
1418
- };
1419
- const proceedRestart = () => ctx.flags.restarted = true;
1420
- const cancelRestart = () => ctx.flags.restarted = false;
1421
- for (const middleware of ctx.policy.middlewares.onError) {
1422
- if (middleware._mode === "fluent") {
1423
- await middleware.func(ctx.error);
1424
- }
1425
- else {
1426
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1427
- }
1428
- }
1429
- if (ctx.flags.restarted) {
1430
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1431
- throw new VigorParseError("RESTART_EXHAUSTED", {
1432
- method: "request",
1433
- cause: ctx.error,
1434
- data: {
1435
- maxAttempts: ctx.policy.settings.maxRestarts,
1436
- error: ctx.error
1437
- }
1438
- });
1439
- return await this.requestRuntime(restartAttempt + 1);
1440
- }
1441
- if (ctx.flags.overrided)
1442
- return {
1443
- success: true,
1444
- data: ctx.result,
1445
- error: null
1446
- };
1447
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1448
- const data = await ctx.policy.settings.default(ctx);
1449
- return {
1450
- success: true,
1451
- data,
1452
- error: null
1453
- };
1454
- }
1455
- return {
1456
- success: false,
1457
- data: null,
1458
- error: ctx.error
1459
- };
1312
+ }
1313
+ return {
1314
+ success: true,
1315
+ data: ctx.result,
1316
+ error: null
1317
+ };
1318
+ } catch (error) {
1319
+ ctx.error = error;
1320
+ ctx.flags.overrided = false;
1321
+ ctx.flags.restarted = false;
1322
+ const setResult = (res) => {
1323
+ ctx.flags.overrided = true;
1324
+ ctx.result = res;
1325
+ };
1326
+ const proceedRestart = () => ctx.flags.restarted = true;
1327
+ const cancelRestart = () => ctx.flags.restarted = false;
1328
+ for (const middleware of ctx.policy.middlewares.onError) {
1329
+ if (middleware._mode === "fluent") {
1330
+ await middleware.func(ctx.error);
1331
+ } else {
1332
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1460
1333
  }
1461
- }
1462
- }
1334
+ }
1335
+ if (ctx.flags.restarted) {
1336
+ if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1337
+ method: "request",
1338
+ cause: ctx.error,
1339
+ data: {
1340
+ maxAttempts: ctx.policy.settings.maxRestarts,
1341
+ error: ctx.error
1342
+ }
1343
+ });
1344
+ return await this.requestRuntime(restartAttempt + 1);
1345
+ }
1346
+ if (ctx.flags.overrided) return {
1347
+ success: true,
1348
+ data: ctx.result,
1349
+ error: null
1350
+ };
1351
+ if (!isVigorEmpty(ctx.policy.settings.default)) {
1352
+ const data = await ctx.policy.settings.default(ctx);
1353
+ return {
1354
+ success: true,
1355
+ data,
1356
+ error: null
1357
+ };
1358
+ }
1359
+ return {
1360
+ success: false,
1361
+ data: null,
1362
+ error: ctx.error
1363
+ };
1364
+ }
1365
+ }
1366
+ };
1463
1367
 
1464
- const VigorFetchPolicyBase = {
1465
- __brand: createBrand("Fetch", "Policy<Schema"),
1466
- method: VigorEmpty,
1467
- origin: VigorEmpty,
1468
- path: [],
1469
- query: [],
1470
- hash: "",
1471
- headers: {},
1472
- body: VigorEmpty,
1473
- extra: {},
1474
- settings: VigorFetchPolicySettingsBase,
1475
- middlewares: VigorFetchPolicyMiddlewaresBase,
1476
- retry: VigorRetryBase,
1477
- parse: VigorParseBase
1368
+ // src/fetch/policy.ts
1369
+ var VigorFetchPolicyBase = {
1370
+ __brand: createBrand("Fetch", "Policy<Schema"),
1371
+ method: VigorEmpty,
1372
+ origin: VigorEmpty,
1373
+ path: [],
1374
+ query: [],
1375
+ hash: "",
1376
+ headers: {},
1377
+ body: VigorEmpty,
1378
+ extra: {},
1379
+ settings: VigorFetchPolicySettingsBase,
1380
+ middlewares: VigorFetchPolicyMiddlewaresBase,
1381
+ retry: VigorRetryBase,
1382
+ parse: VigorParseBase
1478
1383
  };
1479
1384
 
1480
- const VigorFetchContextBase = {
1481
- __brand: createBrand("Fetch", "Context<Schema"),
1482
- href: "",
1483
- response: VigorDefault,
1484
- result: VigorDefault,
1485
- error: VigorDefault,
1486
- options: VigorDefault,
1487
- flags: {
1488
- overrided: false,
1489
- restarted: false
1490
- },
1491
- record: {},
1492
- policy: VigorFetchPolicyBase
1385
+ // src/fetch/context.ts
1386
+ var VigorFetchContextBase = {
1387
+ __brand: createBrand("Fetch", "Context<Schema"),
1388
+ href: "",
1389
+ response: VigorDefault,
1390
+ result: VigorDefault,
1391
+ error: VigorDefault,
1392
+ options: VigorDefault,
1393
+ flags: {
1394
+ overrided: false,
1395
+ restarted: false
1396
+ },
1397
+ record: {},
1398
+ policy: VigorFetchPolicyBase
1493
1399
  };
1494
1400
 
1495
- const VigorFetchErrorMessageFuncs = {
1496
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1497
- INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1498
- INVALID_PROTOCOL: ({ origin, base }) => base
1499
- ? `Invalid URL: could not resolve "${origin}" against base "${base}"`
1500
- : `Invalid URL: "${origin}" is not an absolute URL, and no base (window.location) is available to resolve it against — pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,
1501
- FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1502
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1401
+ // src/fetch/error.ts
1402
+ var VigorFetchErrorMessageFuncs = {
1403
+ VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1404
+ INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1405
+ 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`,
1406
+ FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1407
+ RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1408
+ };
1409
+ var VigorFetchError = class extends VigorError {
1410
+ /**
1411
+ * @param code - One of the fetch module's error codes.
1412
+ * @param options - Error metadata, including the `data` payload for `code`.
1413
+ */
1414
+ constructor(code, options) {
1415
+ const messageFn = VigorFetchErrorMessageFuncs[code];
1416
+ super(code, messageFn(options.data), options);
1417
+ }
1503
1418
  };
1504
- /** Error type thrown by the fetch module. */
1505
- class VigorFetchError extends VigorError {
1506
- /**
1507
- * @param code - One of the fetch module's error codes.
1508
- * @param options - Error metadata, including the `data` payload for `code`.
1509
- */
1510
- constructor(code, options) {
1511
- const messageFn = VigorFetchErrorMessageFuncs[code];
1512
- super(code, messageFn(options.data), options);
1513
- }
1514
- }
1515
1419
 
1516
- const VigorFetchBase = {
1517
- __brand: createBrand("Fetch", "Schema"),
1518
- policy: VigorFetchPolicyBase,
1519
- context: VigorFetchContextBase
1420
+ // src/fetch/main.ts
1421
+ var VigorFetchBase = {
1422
+ __brand: createBrand("Fetch", "Schema"),
1423
+ policy: VigorFetchPolicyBase,
1424
+ context: VigorFetchContextBase
1520
1425
  };
1521
- /**
1522
- * Immutable builder that performs an HTTP request, composing an internal
1523
- * {@link VigorRetry} engine (for retry/timeout/backoff) and a
1524
- * {@link VigorParse} engine (for response parsing), with a configurable
1525
- * middleware pipeline around request building and response handling.
1526
- */
1527
- class VigorFetch extends VigorStatus {
1528
- constructor(config = VigorFetchBase) {
1529
- super(VigorFetchBase, config);
1530
- }
1531
- _create(config) {
1532
- return new VigorFetch(config);
1533
- }
1534
- /** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
1535
- method(str) { return this._next({ policy: { method: str } }); }
1536
- /** Sets the request origin, either an absolute URL or a path relative to the current page. */
1537
- origin(str) { return this._next({ policy: { origin: str } }); }
1538
- /** Appends path segments to the request URL. */
1539
- path(...strs) {
1540
- return this._next({ policy: { path: this._stringifyList(strs) } });
1541
- }
1542
- /** Adds query-string parameter objects to the request URL. */
1543
- query(...objs) {
1544
- return this._next({ policy: { query: objs } });
1545
- }
1546
- /** Sets the URL fragment ("hash"), replacing any previous value. */
1547
- hash(str) { return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } }); }
1548
- /**
1549
- * Sets request headers.
1550
- *
1551
- * @param mode - `"overwrite"` discards all previously configured headers
1552
- * and keeps only the ones passed here. `"merge"` behaves like
1553
- * `Object.assign`, overwriting only the keys that overlap and keeping
1554
- * the rest.
1555
- */
1556
- headers(mode, obj) {
1557
- if (mode === "overwrite")
1558
- return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1559
- return this._next({ policy: { headers: obj } });
1560
- }
1561
- /**
1562
- * Sets the request body.
1563
- *
1564
- * @param mode - `"overwrite"` discards the previous body and fully
1565
- * replaces it with this value. `"merge"` shallow-merges (via
1566
- * `Object.assign`) when both the previous and new body are plain
1567
- * objects; for any other body type (string/Blob/FormData/etc) it is
1568
- * simply replaced.
1569
- */
1570
- body(mode, obj) {
1571
- if (mode === "overwrite")
1572
- return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1573
- return this._next({ policy: { body: obj } });
1574
- }
1575
- /**
1576
- * Sets additional `RequestInit` options other than headers/body/method/signal
1577
- * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1578
- * `referrerPolicy`, `keepalive`, `integrity`).
1579
- *
1580
- * @param mode - `"overwrite"` discards all previously configured options
1581
- * and replaces them with this value. `"merge"` shallow-merges this
1582
- * value onto the previous options.
1583
- */
1584
- options(mode, obj) {
1585
- if (mode === "overwrite")
1586
- return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1587
- return this._next({ policy: { extra: obj } });
1588
- }
1589
- /** Configures the fetch policy's general settings. */
1590
- settings(input) {
1591
- if (typeof input === 'function' || input instanceof VigorFetchPolicySettings) {
1592
- const result = typeof input === 'function'
1593
- ? input(new VigorFetchPolicySettings())
1594
- : input;
1595
- return this._next({ policy: { settings: result.config.policy.settings } });
1596
- }
1597
- return this._next({ policy: { settings: input } });
1598
- }
1599
- /** Configures the fetch policy's middleware pipeline. */
1600
- middlewares(input) {
1601
- if (typeof input === 'function' || input instanceof VigorFetchPolicyMiddlewares) {
1602
- const result = typeof input === 'function'
1603
- ? input(new VigorFetchPolicyMiddlewares())
1604
- : input;
1605
- return this._next({ policy: { middlewares: result.config.policy.middlewares } });
1606
- }
1607
- return this._next({ policy: { middlewares: input } });
1608
- }
1609
- /** Configures the retry engine used to send the underlying request. */
1610
- retry(input) {
1611
- if (typeof input === 'function' || input instanceof VigorRetry) {
1612
- const result = typeof input === 'function'
1613
- ? input(new VigorRetry())
1614
- : input;
1615
- return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1616
- }
1617
- return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
1618
- }
1619
- /** Configures the parse engine used to interpret the response. */
1620
- parse(input) {
1621
- if (typeof input === 'function' || input instanceof VigorParse) {
1622
- const result = typeof input === 'function'
1623
- ? input(new VigorParse())
1624
- : input;
1625
- return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1626
- }
1627
- return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
1628
- }
1629
- /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1630
- _stringifyList(unkList) {
1631
- return unkList
1632
- .filter(unk => unk !== null && unk !== undefined)
1633
- .map(unk => unk instanceof Date ? unk.toISOString() : String(unk));
1634
- }
1635
- /**
1636
- * Resolves the base URL used to interpret a relative `origin`. In a
1637
- * browser environment this is the current page location; in
1638
- * environments without `location` (e.g. Node), no base is available and
1639
- * `origin` must be an absolute URL.
1640
- */
1641
- _resolveBase() {
1642
- if (typeof globalThis !== 'undefined' && globalThis.location?.href) {
1643
- return globalThis.location.href;
1644
- }
1645
- return undefined;
1646
- }
1647
- /**
1648
- * Builds the final request URL from the configured origin, path
1649
- * segments, query parameters, and hash. An absolute `origin` ignores
1650
- * the resolved base (per the `URL` spec); a relative `origin` is
1651
- * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
1652
- */
1653
- _buildUrl(origin, path, query, hash) {
1654
- const base = this._resolveBase();
1655
- let originObj;
1656
- try {
1657
- originObj = new URL(origin, base);
1658
- }
1659
- catch {
1660
- throw new VigorFetchError("INVALID_PROTOCOL", {
1661
- method: "_buildUrl",
1662
- data: { origin, base }
1663
- });
1664
- }
1665
- const baseStr = originObj.origin;
1666
- const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, '')];
1667
- for (const p of path)
1668
- pathParts.push(p.replace(/^\/+|\/+$/g, ''));
1669
- const pathStr = pathParts.filter(Boolean).join('/');
1670
- const mainObj = new URL(pathStr, baseStr);
1671
- const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
1672
- const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap(q => Object.entries(q))];
1673
- for (const [key, val] of queryEntries) {
1674
- if (val === undefined || val === null)
1675
- continue;
1676
- if (Array.isArray(val)) {
1677
- for (const e of val)
1678
- mainObj.searchParams.append(key, parseVal(e));
1679
- }
1680
- else {
1681
- mainObj.searchParams.append(key, parseVal(val));
1426
+ var VigorFetch = class _VigorFetch extends VigorStatus {
1427
+ constructor(config = VigorFetchBase) {
1428
+ super(VigorFetchBase, config);
1429
+ }
1430
+ _create(config) {
1431
+ return new _VigorFetch(config);
1432
+ }
1433
+ /** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
1434
+ method(str) {
1435
+ return this._next({ policy: { method: str } });
1436
+ }
1437
+ /** Sets the request origin, either an absolute URL or a path relative to the current page. */
1438
+ origin(str) {
1439
+ return this._next({ policy: { origin: str } });
1440
+ }
1441
+ /** Appends path segments to the request URL. */
1442
+ path(...strs) {
1443
+ return this._next({ policy: { path: this._stringifyList(strs) } });
1444
+ }
1445
+ /** Adds query-string parameter objects to the request URL. */
1446
+ query(...objs) {
1447
+ return this._next({ policy: { query: objs } });
1448
+ }
1449
+ /** Sets the URL fragment ("hash"), replacing any previous value. */
1450
+ hash(str) {
1451
+ return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } });
1452
+ }
1453
+ /**
1454
+ * Sets request headers.
1455
+ *
1456
+ * @param mode - `"overwrite"` discards all previously configured headers
1457
+ * and keeps only the ones passed here. `"merge"` behaves like
1458
+ * `Object.assign`, overwriting only the keys that overlap and keeping
1459
+ * the rest.
1460
+ */
1461
+ headers(mode, obj) {
1462
+ if (mode === "overwrite") return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1463
+ return this._next({ policy: { headers: obj } });
1464
+ }
1465
+ /**
1466
+ * Sets the request body.
1467
+ *
1468
+ * @param mode - `"overwrite"` discards the previous body and fully
1469
+ * replaces it with this value. `"merge"` shallow-merges (via
1470
+ * `Object.assign`) when both the previous and new body are plain
1471
+ * objects; for any other body type (string/Blob/FormData/etc) it is
1472
+ * simply replaced.
1473
+ */
1474
+ body(mode, obj) {
1475
+ if (mode === "overwrite") return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1476
+ return this._next({ policy: { body: obj } });
1477
+ }
1478
+ /**
1479
+ * Sets additional `RequestInit` options other than headers/body/method/signal
1480
+ * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1481
+ * `referrerPolicy`, `keepalive`, `integrity`).
1482
+ *
1483
+ * @param mode - `"overwrite"` discards all previously configured options
1484
+ * and replaces them with this value. `"merge"` shallow-merges this
1485
+ * value onto the previous options.
1486
+ */
1487
+ options(mode, obj) {
1488
+ if (mode === "overwrite") return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1489
+ return this._next({ policy: { extra: obj } });
1490
+ }
1491
+ /** Configures the fetch policy's general settings. */
1492
+ settings(input) {
1493
+ if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
1494
+ const result = typeof input === "function" ? input(new VigorFetchPolicySettings()) : input;
1495
+ return this._next(
1496
+ { policy: { settings: result.config.policy.settings } }
1497
+ );
1498
+ }
1499
+ return this._next({ policy: { settings: input } });
1500
+ }
1501
+ /** Configures the fetch policy's middleware pipeline. */
1502
+ middlewares(input) {
1503
+ if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
1504
+ const result = typeof input === "function" ? input(new VigorFetchPolicyMiddlewares()) : input;
1505
+ return this._next(
1506
+ { policy: { middlewares: result.config.policy.middlewares } }
1507
+ );
1508
+ }
1509
+ return this._next({ policy: { middlewares: input } });
1510
+ }
1511
+ /** Configures the retry engine used to send the underlying request. */
1512
+ retry(input) {
1513
+ if (typeof input === "function" || input instanceof VigorRetry) {
1514
+ const result = typeof input === "function" ? input(new VigorRetry()) : input;
1515
+ return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1516
+ }
1517
+ return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
1518
+ }
1519
+ /** Configures the parse engine used to interpret the response. */
1520
+ parse(input) {
1521
+ if (typeof input === "function" || input instanceof VigorParse) {
1522
+ const result = typeof input === "function" ? input(new VigorParse()) : input;
1523
+ return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1524
+ }
1525
+ return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
1526
+ }
1527
+ /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1528
+ _stringifyList(unkList) {
1529
+ return unkList.filter((unk) => unk !== null && unk !== void 0).map((unk) => unk instanceof Date ? unk.toISOString() : String(unk));
1530
+ }
1531
+ /**
1532
+ * Resolves the base URL used to interpret a relative `origin`. In a
1533
+ * browser environment this is the current page location; in
1534
+ * environments without `location` (e.g. Node), no base is available and
1535
+ * `origin` must be an absolute URL.
1536
+ */
1537
+ _resolveBase() {
1538
+ if (typeof globalThis !== "undefined" && globalThis.location?.href) {
1539
+ return globalThis.location.href;
1540
+ }
1541
+ return void 0;
1542
+ }
1543
+ /**
1544
+ * Builds the final request URL from the configured origin, path
1545
+ * segments, query parameters, and hash. An absolute `origin` ignores
1546
+ * the resolved base (per the `URL` spec); a relative `origin` is
1547
+ * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
1548
+ */
1549
+ _buildUrl(origin, path, query, hash) {
1550
+ const base = this._resolveBase();
1551
+ let originObj;
1552
+ try {
1553
+ originObj = new URL(origin, base);
1554
+ } catch {
1555
+ throw new VigorFetchError("INVALID_PROTOCOL", {
1556
+ method: "_buildUrl",
1557
+ data: { origin, base }
1558
+ });
1559
+ }
1560
+ const baseStr = originObj.origin;
1561
+ const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, "")];
1562
+ for (const p of path) pathParts.push(p.replace(/^\/+|\/+$/g, ""));
1563
+ const pathStr = pathParts.filter(Boolean).join("/");
1564
+ const mainObj = new URL(pathStr, baseStr);
1565
+ const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
1566
+ const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap((q) => Object.entries(q))];
1567
+ for (const [key, val] of queryEntries) {
1568
+ if (val === void 0 || val === null) continue;
1569
+ if (Array.isArray(val)) {
1570
+ for (const e of val) mainObj.searchParams.append(key, parseVal(e));
1571
+ } else {
1572
+ mainObj.searchParams.append(key, parseVal(val));
1573
+ }
1574
+ }
1575
+ mainObj.hash = hash || originObj.hash;
1576
+ return mainObj.href;
1577
+ }
1578
+ /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1579
+ _normalizeBody(body) {
1580
+ if (body == null) return { headers: {}, body };
1581
+ if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1582
+ if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1583
+ if (body instanceof ArrayBuffer) return { headers: { "Content-Type": "application/octet-stream" }, body };
1584
+ if (body instanceof URLSearchParams) return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1585
+ if (body instanceof FormData) return { headers: {}, body };
1586
+ if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1587
+ throw new VigorFetchError("INVALID_BODY", {
1588
+ method: "_normalizeBody",
1589
+ data: { received: body }
1590
+ });
1591
+ }
1592
+ /** Runs the request and returns its parsed result directly, throwing on final failure. */
1593
+ async request() {
1594
+ const res = await this.requestVerbose();
1595
+ if (res.success) return res.data;
1596
+ throw res.error;
1597
+ }
1598
+ /** Runs the request and returns a result/error envelope instead of throwing. */
1599
+ async requestVerbose() {
1600
+ return await this.requestRuntime();
1601
+ }
1602
+ /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1603
+ async requestRuntime(restartAttempt = 1) {
1604
+ const config = this._merge(this.config, {});
1605
+ let ctx = {
1606
+ ...config.context,
1607
+ policy: config.policy
1608
+ };
1609
+ const throwError = (err) => {
1610
+ throw err;
1611
+ };
1612
+ try {
1613
+ if (isVigorEmpty(ctx.policy.origin)) throw new VigorFetchError("VALUE_REQUIRED", {
1614
+ method: "request",
1615
+ data: { key: "origin" }
1616
+ });
1617
+ ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1618
+ const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== void 0;
1619
+ const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
1620
+ let options = {
1621
+ ...ctx.policy.extra,
1622
+ method,
1623
+ headers: {}
1624
+ };
1625
+ if (hasBody) {
1626
+ const normalized = this._normalizeBody(ctx.policy.body);
1627
+ if (normalized.body !== void 0) options.body = normalized.body;
1628
+ Object.assign(options.headers, normalized.headers);
1629
+ }
1630
+ Object.assign(options.headers, ctx.policy.headers);
1631
+ for (const middleware of ctx.policy.middlewares.before) {
1632
+ if (middleware._mode === "fluent") {
1633
+ await middleware.func(ctx);
1634
+ } else {
1635
+ ctx = await middleware.func(ctx, {
1636
+ throwError,
1637
+ setOptions: (o) => {
1638
+ options = o;
1639
+ },
1640
+ setHeaders: (h) => {
1641
+ options.headers = h;
1642
+ },
1643
+ setBody: (b) => {
1644
+ options.body = b;
1682
1645
  }
1646
+ });
1683
1647
  }
1684
- mainObj.hash = hash || originObj.hash;
1685
- return mainObj.href;
1686
- }
1687
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1688
- _normalizeBody(body) {
1689
- if (body == null)
1690
- return { headers: {}, body: body };
1691
- if (typeof body === "string")
1692
- return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1693
- if (body instanceof Blob)
1694
- return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1695
- if (body instanceof ArrayBuffer)
1696
- return { headers: { "Content-Type": "application/octet-stream" }, body };
1697
- if (body instanceof URLSearchParams)
1698
- return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1699
- if (body instanceof FormData)
1700
- return { headers: {}, body };
1701
- if (typeof body === "object")
1702
- return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1703
- throw new VigorFetchError("INVALID_BODY", {
1704
- method: "_normalizeBody",
1705
- data: { received: body }
1706
- });
1707
- }
1708
- /** Runs the request and returns its parsed result directly, throwing on final failure. */
1709
- async request() {
1710
- const res = await this.requestVerbose();
1711
- if (res.success)
1712
- return res.data;
1713
- throw res.error;
1714
- }
1715
- /** Runs the request and returns a result/error envelope instead of throwing. */
1716
- async requestVerbose() {
1717
- return await this.requestRuntime();
1718
- }
1719
- /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1720
- async requestRuntime(restartAttempt = 1) {
1721
- const config = this._merge(this.config, {});
1722
- let ctx = {
1723
- ...config.context,
1724
- policy: config.policy
1725
- };
1726
- const throwError = (err) => { throw err; };
1727
- try {
1728
- if (isVigorEmpty(ctx.policy.origin))
1729
- throw new VigorFetchError("VALUE_REQUIRED", {
1730
- method: "request",
1731
- data: { key: "origin" }
1732
- });
1733
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1734
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== undefined;
1735
- const method = isVigorEmpty(ctx.policy.method) ? (hasBody ? "POST" : "GET") : ctx.policy.method;
1736
- let options = {
1737
- ...ctx.policy.extra,
1738
- method: method,
1739
- headers: {}
1740
- };
1741
- if (hasBody) {
1742
- const normalized = this._normalizeBody(ctx.policy.body);
1743
- if (normalized.body !== undefined)
1744
- options.body = normalized.body;
1745
- Object.assign(options.headers, normalized.headers);
1746
- }
1747
- Object.assign(options.headers, ctx.policy.headers);
1748
- for (const middleware of ctx.policy.middlewares.before) {
1749
- if (middleware._mode === "fluent") {
1750
- await middleware.func(ctx);
1751
- }
1752
- else {
1753
- ctx = await middleware.func(ctx, {
1754
- throwError,
1755
- setOptions: (o) => { options = o; },
1756
- setHeaders: (h) => { options.headers = h; },
1757
- setBody: (b) => { options.body = b; }
1758
- });
1759
- }
1648
+ }
1649
+ ctx.options = options;
1650
+ const retryEngine = new VigorRetry(ctx.policy.retry).target(async (signal) => {
1651
+ return await fetch(ctx.href, { ...options, signal });
1652
+ }).middlewares(
1653
+ (m) => m.after("intercept", async (rctx, api) => {
1654
+ const response = rctx.result;
1655
+ if (!response.ok) {
1656
+ let parsed = void 0;
1657
+ try {
1658
+ parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
1659
+ } catch {
1760
1660
  }
1761
- ctx.options = options;
1762
- const retryEngine = new VigorRetry(ctx.policy.retry)
1763
- .target(async (signal) => {
1764
- return await fetch(ctx.href, { ...options, signal });
1765
- })
1766
- .middlewares(m => m
1767
- .after("intercept", async (rctx, api) => {
1768
- const response = rctx.result;
1769
- if (!response.ok) {
1770
- let parsed = undefined;
1771
- try {
1772
- parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
1773
- }
1774
- catch {
1775
- }
1776
- api.throwError(new VigorFetchError("FETCH_FAILED", {
1777
- method: "request",
1778
- data: {
1779
- status: response.status,
1780
- statusText: response.statusText,
1781
- response,
1782
- url: response.url,
1783
- parsed
1784
- }
1785
- }));
1786
- }
1787
- return rctx;
1788
- })
1789
- .retryIf("intercept", async (rctx, api) => {
1790
- const response = rctx.error instanceof VigorFetchError
1791
- ? rctx.error.data?.response
1792
- : undefined;
1793
- if (response && ctx.policy.settings.unretryStatus.includes(response.status))
1794
- api.cancelRetry();
1795
- else
1796
- api.proceedRetry();
1797
- return rctx;
1798
- })
1799
- .onRetry("intercept", async (rctx, api) => {
1800
- const response = rctx.error instanceof VigorFetchError
1801
- ? rctx.error.data?.response
1802
- : undefined;
1803
- if (response?.status === 429) {
1804
- let retryHeader = null;
1805
- for (const header of ctx.policy.settings.retryHeaders) {
1806
- retryHeader = response.headers.get(header);
1807
- if (retryHeader)
1808
- break;
1809
- }
1810
- if (retryHeader) {
1811
- const toNumber = Number(retryHeader);
1812
- const delay = !isNaN(toNumber)
1813
- ? toNumber * 1000
1814
- : (() => {
1815
- const toDate = new Date(retryHeader).getTime();
1816
- return !isNaN(toDate) ? toDate - Date.now() : null;
1817
- })();
1818
- if (delay !== null && delay > 0)
1819
- api.setDelay(delay);
1820
- }
1821
- }
1822
- return rctx;
1661
+ api.throwError(new VigorFetchError("FETCH_FAILED", {
1662
+ method: "request",
1663
+ data: {
1664
+ status: response.status,
1665
+ statusText: response.statusText,
1666
+ response,
1667
+ url: response.url,
1668
+ parsed
1669
+ }
1823
1670
  }));
1824
- ctx.response = await retryEngine.request();
1825
- const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
1826
- ctx.result = await parseEngine.request();
1827
- for (const middleware of ctx.policy.middlewares.after) {
1828
- if (middleware._mode === "fluent") {
1829
- await middleware.func(ctx);
1830
- }
1831
- else {
1832
- ctx = await middleware.func(ctx, { throwError, setResult: (r) => { ctx.result = r; } });
1833
- }
1671
+ }
1672
+ return rctx;
1673
+ }).retryIf("intercept", async (rctx, api) => {
1674
+ const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1675
+ if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1676
+ else api.proceedRetry();
1677
+ return rctx;
1678
+ }).onRetry("intercept", async (rctx, api) => {
1679
+ const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1680
+ if (response?.status === 429) {
1681
+ let retryHeader = null;
1682
+ for (const header of ctx.policy.settings.retryHeaders) {
1683
+ retryHeader = response.headers.get(header);
1684
+ if (retryHeader) break;
1834
1685
  }
1835
- const setResult = (r) => { ctx.result = r; };
1836
- for (const middleware of ctx.policy.middlewares.onResult) {
1837
- if (middleware._mode === "fluent") {
1838
- ctx.result = await middleware.func(ctx.result);
1839
- }
1840
- else {
1841
- ctx = await middleware.func(ctx, { setResult, throwError });
1842
- }
1686
+ if (retryHeader) {
1687
+ const toNumber = Number(retryHeader);
1688
+ const delay = !isNaN(toNumber) ? toNumber * 1e3 : (() => {
1689
+ const toDate = new Date(retryHeader).getTime();
1690
+ return !isNaN(toDate) ? toDate - Date.now() : null;
1691
+ })();
1692
+ if (delay !== null && delay > 0) api.setDelay(delay);
1843
1693
  }
1844
- return {
1845
- success: true,
1846
- data: ctx.result,
1847
- error: null
1848
- };
1694
+ }
1695
+ return rctx;
1696
+ })
1697
+ );
1698
+ ctx.response = await retryEngine.request();
1699
+ const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
1700
+ ctx.result = await parseEngine.request();
1701
+ for (const middleware of ctx.policy.middlewares.after) {
1702
+ if (middleware._mode === "fluent") {
1703
+ await middleware.func(ctx);
1704
+ } else {
1705
+ ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
1706
+ ctx.result = r;
1707
+ } });
1849
1708
  }
1850
- catch (error) {
1851
- ctx.error = error;
1852
- ctx.flags.overrided = false;
1853
- ctx.flags.restarted = false;
1854
- const setResult = (r) => {
1855
- ctx.flags.overrided = true;
1856
- ctx.result = r;
1857
- };
1858
- const proceedRestart = () => ctx.flags.restarted = true;
1859
- const cancelRestart = () => ctx.flags.restarted = false;
1860
- for (const middleware of ctx.policy.middlewares.onError) {
1861
- if (middleware._mode === "fluent") {
1862
- await middleware.func(ctx.error);
1863
- }
1864
- else {
1865
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1866
- }
1867
- }
1868
- if (ctx.flags.restarted) {
1869
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1870
- throw new VigorFetchError("RESTART_EXHAUSTED", {
1871
- method: "request",
1872
- cause: ctx.error,
1873
- data: {
1874
- maxAttempts: ctx.policy.settings.maxRestarts,
1875
- error: ctx.error
1876
- }
1877
- });
1878
- return await this.requestRuntime(restartAttempt + 1);
1879
- }
1880
- if (ctx.flags.overrided)
1881
- return {
1882
- success: true,
1883
- data: ctx.result,
1884
- error: null
1885
- };
1886
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1887
- const data = await ctx.policy.settings.default(ctx);
1888
- return {
1889
- success: true,
1890
- data,
1891
- error: null
1892
- };
1893
- }
1894
- return {
1895
- success: false,
1896
- data: null,
1897
- error
1898
- };
1709
+ }
1710
+ const setResult = (r) => {
1711
+ ctx.result = r;
1712
+ };
1713
+ for (const middleware of ctx.policy.middlewares.onResult) {
1714
+ if (middleware._mode === "fluent") {
1715
+ ctx.result = await middleware.func(ctx.result);
1716
+ } else {
1717
+ ctx = await middleware.func(ctx, { setResult, throwError });
1899
1718
  }
1900
- }
1901
- }
1719
+ }
1720
+ return {
1721
+ success: true,
1722
+ data: ctx.result,
1723
+ error: null
1724
+ };
1725
+ } catch (error) {
1726
+ ctx.error = error;
1727
+ ctx.flags.overrided = false;
1728
+ ctx.flags.restarted = false;
1729
+ const setResult = (r) => {
1730
+ ctx.flags.overrided = true;
1731
+ ctx.result = r;
1732
+ };
1733
+ const proceedRestart = () => ctx.flags.restarted = true;
1734
+ const cancelRestart = () => ctx.flags.restarted = false;
1735
+ for (const middleware of ctx.policy.middlewares.onError) {
1736
+ if (middleware._mode === "fluent") {
1737
+ await middleware.func(ctx.error);
1738
+ } else {
1739
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1740
+ }
1741
+ }
1742
+ if (ctx.flags.restarted) {
1743
+ if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
1744
+ method: "request",
1745
+ cause: ctx.error,
1746
+ data: {
1747
+ maxAttempts: ctx.policy.settings.maxRestarts,
1748
+ error: ctx.error
1749
+ }
1750
+ });
1751
+ return await this.requestRuntime(restartAttempt + 1);
1752
+ }
1753
+ if (ctx.flags.overrided) return {
1754
+ success: true,
1755
+ data: ctx.result,
1756
+ error: null
1757
+ };
1758
+ if (!isVigorEmpty(ctx.policy.settings.default)) {
1759
+ const data = await ctx.policy.settings.default(ctx);
1760
+ return {
1761
+ success: true,
1762
+ data,
1763
+ error: null
1764
+ };
1765
+ }
1766
+ return {
1767
+ success: false,
1768
+ data: null,
1769
+ error
1770
+ };
1771
+ }
1772
+ }
1773
+ };
1902
1774
 
1903
- const vigor = {
1904
- use: (plugin, options) => {
1905
- plugin.func(vigor, options);
1775
+ // src/entry/main.ts
1776
+ var vigorBase = {
1777
+ retry: (...task) => task[0] !== void 0 ? new VigorRetry().target(task[0]) : new VigorRetry(),
1778
+ parse: (...response) => response[0] !== void 0 ? new VigorParse().target(response[0]) : new VigorParse(),
1779
+ fetch: (...origin) => origin[0] !== void 0 ? new VigorFetch().origin(origin[0]) : new VigorFetch(),
1780
+ all: (...tasks) => tasks.length > 0 ? new VigorAll().target(...tasks) : new VigorAll(),
1781
+ builders: {
1782
+ fetch: {
1783
+ settings: () => new VigorFetchPolicySettings(),
1784
+ middlewares: () => new VigorFetchPolicyMiddlewares()
1906
1785
  },
1907
- retry: (task) => task ? new VigorRetry().target(task) : new VigorRetry(),
1908
- parse: (response) => response ? new VigorParse().target(response) : new VigorParse(),
1909
- fetch: (origin) => origin ? new VigorFetch().origin(origin) : new VigorFetch(),
1910
- all: (...tasks) => tasks.length > 0 ? new VigorAll().target(...tasks) : new VigorAll(),
1911
- builders: {
1912
- fetch: {
1913
- settings: () => new VigorFetchPolicySettings(),
1914
- middlewares: () => new VigorFetchPolicyMiddlewares(),
1915
- },
1916
- retry: {
1917
- settings: () => new VigorRetryPolicySettings(),
1918
- middlewares: () => new VigorRetryPolicyMiddlewares(),
1919
- algorithms: () => new VigorRetryPolicyAlgorithms(),
1920
- algorithm: {
1921
- constant: () => new VigorRetryPolicyAlgorithmsConstant(),
1922
- linear: () => new VigorRetryPolicyAlgorithmsLinear(),
1923
- backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
1924
- custom: () => new VigorRetryPolicyAlgorithmsCustom(),
1925
- },
1926
- },
1927
- parse: {
1928
- settings: () => new VigorParsePolicySettings(),
1929
- middlewares: () => new VigorParsePolicyMiddlewares(),
1930
- strategies: () => new VigorParsePolicyStrategies(),
1931
- },
1932
- all: {
1933
- settings: () => new VigorAllPolicySettings(),
1934
- middlewares: () => new VigorAllPolicyMiddlewares(),
1935
- },
1786
+ retry: {
1787
+ settings: () => new VigorRetryPolicySettings(),
1788
+ middlewares: () => new VigorRetryPolicyMiddlewares(),
1789
+ algorithms: () => new VigorRetryPolicyAlgorithms(),
1790
+ algorithm: {
1791
+ constant: () => new VigorRetryPolicyAlgorithmsConstant(),
1792
+ linear: () => new VigorRetryPolicyAlgorithmsLinear(),
1793
+ backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
1794
+ custom: () => new VigorRetryPolicyAlgorithmsCustom()
1795
+ }
1796
+ },
1797
+ parse: {
1798
+ settings: () => new VigorParsePolicySettings(),
1799
+ middlewares: () => new VigorParsePolicyMiddlewares(),
1800
+ strategies: () => new VigorParsePolicyStrategies()
1801
+ },
1802
+ all: {
1803
+ settings: () => new VigorAllPolicySettings(),
1804
+ middlewares: () => new VigorAllPolicyMiddlewares()
1936
1805
  }
1806
+ }
1807
+ };
1808
+ var cloneVigor = (v) => ({
1809
+ ...v,
1810
+ builders: {
1811
+ fetch: { ...v.builders.fetch },
1812
+ retry: { ...v.builders.retry, algorithm: { ...v.builders.retry.algorithm } },
1813
+ parse: { ...v.builders.parse },
1814
+ all: { ...v.builders.all }
1815
+ }
1816
+ });
1817
+ var vigor = {
1818
+ ...vigorBase,
1819
+ use: (plugin, options) => {
1820
+ const ext = plugin.func(vigor, options);
1821
+ return { ...cloneVigor(vigor), ...ext };
1822
+ }
1937
1823
  };
1938
1824
 
1939
- exports.VigorAll = VigorAll;
1940
- exports.VigorAllBase = VigorAllBase;
1941
- exports.VigorAllError = VigorAllError;
1942
- exports.VigorAllErrorMessageFuncs = VigorAllErrorMessageFuncs;
1943
- exports.VigorAllPolicyBase = VigorAllPolicyBase;
1944
- exports.VigorAllPolicyMiddlewares = VigorAllPolicyMiddlewares;
1945
- exports.VigorAllPolicyMiddlewaresBase = VigorAllPolicyMiddlewaresBase;
1946
- exports.VigorAllPolicySettings = VigorAllPolicySettings;
1947
- exports.VigorAllPolicySettingsBase = VigorAllPolicySettingsBase;
1948
- exports.VigorError = VigorError;
1949
- exports.VigorFetch = VigorFetch;
1950
- exports.VigorFetchBase = VigorFetchBase;
1951
- exports.VigorFetchError = VigorFetchError;
1952
- exports.VigorFetchErrorMessageFuncs = VigorFetchErrorMessageFuncs;
1953
- exports.VigorFetchPolicyBase = VigorFetchPolicyBase;
1954
- exports.VigorFetchPolicyMiddlewares = VigorFetchPolicyMiddlewares;
1955
- exports.VigorFetchPolicyMiddlewaresBase = VigorFetchPolicyMiddlewaresBase;
1956
- exports.VigorFetchPolicySettings = VigorFetchPolicySettings;
1957
- exports.VigorFetchPolicySettingsBase = VigorFetchPolicySettingsBase;
1958
- exports.VigorJitter = VigorJitter;
1959
- exports.VigorParse = VigorParse;
1960
- exports.VigorParseBase = VigorParseBase;
1961
- exports.VigorParseContentTypeStrategy = VigorParseContentTypeStrategy;
1962
- exports.VigorParseError = VigorParseError;
1963
- exports.VigorParseErrorMessageFuncs = VigorParseErrorMessageFuncs;
1964
- exports.VigorParsePolicyBase = VigorParsePolicyBase;
1965
- exports.VigorParsePolicyMiddlewares = VigorParsePolicyMiddlewares;
1966
- exports.VigorParsePolicyMiddlewaresBase = VigorParsePolicyMiddlewaresBase;
1967
- exports.VigorParsePolicySettings = VigorParsePolicySettings;
1968
- exports.VigorParsePolicySettingsBase = VigorParsePolicySettingsBase;
1969
- exports.VigorParsePolicyStrategies = VigorParsePolicyStrategies;
1970
- exports.VigorParsePolicyStrategiesBase = VigorParsePolicyStrategiesBase;
1971
- exports.VigorParseSniffStrategy = VigorParseSniffStrategy;
1972
- exports.VigorRetry = VigorRetry;
1973
- exports.VigorRetryBase = VigorRetryBase;
1974
- exports.VigorRetryError = VigorRetryError;
1975
- exports.VigorRetryErrorMessageFuncs = VigorRetryErrorMessageFuncs;
1976
- exports.VigorRetryPolicyAlgorithms = VigorRetryPolicyAlgorithms;
1977
- exports.VigorRetryPolicyAlgorithmsBackoff = VigorRetryPolicyAlgorithmsBackoff;
1978
- exports.VigorRetryPolicyAlgorithmsBackoffBase = VigorRetryPolicyAlgorithmsBackoffBase;
1979
- exports.VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsBase;
1980
- exports.VigorRetryPolicyAlgorithmsConstant = VigorRetryPolicyAlgorithmsConstant;
1981
- exports.VigorRetryPolicyAlgorithmsConstantBase = VigorRetryPolicyAlgorithmsConstantBase;
1982
- exports.VigorRetryPolicyAlgorithmsCustom = VigorRetryPolicyAlgorithmsCustom;
1983
- exports.VigorRetryPolicyAlgorithmsCustomBase = VigorRetryPolicyAlgorithmsCustomBase;
1984
- exports.VigorRetryPolicyAlgorithmsLinear = VigorRetryPolicyAlgorithmsLinear;
1985
- exports.VigorRetryPolicyAlgorithmsLinearBase = VigorRetryPolicyAlgorithmsLinearBase;
1986
- exports.VigorRetryPolicyBase = VigorRetryPolicyBase;
1987
- exports.VigorRetryPolicyMiddlewares = VigorRetryPolicyMiddlewares;
1988
- exports.VigorRetryPolicyMiddlewaresBase = VigorRetryPolicyMiddlewaresBase;
1989
- exports.VigorRetryPolicySettings = VigorRetryPolicySettings;
1990
- exports.VigorRetryPolicySettingsBase = VigorRetryPolicySettingsBase;
1991
- exports.VigorStatus = VigorStatus;
1992
- exports.default = vigor;
1993
- exports.vigor = vigor;
1825
+ // src/index.ts
1826
+ var index_default = vigor;
1827
+ export {
1828
+ VigorAll,
1829
+ VigorAllBase,
1830
+ VigorAllError,
1831
+ VigorAllErrorMessageFuncs,
1832
+ VigorAllPolicyBase,
1833
+ VigorAllPolicyMiddlewares,
1834
+ VigorAllPolicyMiddlewaresBase,
1835
+ VigorAllPolicySettings,
1836
+ VigorAllPolicySettingsBase,
1837
+ VigorError,
1838
+ VigorFetch,
1839
+ VigorFetchBase,
1840
+ VigorFetchError,
1841
+ VigorFetchErrorMessageFuncs,
1842
+ VigorFetchPolicyBase,
1843
+ VigorFetchPolicyMiddlewares,
1844
+ VigorFetchPolicyMiddlewaresBase,
1845
+ VigorFetchPolicySettings,
1846
+ VigorFetchPolicySettingsBase,
1847
+ VigorJitter,
1848
+ VigorParse,
1849
+ VigorParseBase,
1850
+ VigorParseContentTypeStrategy,
1851
+ VigorParseError,
1852
+ VigorParseErrorMessageFuncs,
1853
+ VigorParsePolicyBase,
1854
+ VigorParsePolicyMiddlewares,
1855
+ VigorParsePolicyMiddlewaresBase,
1856
+ VigorParsePolicySettings,
1857
+ VigorParsePolicySettingsBase,
1858
+ VigorParsePolicyStrategies,
1859
+ VigorParsePolicyStrategiesBase,
1860
+ VigorParseSniffStrategy,
1861
+ VigorRetry,
1862
+ VigorRetryBase,
1863
+ VigorRetryError,
1864
+ VigorRetryErrorMessageFuncs,
1865
+ VigorRetryPolicyAlgorithms,
1866
+ VigorRetryPolicyAlgorithmsBackoff,
1867
+ VigorRetryPolicyAlgorithmsBackoffBase,
1868
+ VigorRetryPolicyAlgorithmsBase,
1869
+ VigorRetryPolicyAlgorithmsConstant,
1870
+ VigorRetryPolicyAlgorithmsConstantBase,
1871
+ VigorRetryPolicyAlgorithmsCustom,
1872
+ VigorRetryPolicyAlgorithmsCustomBase,
1873
+ VigorRetryPolicyAlgorithmsLinear,
1874
+ VigorRetryPolicyAlgorithmsLinearBase,
1875
+ VigorRetryPolicyBase,
1876
+ VigorRetryPolicyMiddlewares,
1877
+ VigorRetryPolicyMiddlewaresBase,
1878
+ VigorRetryPolicySettings,
1879
+ VigorRetryPolicySettingsBase,
1880
+ VigorStatus,
1881
+ index_default as default,
1882
+ vigor
1883
+ };