@zap-studio/fetch 0.5.5 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +70 -65
  2. package/README.md +53 -212
  3. package/dist/{errors.d.mts → errors.d.ts} +1 -1
  4. package/dist/errors.d.ts.map +1 -0
  5. package/dist/{errors.mjs → errors.js} +1 -1
  6. package/dist/errors.js.map +1 -0
  7. package/dist/{index.d.mts → index.d.ts} +16 -3
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +316 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/{types.d.mts → types.d.ts} +30 -2
  12. package/dist/types.d.ts.map +1 -0
  13. package/dist/types.js +0 -0
  14. package/package.json +8 -21
  15. package/dist/constants.d.mts +0 -17
  16. package/dist/constants.d.mts.map +0 -1
  17. package/dist/constants.mjs +0 -21
  18. package/dist/constants.mjs.map +0 -1
  19. package/dist/errors.d.mts.map +0 -1
  20. package/dist/errors.mjs.map +0 -1
  21. package/dist/headers.d.mts +0 -26
  22. package/dist/headers.d.mts.map +0 -1
  23. package/dist/headers.mjs +0 -34
  24. package/dist/headers.mjs.map +0 -1
  25. package/dist/index.d.mts.map +0 -1
  26. package/dist/index.mjs +0 -103
  27. package/dist/index.mjs.map +0 -1
  28. package/dist/internal.d.mts +0 -32
  29. package/dist/internal.d.mts.map +0 -1
  30. package/dist/internal.mjs +0 -75
  31. package/dist/internal.mjs.map +0 -1
  32. package/dist/methods.d.mts +0 -22
  33. package/dist/methods.d.mts.map +0 -1
  34. package/dist/methods.mjs +0 -58
  35. package/dist/methods.mjs.map +0 -1
  36. package/dist/request.d.mts +0 -30
  37. package/dist/request.d.mts.map +0 -1
  38. package/dist/request.mjs +0 -43
  39. package/dist/request.mjs.map +0 -1
  40. package/dist/types.d.mts.map +0 -1
  41. package/dist/types.mjs +0 -1
  42. package/dist/url.d.mts +0 -26
  43. package/dist/url.d.mts.map +0 -1
  44. package/dist/url.mjs +0 -60
  45. package/dist/url.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,103 +0,0 @@
1
- import { GLOBAL_DEFAULTS } from "./constants.mjs";
2
- import { fetchInternal } from "./internal.mjs";
3
- import { createMethod } from "./methods.mjs";
4
- import { isStandardSchema } from "@zap-studio/validation";
5
- //#region src/index.ts
6
- /**
7
- * Public entrypoint for the fetch package.
8
- *
9
- * Exposes:
10
- * - `$fetch` low-level typed fetch function
11
- * - `api` method shortcuts
12
- * - `createFetch` instance factory
13
- *
14
- * @module @zap-studio/fetch
15
- */
16
- async function $fetch(input, schemaOrOptions, optionsOrUndefined) {
17
- const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
18
- return await fetchInternal(input, schema, options, GLOBAL_DEFAULTS);
19
- }
20
- /**
21
- * Convenience methods for common HTTP verbs.
22
- *
23
- * These methods always require a schema for validation.
24
- * For raw responses without validation, use `$fetch` directly.
25
- *
26
- * Each method has the same throw behavior as {@link $fetch}.
27
- *
28
- * @example
29
- * import { z } from "zod";
30
- * import { api } from "@zap-studio/fetch";
31
- *
32
- * const PostSchema = z.object({
33
- * id: z.number(),
34
- * title: z.string(),
35
- * content: z.string(),
36
- * });
37
- *
38
- * async function fetchPost(postId: number) {
39
- * const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);
40
- * return post; // post is typed as { id: number; title: string; content: string; }
41
- * }
42
- */
43
- const api = {
44
- delete: createMethod($fetch, "DELETE"),
45
- get: createMethod($fetch, "GET"),
46
- patch: createMethod($fetch, "PATCH"),
47
- post: createMethod($fetch, "POST"),
48
- put: createMethod($fetch, "PUT")
49
- };
50
- /**
51
- * Creates a custom fetch instance with pre-configured defaults.
52
- *
53
- * Use this factory to create API clients with a base URL, default headers,
54
- * and other shared configuration. Each instance is independent.
55
- *
56
- * The returned `$fetch` and `api` methods have the same throw behavior as the
57
- * top-level {@link $fetch} export.
58
- *
59
- * @example
60
- * import { z } from "zod";
61
- * import { createFetch } from "@zap-studio/fetch";
62
- *
63
- * // Create a configured instance
64
- * const { $fetch, api } = createFetch({
65
- * baseURL: "https://api.example.com",
66
- * headers: { "Authorization": "Bearer token" },
67
- * });
68
- *
69
- * const UserSchema = z.object({ id: z.number(), name: z.string() });
70
- *
71
- * // Now use relative paths - baseURL is prepended automatically
72
- * const user = await api.get("/users/1", UserSchema);
73
- *
74
- * // Or use $fetch directly
75
- * const response = await $fetch("/users", UserSchema, { method: "POST", json: { name: "John" } });
76
- */
77
- const createFetch = (factoryOptions = {}) => {
78
- const defaults = {
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
84
- };
85
- async function customFetch(input, schemaOrOptions, optionsOrUndefined) {
86
- const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
87
- return await fetchInternal(input, schema, options, defaults);
88
- }
89
- return {
90
- $fetch: customFetch,
91
- api: {
92
- delete: createMethod(customFetch, "DELETE"),
93
- get: createMethod(customFetch, "GET"),
94
- patch: createMethod(customFetch, "PATCH"),
95
- post: createMethod(customFetch, "POST"),
96
- put: createMethod(customFetch, "PUT")
97
- }
98
- };
99
- };
100
- //#endregion
101
- export { $fetch, api, createFetch };
102
-
103
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
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 } from \"@zap-studio/validation\";\nimport 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 {unknown} 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(\n input: FetchInput,\n options?: ExtendedRequestInit\n): 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 delete: createMethod($fetch, \"DELETE\"),\n get: createMethod($fetch, \"GET\"),\n patch: createMethod($fetch, \"PATCH\"),\n post: createMethod($fetch, \"POST\"),\n put: createMethod($fetch, \"PUT\"),\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 const createFetch = (\n factoryOptions: Partial<FetchDefaults> = {}\n): {\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:\n factoryOptions.throwOnFetchError ?? GLOBAL_DEFAULTS.throwOnFetchError,\n throwOnValidationError:\n factoryOptions.throwOnValidationError ??\n 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(\n input: FetchInput,\n options?: ExtendedRequestInit\n ): 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 delete: createMethod(customFetch, \"DELETE\"),\n get: createMethod(customFetch, \"GET\"),\n patch: createMethod(customFetch, \"PATCH\"),\n post: createMethod(customFetch, \"POST\"),\n put: createMethod(customFetch, \"PUT\"),\n };\n\n return {\n $fetch: customFetch,\n api: customApi,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;AAwFA,eAAsB,OACpB,OACA,iBACA,oBACkB;CAClB,MAAM,CAAC,QAAQ,WAAW,iBAAiB,eAAe,IACtD,CAAC,iBAAiB,kBAAkB,IACpC,CAAC,KAAA,GAAW,eAAe;CAE/B,OAAO,MAAM,cAAc,OAAO,QAAQ,SAAS,eAAe;AACpE;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,MAAkB;CAC7B,QAAQ,aAAa,QAAQ,QAAQ;CACrC,KAAK,aAAa,QAAQ,KAAK;CAC/B,OAAO,aAAa,QAAQ,OAAO;CACnC,MAAM,aAAa,QAAQ,MAAM;CACjC,KAAK,aAAa,QAAQ,KAAK;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,eACX,iBAAyC,CAAC,MAIvC;CACH,MAAM,WAA0B;EAC9B,GAAG;EACH,GAAG;EACH,SAAS,eAAe,WAAW,gBAAgB;EACnD,mBACE,eAAe,qBAAqB,gBAAgB;EACtD,wBACE,eAAe,0BACf,gBAAgB;CACpB;CAqBA,eAAe,YACb,OACA,iBACA,oBACkB;EAClB,MAAM,CAAC,QAAQ,WAAW,iBAAiB,eAAe,IACtD,CAAC,iBAAiB,kBAAkB,IACpC,CAAC,KAAA,GAAW,eAAe;EAE/B,OAAO,MAAM,cAAc,OAAO,QAAQ,SAAS,QAAQ;CAC7D;CAUA,OAAO;EACL,QAAQ;EACR,KAAK;GATL,QAAQ,aAAa,aAAa,QAAQ;GAC1C,KAAK,aAAa,aAAa,KAAK;GACpC,OAAO,aAAa,aAAa,OAAO;GACxC,MAAM,aAAa,aAAa,MAAM;GACtC,KAAK,aAAa,aAAa,KAAK;EAKvB;CACf;AACF"}
@@ -1,32 +0,0 @@
1
- import { ExtendedRequestInit, FetchDefaults, FetchInput } from "./types.mjs";
2
- import { StandardSchemaV1 } from "@zap-studio/validation";
3
- //#region src/internal.d.ts
4
- /**
5
- * Internal fetch implementation used by both $fetch and createFetch.
6
- *
7
- * This function normalizes request input, resolves final URL + query params,
8
- * executes `fetch`, optionally throws `FetchError`, and optionally validates
9
- * JSON response payloads using Standard Schema.
10
- *
11
- * @param input - Request URL, path, or Request object.
12
- * @param schema - Optional Standard Schema for response validation.
13
- * @param options - Optional request options and package-specific flags.
14
- * @param defaults - Effective client defaults.
15
- * @returns Raw `Response` when no schema is provided; otherwise validated output.
16
- * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.
17
- * @throws {ValidationError} When a schema is provided, validation returns issues, and
18
- * `throwOnValidationError` is `true`.
19
- * @throws {TypeError} When both `body` and `json` are provided, when JSON request
20
- * serialization fails, when request construction fails, when headers/search params are
21
- * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`
22
- * implementation rejects network-level failures as `TypeError`.
23
- * @throws {DOMException} When the runtime rejects an aborted request or response body read
24
- * as an `AbortError` DOMException.
25
- * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the
26
- * response body.
27
- * @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.
28
- */
29
- declare const fetchInternal: (input: FetchInput, schema: StandardSchemaV1 | undefined, options: ExtendedRequestInit | undefined, defaults: FetchDefaults) => Promise<unknown>;
30
- //#endregion
31
- export { fetchInternal };
32
- //# sourceMappingURL=internal.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"internal.d.mts","names":[],"sources":["../src/internal.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;cAoGa,gBACX,OAAO,YACP,QAAQ,8BACR,SAAS,iCACT,UAAU,kBACT"}
package/dist/internal.mjs DELETED
@@ -1,75 +0,0 @@
1
- import { FetchError } from "./errors.mjs";
2
- import { mergeHeaders } from "./headers.mjs";
3
- import { normalizeRequest } from "./request.mjs";
4
- import { resolveRequestUrl } from "./url.mjs";
5
- import { standardValidate } from "@zap-studio/validation";
6
- //#region src/internal.ts
7
- /**
8
- * Normalizes request-level options into a final RequestInit payload and runtime flags.
9
- *
10
- * @param options - Request-level options.
11
- * @param defaults - Client-level defaults.
12
- * @returns Fully merged request init payload and effective runtime flags.
13
- */
14
- const prepareRequestInit = (options, defaults) => {
15
- const { headers, json, searchParams, throwOnFetchError = defaults.throwOnFetchError, throwOnValidationError = defaults.throwOnValidationError, ...rest } = options;
16
- const init = { ...rest };
17
- const mergedHeaders = mergeHeaders(defaults.headers, headers);
18
- if (mergedHeaders !== void 0) init.headers = mergedHeaders;
19
- if (json !== void 0) {
20
- if (init.body !== void 0 && init.body !== null) throw new TypeError("Cannot provide both `body` and `json`.");
21
- init.body = JSON.stringify(json);
22
- if (init.headers === void 0) init.headers = new Headers({ "Content-Type": "application/json" });
23
- else {
24
- const requestHeaders = new Headers(init.headers);
25
- if (!requestHeaders.has("Content-Type")) requestHeaders.set("Content-Type", "application/json");
26
- init.headers = requestHeaders;
27
- }
28
- }
29
- return {
30
- init,
31
- searchParams,
32
- throwOnFetchError,
33
- throwOnValidationError
34
- };
35
- };
36
- /**
37
- * Internal fetch implementation used by both $fetch and createFetch.
38
- *
39
- * This function normalizes request input, resolves final URL + query params,
40
- * executes `fetch`, optionally throws `FetchError`, and optionally validates
41
- * JSON response payloads using Standard Schema.
42
- *
43
- * @param input - Request URL, path, or Request object.
44
- * @param schema - Optional Standard Schema for response validation.
45
- * @param options - Optional request options and package-specific flags.
46
- * @param defaults - Effective client defaults.
47
- * @returns Raw `Response` when no schema is provided; otherwise validated output.
48
- * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.
49
- * @throws {ValidationError} When a schema is provided, validation returns issues, and
50
- * `throwOnValidationError` is `true`.
51
- * @throws {TypeError} When both `body` and `json` are provided, when JSON request
52
- * serialization fails, when request construction fails, when headers/search params are
53
- * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`
54
- * implementation rejects network-level failures as `TypeError`.
55
- * @throws {DOMException} When the runtime rejects an aborted request or response body read
56
- * as an `AbortError` DOMException.
57
- * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the
58
- * response body.
59
- * @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.
60
- */
61
- const fetchInternal = async (input, schema, options, defaults) => {
62
- const request = normalizeRequest(input, options);
63
- const { init, searchParams, throwOnFetchError, throwOnValidationError } = prepareRequestInit(request.options, defaults);
64
- const url = resolveRequestUrl(request.url, defaults, searchParams);
65
- const response = request.request ? await fetch(new Request(url, request.request), init) : await fetch(url, init);
66
- if (throwOnFetchError && !response.ok) throw new FetchError(`HTTP ${response.status}: ${response.statusText}`, response);
67
- if (schema === void 0) return response;
68
- const raw = await response.json();
69
- if (throwOnValidationError) return await standardValidate(schema, raw, { throwOnError: true });
70
- return await standardValidate(schema, raw, { throwOnError: false });
71
- };
72
- //#endregion
73
- export { fetchInternal };
74
-
75
- //# sourceMappingURL=internal.mjs.map
@@ -1 +0,0 @@
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 {\n ExtendedRequestInit,\n FetchDefaults,\n FetchInput,\n} from \"./types.js\";\nimport { resolveRequestUrl } from \"./url.js\";\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 */\nconst 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: RequestInit = { ...rest };\n const mergedHeaders = mergeHeaders(defaults.headers, headers);\n if (mergedHeaders !== undefined) {\n init.headers = mergedHeaders;\n }\n\n if (json !== undefined) {\n if (init.body !== undefined && 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 === undefined) {\n init.headers = new Headers({ \"Content-Type\": \"application/json\" });\n } else {\n const requestHeaders = new Headers(init.headers);\n if (!requestHeaders.has(\"Content-Type\")) {\n requestHeaders.set(\"Content-Type\", \"application/json\");\n }\n init.headers = requestHeaders;\n }\n }\n\n return {\n init,\n searchParams,\n throwOnFetchError,\n throwOnValidationError,\n };\n};\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 {unknown} Any error thrown or rejected by the provided Standard Schema validator.\n */\nexport const fetchInternal = async (\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 } =\n prepareRequestInit(request.options, defaults);\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(\n `HTTP ${response.status}: ${response.statusText}`,\n response\n );\n }\n\n if (schema === undefined) {\n return response;\n }\n\n const raw: unknown = await response.json();\n if (throwOnValidationError) {\n return await standardValidate(schema, raw, { throwOnError: true });\n }\n return await standardValidate(schema, raw, { throwOnError: false });\n};\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAM,sBACJ,SACA,aAMG;CACH,MAAM,EACJ,SACA,MACA,cACA,oBAAoB,SAAS,mBAC7B,yBAAyB,SAAS,wBAClC,GAAG,SACD;CAEJ,MAAM,OAAoB,EAAE,GAAG,KAAK;CACpC,MAAM,gBAAgB,aAAa,SAAS,SAAS,OAAO;CAC5D,IAAI,kBAAkB,KAAA,GACpB,KAAK,UAAU;CAGjB,IAAI,SAAS,KAAA,GAAW;EACtB,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS,MAC3C,MAAM,IAAI,UAAU,wCAAwC;EAG9D,KAAK,OAAO,KAAK,UAAU,IAAI;EAC/B,IAAI,KAAK,YAAY,KAAA,GACnB,KAAK,UAAU,IAAI,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;OAC5D;GACL,MAAM,iBAAiB,IAAI,QAAQ,KAAK,OAAO;GAC/C,IAAI,CAAC,eAAe,IAAI,cAAc,GACpC,eAAe,IAAI,gBAAgB,kBAAkB;GAEvD,KAAK,UAAU;EACjB;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB,OAC3B,OACA,QACA,SACA,aACqB;CACrB,MAAM,UAAU,iBAAiB,OAAO,OAAO;CAC/C,MAAM,EAAE,MAAM,cAAc,mBAAmB,2BAC7C,mBAAmB,QAAQ,SAAS,QAAQ;CAC9C,MAAM,MAAM,kBAAkB,QAAQ,KAAK,UAAU,YAAY;CACjE,MAAM,WAAW,QAAQ,UACrB,MAAM,MAAM,IAAI,QAAQ,KAAK,QAAQ,OAAO,GAAG,IAAI,IACnD,MAAM,MAAM,KAAK,IAAI;CAEzB,IAAI,qBAAqB,CAAC,SAAS,IACjC,MAAM,IAAI,WACR,QAAQ,SAAS,OAAO,IAAI,SAAS,cACrC,QACF;CAGF,IAAI,WAAW,KAAA,GACb,OAAO;CAGT,MAAM,MAAe,MAAM,SAAS,KAAK;CACzC,IAAI,wBACF,OAAO,MAAM,iBAAiB,QAAQ,KAAK,EAAE,cAAc,KAAK,CAAC;CAEnE,OAAO,MAAM,iBAAiB,QAAQ,KAAK,EAAE,cAAc,MAAM,CAAC;AACpE"}
@@ -1,22 +0,0 @@
1
- import { $Fetch } from "./types.mjs";
2
- //#region src/methods.d.ts
3
- /**
4
- * Creates an HTTP method helper bound to a fetch function.
5
- *
6
- * The returned function mirrors `$Fetch` overloads but forces the provided
7
- * HTTP method (`GET`, `POST`, etc.) into request options.
8
- *
9
- * @param fetchFn - Fetch function to wrap.
10
- * @param method - HTTP method to enforce.
11
- * @returns Method-bound fetch function.
12
- * @throws {unknown} Any error thrown or rejected by `fetchFn` when the returned method-bound
13
- * fetch function is called.
14
- *
15
- * @example
16
- * const get = createMethod($fetch, "GET");
17
- * const user = await get("/users/1", UserSchema);
18
- */
19
- declare const createMethod: (fetchFn: $Fetch, method: string) => $Fetch;
20
- //#endregion
21
- export { createMethod };
22
- //# sourceMappingURL=methods.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"methods.d.mts","names":[],"sources":["../src/methods.ts"],"mappings":";;;;;;;;;;;;;;;;;;cA2Ba,eAAgB,SAAS,QAAQ,mBAAiB"}
package/dist/methods.mjs DELETED
@@ -1,58 +0,0 @@
1
- import { isStandardSchema } from "@zap-studio/validation";
2
- //#region src/methods.ts
3
- /**
4
- * Method helper factories used to build verb-specific fetch functions.
5
- *
6
- * @module @zap-studio/fetch/methods
7
- */
8
- /**
9
- * Creates an HTTP method helper bound to a fetch function.
10
- *
11
- * The returned function mirrors `$Fetch` overloads but forces the provided
12
- * HTTP method (`GET`, `POST`, etc.) into request options.
13
- *
14
- * @param fetchFn - Fetch function to wrap.
15
- * @param method - HTTP method to enforce.
16
- * @returns Method-bound fetch function.
17
- * @throws {unknown} Any error thrown or rejected by `fetchFn` when the returned method-bound
18
- * fetch function is called.
19
- *
20
- * @example
21
- * const get = createMethod($fetch, "GET");
22
- * const user = await get("/users/1", UserSchema);
23
- */
24
- const createMethod = (fetchFn, method) => {
25
- /**
26
- * Method-bound `$Fetch` implementation.
27
- *
28
- * Resolves schema/option overloads and injects the configured HTTP method.
29
- */
30
- async function methodFetch(input, schemaOrOptions, optionsOrUndefined) {
31
- if (isStandardSchema(schemaOrOptions)) {
32
- if (optionsOrUndefined?.throwOnValidationError === false) return await fetchFn(input, schemaOrOptions, {
33
- ...optionsOrUndefined,
34
- method,
35
- throwOnValidationError: false
36
- });
37
- const { throwOnValidationError, ...restOptions } = optionsOrUndefined ?? {};
38
- if (throwOnValidationError === true) return await fetchFn(input, schemaOrOptions, {
39
- ...restOptions,
40
- method,
41
- throwOnValidationError: true
42
- });
43
- return await fetchFn(input, schemaOrOptions, {
44
- ...restOptions,
45
- method
46
- });
47
- }
48
- return await fetchFn(input, {
49
- ...schemaOrOptions,
50
- method
51
- });
52
- }
53
- return methodFetch;
54
- };
55
- //#endregion
56
- export { createMethod };
57
-
58
- //# sourceMappingURL=methods.mjs.map
@@ -1 +0,0 @@
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 } from \"@zap-studio/validation\";\nimport 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 {unknown} 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 const createMethod = (fetchFn: $Fetch, 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(\n input: FetchInput,\n options?: ExtendedRequestInit\n ): Promise<Response>;\n\n /**\n * Method-bound `$Fetch` implementation.\n *\n * Resolves schema/option overloads and injects the configured HTTP method.\n */\n async 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 await fetchFn(input, schemaOrOptions, {\n ...optionsOrUndefined,\n method,\n throwOnValidationError: false,\n });\n }\n\n const { throwOnValidationError, ...restOptions } =\n optionsOrUndefined ?? {};\n\n if (throwOnValidationError === true) {\n return await fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n throwOnValidationError: true,\n });\n }\n\n return await fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n });\n }\n\n return await fetchFn(input, {\n ...schemaOrOptions,\n method,\n });\n }\n\n return methodFetch;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB,SAAiB,WAA2B;;;;;;CA2BvE,eAAe,YACb,OACA,iBACA,oBACkB;EAClB,IAAI,iBAAiB,eAAe,GAAG;GACrC,IAAI,oBAAoB,2BAA2B,OACjD,OAAO,MAAM,QAAQ,OAAO,iBAAiB;IAC3C,GAAG;IACH;IACA,wBAAwB;GAC1B,CAAC;GAGH,MAAM,EAAE,wBAAwB,GAAG,gBACjC,sBAAsB,CAAC;GAEzB,IAAI,2BAA2B,MAC7B,OAAO,MAAM,QAAQ,OAAO,iBAAiB;IAC3C,GAAG;IACH;IACA,wBAAwB;GAC1B,CAAC;GAGH,OAAO,MAAM,QAAQ,OAAO,iBAAiB;IAC3C,GAAG;IACH;GACF,CAAC;EACH;EAEA,OAAO,MAAM,QAAQ,OAAO;GAC1B,GAAG;GACH;EACF,CAAC;CACH;CAEA,OAAO;AACT"}
@@ -1,30 +0,0 @@
1
- import { ExtendedRequestInit, FetchInput } from "./types.mjs";
2
- //#region src/request.d.ts
3
- /**
4
- * Normalized representation used by internal request execution.
5
- *
6
- * - `url`: resolved string URL from the input (string or `URL`; `Request` uses `request.url`)
7
- * - `request`: original Request clone when input is a Request
8
- * - `options`: normalized request options merged with Request headers
9
- */
10
- interface NormalizedRequest {
11
- url: string;
12
- request?: Request;
13
- options: ExtendedRequestInit;
14
- }
15
- /**
16
- * Normalizes fetch `input` and request-level options into a consistent internal shape.
17
- *
18
- * @param input - Request URL/path or Request instance.
19
- * @param options - Optional request options.
20
- * @returns A normalized request structure for internal processing.
21
- * @throws {TypeError} When cloning a `Request` fails or the merged headers are invalid.
22
- *
23
- * @example
24
- * const normalized = normalizeRequest("/users", { method: "GET" });
25
- * console.log(normalized.url); // "/users"
26
- */
27
- declare const normalizeRequest: (input: FetchInput, options?: ExtendedRequestInit) => NormalizedRequest;
28
- //#endregion
29
- export { NormalizedRequest, normalizeRequest };
30
- //# sourceMappingURL=request.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"request.d.mts","names":[],"sources":["../src/request.ts"],"mappings":";;;;;;;;;UAkBiB;EACf;EACA,UAAU;EACV,SAAS;;;;;;;;;;;;;;cAeE,mBACX,OAAO,YACP,UAAU,wBACT"}
package/dist/request.mjs DELETED
@@ -1,43 +0,0 @@
1
- import { mergeHeaders } from "./headers.mjs";
2
- //#region src/request.ts
3
- /**
4
- * Request normalization helpers for fetch `input` values.
5
- *
6
- * @module @zap-studio/fetch/request
7
- */
8
- const EMPTY_OPTIONS = {};
9
- /**
10
- * Normalizes fetch `input` and request-level options into a consistent internal shape.
11
- *
12
- * @param input - Request URL/path or Request instance.
13
- * @param options - Optional request options.
14
- * @returns A normalized request structure for internal processing.
15
- * @throws {TypeError} When cloning a `Request` fails or the merged headers are invalid.
16
- *
17
- * @example
18
- * const normalized = normalizeRequest("/users", { method: "GET" });
19
- * console.log(normalized.url); // "/users"
20
- */
21
- const normalizeRequest = (input, options) => {
22
- if (!(input instanceof Request)) {
23
- const url = input instanceof URL ? input.href : input;
24
- return {
25
- options: options ?? EMPTY_OPTIONS,
26
- url
27
- };
28
- }
29
- const request = new Request(input);
30
- const { headers, ...rest } = options ?? {};
31
- const mergedHeaders = mergeHeaders(request.headers, headers);
32
- const normalizedOptions = { ...rest };
33
- if (mergedHeaders !== void 0) normalizedOptions.headers = mergedHeaders;
34
- return {
35
- options: normalizedOptions,
36
- request,
37
- url: request.url
38
- };
39
- };
40
- //#endregion
41
- export { normalizeRequest };
42
-
43
- //# sourceMappingURL=request.mjs.map
@@ -1 +0,0 @@
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 const 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 options: options ?? EMPTY_OPTIONS,\n url,\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 !== undefined) {\n normalizedOptions.headers = mergedHeaders;\n }\n\n return {\n options: normalizedOptions,\n request,\n url: request.url,\n };\n};\n"],"mappings":";;;;;;;AASA,MAAM,gBAAgB,CAAC;;;;;;;;;;;;;AA2BvB,MAAa,oBACX,OACA,YACsB;CACtB,IAAI,EAAE,iBAAiB,UAAU;EAC/B,MAAM,MAAM,iBAAiB,MAAM,MAAM,OAAO;EAChD,OAAO;GACL,SAAS,WAAW;GACpB;EACF;CACF;CAEA,MAAM,UAAU,IAAI,QAAQ,KAAK;CACjC,MAAM,EAAE,SAAS,GAAG,SAAS,WAAW,CAAC;CACzC,MAAM,gBAAgB,aAAa,QAAQ,SAAS,OAAO;CAC3D,MAAM,oBAAoB,EAAE,GAAG,KAAK;CAEpC,IAAI,kBAAkB,KAAA,GACpB,kBAAkB,UAAU;CAG9B,OAAO;EACL,SAAS;EACT;EACA,KAAK,QAAQ;CACf;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,aAAa,kBAAkB;KAEtC,uBAAuB,6BAA6B;KAEpD,kBAAkB;EACrB;;KAGG,eAAe,KAAK;;;;;EAKvB;EACA;;UAGQ;;;;;EAKR,eAAe;;;;;EAKf;;;;;EAKA;;;;;;;;;;;;KAaU,uBAAuB,kBAAkB,gBACnD;;;;;;;;;;;UAYe;;;;;EAKf;;;;;EAKA,UAAU;;;;;EAKV,eAAe;;;;;EAKf;;;;;EAKA;;;;;UAMe;;;;;;;;;;;;;;;;GAgBd,gBAAgB,kBACf,OAAO,YACP,QAAQ,SACR,SAAS;IAAwB;MAChC,QAAQ,iBAAiB,OAAO,iBAAiB,YAAY;;;;;;;;;;;;;;;;;GAkB/D,gBAAgB,kBACf,OAAO,YACP,QAAQ,SACR,UAAU;IACR;MAED,QAAQ,iBAAiB,YAAY;;;;;;;;;;;;GAavC,OAAO,YAAY,UAAU,sBAAsB,QAAQ;;;;;;;;UAS7C;;;;EAIf,QAAQ;;;;EAIR,KAAK;;;;EAIL,OAAO;;;;EAIP,MAAM;;;;EAIN,KAAK"}
package/dist/types.mjs DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/url.d.mts DELETED
@@ -1,26 +0,0 @@
1
- import { ExtendedRequestInit, FetchDefaults } from "./types.mjs";
2
- //#region src/url.d.ts
3
- /**
4
- * Resolves final request URL by applying baseURL and layered search params.
5
- *
6
- * Search param precedence:
7
- * 1. `defaults.searchParams`
8
- * 2. search params already present in `resourceUrl`
9
- * 3. per-request `searchParams`
10
- *
11
- * @example
12
- * const finalUrl = resolveRequestUrl(
13
- * "/users?page=2",
14
- * { ...defaults, baseURL: "https://api.example.com", searchParams: { locale: "en" } },
15
- * { page: "3" },
16
- * );
17
- * // https://api.example.com/users?locale=en&page=3
18
- *
19
- * @throws {TypeError} When `baseURL` and `resourceUrl` cannot be resolved by
20
- * `URL`, or when default/per-request search params cannot be converted by
21
- * `URLSearchParams`.
22
- */
23
- declare const resolveRequestUrl: (resourceUrl: string, defaults: FetchDefaults, searchParams?: ExtendedRequestInit["searchParams"]) => string;
24
- //#endregion
25
- export { resolveRequestUrl };
26
- //# sourceMappingURL=url.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"url.d.mts","names":[],"sources":["../src/url.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;cAmFa,oBACX,qBACA,UAAU,eACV,eAAe"}
package/dist/url.mjs DELETED
@@ -1,60 +0,0 @@
1
- //#region src/url.ts
2
- /**
3
- * Copies search params into target, overriding duplicate keys.
4
- */
5
- const mergeSearchParams = (target, source) => {
6
- for (const [key, value] of new URLSearchParams(source)) target.set(key, value);
7
- };
8
- /**
9
- * Ensures a URL has a trailing slash for relative URL resolution.
10
- */
11
- const ensureTrailingSlash = (url) => url.endsWith("/") ? url : `${url}/`;
12
- /**
13
- * Resolves search params by applying default params, URL params, then request params.
14
- */
15
- const resolveSearchParams = (url, defaultSearchParams, searchParams) => {
16
- if (defaultSearchParams === void 0 && searchParams === void 0) return url;
17
- const hashIndex = url.indexOf("#");
18
- const hasFragment = hashIndex !== -1;
19
- const urlWithoutHash = hasFragment ? url.slice(0, hashIndex) : url;
20
- const hash = hasFragment ? url.slice(hashIndex + 1) : "";
21
- const queryIndex = urlWithoutHash.indexOf("?");
22
- const pathname = queryIndex === -1 ? urlWithoutHash : urlWithoutHash.slice(0, queryIndex);
23
- const urlSearchParams = queryIndex === -1 ? void 0 : urlWithoutHash.slice(queryIndex + 1);
24
- const resolvedSearchParams = new URLSearchParams();
25
- mergeSearchParams(resolvedSearchParams, defaultSearchParams);
26
- mergeSearchParams(resolvedSearchParams, urlSearchParams);
27
- mergeSearchParams(resolvedSearchParams, searchParams);
28
- const resolvedSearch = resolvedSearchParams.toString();
29
- const fragmentSuffix = hasFragment ? `#${hash}` : "";
30
- if (resolvedSearch.length === 0) return `${pathname}${fragmentSuffix}`;
31
- return `${pathname}?${resolvedSearch}${fragmentSuffix}`;
32
- };
33
- /**
34
- * Resolves final request URL by applying baseURL and layered search params.
35
- *
36
- * Search param precedence:
37
- * 1. `defaults.searchParams`
38
- * 2. search params already present in `resourceUrl`
39
- * 3. per-request `searchParams`
40
- *
41
- * @example
42
- * const finalUrl = resolveRequestUrl(
43
- * "/users?page=2",
44
- * { ...defaults, baseURL: "https://api.example.com", searchParams: { locale: "en" } },
45
- * { page: "3" },
46
- * );
47
- * // https://api.example.com/users?locale=en&page=3
48
- *
49
- * @throws {TypeError} When `baseURL` and `resourceUrl` cannot be resolved by
50
- * `URL`, or when default/per-request search params cannot be converted by
51
- * `URLSearchParams`.
52
- */
53
- const resolveRequestUrl = (resourceUrl, defaults, searchParams) => {
54
- const url = defaults.baseURL ? new URL(resourceUrl, ensureTrailingSlash(defaults.baseURL)).toString() : resourceUrl;
55
- return resolveSearchParams(url, defaults.searchParams, searchParams);
56
- };
57
- //#endregion
58
- export { resolveRequestUrl };
59
-
60
- //# sourceMappingURL=url.mjs.map
package/dist/url.mjs.map DELETED
@@ -1 +0,0 @@
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 * Copies search params into target, overriding duplicate keys.\n */\nconst 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\n/**\n * Ensures a URL has a trailing slash for relative URL resolution.\n */\nconst ensureTrailingSlash = (url: string): string =>\n url.endsWith(\"/\") ? url : `${url}/`;\n\n/**\n * Resolves search params by applying default params, URL params, then request params.\n */\nconst resolveSearchParams = (\n url: string,\n defaultSearchParams: FetchDefaults[\"searchParams\"] | undefined,\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined\n): string => {\n if (defaultSearchParams === undefined && searchParams === undefined) {\n return url;\n }\n\n const hashIndex = url.indexOf(\"#\");\n const hasFragment = hashIndex !== -1;\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 =\n queryIndex === -1 ? urlWithoutHash : urlWithoutHash.slice(0, queryIndex);\n const urlSearchParams =\n queryIndex === -1 ? undefined : urlWithoutHash.slice(queryIndex + 1);\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.length === 0) {\n return `${pathname}${fragmentSuffix}`;\n }\n\n return `${pathname}?${resolvedSearch}${fragmentSuffix}`;\n};\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 const resolveRequestUrl = (\n resourceUrl: string,\n defaults: FetchDefaults,\n searchParams?: ExtendedRequestInit[\"searchParams\"]\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"],"mappings":";;;;AAWA,MAAM,qBACJ,QACA,WACS;CACT,KAAK,MAAM,CAAC,KAAK,UAAU,IAAI,gBAAgB,MAAM,GACnD,OAAO,IAAI,KAAK,KAAK;AAEzB;;;;AAKA,MAAM,uBAAuB,QAC3B,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,IAAI;;;;AAKnC,MAAM,uBACJ,KACA,qBACA,iBACW;CACX,IAAI,wBAAwB,KAAA,KAAa,iBAAiB,KAAA,GACxD,OAAO;CAGT,MAAM,YAAY,IAAI,QAAQ,GAAG;CACjC,MAAM,cAAc,cAAc;CAClC,MAAM,iBAAiB,cAAc,IAAI,MAAM,GAAG,SAAS,IAAI;CAC/D,MAAM,OAAO,cAAc,IAAI,MAAM,YAAY,CAAC,IAAI;CACtD,MAAM,aAAa,eAAe,QAAQ,GAAG;CAC7C,MAAM,WACJ,eAAe,KAAK,iBAAiB,eAAe,MAAM,GAAG,UAAU;CACzE,MAAM,kBACJ,eAAe,KAAK,KAAA,IAAY,eAAe,MAAM,aAAa,CAAC;CACrE,MAAM,uBAAuB,IAAI,gBAAgB;CAEjD,kBAAkB,sBAAsB,mBAAmB;CAC3D,kBAAkB,sBAAsB,eAAe;CACvD,kBAAkB,sBAAsB,YAAY;CAEpD,MAAM,iBAAiB,qBAAqB,SAAS;CACrD,MAAM,iBAAiB,cAAc,IAAI,SAAS;CAElD,IAAI,eAAe,WAAW,GAC5B,OAAO,GAAG,WAAW;CAGvB,OAAO,GAAG,SAAS,GAAG,iBAAiB;AACzC;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,qBACX,aACA,UACA,iBACW;CACX,MAAM,MAAM,SAAS,UACjB,IAAI,IAAI,aAAa,oBAAoB,SAAS,OAAO,CAAC,CAAC,CAAC,SAAS,IACrE;CAEJ,OAAO,oBAAoB,KAAK,SAAS,cAAc,YAAY;AACrE"}