vigor-fetch 4.0.3 → 4.0.5

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,1985 +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
- data: {
1007
- maxAttempts: ctx.policy.settings.maxAttempts
1008
- }
1009
- });
1010
- }
1011
- catch (error) {
1012
- ctx.error = error;
1013
- ctx.flags.doRestart = false;
1014
- ctx.flags.overridden = false;
1015
859
  const setResult = (res) => {
1016
- ctx.flags.overridden = true;
1017
- ctx.result = res;
860
+ ctx.result = res;
1018
861
  };
1019
- const proceedRestart = () => ctx.flags.doRestart = true;
1020
- const cancelRestart = () => ctx.flags.doRestart = false;
1021
- for (const middleware of ctx.policy.middlewares.onError) {
1022
- if (middleware._mode === "fluent") {
1023
- await middleware.func(ctx.error);
1024
- }
1025
- else {
1026
- ctx = await middleware.func(ctx, {
1027
- setResult,
1028
- throwError,
1029
- proceedRestart,
1030
- cancelRestart
1031
- });
1032
- }
1033
- }
1034
- if (ctx.flags.doRestart) {
1035
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1036
- throw new VigorRetryError("RESTART_EXHAUSTED", {
1037
- method: "request",
1038
- data: {
1039
- maxAttempts: ctx.policy.settings.maxRestarts
1040
- }
1041
- });
1042
- return await this.requestRuntime(restartAttempt + 1);
1043
- }
1044
- if (ctx.flags.overridden)
1045
- return {
1046
- success: true,
1047
- data: ctx.result,
1048
- error: null
1049
- };
1050
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1051
- const data = await ctx.policy.settings.default(ctx);
1052
- return {
1053
- success: true,
1054
- data,
1055
- error: null
1056
- };
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
+ }
1057
871
  }
1058
872
  return {
1059
- success: false,
1060
- data: null,
1061
- error: ctx.error
873
+ success: true,
874
+ data: ctx.result,
875
+ error: null
1062
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));
1063
915
  }
1064
- }
1065
- }
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
+ };
1066
979
 
1067
- const VigorParsePolicySettingsBase = {
1068
- __brand: createBrand("Parse", "Policy<Settings<Schema"),
1069
- raw: false,
1070
- default: VigorEmpty,
1071
- 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
+ }
1072
1012
  };
1073
- /** Immutable builder for a parse policy's general settings. */
1074
- class VigorParsePolicySettings extends VigorStatus {
1075
- constructor(config = VigorParseBase) {
1076
- super(VigorParseBase, config);
1077
- }
1078
- _create(config) {
1079
- return new VigorParsePolicySettings(config);
1080
- }
1081
- /** When enabled, skips content-type based parsing and returns the raw response. */
1082
- raw(bool) {
1083
- return this._next({
1084
- policy: { settings: { raw: bool } }
1085
- });
1086
- }
1087
- /** Sets the fallback value/factory used when parsing ultimately fails. */
1088
- default(func) {
1089
- return this._next({
1090
- policy: { settings: { default: func } }
1091
- });
1092
- }
1093
- /** Sets the maximum number of full restarts allowed. */
1094
- maxRestarts(num) {
1095
- return this._next({
1096
- policy: { settings: { maxRestarts: num } }
1097
- });
1098
- }
1099
- }
1100
1013
 
1101
- const VigorParsePolicyMiddlewaresBase = {
1102
- __brand: createBrand("Parse", "Policy<Middlewares<Schema"),
1103
- before: [],
1104
- after: [],
1105
- onResult: [],
1106
- 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
+ }
1107
1041
  };
1108
- /**
1109
- * Immutable builder for a parse policy's middleware pipeline (`before`,
1110
- * `after`, `onResult`, `onError`). Each stage accepts either "fluent"
1111
- * middleware (returns a plain value merged into the context) or
1112
- * "intercept" middleware (receives an explicit API to mutate control flow).
1113
- */
1114
- class VigorParsePolicyMiddlewares extends VigorStatus {
1115
- constructor(config = VigorParseBase) {
1116
- super(VigorParseBase, config);
1117
- }
1118
- _create(config) {
1119
- return new VigorParsePolicyMiddlewares(config);
1120
- }
1121
- before(type, func) {
1122
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
1123
- }
1124
- after(type, func) {
1125
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
1126
- }
1127
- onResult(type, func) {
1128
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
1129
- }
1130
- onError(type, func) {
1131
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
1132
- }
1133
- }
1134
1042
 
1135
- const VigorParseErrorMessageFuncs = {
1136
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1137
- INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1138
- PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1139
- PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1140
- 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
+ }
1141
1060
  };
1142
- /** Error type thrown by the parse module. */
1143
- class VigorParseError extends VigorError {
1144
- /**
1145
- * @param code - One of the parse module's error codes.
1146
- * @param options - Error metadata, including the `data` payload for `code`.
1147
- */
1148
- constructor(code, options) {
1149
- const messageFn = VigorParseErrorMessageFuncs[code];
1150
- super(code, messageFn(options.data), options);
1151
- }
1152
- }
1153
1061
 
1154
- const VigorParsePolicyStrategiesBase = {
1155
- __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1156
- funcs: []
1062
+ // src/parse/strategies.ts
1063
+ var VigorParsePolicyStrategiesBase = {
1064
+ __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1065
+ funcs: []
1157
1066
  };
1158
- const ContentTypeParsers = [
1159
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1160
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1161
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1162
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1163
- { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1164
- { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1165
- { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1166
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1167
- { 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() }
1168
1077
  ];
1169
- const SniffMethods = [
1170
- { title: "json", method: (res) => res.json() },
1171
- { title: "formData", method: (res) => res.formData() },
1172
- { title: "text", method: (res) => res.text() },
1173
- { 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() }
1174
1083
  ];
1175
- /** Parses a response by matching its `Content-Type` header against a known parser table. */
1176
- const VigorParseContentTypeStrategy = async (response) => {
1177
- const contentTypeHeader = response.headers.get("content-type");
1178
- if (!contentTypeHeader)
1179
- throw new VigorParseError("INVALID_CONTENT_TYPE", {
1180
- method: "VigorParseContentTypeStrategy",
1181
- data: { received: contentTypeHeader }
1182
- });
1183
- const toDo = ContentTypeParsers.find(parser => parser.regExp.test(contentTypeHeader));
1184
- if (!toDo)
1185
- throw new VigorParseError("PARSER_NOT_FOUND", {
1186
- method: "VigorParseContentTypeStrategy",
1187
- data: {
1188
- expected: ContentTypeParsers.map(p => p.header),
1189
- received: contentTypeHeader
1190
- }
1191
- });
1192
- 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);
1193
1099
  };
1194
- /** Parses a response by trying a sequence of body-reading methods until one succeeds. */
1195
- const VigorParseSniffStrategy = async (response) => {
1196
- for (const [i, parser] of SniffMethods.entries()) {
1197
- const cloned = (i === SniffMethods.length - 1) ? response : response.clone();
1198
- try {
1199
- return await parser.method(cloned);
1200
- }
1201
- catch { }
1202
- }
1203
- throw new VigorParseError("PARSER_ALL_FAILED", {
1204
- method: "VigorParseSniffStrategy",
1205
- data: { tried: SniffMethods.map(p => p.title) }
1206
- });
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
+ }
1207
1169
  };
1208
- /** Immutable builder for a parse policy's fallback chain of parsing strategies. */
1209
- class VigorParsePolicyStrategies extends VigorStatus {
1210
- constructor(config = VigorParseBase) {
1211
- super(VigorParseBase, config);
1212
- }
1213
- _create(config) {
1214
- return new VigorParsePolicyStrategies(config);
1215
- }
1216
- /**
1217
- * Adds strategy functions to the fallback chain.
1218
- *
1219
- * @param replace - When `true`, replaces the existing chain instead of
1220
- * appending to it (the default is to concat, since strategies are
1221
- * tried in sequence as a fallback chain).
1222
- */
1223
- _set(funcs, replace) {
1224
- return this._next({ policy: { strategies: { funcs } } }, replace ? { policy: { strategies: { funcs: "replace" } } } : undefined);
1225
- }
1226
- /** Adds the content-type based parsing strategy. */
1227
- contentType(replace) { return this._set([VigorParseContentTypeStrategy], replace); }
1228
- /** Adds the sniffing (try-each-method) parsing strategy. */
1229
- sniff(replace) { return this._set([VigorParseSniffStrategy], replace); }
1230
- /** Adds a strategy that always parses the response as JSON. */
1231
- json(replace) { return this._set([(res) => res.json()], replace); }
1232
- /** Adds a strategy that always parses the response as text. */
1233
- text(replace) { return this._set([(res) => res.text()], replace); }
1234
- /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1235
- arrayBuffer(replace) { return this._set([(res) => res.arrayBuffer()], replace); }
1236
- /** Adds a strategy that always parses the response as a `Blob`. */
1237
- blob(replace) { return this._set([(res) => res.blob()], replace); }
1238
- /** Adds a strategy that always parses the response as a `Uint8Array`. */
1239
- bytes(replace) { return this._set([(res) => res.arrayBuffer().then(b => new Uint8Array(b))], replace); }
1240
- /** Adds a strategy that always parses the response as `FormData`. */
1241
- formData(replace) { return this._set([(res) => res.formData()], replace); }
1242
- /** Adds a user-supplied custom parsing strategy. */
1243
- custom(func, replace) { return this._set([func], replace); }
1244
- }
1245
1170
 
1246
- const VigorParsePolicyBase = {
1247
- __brand: createBrand("Parse", "Policy<Schema"),
1248
- target: VigorDefault,
1249
- settings: VigorParsePolicySettingsBase,
1250
- middlewares: VigorParsePolicyMiddlewaresBase,
1251
- 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
1252
1178
  };
1253
1179
 
1254
- const VigorParseContextBase = {
1255
- __brand: createBrand("Parse", "Context<Schema"),
1256
- result: VigorDefault,
1257
- error: VigorDefault,
1258
- response: VigorDefault,
1259
- flags: {
1260
- overrided: false,
1261
- restarted: false
1262
- },
1263
- record: {},
1264
- 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
1265
1192
  };
1266
1193
 
1267
- const VigorParseBase = {
1268
- __brand: createBrand("Parse", "Schema"),
1269
- policy: VigorParsePolicyBase,
1270
- context: VigorParseContextBase
1194
+ // src/parse/main.ts
1195
+ var VigorParseBase = {
1196
+ __brand: createBrand("Parse", "Schema"),
1197
+ policy: VigorParsePolicyBase,
1198
+ context: VigorParseContextBase
1271
1199
  };
1272
- /**
1273
- * Immutable builder that parses an HTTP response into a result value,
1274
- * trying each configured strategy in sequence with an optional middleware
1275
- * pipeline and restart-on-failure support.
1276
- */
1277
- class VigorParse extends VigorStatus {
1278
- constructor(config = VigorParseBase) {
1279
- super(VigorParseBase, config);
1280
- }
1281
- _create(config) {
1282
- return new VigorParse(config);
1283
- }
1284
- /** Sets the `Response` object to parse. */
1285
- target(response) {
1286
- return this._next({ policy: { target: response } });
1287
- }
1288
- /** Configures the parse policy's general settings. */
1289
- settings(input) {
1290
- if (typeof input === 'function' || input instanceof VigorParsePolicySettings) {
1291
- const result = typeof input === 'function'
1292
- ? input(new VigorParsePolicySettings())
1293
- : input;
1294
- return this._next({
1295
- policy: { settings: result.config.policy.settings }
1296
- });
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 });
1297
1273
  }
1298
- return this._next({ policy: { settings: input } });
1299
- }
1300
- /** Configures the parse policy's middleware pipeline. */
1301
- middlewares(input) {
1302
- if (typeof input === 'function' || input instanceof VigorParsePolicyMiddlewares) {
1303
- const result = typeof input === 'function'
1304
- ? input(new VigorParsePolicyMiddlewares())
1305
- : input;
1306
- return this._next({
1307
- policy: { middlewares: result.config.policy.middlewares }
1308
- });
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
+ }
1309
1289
  }
1310
- return this._next({ policy: { middlewares: input } });
1311
- }
1312
- /** Configures the parse policy's fallback chain of parsing strategies. */
1313
- strategies(input) {
1314
- if (typeof input === 'function' || input instanceof VigorParsePolicyStrategies) {
1315
- const result = typeof input === 'function'
1316
- ? input(new VigorParsePolicyStrategies())
1317
- : input;
1318
- return this._next({
1319
- policy: { strategies: result.config.policy.strategies }
1320
- });
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 });
1321
1304
  }
1322
- return this._next({ policy: { strategies: input } });
1323
- }
1324
- /** Runs parsing and returns the result directly, throwing on final failure. */
1325
- async request() {
1326
- const res = await this.requestVerbose();
1327
- if (res.success)
1328
- return res.data;
1329
- throw res.error;
1330
- }
1331
- /** Runs parsing and returns a result/error envelope instead of throwing. */
1332
- async requestVerbose() {
1333
- return await this.requestRuntime();
1334
- }
1335
- /** Internal execution loop implementing the strategy fallback and restart handling. */
1336
- async requestRuntime(restartAttempt = 1) {
1337
- const config = this._merge(this.config, {});
1338
- let ctx = {
1339
- ...config.context,
1340
- policy: config.policy
1341
- };
1342
- if (isVigorDefault(ctx.policy.target))
1343
- throw new VigorParseError("VALUE_REQUIRED", {
1344
- method: "request",
1345
- data: { key: "target" },
1346
- context: ctx
1347
- });
1348
- ctx.response = ctx.policy.target;
1349
- const throwError = (err) => { throw err; };
1350
- try {
1351
- for (const middleware of ctx.policy.middlewares.before) {
1352
- if (middleware._mode === "fluent") {
1353
- await middleware.func(ctx);
1354
- }
1355
- else {
1356
- ctx = await middleware.func(ctx, { throwError });
1357
- }
1358
- }
1359
- const response = ctx.response;
1360
- if (ctx.policy.settings.raw) {
1361
- ctx.result = response;
1362
- }
1363
- else {
1364
- const funcs = ctx.policy.strategies.funcs.length > 0
1365
- ? ctx.policy.strategies.funcs
1366
- : [VigorParseContentTypeStrategy];
1367
- let parsed = false;
1368
- for (const [i, func] of funcs.entries()) {
1369
- const cloned = (i === funcs.length - 1) ? response : response.clone();
1370
- try {
1371
- ctx.result = await func(cloned);
1372
- parsed = true;
1373
- break;
1374
- }
1375
- catch { }
1376
- }
1377
- if (!parsed)
1378
- throw new VigorParseError("PARSER_ALL_FAILED", {
1379
- method: "request",
1380
- data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1381
- context: ctx
1382
- });
1383
- }
1384
- const setResult = (res) => { ctx.result = res; };
1385
- for (const middleware of ctx.policy.middlewares.after) {
1386
- if (middleware._mode === "fluent") {
1387
- await middleware.func(ctx);
1388
- }
1389
- else {
1390
- ctx = await middleware.func(ctx, { setResult, throwError });
1391
- }
1392
- }
1393
- for (const middleware of ctx.policy.middlewares.onResult) {
1394
- if (middleware._mode === "fluent") {
1395
- ctx.result = await middleware.func(ctx.result);
1396
- }
1397
- else {
1398
- ctx = await middleware.func(ctx, { setResult, throwError });
1399
- }
1400
- }
1401
- return {
1402
- success: true,
1403
- data: ctx.result,
1404
- error: null
1405
- };
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 });
1406
1311
  }
1407
- catch (error) {
1408
- ctx.error = error;
1409
- ctx.flags.overrided = false;
1410
- ctx.flags.restarted = false;
1411
- const setResult = (res) => {
1412
- ctx.flags.overrided = true;
1413
- ctx.result = res;
1414
- };
1415
- const proceedRestart = () => ctx.flags.restarted = true;
1416
- const cancelRestart = () => ctx.flags.restarted = false;
1417
- for (const middleware of ctx.policy.middlewares.onError) {
1418
- if (middleware._mode === "fluent") {
1419
- await middleware.func(ctx.error);
1420
- }
1421
- else {
1422
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1423
- }
1424
- }
1425
- if (ctx.flags.restarted) {
1426
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1427
- throw new VigorParseError("RESTART_EXHAUSTED", {
1428
- method: "request",
1429
- data: {
1430
- maxAttempts: ctx.policy.settings.maxRestarts
1431
- }
1432
- });
1433
- return await this.requestRuntime(restartAttempt + 1);
1434
- }
1435
- if (ctx.flags.overrided)
1436
- return {
1437
- success: true,
1438
- data: ctx.result,
1439
- error: null
1440
- };
1441
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1442
- const data = await ctx.policy.settings.default(ctx);
1443
- return {
1444
- success: true,
1445
- data,
1446
- error: null
1447
- };
1448
- }
1449
- return {
1450
- success: false,
1451
- data: null,
1452
- error: ctx.error
1453
- };
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 });
1454
1333
  }
1455
- }
1456
- }
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
+ };
1457
1367
 
1458
- const VigorFetchPolicyBase = {
1459
- __brand: createBrand("Fetch", "Policy<Schema"),
1460
- method: VigorEmpty,
1461
- origin: VigorEmpty,
1462
- path: [],
1463
- query: [],
1464
- hash: "",
1465
- headers: {},
1466
- body: VigorEmpty,
1467
- extra: {},
1468
- settings: VigorFetchPolicySettingsBase,
1469
- middlewares: VigorFetchPolicyMiddlewaresBase,
1470
- retry: VigorRetryBase,
1471
- 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
1472
1383
  };
1473
1384
 
1474
- const VigorFetchContextBase = {
1475
- __brand: createBrand("Fetch", "Context<Schema"),
1476
- href: "",
1477
- response: VigorDefault,
1478
- result: VigorDefault,
1479
- error: VigorDefault,
1480
- options: VigorDefault,
1481
- flags: {
1482
- overrided: false,
1483
- restarted: false
1484
- },
1485
- record: {},
1486
- 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
1487
1399
  };
1488
1400
 
1489
- const VigorFetchErrorMessageFuncs = {
1490
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1491
- INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1492
- INVALID_PROTOCOL: ({ origin, base }) => base
1493
- ? `Invalid URL: could not resolve "${origin}" against base "${base}"`
1494
- : `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`,
1495
- FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1496
- 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
+ }
1497
1418
  };
1498
- /** Error type thrown by the fetch module. */
1499
- class VigorFetchError extends VigorError {
1500
- /**
1501
- * @param code - One of the fetch module's error codes.
1502
- * @param options - Error metadata, including the `data` payload for `code`.
1503
- */
1504
- constructor(code, options) {
1505
- const messageFn = VigorFetchErrorMessageFuncs[code];
1506
- super(code, messageFn(options.data), options);
1507
- }
1508
- }
1509
1419
 
1510
- const VigorFetchBase = {
1511
- __brand: createBrand("Fetch", "Schema"),
1512
- policy: VigorFetchPolicyBase,
1513
- context: VigorFetchContextBase
1420
+ // src/fetch/main.ts
1421
+ var VigorFetchBase = {
1422
+ __brand: createBrand("Fetch", "Schema"),
1423
+ policy: VigorFetchPolicyBase,
1424
+ context: VigorFetchContextBase
1514
1425
  };
1515
- /**
1516
- * Immutable builder that performs an HTTP request, composing an internal
1517
- * {@link VigorRetry} engine (for retry/timeout/backoff) and a
1518
- * {@link VigorParse} engine (for response parsing), with a configurable
1519
- * middleware pipeline around request building and response handling.
1520
- */
1521
- class VigorFetch extends VigorStatus {
1522
- constructor(config = VigorFetchBase) {
1523
- super(VigorFetchBase, config);
1524
- }
1525
- _create(config) {
1526
- return new VigorFetch(config);
1527
- }
1528
- /** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
1529
- method(str) { return this._next({ policy: { method: str } }); }
1530
- /** Sets the request origin, either an absolute URL or a path relative to the current page. */
1531
- origin(str) { return this._next({ policy: { origin: str } }); }
1532
- /** Appends path segments to the request URL. */
1533
- path(...strs) {
1534
- return this._next({ policy: { path: this._stringifyList(strs) } });
1535
- }
1536
- /** Adds query-string parameter objects to the request URL. */
1537
- query(...objs) {
1538
- return this._next({ policy: { query: objs } });
1539
- }
1540
- /** Sets the URL fragment ("hash"), replacing any previous value. */
1541
- hash(str) { return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } }); }
1542
- /**
1543
- * Sets request headers.
1544
- *
1545
- * @param mode - `"overwrite"` discards all previously configured headers
1546
- * and keeps only the ones passed here. `"merge"` behaves like
1547
- * `Object.assign`, overwriting only the keys that overlap and keeping
1548
- * the rest.
1549
- */
1550
- headers(mode, obj) {
1551
- if (mode === "overwrite")
1552
- return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1553
- return this._next({ policy: { headers: obj } });
1554
- }
1555
- /**
1556
- * Sets the request body.
1557
- *
1558
- * @param mode - `"overwrite"` discards the previous body and fully
1559
- * replaces it with this value. `"merge"` shallow-merges (via
1560
- * `Object.assign`) when both the previous and new body are plain
1561
- * objects; for any other body type (string/Blob/FormData/etc) it is
1562
- * simply replaced.
1563
- */
1564
- body(mode, obj) {
1565
- if (mode === "overwrite")
1566
- return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1567
- return this._next({ policy: { body: obj } });
1568
- }
1569
- /**
1570
- * Sets additional `RequestInit` options other than headers/body/method/signal
1571
- * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1572
- * `referrerPolicy`, `keepalive`, `integrity`).
1573
- *
1574
- * @param mode - `"overwrite"` discards all previously configured options
1575
- * and replaces them with this value. `"merge"` shallow-merges this
1576
- * value onto the previous options.
1577
- */
1578
- options(mode, obj) {
1579
- if (mode === "overwrite")
1580
- return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1581
- return this._next({ policy: { extra: obj } });
1582
- }
1583
- /** Configures the fetch policy's general settings. */
1584
- settings(input) {
1585
- if (typeof input === 'function' || input instanceof VigorFetchPolicySettings) {
1586
- const result = typeof input === 'function'
1587
- ? input(new VigorFetchPolicySettings())
1588
- : input;
1589
- return this._next({ policy: { settings: result.config.policy.settings } });
1590
- }
1591
- return this._next({ policy: { settings: input } });
1592
- }
1593
- /** Configures the fetch policy's middleware pipeline. */
1594
- middlewares(input) {
1595
- if (typeof input === 'function' || input instanceof VigorFetchPolicyMiddlewares) {
1596
- const result = typeof input === 'function'
1597
- ? input(new VigorFetchPolicyMiddlewares())
1598
- : input;
1599
- return this._next({ policy: { middlewares: result.config.policy.middlewares } });
1600
- }
1601
- return this._next({ policy: { middlewares: input } });
1602
- }
1603
- /** Configures the retry engine used to send the underlying request. */
1604
- retry(input) {
1605
- if (typeof input === 'function' || input instanceof VigorRetry) {
1606
- const result = typeof input === 'function'
1607
- ? input(new VigorRetry())
1608
- : input;
1609
- return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1610
- }
1611
- return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
1612
- }
1613
- /** Configures the parse engine used to interpret the response. */
1614
- parse(input) {
1615
- if (typeof input === 'function' || input instanceof VigorParse) {
1616
- const result = typeof input === 'function'
1617
- ? input(new VigorParse())
1618
- : input;
1619
- return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1620
- }
1621
- return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
1622
- }
1623
- /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1624
- _stringifyList(unkList) {
1625
- return unkList
1626
- .filter(unk => unk !== null && unk !== undefined)
1627
- .map(unk => unk instanceof Date ? unk.toISOString() : String(unk));
1628
- }
1629
- /**
1630
- * Resolves the base URL used to interpret a relative `origin`. In a
1631
- * browser environment this is the current page location; in
1632
- * environments without `location` (e.g. Node), no base is available and
1633
- * `origin` must be an absolute URL.
1634
- */
1635
- _resolveBase() {
1636
- if (typeof globalThis !== 'undefined' && globalThis.location?.href) {
1637
- return globalThis.location.href;
1638
- }
1639
- return undefined;
1640
- }
1641
- /**
1642
- * Builds the final request URL from the configured origin, path
1643
- * segments, query parameters, and hash. An absolute `origin` ignores
1644
- * the resolved base (per the `URL` spec); a relative `origin` is
1645
- * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
1646
- */
1647
- _buildUrl(origin, path, query, hash) {
1648
- const base = this._resolveBase();
1649
- let originObj;
1650
- try {
1651
- originObj = new URL(origin, base);
1652
- }
1653
- catch {
1654
- throw new VigorFetchError("INVALID_PROTOCOL", {
1655
- method: "_buildUrl",
1656
- data: { origin, base }
1657
- });
1658
- }
1659
- const baseStr = originObj.origin;
1660
- const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, '')];
1661
- for (const p of path)
1662
- pathParts.push(p.replace(/^\/+|\/+$/g, ''));
1663
- const pathStr = pathParts.filter(Boolean).join('/');
1664
- const mainObj = new URL(pathStr, baseStr);
1665
- const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
1666
- const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap(q => Object.entries(q))];
1667
- for (const [key, val] of queryEntries) {
1668
- if (val === undefined || val === null)
1669
- continue;
1670
- if (Array.isArray(val)) {
1671
- for (const e of val)
1672
- mainObj.searchParams.append(key, parseVal(e));
1673
- }
1674
- else {
1675
- 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;
1676
1645
  }
1646
+ });
1677
1647
  }
1678
- mainObj.hash = hash || originObj.hash;
1679
- return mainObj.href;
1680
- }
1681
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1682
- _normalizeBody(body) {
1683
- if (body == null)
1684
- return { headers: {}, body: body };
1685
- if (typeof body === "string")
1686
- return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1687
- if (body instanceof Blob)
1688
- return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1689
- if (body instanceof ArrayBuffer)
1690
- return { headers: { "Content-Type": "application/octet-stream" }, body };
1691
- if (body instanceof URLSearchParams)
1692
- return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1693
- if (body instanceof FormData)
1694
- return { headers: {}, body };
1695
- if (typeof body === "object")
1696
- return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1697
- throw new VigorFetchError("INVALID_BODY", {
1698
- method: "_normalizeBody",
1699
- data: { received: body }
1700
- });
1701
- }
1702
- /** Runs the request and returns its parsed result directly, throwing on final failure. */
1703
- async request() {
1704
- const res = await this.requestVerbose();
1705
- if (res.success)
1706
- return res.data;
1707
- throw res.error;
1708
- }
1709
- /** Runs the request and returns a result/error envelope instead of throwing. */
1710
- async requestVerbose() {
1711
- return await this.requestRuntime();
1712
- }
1713
- /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1714
- async requestRuntime(restartAttempt = 1) {
1715
- const config = this._merge(this.config, {});
1716
- let ctx = {
1717
- ...config.context,
1718
- policy: config.policy
1719
- };
1720
- const throwError = (err) => { throw err; };
1721
- try {
1722
- if (isVigorEmpty(ctx.policy.origin))
1723
- throw new VigorFetchError("VALUE_REQUIRED", {
1724
- method: "request",
1725
- data: { key: "origin" }
1726
- });
1727
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1728
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== undefined;
1729
- const method = ctx.policy.method || (hasBody ? "POST" : "GET");
1730
- let options = {
1731
- ...ctx.policy.extra,
1732
- method: method,
1733
- headers: {}
1734
- };
1735
- if (hasBody) {
1736
- const normalized = this._normalizeBody(ctx.policy.body);
1737
- if (normalized.body !== undefined)
1738
- options.body = normalized.body;
1739
- Object.assign(options.headers, normalized.headers);
1740
- }
1741
- Object.assign(options.headers, ctx.policy.headers);
1742
- for (const middleware of ctx.policy.middlewares.before) {
1743
- if (middleware._mode === "fluent") {
1744
- await middleware.func(ctx);
1745
- }
1746
- else {
1747
- ctx = await middleware.func(ctx, {
1748
- throwError,
1749
- setOptions: (o) => { options = o; },
1750
- setHeaders: (h) => { options.headers = h; },
1751
- setBody: (b) => { options.body = b; }
1752
- });
1753
- }
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 {
1754
1660
  }
1755
- ctx.options = options;
1756
- const retryEngine = new VigorRetry(ctx.policy.retry)
1757
- .target(async (signal) => {
1758
- return await fetch(ctx.href, { ...options, signal });
1759
- })
1760
- .middlewares(m => m
1761
- .after("intercept", async (rctx, api) => {
1762
- const response = rctx.result;
1763
- if (!response.ok) {
1764
- let parsed = undefined;
1765
- try {
1766
- parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
1767
- }
1768
- catch {
1769
- }
1770
- api.throwError(new VigorFetchError("FETCH_FAILED", {
1771
- method: "request",
1772
- data: {
1773
- status: response.status,
1774
- statusText: response.statusText,
1775
- response,
1776
- url: response.url,
1777
- parsed
1778
- }
1779
- }));
1780
- }
1781
- return rctx;
1782
- })
1783
- .retryIf("intercept", async (rctx, api) => {
1784
- const response = rctx.error instanceof VigorFetchError
1785
- ? rctx.error.data?.response
1786
- : undefined;
1787
- if (response && ctx.policy.settings.unretryStatus.includes(response.status))
1788
- api.cancelRetry();
1789
- else
1790
- api.proceedRetry();
1791
- return rctx;
1792
- })
1793
- .onRetry("intercept", async (rctx, api) => {
1794
- const response = rctx.error instanceof VigorFetchError
1795
- ? rctx.error.data?.response
1796
- : undefined;
1797
- if (response?.status === 429) {
1798
- let retryHeader = null;
1799
- for (const header of ctx.policy.settings.retryHeaders) {
1800
- retryHeader = response.headers.get(header);
1801
- if (retryHeader)
1802
- break;
1803
- }
1804
- if (retryHeader) {
1805
- const toNumber = Number(retryHeader);
1806
- const delay = !isNaN(toNumber)
1807
- ? toNumber * 1000
1808
- : (() => {
1809
- const toDate = new Date(retryHeader).getTime();
1810
- return !isNaN(toDate) ? toDate - Date.now() : null;
1811
- })();
1812
- if (delay !== null && delay > 0)
1813
- api.setDelay(delay);
1814
- }
1815
- }
1816
- 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
+ }
1817
1670
  }));
1818
- ctx.response = await retryEngine.request();
1819
- const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
1820
- ctx.result = await parseEngine.request();
1821
- for (const middleware of ctx.policy.middlewares.after) {
1822
- if (middleware._mode === "fluent") {
1823
- await middleware.func(ctx);
1824
- }
1825
- else {
1826
- ctx = await middleware.func(ctx, { throwError, setResult: (r) => { ctx.result = r; } });
1827
- }
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;
1828
1685
  }
1829
- const setResult = (r) => { ctx.result = r; };
1830
- for (const middleware of ctx.policy.middlewares.onResult) {
1831
- if (middleware._mode === "fluent") {
1832
- ctx.result = await middleware.func(ctx.result);
1833
- }
1834
- else {
1835
- ctx = await middleware.func(ctx, { setResult, throwError });
1836
- }
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);
1837
1693
  }
1838
- return {
1839
- success: true,
1840
- data: ctx.result,
1841
- error: null
1842
- };
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
+ } });
1843
1708
  }
1844
- catch (error) {
1845
- ctx.error = error;
1846
- ctx.flags.overrided = false;
1847
- ctx.flags.restarted = false;
1848
- const setResult = (r) => {
1849
- ctx.flags.overrided = true;
1850
- ctx.result = r;
1851
- };
1852
- const proceedRestart = () => ctx.flags.restarted = true;
1853
- const cancelRestart = () => ctx.flags.restarted = false;
1854
- for (const middleware of ctx.policy.middlewares.onError) {
1855
- if (middleware._mode === "fluent") {
1856
- await middleware.func(ctx.error);
1857
- }
1858
- else {
1859
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1860
- }
1861
- }
1862
- if (ctx.flags.restarted) {
1863
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1864
- throw new VigorFetchError("RESTART_EXHAUSTED", {
1865
- method: "request",
1866
- data: {
1867
- maxAttempts: ctx.policy.settings.maxRestarts
1868
- }
1869
- });
1870
- return await this.requestRuntime(restartAttempt + 1);
1871
- }
1872
- if (ctx.flags.overrided)
1873
- return {
1874
- success: true,
1875
- data: ctx.result,
1876
- error: null
1877
- };
1878
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1879
- const data = await ctx.policy.settings.default(ctx);
1880
- return {
1881
- success: true,
1882
- data,
1883
- error: null
1884
- };
1885
- }
1886
- return {
1887
- success: false,
1888
- data: null,
1889
- error
1890
- };
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 });
1891
1718
  }
1892
- }
1893
- }
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
+ };
1894
1774
 
1895
- const vigor = {
1896
- use: (plugin, options) => {
1897
- 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()
1898
1785
  },
1899
- retry: (task) => task ? new VigorRetry().target(task) : new VigorRetry(),
1900
- parse: (response) => response ? new VigorParse().target(response) : new VigorParse(),
1901
- fetch: (origin) => origin ? new VigorFetch().origin(origin) : new VigorFetch(),
1902
- all: (...tasks) => tasks.length > 0 ? new VigorAll().target(...tasks) : new VigorAll(),
1903
- builders: {
1904
- fetch: {
1905
- settings: () => new VigorFetchPolicySettings(),
1906
- middlewares: () => new VigorFetchPolicyMiddlewares(),
1907
- },
1908
- retry: {
1909
- settings: () => new VigorRetryPolicySettings(),
1910
- middlewares: () => new VigorRetryPolicyMiddlewares(),
1911
- algorithms: () => new VigorRetryPolicyAlgorithms(),
1912
- algorithm: {
1913
- constant: () => new VigorRetryPolicyAlgorithmsConstant(),
1914
- linear: () => new VigorRetryPolicyAlgorithmsLinear(),
1915
- backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
1916
- custom: () => new VigorRetryPolicyAlgorithmsCustom(),
1917
- },
1918
- },
1919
- parse: {
1920
- settings: () => new VigorParsePolicySettings(),
1921
- middlewares: () => new VigorParsePolicyMiddlewares(),
1922
- strategies: () => new VigorParsePolicyStrategies(),
1923
- },
1924
- all: {
1925
- settings: () => new VigorAllPolicySettings(),
1926
- middlewares: () => new VigorAllPolicyMiddlewares(),
1927
- },
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()
1928
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
+ }
1929
1823
  };
1930
1824
 
1931
- exports.VigorAll = VigorAll;
1932
- exports.VigorAllBase = VigorAllBase;
1933
- exports.VigorAllError = VigorAllError;
1934
- exports.VigorAllErrorMessageFuncs = VigorAllErrorMessageFuncs;
1935
- exports.VigorAllPolicyBase = VigorAllPolicyBase;
1936
- exports.VigorAllPolicyMiddlewares = VigorAllPolicyMiddlewares;
1937
- exports.VigorAllPolicyMiddlewaresBase = VigorAllPolicyMiddlewaresBase;
1938
- exports.VigorAllPolicySettings = VigorAllPolicySettings;
1939
- exports.VigorAllPolicySettingsBase = VigorAllPolicySettingsBase;
1940
- exports.VigorError = VigorError;
1941
- exports.VigorFetch = VigorFetch;
1942
- exports.VigorFetchBase = VigorFetchBase;
1943
- exports.VigorFetchError = VigorFetchError;
1944
- exports.VigorFetchErrorMessageFuncs = VigorFetchErrorMessageFuncs;
1945
- exports.VigorFetchPolicyBase = VigorFetchPolicyBase;
1946
- exports.VigorFetchPolicyMiddlewares = VigorFetchPolicyMiddlewares;
1947
- exports.VigorFetchPolicyMiddlewaresBase = VigorFetchPolicyMiddlewaresBase;
1948
- exports.VigorFetchPolicySettings = VigorFetchPolicySettings;
1949
- exports.VigorFetchPolicySettingsBase = VigorFetchPolicySettingsBase;
1950
- exports.VigorJitter = VigorJitter;
1951
- exports.VigorParse = VigorParse;
1952
- exports.VigorParseBase = VigorParseBase;
1953
- exports.VigorParseContentTypeStrategy = VigorParseContentTypeStrategy;
1954
- exports.VigorParseError = VigorParseError;
1955
- exports.VigorParseErrorMessageFuncs = VigorParseErrorMessageFuncs;
1956
- exports.VigorParsePolicyBase = VigorParsePolicyBase;
1957
- exports.VigorParsePolicyMiddlewares = VigorParsePolicyMiddlewares;
1958
- exports.VigorParsePolicyMiddlewaresBase = VigorParsePolicyMiddlewaresBase;
1959
- exports.VigorParsePolicySettings = VigorParsePolicySettings;
1960
- exports.VigorParsePolicySettingsBase = VigorParsePolicySettingsBase;
1961
- exports.VigorParsePolicyStrategies = VigorParsePolicyStrategies;
1962
- exports.VigorParsePolicyStrategiesBase = VigorParsePolicyStrategiesBase;
1963
- exports.VigorParseSniffStrategy = VigorParseSniffStrategy;
1964
- exports.VigorRetry = VigorRetry;
1965
- exports.VigorRetryBase = VigorRetryBase;
1966
- exports.VigorRetryError = VigorRetryError;
1967
- exports.VigorRetryErrorMessageFuncs = VigorRetryErrorMessageFuncs;
1968
- exports.VigorRetryPolicyAlgorithms = VigorRetryPolicyAlgorithms;
1969
- exports.VigorRetryPolicyAlgorithmsBackoff = VigorRetryPolicyAlgorithmsBackoff;
1970
- exports.VigorRetryPolicyAlgorithmsBackoffBase = VigorRetryPolicyAlgorithmsBackoffBase;
1971
- exports.VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsBase;
1972
- exports.VigorRetryPolicyAlgorithmsConstant = VigorRetryPolicyAlgorithmsConstant;
1973
- exports.VigorRetryPolicyAlgorithmsConstantBase = VigorRetryPolicyAlgorithmsConstantBase;
1974
- exports.VigorRetryPolicyAlgorithmsCustom = VigorRetryPolicyAlgorithmsCustom;
1975
- exports.VigorRetryPolicyAlgorithmsCustomBase = VigorRetryPolicyAlgorithmsCustomBase;
1976
- exports.VigorRetryPolicyAlgorithmsLinear = VigorRetryPolicyAlgorithmsLinear;
1977
- exports.VigorRetryPolicyAlgorithmsLinearBase = VigorRetryPolicyAlgorithmsLinearBase;
1978
- exports.VigorRetryPolicyBase = VigorRetryPolicyBase;
1979
- exports.VigorRetryPolicyMiddlewares = VigorRetryPolicyMiddlewares;
1980
- exports.VigorRetryPolicyMiddlewaresBase = VigorRetryPolicyMiddlewaresBase;
1981
- exports.VigorRetryPolicySettings = VigorRetryPolicySettings;
1982
- exports.VigorRetryPolicySettingsBase = VigorRetryPolicySettingsBase;
1983
- exports.VigorStatus = VigorStatus;
1984
- exports.default = vigor;
1985
- 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
+ };