@npora/request 1.9.1 → 1.10.1

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/README.md CHANGED
@@ -1,10 +1,40 @@
1
1
  # @npora/request
2
2
 
3
- A TypeScript-first HTTP client built on the standard Fetch API.
4
-
5
- Npora Request adds typed configuration, a predictable request lifecycle,
6
- interceptors, plugins, unified errors, retries, caching, authentication, and
7
- upload/download progress without adding runtime dependencies.
3
+ A production-focused, TypeScript-first HTTP client built on the standard Fetch
4
+ API, with zero runtime dependencies.
5
+
6
+ Npora Request keeps the native Fetch model while adding the contracts and
7
+ resilience needed by real applications: inferred response types, runtime
8
+ validation, incremental streaming, stable errors, deterministic extension
9
+ ordering, retries, caching, concurrency control, circuit breaking,
10
+ authentication, and upload/download progress.
11
+
12
+ ## Why Npora Request
13
+
14
+ - **Trust responses at runtime.** Standard Schema v1 validation checks and can
15
+ transform untrusted data while preserving full response and error metadata.
16
+ - **Stream without buffering everything.** SSE and NDJSON are exposed as lazy
17
+ async iterables with cancellation, timeout, and response-size enforcement.
18
+ - **Add resilience without hiding the transport.** Retry, cache, circuit
19
+ breaker, concurrency, authentication, logging, and progress are isolated,
20
+ composable plugins over the standard Fetch API.
21
+ - **Use one predictable contract everywhere.** Browsers, Web Workers, Node.js,
22
+ ESM, and CommonJS share the same typed lifecycle and stable error codes.
23
+ - **Ship less supply-chain risk.** The package has no runtime dependencies and
24
+ verifies public exports, browser behavior, security regressions, and size
25
+ budgets before release.
26
+
27
+ ## Features
28
+
29
+ - Data-first and complete-response APIs with TypeScript inference.
30
+ - Standard Schema v1 validation and transformation for untrusted responses.
31
+ - Incremental SSE and NDJSON async iterables with cancellation and size limits.
32
+ - Unified errors across Fetch, XHR, parsing, validation, timeouts, and aborts.
33
+ - Request/response/error interceptors with deterministic priority ordering.
34
+ - Official retry, cache, circuit-breaker, concurrency, authentication, logger,
35
+ upload, and download plugins.
36
+ - Method-aware `MockAdapter` routing, matching, delays, failures, and history.
37
+ - Browser, Web Worker, ESM, and CommonJS support with zero runtime dependencies.
8
38
 
9
39
  ## Install
10
40
 
@@ -20,6 +50,18 @@ Node.js 22 or newer is required. Modern Chromium-based browsers, Firefox,
20
50
  Safari/WebKit, and Web Workers are supported through their native Fetch
21
51
  implementations.
22
52
 
53
+ ## Version support
54
+
55
+ | Version | Status | Guidance |
56
+ | --- | --- | --- |
57
+ | `latest` | Current | Recommended for all new and existing applications. |
58
+ | Earlier releases `>=1.0.0` | Historical stable | Upgrade to `latest` for current fixes and security hardening. |
59
+ | `<1.0.0` | Deprecated and unsupported | Upgrade immediately; 0.x receives no fixes or security updates. |
60
+
61
+ All published releases before `1.0.0` are deprecated by project policy. Do not
62
+ use a 0.x release in production, documentation examples, dependency templates,
63
+ or new lockfiles.
64
+
23
65
  ## Quick start
24
66
 
25
67
  ```ts
@@ -53,6 +95,33 @@ console.log(response.headers)
53
95
  console.log(response.raw)
54
96
  ```
55
97
 
98
+ ## Response validation
99
+
100
+ Validate untrusted response data with any Standard Schema v1 compatible
101
+ library, including Zod 3.24+, Valibot, or ArkType. The schema output type is
102
+ inferred automatically and schemas may transform the parsed value:
103
+
104
+ ```ts
105
+ import { z } from 'zod'
106
+
107
+ const userSchema = z.object({
108
+ id: z.number(),
109
+ name: z.string()
110
+ })
111
+
112
+ const user = await api.get('/users/1', {
113
+ schema: userSchema
114
+ })
115
+
116
+ console.log(user.name)
117
+ ```
118
+
119
+ Validation failures throw `SchemaValidationError` with the stable
120
+ `SCHEMA_ERROR` code, validation issues, schema vendor, parsed response data,
121
+ and complete response metadata. Standard Schema support adds no runtime
122
+ dependency to Npora Request. Schemas are configured per endpoint so one
123
+ endpoint contract cannot be inherited by unrelated requests.
124
+
56
125
  ## Streaming responses
57
126
 
58
127
  SSE and NDJSON responses are decoded incrementally as async iterables. The
@@ -77,7 +146,8 @@ for await (const user of records) {
77
146
 
78
147
  Iteration is lazy and does not buffer the complete response. Breaking out of
79
148
  the loop cancels the response reader. `maxResponseSize` remains enforced while
80
- the stream is consumed.
149
+ the stream is consumed. A response schema validates the parsed response value
150
+ once; it does not validate individual SSE events or NDJSON records.
81
151
 
82
152
  ## Request configuration
83
153
 
@@ -318,10 +388,23 @@ Stable request error codes:
318
388
  - `TIMEOUT_ERROR`
319
389
  - `ABORT_ERROR`
320
390
  - `PARSER_ERROR`
391
+ - `SCHEMA_ERROR`
321
392
  - `RESPONSE_TOO_LARGE`
322
393
  - `CIRCUIT_OPEN`
323
394
  - `CONCURRENCY_LIMIT`
324
395
 
396
+ `SchemaValidationError` extends `RequestError`, so applications can handle all
397
+ request failures through the unified base class while still inspecting schema
398
+ issues when `error.code === 'SCHEMA_ERROR'`.
399
+
400
+ ## Supply-chain verification
401
+
402
+ The published package contains only the built `dist` artifacts, has no runtime
403
+ dependencies, and is released through npm trusted publishing with provenance.
404
+ Repository release gates verify the exact dependency tree against malware
405
+ advisories, npm registry signatures, known vulnerabilities, the package file
406
+ allowlist, and size budgets.
407
+
325
408
  ## Documentation
326
409
 
327
410
  - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
package/dist/index.cjs CHANGED
@@ -17,6 +17,24 @@ var RequestError = class extends Error {
17
17
  }
18
18
  };
19
19
  //#endregion
20
+ //#region src/errors/SchemaValidationError.ts
21
+ /**
22
+ * Response failure reported by a Standard Schema compatible validator.
23
+ */
24
+ var SchemaValidationError = class extends RequestError {
25
+ constructor(message, response, schemaVendor, issues = [], cause) {
26
+ super(message, {
27
+ code: "SCHEMA_ERROR",
28
+ response,
29
+ cause
30
+ });
31
+ this.name = "SchemaValidationError";
32
+ this.issues = issues;
33
+ this.schemaVendor = schemaVendor;
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ };
37
+ //#endregion
20
38
  //#region src/utils/createTimeoutSignal.ts
21
39
  function createTimeoutSignal(signal, timeout) {
22
40
  if (!timeout || timeout <= 0) return {
@@ -619,10 +637,22 @@ function validateRequestConfig(config) {
619
637
  validateURL(config);
620
638
  validateTimeout(config);
621
639
  validateLimits(config);
640
+ validateSchema(config);
622
641
  const headers = validateHeaders(config);
623
642
  validateBody(config);
624
643
  return headers;
625
644
  }
645
+ function validateSchema(config) {
646
+ if (config.schema === void 0) return;
647
+ try {
648
+ const candidate = config.schema;
649
+ if (typeof candidate !== "object" && typeof candidate !== "function" || candidate === null) throw new TypeError("Schema must be an object or function");
650
+ const standard = candidate["~standard"];
651
+ if (typeof standard !== "object" || standard === null || standard.version !== 1 || typeof standard.vendor !== "string" || typeof standard.validate !== "function") throw new TypeError("Schema does not implement Standard Schema v1");
652
+ } catch (error) {
653
+ throw configError("Request schema must implement Standard Schema v1", config, error);
654
+ }
655
+ }
626
656
  function validateLimits(config) {
627
657
  validateLimit(config.maxResponseSize, "Request maxResponseSize", config);
628
658
  validateLimit(config.maxFormDataDepth, "Request maxFormDataDepth", config);
@@ -1217,9 +1247,35 @@ var Pipeline = class {
1217
1247
  }
1218
1248
  async processResponse(context) {
1219
1249
  if (this.hooks.hasResponseHooks) await this.hooks.runResponse(context);
1250
+ await this.validateResponseSchema(context);
1220
1251
  if (this.interceptors.response.active) context.response = await this.interceptors.response.run(context.response);
1221
1252
  return context.response;
1222
1253
  }
1254
+ async validateResponseSchema(context) {
1255
+ const schema = context.config.schema;
1256
+ const response = context.response;
1257
+ if (!schema || !response) return;
1258
+ let result;
1259
+ let schemaVendor = "unknown";
1260
+ try {
1261
+ const standard = schema["~standard"];
1262
+ schemaVendor = standard.vendor;
1263
+ result = await standard.validate(response.data);
1264
+ } catch (error) {
1265
+ throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1266
+ }
1267
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1268
+ const issues = "issues" in result ? result.issues : void 0;
1269
+ if (issues !== void 0) {
1270
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1271
+ throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1272
+ }
1273
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1274
+ context.response = {
1275
+ ...response,
1276
+ data: result.value
1277
+ };
1278
+ }
1223
1279
  async notifyError(context, error) {
1224
1280
  context.error = error;
1225
1281
  if (this.hooks.hasErrorHooks) try {
@@ -1857,7 +1913,7 @@ var MemoryCacheStore = class {
1857
1913
  get(key) {
1858
1914
  const entry = this.entries.get(key);
1859
1915
  if (!entry) return;
1860
- if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1916
+ if (isExpired(entry.expiresAt)) {
1861
1917
  this.entries.delete(key);
1862
1918
  return;
1863
1919
  }
@@ -1909,10 +1965,11 @@ function cachePlugin(options = {}) {
1909
1965
  context.hooks.onRequest(async (requestContext) => {
1910
1966
  const cache = resolveExtensionConfig(requestContext.config, "cache");
1911
1967
  if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) return;
1968
+ normalizeCacheTtl(cache.ttl, requestContext.config);
1912
1969
  const key = createCacheKey(requestContext.config, cache, varyHeaders);
1913
1970
  const record = await readStore(store, key);
1914
1971
  if (!active) return;
1915
- if (record) if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) await deleteStore(store, key);
1972
+ if (record) if (isExpired(record.expiresAt)) await deleteStore(store, key);
1916
1973
  else {
1917
1974
  const cachedResponse = restoreCacheEntry(record, requestContext.config);
1918
1975
  if (cachedResponse) {
@@ -1946,7 +2003,7 @@ function cachePlugin(options = {}) {
1946
2003
  await deleteStore(store, key);
1947
2004
  return;
1948
2005
  }
1949
- const ttl = cache.ttl ?? 3e4;
2006
+ const ttl = normalizeCacheTtl(cache.ttl, requestContext.config);
1950
2007
  const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
1951
2008
  completedRecords.set(requestContext, record);
1952
2009
  if (ttl <= 0 || !allowsPersistentCaching(requestContext.response)) {
@@ -1969,7 +2026,7 @@ function cachePlugin(options = {}) {
1969
2026
  }
1970
2027
  const record = completedRecords.get(requestContext);
1971
2028
  completedRecords.delete(requestContext);
1972
- if (record && requestContext.response && !requestContext.error) {
2029
+ if (record && requestContext.response && (!requestContext.error || isSchemaValidationFailure(requestContext.error))) {
1973
2030
  pending.resolve(record);
1974
2031
  return;
1975
2032
  }
@@ -2103,6 +2160,9 @@ function isCacheableRequest(config, methods) {
2103
2160
  function isAsyncIterable(value) {
2104
2161
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
2105
2162
  }
2163
+ function isSchemaValidationFailure(error) {
2164
+ return error instanceof RequestError && error.code === "SCHEMA_ERROR";
2165
+ }
2106
2166
  function allowsPersistentCaching(response) {
2107
2167
  if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
2108
2168
  return !response.headers.get("vary")?.split(",").some((name) => name.trim() === "*");
@@ -2177,6 +2237,17 @@ function normalizeMaxEntries(value) {
2177
2237
  if (!Number.isFinite(value)) return value > 0 ? Number.POSITIVE_INFINITY : 0;
2178
2238
  return Math.max(0, Math.floor(value));
2179
2239
  }
2240
+ function normalizeCacheTtl(value, config) {
2241
+ const ttl = value ?? 3e4;
2242
+ if (ttl !== Number.POSITIVE_INFINITY && (!Number.isFinite(ttl) || ttl < 0)) throw new RequestError("Cache ttl must be a non-negative finite number or Infinity", {
2243
+ code: "CONFIG_ERROR",
2244
+ config
2245
+ });
2246
+ return ttl;
2247
+ }
2248
+ function isExpired(expiresAt) {
2249
+ return Number.isNaN(expiresAt) || Date.now() > expiresAt;
2250
+ }
2180
2251
  //#endregion
2181
2252
  //#region src/plugins/circuitBreakerPlugin.ts
2182
2253
  function circuitBreakerPlugin(options = {}) {
@@ -3186,6 +3257,7 @@ exports.MemoryCacheStore = MemoryCacheStore;
3186
3257
  exports.MockAdapter = MockAdapter;
3187
3258
  exports.PluginError = PluginError;
3188
3259
  exports.RequestError = RequestError;
3260
+ exports.SchemaValidationError = SchemaValidationError;
3189
3261
  exports.authPlugin = authPlugin;
3190
3262
  exports.cachePlugin = cachePlugin;
3191
3263
  exports.circuitBreakerPlugin = circuitBreakerPlugin;
package/dist/index.d.cts CHANGED
@@ -4,6 +4,49 @@
4
4
  */
5
5
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
+ //#region src/types/standardSchema.d.ts
8
+ /**
9
+ * Standard Schema v1 interface.
10
+ *
11
+ * Compatible schema libraries can be consumed without a runtime dependency on
12
+ * `@standard-schema/spec`.
13
+ */
14
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
15
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
16
+ }
17
+ declare namespace StandardSchemaV1 {
18
+ interface Props<Input = unknown, Output = Input> {
19
+ readonly version: 1;
20
+ readonly vendor: string;
21
+ readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
22
+ readonly types?: Types<Input, Output>;
23
+ }
24
+ interface Options {
25
+ readonly libraryOptions?: Record<string, unknown>;
26
+ }
27
+ type Result<Output> = SuccessResult<Output> | FailureResult;
28
+ interface SuccessResult<Output> {
29
+ readonly value: Output;
30
+ readonly issues?: undefined;
31
+ }
32
+ interface FailureResult {
33
+ readonly issues: ReadonlyArray<Issue>;
34
+ }
35
+ interface Issue {
36
+ readonly message: string;
37
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment>;
38
+ }
39
+ interface PathSegment {
40
+ readonly key: PropertyKey;
41
+ }
42
+ interface Types<Input = unknown, Output = Input> {
43
+ readonly input: Input;
44
+ readonly output: Output;
45
+ }
46
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
47
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
48
+ }
49
+ //#endregion
7
50
  //#region src/types/extensions.d.ts
8
51
  type CircuitState = 'closed' | 'open' | 'half-open';
9
52
  interface CircuitBreakerOptions {
@@ -91,6 +134,12 @@ interface RetryEvent {
91
134
  }
92
135
  interface CacheOptions {
93
136
  enabled?: boolean;
137
+ /**
138
+ * Time in milliseconds before a cached response expires.
139
+ * Use `0` to disable persistence or `Infinity` to retain it indefinitely.
140
+ *
141
+ * @default 30000
142
+ */
94
143
  ttl?: number;
95
144
  key?: string;
96
145
  /**
@@ -274,6 +323,12 @@ interface RequestConfig {
274
323
  */
275
324
  maxFormDataDepth?: number;
276
325
  responseType?: ResponseType;
326
+ /**
327
+ * Validate and optionally transform the parsed response value.
328
+ *
329
+ * Accepts any Standard Schema v1 compatible validator.
330
+ */
331
+ schema?: StandardSchemaV1;
277
332
  validateStatus?: (status: number) => boolean;
278
333
  extensions?: RequestExtensions;
279
334
  }
@@ -353,7 +408,7 @@ interface Adapter {
353
408
  /**
354
409
  * Client creation options.
355
410
  */
356
- interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method'>> {
411
+ interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method' | 'schema'>> {
357
412
  /**
358
413
  * Request adapter.
359
414
  *
@@ -533,6 +588,10 @@ interface Plugin {
533
588
  }
534
589
  //#endregion
535
590
  //#region src/client/Client.d.ts
591
+ type MethodConfig = Omit<RequestConfig, 'url' | 'method'>;
592
+ type SchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<MethodConfig, 'schema'> & {
593
+ schema: Schema;
594
+ };
536
595
  declare class Client {
537
596
  private readonly defaults;
538
597
  private readonly adapter;
@@ -552,38 +611,56 @@ declare class Client {
552
611
  use(plugin: Plugin): this;
553
612
  unuse(pluginName: string): this;
554
613
  hasPlugin(pluginName: string): boolean;
614
+ request<Schema extends StandardSchemaV1>(config: RequestConfig & {
615
+ schema: Schema;
616
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
555
617
  request<T = unknown>(config: RequestConfig): Promise<T>;
618
+ requestResponse<Schema extends StandardSchemaV1>(config: RequestConfig & {
619
+ schema: Schema;
620
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
556
621
  requestResponse<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
557
- get<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
558
- getResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
559
- post<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
560
- postResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
561
- put<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
562
- putResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
563
- patch<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
564
- patchResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
565
- delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
566
- deleteResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
567
- head(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<void>;
568
- headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
569
- options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
570
- optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
622
+ get<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
623
+ get<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
624
+ getResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
625
+ getResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
626
+ post<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
627
+ post<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
628
+ postResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
629
+ postResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
630
+ put<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
631
+ put<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
632
+ putResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
633
+ putResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
634
+ patch<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
635
+ patch<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
636
+ patchResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
637
+ patchResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
638
+ delete<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
639
+ delete<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
640
+ deleteResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
641
+ deleteResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
642
+ head(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<void>;
643
+ headResponse(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<NporaResponse<void>>;
644
+ options<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
645
+ options<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
646
+ optionsResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
647
+ optionsResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
571
648
  /**
572
649
  * Consume a server-sent event response as a lazy async iterable.
573
650
  */
574
- sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
651
+ sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<ServerSentEvent>>;
575
652
  /**
576
653
  * Consume a server-sent event response with complete response metadata.
577
654
  */
578
- sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
655
+ sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
579
656
  /**
580
657
  * Consume newline-delimited JSON records as a lazy async iterable.
581
658
  */
582
- ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
659
+ ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<T>>;
583
660
  /**
584
661
  * Consume newline-delimited JSON with complete response metadata.
585
662
  */
586
- ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
663
+ ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<T>>>;
587
664
  private createPipeline;
588
665
  private validatePlugin;
589
666
  private findDependent;
@@ -599,7 +676,7 @@ declare function createClient(options?: ClientOptions): Client;
599
676
  /**
600
677
  * Public request error codes.
601
678
  */
602
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
679
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'SCHEMA_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
603
680
  interface RequestErrorOptions<T = unknown> {
604
681
  /**
605
682
  * Stable machine-readable error code.
@@ -639,6 +716,16 @@ declare class RequestError<T = unknown> extends Error {
639
716
  constructor(message: string, options: RequestErrorOptions<T>);
640
717
  }
641
718
  //#endregion
719
+ //#region src/errors/SchemaValidationError.d.ts
720
+ /**
721
+ * Response failure reported by a Standard Schema compatible validator.
722
+ */
723
+ declare class SchemaValidationError<T = unknown> extends RequestError<T> {
724
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
725
+ readonly schemaVendor: string;
726
+ constructor(message: string, response: NporaResponse<T>, schemaVendor: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, cause?: unknown);
727
+ }
728
+ //#endregion
642
729
  //#region src/plugins/PluginError.d.ts
643
730
  type PluginErrorCode = 'MISSING_DEPENDENCY' | 'PLUGIN_CONFLICT' | 'DEPENDENCY_IN_USE';
644
731
  interface PluginErrorOptions {
@@ -905,4 +992,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
905
992
  //#region src/plugins/uploadPlugin.d.ts
906
993
  declare function uploadPlugin(): Plugin;
907
994
  //#endregion
908
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
995
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,49 @@
4
4
  */
5
5
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
+ //#region src/types/standardSchema.d.ts
8
+ /**
9
+ * Standard Schema v1 interface.
10
+ *
11
+ * Compatible schema libraries can be consumed without a runtime dependency on
12
+ * `@standard-schema/spec`.
13
+ */
14
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
15
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
16
+ }
17
+ declare namespace StandardSchemaV1 {
18
+ interface Props<Input = unknown, Output = Input> {
19
+ readonly version: 1;
20
+ readonly vendor: string;
21
+ readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
22
+ readonly types?: Types<Input, Output>;
23
+ }
24
+ interface Options {
25
+ readonly libraryOptions?: Record<string, unknown>;
26
+ }
27
+ type Result<Output> = SuccessResult<Output> | FailureResult;
28
+ interface SuccessResult<Output> {
29
+ readonly value: Output;
30
+ readonly issues?: undefined;
31
+ }
32
+ interface FailureResult {
33
+ readonly issues: ReadonlyArray<Issue>;
34
+ }
35
+ interface Issue {
36
+ readonly message: string;
37
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment>;
38
+ }
39
+ interface PathSegment {
40
+ readonly key: PropertyKey;
41
+ }
42
+ interface Types<Input = unknown, Output = Input> {
43
+ readonly input: Input;
44
+ readonly output: Output;
45
+ }
46
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
47
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
48
+ }
49
+ //#endregion
7
50
  //#region src/types/extensions.d.ts
8
51
  type CircuitState = 'closed' | 'open' | 'half-open';
9
52
  interface CircuitBreakerOptions {
@@ -91,6 +134,12 @@ interface RetryEvent {
91
134
  }
92
135
  interface CacheOptions {
93
136
  enabled?: boolean;
137
+ /**
138
+ * Time in milliseconds before a cached response expires.
139
+ * Use `0` to disable persistence or `Infinity` to retain it indefinitely.
140
+ *
141
+ * @default 30000
142
+ */
94
143
  ttl?: number;
95
144
  key?: string;
96
145
  /**
@@ -274,6 +323,12 @@ interface RequestConfig {
274
323
  */
275
324
  maxFormDataDepth?: number;
276
325
  responseType?: ResponseType;
326
+ /**
327
+ * Validate and optionally transform the parsed response value.
328
+ *
329
+ * Accepts any Standard Schema v1 compatible validator.
330
+ */
331
+ schema?: StandardSchemaV1;
277
332
  validateStatus?: (status: number) => boolean;
278
333
  extensions?: RequestExtensions;
279
334
  }
@@ -353,7 +408,7 @@ interface Adapter {
353
408
  /**
354
409
  * Client creation options.
355
410
  */
356
- interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method'>> {
411
+ interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method' | 'schema'>> {
357
412
  /**
358
413
  * Request adapter.
359
414
  *
@@ -533,6 +588,10 @@ interface Plugin {
533
588
  }
534
589
  //#endregion
535
590
  //#region src/client/Client.d.ts
591
+ type MethodConfig = Omit<RequestConfig, 'url' | 'method'>;
592
+ type SchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<MethodConfig, 'schema'> & {
593
+ schema: Schema;
594
+ };
536
595
  declare class Client {
537
596
  private readonly defaults;
538
597
  private readonly adapter;
@@ -552,38 +611,56 @@ declare class Client {
552
611
  use(plugin: Plugin): this;
553
612
  unuse(pluginName: string): this;
554
613
  hasPlugin(pluginName: string): boolean;
614
+ request<Schema extends StandardSchemaV1>(config: RequestConfig & {
615
+ schema: Schema;
616
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
555
617
  request<T = unknown>(config: RequestConfig): Promise<T>;
618
+ requestResponse<Schema extends StandardSchemaV1>(config: RequestConfig & {
619
+ schema: Schema;
620
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
556
621
  requestResponse<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
557
- get<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
558
- getResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
559
- post<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
560
- postResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
561
- put<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
562
- putResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
563
- patch<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
564
- patchResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
565
- delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
566
- deleteResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
567
- head(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<void>;
568
- headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
569
- options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
570
- optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
622
+ get<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
623
+ get<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
624
+ getResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
625
+ getResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
626
+ post<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
627
+ post<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
628
+ postResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
629
+ postResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
630
+ put<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
631
+ put<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
632
+ putResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
633
+ putResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
634
+ patch<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
635
+ patch<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
636
+ patchResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
637
+ patchResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
638
+ delete<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
639
+ delete<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
640
+ deleteResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
641
+ deleteResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
642
+ head(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<void>;
643
+ headResponse(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<NporaResponse<void>>;
644
+ options<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
645
+ options<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
646
+ optionsResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
647
+ optionsResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
571
648
  /**
572
649
  * Consume a server-sent event response as a lazy async iterable.
573
650
  */
574
- sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
651
+ sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<ServerSentEvent>>;
575
652
  /**
576
653
  * Consume a server-sent event response with complete response metadata.
577
654
  */
578
- sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
655
+ sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
579
656
  /**
580
657
  * Consume newline-delimited JSON records as a lazy async iterable.
581
658
  */
582
- ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
659
+ ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<T>>;
583
660
  /**
584
661
  * Consume newline-delimited JSON with complete response metadata.
585
662
  */
586
- ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
663
+ ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<T>>>;
587
664
  private createPipeline;
588
665
  private validatePlugin;
589
666
  private findDependent;
@@ -599,7 +676,7 @@ declare function createClient(options?: ClientOptions): Client;
599
676
  /**
600
677
  * Public request error codes.
601
678
  */
602
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
679
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'SCHEMA_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
603
680
  interface RequestErrorOptions<T = unknown> {
604
681
  /**
605
682
  * Stable machine-readable error code.
@@ -639,6 +716,16 @@ declare class RequestError<T = unknown> extends Error {
639
716
  constructor(message: string, options: RequestErrorOptions<T>);
640
717
  }
641
718
  //#endregion
719
+ //#region src/errors/SchemaValidationError.d.ts
720
+ /**
721
+ * Response failure reported by a Standard Schema compatible validator.
722
+ */
723
+ declare class SchemaValidationError<T = unknown> extends RequestError<T> {
724
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
725
+ readonly schemaVendor: string;
726
+ constructor(message: string, response: NporaResponse<T>, schemaVendor: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, cause?: unknown);
727
+ }
728
+ //#endregion
642
729
  //#region src/plugins/PluginError.d.ts
643
730
  type PluginErrorCode = 'MISSING_DEPENDENCY' | 'PLUGIN_CONFLICT' | 'DEPENDENCY_IN_USE';
644
731
  interface PluginErrorOptions {
@@ -905,4 +992,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
905
992
  //#region src/plugins/uploadPlugin.d.ts
906
993
  declare function uploadPlugin(): Plugin;
907
994
  //#endregion
908
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
995
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -16,6 +16,24 @@ var RequestError = class extends Error {
16
16
  }
17
17
  };
18
18
  //#endregion
19
+ //#region src/errors/SchemaValidationError.ts
20
+ /**
21
+ * Response failure reported by a Standard Schema compatible validator.
22
+ */
23
+ var SchemaValidationError = class extends RequestError {
24
+ constructor(message, response, schemaVendor, issues = [], cause) {
25
+ super(message, {
26
+ code: "SCHEMA_ERROR",
27
+ response,
28
+ cause
29
+ });
30
+ this.name = "SchemaValidationError";
31
+ this.issues = issues;
32
+ this.schemaVendor = schemaVendor;
33
+ Object.setPrototypeOf(this, new.target.prototype);
34
+ }
35
+ };
36
+ //#endregion
19
37
  //#region src/utils/createTimeoutSignal.ts
20
38
  function createTimeoutSignal(signal, timeout) {
21
39
  if (!timeout || timeout <= 0) return {
@@ -618,10 +636,22 @@ function validateRequestConfig(config) {
618
636
  validateURL(config);
619
637
  validateTimeout(config);
620
638
  validateLimits(config);
639
+ validateSchema(config);
621
640
  const headers = validateHeaders(config);
622
641
  validateBody(config);
623
642
  return headers;
624
643
  }
644
+ function validateSchema(config) {
645
+ if (config.schema === void 0) return;
646
+ try {
647
+ const candidate = config.schema;
648
+ if (typeof candidate !== "object" && typeof candidate !== "function" || candidate === null) throw new TypeError("Schema must be an object or function");
649
+ const standard = candidate["~standard"];
650
+ if (typeof standard !== "object" || standard === null || standard.version !== 1 || typeof standard.vendor !== "string" || typeof standard.validate !== "function") throw new TypeError("Schema does not implement Standard Schema v1");
651
+ } catch (error) {
652
+ throw configError("Request schema must implement Standard Schema v1", config, error);
653
+ }
654
+ }
625
655
  function validateLimits(config) {
626
656
  validateLimit(config.maxResponseSize, "Request maxResponseSize", config);
627
657
  validateLimit(config.maxFormDataDepth, "Request maxFormDataDepth", config);
@@ -1216,9 +1246,35 @@ var Pipeline = class {
1216
1246
  }
1217
1247
  async processResponse(context) {
1218
1248
  if (this.hooks.hasResponseHooks) await this.hooks.runResponse(context);
1249
+ await this.validateResponseSchema(context);
1219
1250
  if (this.interceptors.response.active) context.response = await this.interceptors.response.run(context.response);
1220
1251
  return context.response;
1221
1252
  }
1253
+ async validateResponseSchema(context) {
1254
+ const schema = context.config.schema;
1255
+ const response = context.response;
1256
+ if (!schema || !response) return;
1257
+ let result;
1258
+ let schemaVendor = "unknown";
1259
+ try {
1260
+ const standard = schema["~standard"];
1261
+ schemaVendor = standard.vendor;
1262
+ result = await standard.validate(response.data);
1263
+ } catch (error) {
1264
+ throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1265
+ }
1266
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1267
+ const issues = "issues" in result ? result.issues : void 0;
1268
+ if (issues !== void 0) {
1269
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1270
+ throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1271
+ }
1272
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1273
+ context.response = {
1274
+ ...response,
1275
+ data: result.value
1276
+ };
1277
+ }
1222
1278
  async notifyError(context, error) {
1223
1279
  context.error = error;
1224
1280
  if (this.hooks.hasErrorHooks) try {
@@ -1856,7 +1912,7 @@ var MemoryCacheStore = class {
1856
1912
  get(key) {
1857
1913
  const entry = this.entries.get(key);
1858
1914
  if (!entry) return;
1859
- if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1915
+ if (isExpired(entry.expiresAt)) {
1860
1916
  this.entries.delete(key);
1861
1917
  return;
1862
1918
  }
@@ -1908,10 +1964,11 @@ function cachePlugin(options = {}) {
1908
1964
  context.hooks.onRequest(async (requestContext) => {
1909
1965
  const cache = resolveExtensionConfig(requestContext.config, "cache");
1910
1966
  if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) return;
1967
+ normalizeCacheTtl(cache.ttl, requestContext.config);
1911
1968
  const key = createCacheKey(requestContext.config, cache, varyHeaders);
1912
1969
  const record = await readStore(store, key);
1913
1970
  if (!active) return;
1914
- if (record) if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) await deleteStore(store, key);
1971
+ if (record) if (isExpired(record.expiresAt)) await deleteStore(store, key);
1915
1972
  else {
1916
1973
  const cachedResponse = restoreCacheEntry(record, requestContext.config);
1917
1974
  if (cachedResponse) {
@@ -1945,7 +2002,7 @@ function cachePlugin(options = {}) {
1945
2002
  await deleteStore(store, key);
1946
2003
  return;
1947
2004
  }
1948
- const ttl = cache.ttl ?? 3e4;
2005
+ const ttl = normalizeCacheTtl(cache.ttl, requestContext.config);
1949
2006
  const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
1950
2007
  completedRecords.set(requestContext, record);
1951
2008
  if (ttl <= 0 || !allowsPersistentCaching(requestContext.response)) {
@@ -1968,7 +2025,7 @@ function cachePlugin(options = {}) {
1968
2025
  }
1969
2026
  const record = completedRecords.get(requestContext);
1970
2027
  completedRecords.delete(requestContext);
1971
- if (record && requestContext.response && !requestContext.error) {
2028
+ if (record && requestContext.response && (!requestContext.error || isSchemaValidationFailure(requestContext.error))) {
1972
2029
  pending.resolve(record);
1973
2030
  return;
1974
2031
  }
@@ -2102,6 +2159,9 @@ function isCacheableRequest(config, methods) {
2102
2159
  function isAsyncIterable(value) {
2103
2160
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
2104
2161
  }
2162
+ function isSchemaValidationFailure(error) {
2163
+ return error instanceof RequestError && error.code === "SCHEMA_ERROR";
2164
+ }
2105
2165
  function allowsPersistentCaching(response) {
2106
2166
  if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
2107
2167
  return !response.headers.get("vary")?.split(",").some((name) => name.trim() === "*");
@@ -2176,6 +2236,17 @@ function normalizeMaxEntries(value) {
2176
2236
  if (!Number.isFinite(value)) return value > 0 ? Number.POSITIVE_INFINITY : 0;
2177
2237
  return Math.max(0, Math.floor(value));
2178
2238
  }
2239
+ function normalizeCacheTtl(value, config) {
2240
+ const ttl = value ?? 3e4;
2241
+ if (ttl !== Number.POSITIVE_INFINITY && (!Number.isFinite(ttl) || ttl < 0)) throw new RequestError("Cache ttl must be a non-negative finite number or Infinity", {
2242
+ code: "CONFIG_ERROR",
2243
+ config
2244
+ });
2245
+ return ttl;
2246
+ }
2247
+ function isExpired(expiresAt) {
2248
+ return Number.isNaN(expiresAt) || Date.now() > expiresAt;
2249
+ }
2179
2250
  //#endregion
2180
2251
  //#region src/plugins/circuitBreakerPlugin.ts
2181
2252
  function circuitBreakerPlugin(options = {}) {
@@ -3178,4 +3249,4 @@ function uploadPlugin() {
3178
3249
  };
3179
3250
  }
3180
3251
  //#endregion
3181
- export { Client, FetchAdapter, InterceptorManager, MemoryCacheStore, MockAdapter, PluginError, RequestError, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
3252
+ export { Client, FetchAdapter, InterceptorManager, MemoryCacheStore, MockAdapter, PluginError, RequestError, SchemaValidationError, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.9.1",
3
+ "version": "1.10.1",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",