@zap-studio/fetch 0.5.2 → 0.5.4
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/CHANGELOG.md +13 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/errors.d.mts +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/headers.d.mts +1 -1
- package/dist/headers.mjs +4 -5
- package/dist/headers.mjs.map +1 -1
- package/dist/index.mjs +6 -6
- package/dist/index.mjs.map +1 -1
- package/dist/internal.mjs +6 -3
- package/dist/internal.mjs.map +1 -1
- package/dist/methods.mjs +1 -1
- package/dist/methods.mjs.map +1 -1
- package/dist/request.d.mts.map +1 -1
- package/dist/request.mjs +3 -2
- package/dist/request.mjs.map +1 -1
- package/dist/types.d.mts +3 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/url.mjs +8 -3
- package/dist/url.mjs.map +1 -1
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @zap-studio/fetch
|
|
2
2
|
|
|
3
|
+
## 0.5.4
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Added fetch ecosystem benchmarks and grouped benchmark output for easier cross-library comparisons.
|
|
8
|
+
- Applied small internal performance optimizations in request preparation, URL resolution, and header merging without changing public API behavior.
|
|
9
|
+
|
|
10
|
+
## 0.5.3
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Refactor `createFetch(...)` to derive fallback defaults from `GLOBAL_DEFAULTS` instead of re-defining primitive defaults inline.
|
|
15
|
+
|
|
3
16
|
## 0.5.2
|
|
4
17
|
|
|
5
18
|
### Changed
|
package/dist/constants.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/**\n * Shared defaults and constants for fetch behavior.\n *\n * @module\n */\n\nimport type { FetchDefaults } from \"./types.js\";\n\n/**\n * Default options for the global $fetch\n *\n * These defaults are used by the top-level `$fetch` export.\n * Use `createFetch(...)` when you need per-client defaults.\n *\n * @example\n * import { GLOBAL_DEFAULTS } from \"@zap-studio/fetch/constants\";\n *\n * console.log(GLOBAL_DEFAULTS.throwOnFetchError); // true\n */\nexport const GLOBAL_DEFAULTS: FetchDefaults = {\n baseURL: \"\",\n throwOnFetchError: true,\n throwOnValidationError: true,\n};\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAa,kBAAiC;CAC5C,SAAS;CACT,mBAAmB;CACnB,wBAAwB;CACzB"}
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/**\n * Shared defaults and constants for fetch behavior.\n *\n * @module @zap-studio/fetch/constants\n */\n\nimport type { FetchDefaults } from \"./types.js\";\n\n/**\n * Default options for the global $fetch\n *\n * These defaults are used by the top-level `$fetch` export.\n * Use `createFetch(...)` when you need per-client defaults.\n *\n * @example\n * import { GLOBAL_DEFAULTS } from \"@zap-studio/fetch/constants\";\n *\n * console.log(GLOBAL_DEFAULTS.throwOnFetchError); // true\n */\nexport const GLOBAL_DEFAULTS: FetchDefaults = {\n baseURL: \"\",\n throwOnFetchError: true,\n throwOnValidationError: true,\n};\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAa,kBAAiC;CAC5C,SAAS;CACT,mBAAmB;CACnB,wBAAwB;CACzB"}
|
package/dist/errors.d.mts
CHANGED
package/dist/errors.mjs
CHANGED
package/dist/errors.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types used by the fetch package.\n *\n * @module\n */\n\n/**\n * Error thrown for HTTP errors (non-2xx responses)\n *\n * Includes the failing `Response` object and status code for\n * downstream error handling and response inspection.\n *\n * @example\n * import { FetchError } from \"@zap-studio/fetch/errors\";\n *\n * try {\n * await $fetch(\"/users/404\");\n * } catch (error) {\n * if (error instanceof FetchError) {\n * console.error(error.status);\n * console.error(await error.response.text());\n * }\n * }\n */\nexport class FetchError extends Error {\n /**\n * HTTP status code from the failing response.\n */\n status: Response[\"status\"];\n /**\n * Full response object for additional inspection.\n */\n response: Response;\n\n /**\n * Creates a FetchError from a non-ok response.\n */\n constructor(message: string, response: Response) {\n super(message);\n this.name = \"FetchError\";\n this.status = response.status;\n this.response = response;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,aAAb,cAAgC,MAAM;;;;CAIpC;;;;CAIA;;;;CAKA,YAAY,SAAiB,UAAoB;AAC/C,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS;AACvB,OAAK,WAAW"}
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types used by the fetch package.\n *\n * @module @zap-studio/fetch/errors\n */\n\n/**\n * Error thrown for HTTP errors (non-2xx responses)\n *\n * Includes the failing `Response` object and status code for\n * downstream error handling and response inspection.\n *\n * @example\n * import { FetchError } from \"@zap-studio/fetch/errors\";\n *\n * try {\n * await $fetch(\"/users/404\");\n * } catch (error) {\n * if (error instanceof FetchError) {\n * console.error(error.status);\n * console.error(await error.response.text());\n * }\n * }\n */\nexport class FetchError extends Error {\n /**\n * HTTP status code from the failing response.\n */\n status: Response[\"status\"];\n /**\n * Full response object for additional inspection.\n */\n response: Response;\n\n /**\n * Creates a FetchError from a non-ok response.\n */\n constructor(message: string, response: Response) {\n super(message);\n this.name = \"FetchError\";\n this.status = response.status;\n this.response = response;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,aAAb,cAAgC,MAAM;;;;CAIpC;;;;CAIA;;;;CAKA,YAAY,SAAiB,UAAoB;AAC/C,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS;AACvB,OAAK,WAAW"}
|
package/dist/headers.d.mts
CHANGED
package/dist/headers.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Header utility helpers for request normalization and merging.
|
|
4
4
|
*
|
|
5
|
-
* @module
|
|
5
|
+
* @module @zap-studio/fetch/headers
|
|
6
6
|
*/
|
|
7
7
|
/**
|
|
8
8
|
* Merges two HeadersInit objects, with the second one taking precedence.
|
|
@@ -22,11 +22,10 @@
|
|
|
22
22
|
*/
|
|
23
23
|
function mergeHeaders(base, override) {
|
|
24
24
|
if (!(base || override)) return;
|
|
25
|
+
if (!base) return new Headers(override);
|
|
26
|
+
if (!override) return new Headers(base);
|
|
25
27
|
const merged = new Headers(base);
|
|
26
|
-
|
|
27
|
-
const overrideHeaders = new Headers(override);
|
|
28
|
-
for (const [key, value] of overrideHeaders.entries()) merged.set(key, value);
|
|
29
|
-
}
|
|
28
|
+
for (const [key, value] of new Headers(override).entries()) merged.set(key, value);
|
|
30
29
|
return merged;
|
|
31
30
|
}
|
|
32
31
|
//#endregion
|
package/dist/headers.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headers.mjs","names":[],"sources":["../src/headers.ts"],"sourcesContent":["/**\n * Header utility helpers for request normalization and merging.\n *\n * @module\n */\n\n/**\n * Merges two HeadersInit objects, with the second one taking precedence.\n *\n * @param base - Base/default headers.\n * @param override - Request-level override headers.\n * @returns A merged `Headers` object, or `undefined` when both inputs are empty.\n * @throws {TypeError} When either header input contains invalid header names or values.\n *\n * @example\n * const headers = mergeHeaders(\n * { Authorization: \"Bearer token\" },\n * { \"X-Trace-Id\": \"abc\" },\n * );\n *\n * console.log(headers?.get(\"Authorization\")); // Bearer token\n */\nexport function mergeHeaders(base?: HeadersInit, override?: HeadersInit): Headers | undefined {\n if (!(base || override)) {\n return;\n }\n\n
|
|
1
|
+
{"version":3,"file":"headers.mjs","names":[],"sources":["../src/headers.ts"],"sourcesContent":["/**\n * Header utility helpers for request normalization and merging.\n *\n * @module @zap-studio/fetch/headers\n */\n\n/**\n * Merges two HeadersInit objects, with the second one taking precedence.\n *\n * @param base - Base/default headers.\n * @param override - Request-level override headers.\n * @returns A merged `Headers` object, or `undefined` when both inputs are empty.\n * @throws {TypeError} When either header input contains invalid header names or values.\n *\n * @example\n * const headers = mergeHeaders(\n * { Authorization: \"Bearer token\" },\n * { \"X-Trace-Id\": \"abc\" },\n * );\n *\n * console.log(headers?.get(\"Authorization\")); // Bearer token\n */\nexport function mergeHeaders(base?: HeadersInit, override?: HeadersInit): Headers | undefined {\n if (!(base || override)) {\n return;\n }\n\n if (!base) {\n return new Headers(override);\n }\n\n if (!override) {\n return new Headers(base);\n }\n\n const merged = new Headers(base);\n for (const [key, value] of new Headers(override).entries()) {\n merged.set(key, value);\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,aAAa,MAAoB,UAA6C;AAC5F,KAAI,EAAE,QAAQ,UACZ;AAGF,KAAI,CAAC,KACH,QAAO,IAAI,QAAQ,SAAS;AAG9B,KAAI,CAAC,SACH,QAAO,IAAI,QAAQ,KAAK;CAG1B,MAAM,SAAS,IAAI,QAAQ,KAAK;AAChC,MAAK,MAAM,CAAC,KAAK,UAAU,IAAI,QAAQ,SAAS,CAAC,SAAS,CACxD,QAAO,IAAI,KAAK,MAAM;AAExB,QAAO"}
|
package/dist/index.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { isStandardSchema } from "@zap-studio/validation";
|
|
|
11
11
|
* - `api` method shortcuts
|
|
12
12
|
* - `createFetch` instance factory
|
|
13
13
|
*
|
|
14
|
-
* @module
|
|
14
|
+
* @module @zap-studio/fetch
|
|
15
15
|
*/
|
|
16
16
|
async function $fetch(input, schemaOrOptions, optionsOrUndefined) {
|
|
17
17
|
const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
|
|
@@ -76,12 +76,12 @@ const api = {
|
|
|
76
76
|
*/
|
|
77
77
|
function createFetch(factoryOptions = {}) {
|
|
78
78
|
const defaults = {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
79
|
+
...GLOBAL_DEFAULTS,
|
|
80
|
+
...factoryOptions,
|
|
81
|
+
baseURL: factoryOptions.baseURL ?? GLOBAL_DEFAULTS.baseURL,
|
|
82
|
+
throwOnFetchError: factoryOptions.throwOnFetchError ?? GLOBAL_DEFAULTS.throwOnFetchError,
|
|
83
|
+
throwOnValidationError: factoryOptions.throwOnValidationError ?? GLOBAL_DEFAULTS.throwOnValidationError
|
|
82
84
|
};
|
|
83
|
-
if (factoryOptions.headers !== void 0) defaults.headers = factoryOptions.headers;
|
|
84
|
-
if (factoryOptions.searchParams !== void 0) defaults.searchParams = factoryOptions.searchParams;
|
|
85
85
|
async function customFetch(input, schemaOrOptions, optionsOrUndefined) {
|
|
86
86
|
const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
|
|
87
87
|
return await fetchInternal(input, schema, options, defaults);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Public entrypoint for the fetch package.\n *\n * Exposes:\n * - `$fetch` low-level typed fetch function\n * - `api` method shortcuts\n * - `createFetch` instance factory\n *\n * @module\n */\n\nimport { isStandardSchema, type StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport { GLOBAL_DEFAULTS } from \"./constants.js\";\nimport { fetchInternal } from \"./internal.js\";\nimport { createMethod } from \"./methods.js\";\nimport type {\n $Fetch,\n ApiMethods,\n ExtendedRequestInit,\n FetchDefaults,\n FetchInput,\n} from \"./types.js\";\n\n/**\n * Type-safe fetch wrapper with Standard Schema validation.\n *\n * - When `throwOnValidationError: true`: validated data of type `TSchema`\n * - When `throwOnValidationError: false`: Standard Schema Result object `{ value?, issues? }`\n * - When `throwOnFetchError: true`: throws `FetchError` on non-ok responses\n *\n * If no schema is provided, returns the raw `Response` object.\n *\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws Any error thrown or rejected by the provided Standard Schema validator.\n *\n * @example\n * import { z } from \"zod\";\n * import { $fetch } from \"@zap-studio/fetch\";\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Basic usage (schema validation)\n * const user = await $fetch(\"/api/users/1\", UserSchema, { headers: { \"Authorization\": \"Bearer token\" } });\n * console.log(\"Validated user:\", user);\n *\n * // Raw usage (no schema validation and typed Response object)\n * const result = await $fetch(\"/api/data\", { method: \"POST\", body: JSON.stringify({ key: \"value\" }) });\n * const json = await result.json() as ResultType;\n * console.log(\"Raw response data:\", json);\n *\n * // Usage with validation errors returned instead of thrown\n * const result = await $fetch(\"/api/users/1\", UserSchema, { throwOnValidationError: false });\n *\n * if (result.issues) {\n * console.error(\"Validation errors:\", result.issues);\n * } else {\n * console.log(\"Validated user:\", result.value);\n * }\n */\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & { throwOnValidationError: false },\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & { throwOnValidationError?: true },\n): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\nexport async function $fetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;\n\nexport async function $fetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit,\n): Promise<unknown> {\n const [schema, options] = isStandardSchema(schemaOrOptions)\n ? [schemaOrOptions, optionsOrUndefined]\n : [undefined, schemaOrOptions];\n\n return await fetchInternal(input, schema, options, GLOBAL_DEFAULTS);\n}\n\n/**\n * Convenience methods for common HTTP verbs.\n *\n * These methods always require a schema for validation.\n * For raw responses without validation, use `$fetch` directly.\n *\n * Each method has the same throw behavior as {@link $fetch}.\n *\n * @example\n * import { z } from \"zod\";\n * import { api } from \"@zap-studio/fetch\";\n *\n * const PostSchema = z.object({\n * id: z.number(),\n * title: z.string(),\n * content: z.string(),\n * });\n *\n * async function fetchPost(postId: number) {\n * const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);\n * return post; // post is typed as { id: number; title: string; content: string; }\n * }\n */\nexport const api: ApiMethods = {\n get: createMethod($fetch, \"GET\"),\n post: createMethod($fetch, \"POST\"),\n put: createMethod($fetch, \"PUT\"),\n patch: createMethod($fetch, \"PATCH\"),\n delete: createMethod($fetch, \"DELETE\"),\n};\n\n/**\n * Creates a custom fetch instance with pre-configured defaults.\n *\n * Use this factory to create API clients with a base URL, default headers,\n * and other shared configuration. Each instance is independent.\n *\n * The returned `$fetch` and `api` methods have the same throw behavior as the\n * top-level {@link $fetch} export.\n *\n * @example\n * import { z } from \"zod\";\n * import { createFetch } from \"@zap-studio/fetch\";\n *\n * // Create a configured instance\n * const { $fetch, api } = createFetch({\n * baseURL: \"https://api.example.com\",\n * headers: { \"Authorization\": \"Bearer token\" },\n * });\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Now use relative paths - baseURL is prepended automatically\n * const user = await api.get(\"/users/1\", UserSchema);\n *\n * // Or use $fetch directly\n * const response = await $fetch(\"/users\", UserSchema, { method: \"POST\", json: { name: \"John\" } });\n */\nexport function createFetch(factoryOptions: Partial<FetchDefaults> = {}): {\n $fetch: $Fetch;\n api: ApiMethods;\n} {\n const defaults: FetchDefaults = {\n baseURL: factoryOptions.baseURL ??
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Public entrypoint for the fetch package.\n *\n * Exposes:\n * - `$fetch` low-level typed fetch function\n * - `api` method shortcuts\n * - `createFetch` instance factory\n *\n * @module @zap-studio/fetch\n */\n\nimport { isStandardSchema, type StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport { GLOBAL_DEFAULTS } from \"./constants.js\";\nimport { fetchInternal } from \"./internal.js\";\nimport { createMethod } from \"./methods.js\";\nimport type {\n $Fetch,\n ApiMethods,\n ExtendedRequestInit,\n FetchDefaults,\n FetchInput,\n} from \"./types.js\";\n\n/**\n * Type-safe fetch wrapper with Standard Schema validation.\n *\n * - When `throwOnValidationError: true`: validated data of type `TSchema`\n * - When `throwOnValidationError: false`: Standard Schema Result object `{ value?, issues? }`\n * - When `throwOnFetchError: true`: throws `FetchError` on non-ok responses\n *\n * If no schema is provided, returns the raw `Response` object.\n *\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws Any error thrown or rejected by the provided Standard Schema validator.\n *\n * @example\n * import { z } from \"zod\";\n * import { $fetch } from \"@zap-studio/fetch\";\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Basic usage (schema validation)\n * const user = await $fetch(\"/api/users/1\", UserSchema, { headers: { \"Authorization\": \"Bearer token\" } });\n * console.log(\"Validated user:\", user);\n *\n * // Raw usage (no schema validation and typed Response object)\n * const result = await $fetch(\"/api/data\", { method: \"POST\", body: JSON.stringify({ key: \"value\" }) });\n * const json = await result.json() as ResultType;\n * console.log(\"Raw response data:\", json);\n *\n * // Usage with validation errors returned instead of thrown\n * const result = await $fetch(\"/api/users/1\", UserSchema, { throwOnValidationError: false });\n *\n * if (result.issues) {\n * console.error(\"Validation errors:\", result.issues);\n * } else {\n * console.log(\"Validated user:\", result.value);\n * }\n */\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & { throwOnValidationError: false },\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & { throwOnValidationError?: true },\n): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\nexport async function $fetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;\n\nexport async function $fetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit,\n): Promise<unknown> {\n const [schema, options] = isStandardSchema(schemaOrOptions)\n ? [schemaOrOptions, optionsOrUndefined]\n : [undefined, schemaOrOptions];\n\n return await fetchInternal(input, schema, options, GLOBAL_DEFAULTS);\n}\n\n/**\n * Convenience methods for common HTTP verbs.\n *\n * These methods always require a schema for validation.\n * For raw responses without validation, use `$fetch` directly.\n *\n * Each method has the same throw behavior as {@link $fetch}.\n *\n * @example\n * import { z } from \"zod\";\n * import { api } from \"@zap-studio/fetch\";\n *\n * const PostSchema = z.object({\n * id: z.number(),\n * title: z.string(),\n * content: z.string(),\n * });\n *\n * async function fetchPost(postId: number) {\n * const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);\n * return post; // post is typed as { id: number; title: string; content: string; }\n * }\n */\nexport const api: ApiMethods = {\n get: createMethod($fetch, \"GET\"),\n post: createMethod($fetch, \"POST\"),\n put: createMethod($fetch, \"PUT\"),\n patch: createMethod($fetch, \"PATCH\"),\n delete: createMethod($fetch, \"DELETE\"),\n};\n\n/**\n * Creates a custom fetch instance with pre-configured defaults.\n *\n * Use this factory to create API clients with a base URL, default headers,\n * and other shared configuration. Each instance is independent.\n *\n * The returned `$fetch` and `api` methods have the same throw behavior as the\n * top-level {@link $fetch} export.\n *\n * @example\n * import { z } from \"zod\";\n * import { createFetch } from \"@zap-studio/fetch\";\n *\n * // Create a configured instance\n * const { $fetch, api } = createFetch({\n * baseURL: \"https://api.example.com\",\n * headers: { \"Authorization\": \"Bearer token\" },\n * });\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Now use relative paths - baseURL is prepended automatically\n * const user = await api.get(\"/users/1\", UserSchema);\n *\n * // Or use $fetch directly\n * const response = await $fetch(\"/users\", UserSchema, { method: \"POST\", json: { name: \"John\" } });\n */\nexport function createFetch(factoryOptions: Partial<FetchDefaults> = {}): {\n $fetch: $Fetch;\n api: ApiMethods;\n} {\n const defaults: FetchDefaults = {\n ...GLOBAL_DEFAULTS,\n ...factoryOptions,\n baseURL: factoryOptions.baseURL ?? GLOBAL_DEFAULTS.baseURL,\n throwOnFetchError: factoryOptions.throwOnFetchError ?? GLOBAL_DEFAULTS.throwOnFetchError,\n throwOnValidationError:\n factoryOptions.throwOnValidationError ?? GLOBAL_DEFAULTS.throwOnValidationError,\n };\n\n async function customFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & { throwOnValidationError: false },\n ): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\n async function customFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & {\n throwOnValidationError?: true;\n },\n ): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\n async function customFetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;\n\n async function customFetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit,\n ): Promise<unknown> {\n const [schema, options] = isStandardSchema(schemaOrOptions)\n ? [schemaOrOptions, optionsOrUndefined]\n : [undefined, schemaOrOptions];\n\n return await fetchInternal(input, schema, options, defaults);\n }\n\n const customApi = {\n get: createMethod(customFetch, \"GET\"),\n post: createMethod(customFetch, \"POST\"),\n put: createMethod(customFetch, \"PUT\"),\n patch: createMethod(customFetch, \"PATCH\"),\n delete: createMethod(customFetch, \"DELETE\"),\n };\n\n return {\n $fetch: customFetch,\n api: customApi,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoFA,eAAsB,OACpB,OACA,iBACA,oBACkB;CAClB,MAAM,CAAC,QAAQ,WAAW,iBAAiB,gBAAgB,GACvD,CAAC,iBAAiB,mBAAmB,GACrC,CAAC,KAAA,GAAW,gBAAgB;AAEhC,QAAO,MAAM,cAAc,OAAO,QAAQ,SAAS,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BrE,MAAa,MAAkB;CAC7B,KAAK,aAAa,QAAQ,MAAM;CAChC,MAAM,aAAa,QAAQ,OAAO;CAClC,KAAK,aAAa,QAAQ,MAAM;CAChC,OAAO,aAAa,QAAQ,QAAQ;CACpC,QAAQ,aAAa,QAAQ,SAAS;CACvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BD,SAAgB,YAAY,iBAAyC,EAAE,EAGrE;CACA,MAAM,WAA0B;EAC9B,GAAG;EACH,GAAG;EACH,SAAS,eAAe,WAAW,gBAAgB;EACnD,mBAAmB,eAAe,qBAAqB,gBAAgB;EACvE,wBACE,eAAe,0BAA0B,gBAAgB;EAC5D;CAkBD,eAAe,YACb,OACA,iBACA,oBACkB;EAClB,MAAM,CAAC,QAAQ,WAAW,iBAAiB,gBAAgB,GACvD,CAAC,iBAAiB,mBAAmB,GACrC,CAAC,KAAA,GAAW,gBAAgB;AAEhC,SAAO,MAAM,cAAc,OAAO,QAAQ,SAAS,SAAS;;AAW9D,QAAO;EACL,QAAQ;EACR,KAVgB;GAChB,KAAK,aAAa,aAAa,MAAM;GACrC,MAAM,aAAa,aAAa,OAAO;GACvC,KAAK,aAAa,aAAa,MAAM;GACrC,OAAO,aAAa,aAAa,QAAQ;GACzC,QAAQ,aAAa,aAAa,SAAS;GAC5C;EAKA"}
|
package/dist/internal.mjs
CHANGED
|
@@ -56,9 +56,12 @@ function prepareRequestInit(options, defaults) {
|
|
|
56
56
|
if (json !== void 0) {
|
|
57
57
|
if (init.body != null) throw new TypeError("Cannot provide both `body` and `json`.");
|
|
58
58
|
init.body = JSON.stringify(json);
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
if (!init.headers) init.headers = new Headers({ "Content-Type": "application/json" });
|
|
60
|
+
else {
|
|
61
|
+
const headers = new Headers(init.headers);
|
|
62
|
+
if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
63
|
+
init.headers = headers;
|
|
64
|
+
}
|
|
62
65
|
}
|
|
63
66
|
return {
|
|
64
67
|
init,
|
package/dist/internal.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/internal.ts"],"sourcesContent":["/**\n * Internal request execution and option preparation utilities.\n *\n * @module\n */\n\nimport type { StandardSchemaV1 } from \"@zap-studio/validation\";\nimport { standardValidate } from \"@zap-studio/validation\";\n\nimport { FetchError } from \"./errors.js\";\nimport { mergeHeaders } from \"./headers.js\";\nimport { normalizeRequest } from \"./request.js\";\nimport type { ExtendedRequestInit, FetchDefaults, FetchInput } from \"./types.js\";\nimport { resolveRequestUrl } from \"./url.js\";\n\n/**\n * Internal fetch implementation used by both $fetch and createFetch.\n *\n * This function normalizes request input, resolves final URL + query params,\n * executes `fetch`, optionally throws `FetchError`, and optionally validates\n * JSON response payloads using Standard Schema.\n *\n * @param input - Request URL, path, or Request object.\n * @param schema - Optional Standard Schema for response validation.\n * @param options - Optional request options and package-specific flags.\n * @param defaults - Effective client defaults.\n * @returns Raw `Response` when no schema is provided; otherwise validated output.\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws Any error thrown or rejected by the provided Standard Schema validator.\n */\nexport async function fetchInternal(\n input: FetchInput,\n schema: StandardSchemaV1 | undefined,\n options: ExtendedRequestInit | undefined,\n defaults: FetchDefaults,\n): Promise<unknown> {\n const request = normalizeRequest(input, options);\n const { init, searchParams, throwOnFetchError, throwOnValidationError } = prepareRequestInit(\n request.options,\n defaults,\n );\n const url = resolveRequestUrl(request.url, defaults, searchParams);\n const response = request.request\n ? await fetch(new Request(url, request.request), init)\n : await fetch(url, init);\n\n if (throwOnFetchError && !response.ok) {\n throw new FetchError(`HTTP ${response.status}: ${response.statusText}`, response);\n }\n\n if (!schema) {\n return response;\n }\n\n const raw = await response.json();\n if (throwOnValidationError) {\n return standardValidate(schema, raw, { throwOnError: true });\n }\n return standardValidate(schema, raw, { throwOnError: false });\n}\n\n/**\n * Normalizes request-level options into a final RequestInit payload and runtime flags.\n *\n * @param options - Request-level options.\n * @param defaults - Client-level defaults.\n * @returns Fully merged request init payload and effective runtime flags.\n */\nfunction prepareRequestInit(\n options: ExtendedRequestInit,\n defaults: FetchDefaults,\n): {\n init: RequestInit;\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined;\n throwOnFetchError: boolean;\n throwOnValidationError: boolean;\n} {\n const {\n headers,\n json,\n searchParams,\n throwOnFetchError = defaults.throwOnFetchError,\n throwOnValidationError = defaults.throwOnValidationError,\n ...rest\n } = options;\n\n const init = {\n ...rest,\n headers: mergeHeaders(defaults.headers, headers),\n } as RequestInit;\n\n if (json !== undefined) {\n if (init.body != null) {\n throw new TypeError(\"Cannot provide both `body` and `json`.\");\n }\n\n init.body = JSON.stringify(json);\n const headers = new Headers(init.headers);\n
|
|
1
|
+
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/internal.ts"],"sourcesContent":["/**\n * Internal request execution and option preparation utilities.\n *\n * @module @zap-studio/fetch/internal\n */\n\nimport type { StandardSchemaV1 } from \"@zap-studio/validation\";\nimport { standardValidate } from \"@zap-studio/validation\";\n\nimport { FetchError } from \"./errors.js\";\nimport { mergeHeaders } from \"./headers.js\";\nimport { normalizeRequest } from \"./request.js\";\nimport type { ExtendedRequestInit, FetchDefaults, FetchInput } from \"./types.js\";\nimport { resolveRequestUrl } from \"./url.js\";\n\n/**\n * Internal fetch implementation used by both $fetch and createFetch.\n *\n * This function normalizes request input, resolves final URL + query params,\n * executes `fetch`, optionally throws `FetchError`, and optionally validates\n * JSON response payloads using Standard Schema.\n *\n * @param input - Request URL, path, or Request object.\n * @param schema - Optional Standard Schema for response validation.\n * @param options - Optional request options and package-specific flags.\n * @param defaults - Effective client defaults.\n * @returns Raw `Response` when no schema is provided; otherwise validated output.\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws Any error thrown or rejected by the provided Standard Schema validator.\n */\nexport async function fetchInternal(\n input: FetchInput,\n schema: StandardSchemaV1 | undefined,\n options: ExtendedRequestInit | undefined,\n defaults: FetchDefaults,\n): Promise<unknown> {\n const request = normalizeRequest(input, options);\n const { init, searchParams, throwOnFetchError, throwOnValidationError } = prepareRequestInit(\n request.options,\n defaults,\n );\n const url = resolveRequestUrl(request.url, defaults, searchParams);\n const response = request.request\n ? await fetch(new Request(url, request.request), init)\n : await fetch(url, init);\n\n if (throwOnFetchError && !response.ok) {\n throw new FetchError(`HTTP ${response.status}: ${response.statusText}`, response);\n }\n\n if (!schema) {\n return response;\n }\n\n const raw = await response.json();\n if (throwOnValidationError) {\n return standardValidate(schema, raw, { throwOnError: true });\n }\n return standardValidate(schema, raw, { throwOnError: false });\n}\n\n/**\n * Normalizes request-level options into a final RequestInit payload and runtime flags.\n *\n * @param options - Request-level options.\n * @param defaults - Client-level defaults.\n * @returns Fully merged request init payload and effective runtime flags.\n */\nfunction prepareRequestInit(\n options: ExtendedRequestInit,\n defaults: FetchDefaults,\n): {\n init: RequestInit;\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined;\n throwOnFetchError: boolean;\n throwOnValidationError: boolean;\n} {\n const {\n headers,\n json,\n searchParams,\n throwOnFetchError = defaults.throwOnFetchError,\n throwOnValidationError = defaults.throwOnValidationError,\n ...rest\n } = options;\n\n const init = {\n ...rest,\n headers: mergeHeaders(defaults.headers, headers),\n } as RequestInit;\n\n if (json !== undefined) {\n if (init.body != null) {\n throw new TypeError(\"Cannot provide both `body` and `json`.\");\n }\n\n init.body = JSON.stringify(json);\n if (!init.headers) {\n init.headers = new Headers({ \"Content-Type\": \"application/json\" });\n } else {\n const headers = new Headers(init.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n init.headers = headers;\n }\n }\n\n return {\n init,\n searchParams,\n throwOnFetchError,\n throwOnValidationError,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,cACpB,OACA,QACA,SACA,UACkB;CAClB,MAAM,UAAU,iBAAiB,OAAO,QAAQ;CAChD,MAAM,EAAE,MAAM,cAAc,mBAAmB,2BAA2B,mBACxE,QAAQ,SACR,SACD;CACD,MAAM,MAAM,kBAAkB,QAAQ,KAAK,UAAU,aAAa;CAClE,MAAM,WAAW,QAAQ,UACrB,MAAM,MAAM,IAAI,QAAQ,KAAK,QAAQ,QAAQ,EAAE,KAAK,GACpD,MAAM,MAAM,KAAK,KAAK;AAE1B,KAAI,qBAAqB,CAAC,SAAS,GACjC,OAAM,IAAI,WAAW,QAAQ,SAAS,OAAO,IAAI,SAAS,cAAc,SAAS;AAGnF,KAAI,CAAC,OACH,QAAO;CAGT,MAAM,MAAM,MAAM,SAAS,MAAM;AACjC,KAAI,uBACF,QAAO,iBAAiB,QAAQ,KAAK,EAAE,cAAc,MAAM,CAAC;AAE9D,QAAO,iBAAiB,QAAQ,KAAK,EAAE,cAAc,OAAO,CAAC;;;;;;;;;AAU/D,SAAS,mBACP,SACA,UAMA;CACA,MAAM,EACJ,SACA,MACA,cACA,oBAAoB,SAAS,mBAC7B,yBAAyB,SAAS,wBAClC,GAAG,SACD;CAEJ,MAAM,OAAO;EACX,GAAG;EACH,SAAS,aAAa,SAAS,SAAS,QAAQ;EACjD;AAED,KAAI,SAAS,KAAA,GAAW;AACtB,MAAI,KAAK,QAAQ,KACf,OAAM,IAAI,UAAU,yCAAyC;AAG/D,OAAK,OAAO,KAAK,UAAU,KAAK;AAChC,MAAI,CAAC,KAAK,QACR,MAAK,UAAU,IAAI,QAAQ,EAAE,gBAAgB,oBAAoB,CAAC;OAC7D;GACL,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,OAAI,CAAC,QAAQ,IAAI,eAAe,CAC9B,SAAQ,IAAI,gBAAgB,mBAAmB;AAEjD,QAAK,UAAU;;;AAInB,QAAO;EACL;EACA;EACA;EACA;EACD"}
|
package/dist/methods.mjs
CHANGED
package/dist/methods.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"methods.mjs","names":[],"sources":["../src/methods.ts"],"sourcesContent":["/**\n * Method helper factories used to build verb-specific fetch functions.\n *\n * @module\n */\n\nimport { isStandardSchema, type StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport type { $Fetch, ExtendedRequestInit, FetchInput } from \"./types.js\";\n\n/**\n * Creates an HTTP method helper bound to a fetch function.\n *\n * The returned function mirrors `$Fetch` overloads but forces the provided\n * HTTP method (`GET`, `POST`, etc.) into request options.\n *\n * @param fetchFn - Fetch function to wrap.\n * @param method - HTTP method to enforce.\n * @returns Method-bound fetch function.\n * @throws Any error thrown or rejected by `fetchFn` when the returned method-bound\n * fetch function is called.\n *\n * @example\n * const get = createMethod($fetch, \"GET\");\n * const user = await get(\"/users/1\", UserSchema);\n */\nexport function createMethod<TFetch extends $Fetch>(fetchFn: TFetch, method: string): $Fetch {\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & {\n throwOnValidationError: false;\n },\n ): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & {\n throwOnValidationError?: true;\n },\n ): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\n function methodFetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;\n\n /**\n * Method-bound `$Fetch` implementation.\n *\n * Resolves schema/option overloads and injects the configured HTTP method.\n */\n function methodFetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit,\n ): Promise<unknown> {\n if (isStandardSchema(schemaOrOptions)) {\n if (optionsOrUndefined?.throwOnValidationError === false) {\n return fetchFn(input, schemaOrOptions, {\n ...optionsOrUndefined,\n method,\n throwOnValidationError: false,\n });\n }\n\n const { throwOnValidationError, ...restOptions } = optionsOrUndefined ?? {};\n\n if (throwOnValidationError === true) {\n return fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n throwOnValidationError: true,\n });\n }\n\n return fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n });\n }\n\n return fetchFn(input, {\n ...schemaOrOptions,\n method,\n });\n }\n\n return methodFetch;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aAAoC,SAAiB,QAAwB;;;;;;CAwB3F,SAAS,YACP,OACA,iBACA,oBACkB;AAClB,MAAI,iBAAiB,gBAAgB,EAAE;AACrC,OAAI,oBAAoB,2BAA2B,MACjD,QAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACA,wBAAwB;IACzB,CAAC;GAGJ,MAAM,EAAE,wBAAwB,GAAG,gBAAgB,sBAAsB,EAAE;AAE3E,OAAI,2BAA2B,KAC7B,QAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACA,wBAAwB;IACzB,CAAC;AAGJ,UAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACD,CAAC;;AAGJ,SAAO,QAAQ,OAAO;GACpB,GAAG;GACH;GACD,CAAC;;AAGJ,QAAO"}
|
|
1
|
+
{"version":3,"file":"methods.mjs","names":[],"sources":["../src/methods.ts"],"sourcesContent":["/**\n * Method helper factories used to build verb-specific fetch functions.\n *\n * @module @zap-studio/fetch/methods\n */\n\nimport { isStandardSchema, type StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport type { $Fetch, ExtendedRequestInit, FetchInput } from \"./types.js\";\n\n/**\n * Creates an HTTP method helper bound to a fetch function.\n *\n * The returned function mirrors `$Fetch` overloads but forces the provided\n * HTTP method (`GET`, `POST`, etc.) into request options.\n *\n * @param fetchFn - Fetch function to wrap.\n * @param method - HTTP method to enforce.\n * @returns Method-bound fetch function.\n * @throws Any error thrown or rejected by `fetchFn` when the returned method-bound\n * fetch function is called.\n *\n * @example\n * const get = createMethod($fetch, \"GET\");\n * const user = await get(\"/users/1\", UserSchema);\n */\nexport function createMethod<TFetch extends $Fetch>(fetchFn: TFetch, method: string): $Fetch {\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & {\n throwOnValidationError: false;\n },\n ): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & {\n throwOnValidationError?: true;\n },\n ): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\n function methodFetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;\n\n /**\n * Method-bound `$Fetch` implementation.\n *\n * Resolves schema/option overloads and injects the configured HTTP method.\n */\n function methodFetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit,\n ): Promise<unknown> {\n if (isStandardSchema(schemaOrOptions)) {\n if (optionsOrUndefined?.throwOnValidationError === false) {\n return fetchFn(input, schemaOrOptions, {\n ...optionsOrUndefined,\n method,\n throwOnValidationError: false,\n });\n }\n\n const { throwOnValidationError, ...restOptions } = optionsOrUndefined ?? {};\n\n if (throwOnValidationError === true) {\n return fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n throwOnValidationError: true,\n });\n }\n\n return fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n });\n }\n\n return fetchFn(input, {\n ...schemaOrOptions,\n method,\n });\n }\n\n return methodFetch;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aAAoC,SAAiB,QAAwB;;;;;;CAwB3F,SAAS,YACP,OACA,iBACA,oBACkB;AAClB,MAAI,iBAAiB,gBAAgB,EAAE;AACrC,OAAI,oBAAoB,2BAA2B,MACjD,QAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACA,wBAAwB;IACzB,CAAC;GAGJ,MAAM,EAAE,wBAAwB,GAAG,gBAAgB,sBAAsB,EAAE;AAE3E,OAAI,2BAA2B,KAC7B,QAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACA,wBAAwB;IACzB,CAAC;AAGJ,UAAO,QAAQ,OAAO,iBAAiB;IACrC,GAAG;IACH;IACD,CAAC;;AAGJ,SAAO,QAAQ,OAAO;GACpB,GAAG;GACH;GACD,CAAC;;AAGJ,QAAO"}
|
package/dist/request.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.d.mts","names":[],"sources":["../src/request.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"request.d.mts","names":[],"sources":["../src/request.ts"],"mappings":";;;;;AAkBA;;;;;UAAiB,iBAAA;EACf,GAAA;EACA,OAAA,GAAU,OAAA;EACV,OAAA,EAAS,mBAAA;AAAA;;AAeX;;;;;;;;;;;iBAAgB,gBAAA,CACd,KAAA,EAAO,UAAA,EACP,OAAA,GAAU,mBAAA,GACT,iBAAA"}
|
package/dist/request.mjs
CHANGED
|
@@ -3,8 +3,9 @@ import { mergeHeaders } from "./headers.mjs";
|
|
|
3
3
|
/**
|
|
4
4
|
* Request normalization helpers for fetch `input` values.
|
|
5
5
|
*
|
|
6
|
-
* @module
|
|
6
|
+
* @module @zap-studio/fetch/request
|
|
7
7
|
*/
|
|
8
|
+
const EMPTY_OPTIONS = {};
|
|
8
9
|
/**
|
|
9
10
|
* Normalizes fetch `input` and request-level options into a consistent internal shape.
|
|
10
11
|
*
|
|
@@ -20,7 +21,7 @@ import { mergeHeaders } from "./headers.mjs";
|
|
|
20
21
|
function normalizeRequest(input, options) {
|
|
21
22
|
if (!(input instanceof Request)) return {
|
|
22
23
|
url: input instanceof URL ? input.href : input,
|
|
23
|
-
options: options ??
|
|
24
|
+
options: options ?? EMPTY_OPTIONS
|
|
24
25
|
};
|
|
25
26
|
const request = new Request(input);
|
|
26
27
|
const { headers, ...rest } = options || {};
|
package/dist/request.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.mjs","names":[],"sources":["../src/request.ts"],"sourcesContent":["/**\n * Request normalization helpers for fetch `input` values.\n *\n * @module\n */\n\nimport { mergeHeaders } from \"./headers.js\";\nimport type { ExtendedRequestInit, FetchInput } from \"./types.js\";\n\n/**\n * Normalized representation used by internal request execution.\n *\n * - `url`: resolved string URL from the input (string or `URL`; `Request` uses `request.url`)\n * - `request`: original Request clone when input is a Request\n * - `options`: normalized request options merged with Request headers\n */\nexport interface NormalizedRequest {\n url: string;\n request?: Request;\n options: ExtendedRequestInit;\n}\n\n/**\n * Normalizes fetch `input` and request-level options into a consistent internal shape.\n *\n * @param input - Request URL/path or Request instance.\n * @param options - Optional request options.\n * @returns A normalized request structure for internal processing.\n * @throws {TypeError} When cloning a `Request` fails or the merged headers are invalid.\n *\n * @example\n * const normalized = normalizeRequest(\"/users\", { method: \"GET\" });\n * console.log(normalized.url); // \"/users\"\n */\nexport function normalizeRequest(\n input: FetchInput,\n options?: ExtendedRequestInit,\n): NormalizedRequest {\n if (!(input instanceof Request)) {\n const url = input instanceof URL ? input.href : input;\n return {\n url,\n options: options ??
|
|
1
|
+
{"version":3,"file":"request.mjs","names":[],"sources":["../src/request.ts"],"sourcesContent":["/**\n * Request normalization helpers for fetch `input` values.\n *\n * @module @zap-studio/fetch/request\n */\n\nimport { mergeHeaders } from \"./headers.js\";\nimport type { ExtendedRequestInit, FetchInput } from \"./types.js\";\n\nconst EMPTY_OPTIONS = {} as ExtendedRequestInit;\n\n/**\n * Normalized representation used by internal request execution.\n *\n * - `url`: resolved string URL from the input (string or `URL`; `Request` uses `request.url`)\n * - `request`: original Request clone when input is a Request\n * - `options`: normalized request options merged with Request headers\n */\nexport interface NormalizedRequest {\n url: string;\n request?: Request;\n options: ExtendedRequestInit;\n}\n\n/**\n * Normalizes fetch `input` and request-level options into a consistent internal shape.\n *\n * @param input - Request URL/path or Request instance.\n * @param options - Optional request options.\n * @returns A normalized request structure for internal processing.\n * @throws {TypeError} When cloning a `Request` fails or the merged headers are invalid.\n *\n * @example\n * const normalized = normalizeRequest(\"/users\", { method: \"GET\" });\n * console.log(normalized.url); // \"/users\"\n */\nexport function normalizeRequest(\n input: FetchInput,\n options?: ExtendedRequestInit,\n): NormalizedRequest {\n if (!(input instanceof Request)) {\n const url = input instanceof URL ? input.href : input;\n return {\n url,\n options: options ?? EMPTY_OPTIONS,\n };\n }\n\n const request = new Request(input);\n const { headers, ...rest } = options || {};\n const mergedHeaders = mergeHeaders(request.headers, headers);\n const normalizedOptions = { ...rest } as ExtendedRequestInit;\n\n if (mergedHeaders) {\n normalizedOptions.headers = mergedHeaders;\n }\n\n return {\n url: request.url,\n request,\n options: normalizedOptions,\n };\n}\n"],"mappings":";;;;;;;AASA,MAAM,gBAAgB,EAAE;;;;;;;;;;;;;AA2BxB,SAAgB,iBACd,OACA,SACmB;AACnB,KAAI,EAAE,iBAAiB,SAErB,QAAO;EACL,KAFU,iBAAiB,MAAM,MAAM,OAAO;EAG9C,SAAS,WAAW;EACrB;CAGH,MAAM,UAAU,IAAI,QAAQ,MAAM;CAClC,MAAM,EAAE,SAAS,GAAG,SAAS,WAAW,EAAE;CAC1C,MAAM,gBAAgB,aAAa,QAAQ,SAAS,QAAQ;CAC5D,MAAM,oBAAoB,EAAE,GAAG,MAAM;AAErC,KAAI,cACF,mBAAkB,UAAU;AAG9B,QAAO;EACL,KAAK,QAAQ;EACb;EACA,SAAS;EACV"}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { StandardSchemaV1 } from "@zap-studio/validation";
|
|
2
2
|
|
|
3
3
|
//#region src/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Accepted `fetch` input type (`string`, `URL`, or `Request`).
|
|
6
|
+
*/
|
|
4
7
|
type FetchInput = Parameters<typeof fetch>[0];
|
|
5
8
|
type URLSearchParamsInput = ConstructorParameters<typeof URLSearchParams>[0];
|
|
6
9
|
type RequestBodyInit = RequestInit & {
|
package/dist/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;AAWkD;KAAtC,UAAA,GAAa,UAAA,QAAkB,KAAA;AAAA,KAEtC,oBAAA,GAAuB,qBAAA,QAA6B,eAAA;AAAA,KAEpD,eAAA,GAAkB,WAAA;EACrB,IAAA;AAAA;AAAA,KAGG,YAAA,GAAe,IAAA,CAAK,WAAA;;;;AAHvB;EAQA,IAAA;EACA,IAAA;AAAA;AAAA,KAGG,iBAAA;;;;;EAKH,YAAA,GAAe,oBAAA;EARf;;;;EAaA,iBAAA;;;;;EAKA,sBAAA;AAAA;;;;;;;;;;;KAaU,mBAAA,IAAuB,eAAA,GAAkB,YAAA,IAAgB,iBAAA;;AAYrE;;;;;;;;;UAAiB,aAAA;;;;AA+BjB;EA1BE,OAAA;;;;;EAKA,OAAA,GAAU,WAAA;;;;;EAKV,YAAA,GAAe,oBAAA;;;;;EAKf,iBAAA;;;;;EAKA,sBAAA;AAAA;;;;UAMe,MAAA;;;;;;;;;;;;;;;;mBAgBE,gBAAA,EACf,KAAA,EAAO,UAAA,EACP,MAAA,EAAQ,OAAA,EACR,OAAA,EAAS,mBAAA;IAAwB,sBAAA;EAAA,IAChC,OAAA,CAAQ,gBAAA,CAAiB,MAAA,CAAO,gBAAA,CAAiB,WAAA,CAAY,OAAA;;;;;;;;;;;;;;;;AA8ClE;mBA5BmB,gBAAA,EACf,KAAA,EAAO,UAAA,EACP,MAAA,EAAQ,OAAA,EACR,OAAA,GAAU,mBAAA;IACR,sBAAA;EAAA,IAED,OAAA,CAAQ,gBAAA,CAAiB,WAAA,CAAY,OAAA;;;;;;;;;;;;GAavC,KAAA,EAAO,UAAA,EAAY,OAAA,GAAU,mBAAA,GAAsB,OAAA,CAAQ,QAAA;AAAA;;;;;;;UAS7C,UAAA;;;;EAIf,MAAA,EAAQ,MAAA;;;;EAIR,GAAA,EAAK,MAAA;;;;EAIL,KAAA,EAAO,MAAA;;;;EAIP,IAAA,EAAM,MAAA;;;;EAIN,GAAA,EAAK,MAAA;AAAA"}
|
package/dist/url.mjs
CHANGED
|
@@ -26,9 +26,14 @@ function resolveRequestUrl(resourceUrl, defaults, searchParams) {
|
|
|
26
26
|
* Resolves search params by applying default params, URL params, then request params.
|
|
27
27
|
*/
|
|
28
28
|
function resolveSearchParams(url, defaultSearchParams, searchParams) {
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
const
|
|
29
|
+
if (!defaultSearchParams && searchParams === void 0) return url;
|
|
30
|
+
const hashIndex = url.indexOf("#");
|
|
31
|
+
const hasFragment = hashIndex >= 0;
|
|
32
|
+
const urlWithoutHash = hasFragment ? url.slice(0, hashIndex) : url;
|
|
33
|
+
const hash = hasFragment ? url.slice(hashIndex + 1) : "";
|
|
34
|
+
const queryIndex = urlWithoutHash.indexOf("?");
|
|
35
|
+
const pathname = queryIndex >= 0 ? urlWithoutHash.slice(0, queryIndex) : urlWithoutHash;
|
|
36
|
+
const urlSearchParams = queryIndex >= 0 ? urlWithoutHash.slice(queryIndex + 1) : void 0;
|
|
32
37
|
const resolvedSearchParams = new URLSearchParams();
|
|
33
38
|
mergeSearchParams(resolvedSearchParams, defaultSearchParams);
|
|
34
39
|
mergeSearchParams(resolvedSearchParams, urlSearchParams);
|
package/dist/url.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url.mjs","names":[],"sources":["../src/url.ts"],"sourcesContent":["/**\n * URL resolution and query merging utilities.\n *\n * @module\n */\n\nimport type { ExtendedRequestInit, FetchDefaults } from \"./types.js\";\n\n/**\n * Resolves final request URL by applying baseURL and layered search params.\n *\n * Search param precedence:\n * 1. `defaults.searchParams`\n * 2. search params already present in `resourceUrl`\n * 3. per-request `searchParams`\n *\n * @example\n * const finalUrl = resolveRequestUrl(\n * \"/users?page=2\",\n * { ...defaults, baseURL: \"https://api.example.com\", searchParams: { locale: \"en\" } },\n * { page: \"3\" },\n * );\n * // https://api.example.com/users?locale=en&page=3\n *\n * @throws {TypeError} When `baseURL` and `resourceUrl` cannot be resolved by\n * `URL`, or when default/per-request search params cannot be converted by\n * `URLSearchParams`.\n */\nexport function resolveRequestUrl(\n resourceUrl: string,\n defaults: FetchDefaults,\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined,\n): string {\n const url = defaults.baseURL\n ? new URL(resourceUrl, ensureTrailingSlash(defaults.baseURL)).toString()\n : resourceUrl;\n\n return resolveSearchParams(url, defaults.searchParams, searchParams);\n}\n\n/**\n * Resolves search params by applying default params, URL params, then request params.\n */\nfunction resolveSearchParams(\n url: string,\n defaultSearchParams: FetchDefaults[\"searchParams\"] | undefined,\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined,\n): string {\n const
|
|
1
|
+
{"version":3,"file":"url.mjs","names":[],"sources":["../src/url.ts"],"sourcesContent":["/**\n * URL resolution and query merging utilities.\n *\n * @module @zap-studio/fetch/url\n */\n\nimport type { ExtendedRequestInit, FetchDefaults } from \"./types.js\";\n\n/**\n * Resolves final request URL by applying baseURL and layered search params.\n *\n * Search param precedence:\n * 1. `defaults.searchParams`\n * 2. search params already present in `resourceUrl`\n * 3. per-request `searchParams`\n *\n * @example\n * const finalUrl = resolveRequestUrl(\n * \"/users?page=2\",\n * { ...defaults, baseURL: \"https://api.example.com\", searchParams: { locale: \"en\" } },\n * { page: \"3\" },\n * );\n * // https://api.example.com/users?locale=en&page=3\n *\n * @throws {TypeError} When `baseURL` and `resourceUrl` cannot be resolved by\n * `URL`, or when default/per-request search params cannot be converted by\n * `URLSearchParams`.\n */\nexport function resolveRequestUrl(\n resourceUrl: string,\n defaults: FetchDefaults,\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined,\n): string {\n const url = defaults.baseURL\n ? new URL(resourceUrl, ensureTrailingSlash(defaults.baseURL)).toString()\n : resourceUrl;\n\n return resolveSearchParams(url, defaults.searchParams, searchParams);\n}\n\n/**\n * Resolves search params by applying default params, URL params, then request params.\n */\nfunction resolveSearchParams(\n url: string,\n defaultSearchParams: FetchDefaults[\"searchParams\"] | undefined,\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined,\n): string {\n if (!defaultSearchParams && searchParams === undefined) {\n return url;\n }\n\n const hashIndex = url.indexOf(\"#\");\n const hasFragment = hashIndex >= 0;\n const urlWithoutHash = hasFragment ? url.slice(0, hashIndex) : url;\n const hash = hasFragment ? url.slice(hashIndex + 1) : \"\";\n const queryIndex = urlWithoutHash.indexOf(\"?\");\n const pathname = queryIndex >= 0 ? urlWithoutHash.slice(0, queryIndex) : urlWithoutHash;\n const urlSearchParams = queryIndex >= 0 ? urlWithoutHash.slice(queryIndex + 1) : undefined;\n const resolvedSearchParams = new URLSearchParams();\n\n mergeSearchParams(resolvedSearchParams, defaultSearchParams);\n mergeSearchParams(resolvedSearchParams, urlSearchParams);\n mergeSearchParams(resolvedSearchParams, searchParams);\n\n const resolvedSearch = resolvedSearchParams.toString();\n const fragmentSuffix = hasFragment ? `#${hash}` : \"\";\n\n if (!resolvedSearch) {\n return `${pathname}${fragmentSuffix}`;\n }\n\n return `${pathname}?${resolvedSearch}${fragmentSuffix}`;\n}\n\n/**\n * Ensures a URL has a trailing slash for relative URL resolution.\n */\nfunction ensureTrailingSlash(url: string): string {\n return url.endsWith(\"/\") ? url : `${url}/`;\n}\n\n/**\n * Copies search params into target, overriding duplicate keys.\n */\nfunction mergeSearchParams(\n target: URLSearchParams,\n source: ExtendedRequestInit[\"searchParams\"] | undefined,\n): void {\n for (const [key, value] of new URLSearchParams(source)) {\n target.set(key, value);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,kBACd,aACA,UACA,cACQ;AAKR,QAAO,oBAJK,SAAS,UACjB,IAAI,IAAI,aAAa,oBAAoB,SAAS,QAAQ,CAAC,CAAC,UAAU,GACtE,aAE4B,SAAS,cAAc,aAAa;;;;;AAMtE,SAAS,oBACP,KACA,qBACA,cACQ;AACR,KAAI,CAAC,uBAAuB,iBAAiB,KAAA,EAC3C,QAAO;CAGT,MAAM,YAAY,IAAI,QAAQ,IAAI;CAClC,MAAM,cAAc,aAAa;CACjC,MAAM,iBAAiB,cAAc,IAAI,MAAM,GAAG,UAAU,GAAG;CAC/D,MAAM,OAAO,cAAc,IAAI,MAAM,YAAY,EAAE,GAAG;CACtD,MAAM,aAAa,eAAe,QAAQ,IAAI;CAC9C,MAAM,WAAW,cAAc,IAAI,eAAe,MAAM,GAAG,WAAW,GAAG;CACzE,MAAM,kBAAkB,cAAc,IAAI,eAAe,MAAM,aAAa,EAAE,GAAG,KAAA;CACjF,MAAM,uBAAuB,IAAI,iBAAiB;AAElD,mBAAkB,sBAAsB,oBAAoB;AAC5D,mBAAkB,sBAAsB,gBAAgB;AACxD,mBAAkB,sBAAsB,aAAa;CAErD,MAAM,iBAAiB,qBAAqB,UAAU;CACtD,MAAM,iBAAiB,cAAc,IAAI,SAAS;AAElD,KAAI,CAAC,eACH,QAAO,GAAG,WAAW;AAGvB,QAAO,GAAG,SAAS,GAAG,iBAAiB;;;;;AAMzC,SAAS,oBAAoB,KAAqB;AAChD,QAAO,IAAI,SAAS,IAAI,GAAG,MAAM,GAAG,IAAI;;;;;AAM1C,SAAS,kBACP,QACA,QACM;AACN,MAAK,MAAM,CAAC,KAAK,UAAU,IAAI,gBAAgB,OAAO,CACpD,QAAO,IAAI,KAAK,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zap-studio/fetch",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A type-safe fetch wrapper for HTTP requests with runtime schema validation.",
|
|
6
6
|
"keywords": [
|
|
@@ -55,7 +55,11 @@
|
|
|
55
55
|
"@zap-studio/validation": "0.3.4"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
+
"@better-fetch/fetch": "^1.1.21",
|
|
58
59
|
"arktype": "^2.2.0",
|
|
60
|
+
"axios": "^1.15.2",
|
|
61
|
+
"ky": "^2.0.2",
|
|
62
|
+
"ofetch": "^1.5.1",
|
|
59
63
|
"typescript": "^6.0.3",
|
|
60
64
|
"valibot": "^1.3.1",
|
|
61
65
|
"vite-plus": "^0.1.19",
|