@kosmojs/fetch 0.0.11 → 0.0.21

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present, Slee Woo and KosmoJS contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@kosmojs/fetch",
4
- "version": "0.0.11",
4
+ "version": "0.0.21",
5
5
  "author": "Slee Woo",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
@@ -12,16 +12,15 @@
12
12
  ],
13
13
  "exports": {
14
14
  ".": {
15
- "types": "./pkg/src/index.d.ts",
15
+ "types": "./pkg/index.d.ts",
16
16
  "default": "./pkg/index.js"
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "qs": "^6.14.0"
20
+ "qs": "^6.15.0"
21
21
  },
22
22
  "devDependencies": {
23
- "@types/qs": "^6.14.0",
24
- "@kosmojs/config": "^0.0.11"
23
+ "@types/qs": "^6.15.0"
25
24
  },
26
25
  "scripts": {
27
26
  "build": "esbuilder src/index.ts",
@@ -0,0 +1,5 @@
1
+ export declare const defaults: {
2
+ responseMode: "json";
3
+ stringify: (data: Record<string, unknown>) => string;
4
+ errorHandler: (...data: any[]) => void;
5
+ };
package/pkg/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { FetchMapper, Options } from "./types";
2
+ export * from "./defaults";
3
+ export * from "./types";
4
+ export * from "./utils";
5
+ declare const _default: (base: string | URL, baseOpts?: Options) => FetchMapper;
6
+ export default _default;
package/pkg/index.js CHANGED
@@ -1,78 +1,89 @@
1
- // src/index.ts
1
+ // src/utils.ts
2
2
  import qs from "qs";
3
+ var stringify = (data) => {
4
+ return qs.stringify(data, {
5
+ arrayFormat: "brackets",
6
+ indices: false,
7
+ encodeValuesOnly: true
8
+ });
9
+ };
10
+ var join = (...args) => {
11
+ for (const a of args) {
12
+ if (typeof a === "string" || typeof a === "number") {
13
+ continue;
14
+ }
15
+ throw new Error(
16
+ `The "path" argument must be of type string or number. Received type ${typeof a} (${JSON.stringify(a)})`
17
+ );
18
+ }
19
+ return args.join("/").replace(/\/+/g, "/");
20
+ };
21
+ var createHost = (host) => {
22
+ if (typeof host === "string") {
23
+ return host;
24
+ }
25
+ if (typeof host === "object") {
26
+ return [
27
+ host.secure ? "https://" : "http://",
28
+ host.hostname,
29
+ host.port ? `:${host.port}` : ""
30
+ ].join("").replace(/\/+$/, "");
31
+ }
32
+ throw new Error(
33
+ "Expected host to be a string or an object like { hostname: string; port?: number; secure?: boolean }"
34
+ );
35
+ };
3
36
 
4
37
  // src/defaults.ts
5
- var defaults_default = {
38
+ var defaults = {
6
39
  responseMode: "json",
7
- get headers() {
8
- return {
9
- Accept: "application/json",
10
- "Content-Type": "application/json"
11
- };
12
- },
13
- stringify: (o) => new URLSearchParams(o).toString(),
40
+ stringify,
14
41
  errorHandler: console.error
15
42
  };
16
43
 
17
44
  // src/index.ts
18
45
  var bodylessMethods = ["GET", "DELETE"];
19
- var index_default = (base, opts) => {
20
- const {
21
- headers: _headers,
22
- responseMode,
23
- stringify: stringify2,
24
- errorHandler,
25
- ...fetchOpts
26
- // Remaining options passed directly to fetch
27
- } = {
28
- ...defaults_default,
29
- ...opts
30
- };
31
- const headers = new Headers({
32
- ..._headers instanceof Headers ? Object.fromEntries(_headers.entries()) : _headers
33
- // Use as-is if already a plain object
34
- });
35
- function wrapper(method) {
36
- function _wrapper(path, data) {
46
+ var index_default = (base, baseOpts) => {
47
+ function factory(method) {
48
+ return async (...args) => {
49
+ const [path, data, opts] = args;
50
+ const {
51
+ responseMode,
52
+ stringify: stringify2,
53
+ errorHandler,
54
+ ...fetchOpts
55
+ // Remaining options passed directly to fetch
56
+ } = {
57
+ ...defaults,
58
+ ...baseOpts,
59
+ ...opts
60
+ };
37
61
  const url = [
38
62
  String(base),
39
- ...Array.isArray(path) ? path : ["string", "number"].includes(typeof path) ? [path] : []
63
+ ...Array.isArray(path) ? path.flat() : ["string", "number"].includes(typeof path) ? [path] : []
40
64
  // No path provided
41
65
  ].join("/");
42
- const optedContentType = opts?.headers instanceof Headers ? opts.headers.get("Content-Type") : opts?.headers?.["Content-Type"];
43
- if (responseMode !== defaults_default.responseMode && !optedContentType) {
44
- const contentType = {
45
- text: "text/plain",
46
- blob: data instanceof Blob ? data.type : void 0,
47
- formData: null,
48
- // Let browser set multipart boundary
49
- arrayBuffer: null,
50
- // No content-type needed
51
- raw: void 0
52
- // Don't modify
53
- }[responseMode];
54
- if (contentType === null) {
55
- headers.delete("Content-Type");
56
- } else if (contentType) {
57
- headers.set("Content-Type", contentType);
58
- }
59
- }
60
- let searchParams = "";
61
- let body = JSON.stringify({});
62
- if (data instanceof Blob || data instanceof FormData || Object.prototype.toString.call(data) === "[object ArrayBuffer]") {
63
- body = data;
64
- } else if (typeof data === "string") {
65
- if (bodylessMethods.includes(method)) {
66
- searchParams = data;
67
- } else {
68
- body = data;
69
- }
70
- } else if (typeof data === "object") {
71
- if (bodylessMethods.includes(method)) {
72
- searchParams = stringify2(data);
66
+ const headers = new Headers({
67
+ ...data?.headers instanceof Headers ? Object.fromEntries(data.headers.entries()) : data?.headers
68
+ // Use as-is if already a plain object
69
+ });
70
+ let contentType;
71
+ let body;
72
+ if (data?.json) {
73
+ contentType = "application/json";
74
+ body = JSON.stringify(data.json);
75
+ } else if (data?.form) {
76
+ if (data.form instanceof FormData) {
77
+ body = data.form;
73
78
  } else {
74
- body = JSON.stringify({ ...data });
79
+ contentType = "application/x-www-form-urlencoded";
80
+ body = stringify2(data.form);
75
81
  }
82
+ } else if (data?.raw) {
83
+ body = data.raw;
84
+ }
85
+ if (contentType && !headers.get("Content-Type")) {
86
+ headers.set("Content-Type", contentType);
76
87
  }
77
88
  const config = {
78
89
  ...fetchOpts,
@@ -81,45 +92,42 @@ var index_default = (base, opts) => {
81
92
  // Only include body for non-bodyless methods
82
93
  ...bodylessMethods.includes(method) ? {} : { body }
83
94
  };
84
- return fetch([url, searchParams].join("?"), config).then((response) => {
95
+ const searchParams = data?.query ? `?${stringify2(data.query)}` : "";
96
+ return fetch(url + searchParams, config).then((response) => {
85
97
  return Promise.all([
86
98
  response,
87
- responseMode === "raw" ? response : response[responseMode]().catch(() => null)
99
+ responseMode === "raw" ? response : response[responseMode]().catch((e) => e)
88
100
  // Parse response body
89
101
  ]);
90
102
  }).then(([response, data2]) => {
91
103
  if (response.ok) {
92
- return data2;
104
+ return data2 instanceof Error ? void 0 : data2;
93
105
  }
94
106
  const error = new Error(
95
107
  data2?.error || response.statusText
96
108
  );
97
109
  error.response = response;
98
110
  error.body = data2;
99
- errorHandler?.(error);
111
+ if (errorHandler) {
112
+ return errorHandler(error);
113
+ }
100
114
  throw error;
101
115
  });
102
- }
103
- return _wrapper;
116
+ };
104
117
  }
105
118
  return {
106
- GET: wrapper("GET"),
107
- POST: wrapper("POST"),
108
- PUT: wrapper("PUT"),
109
- PATCH: wrapper("PATCH"),
110
- DELETE: wrapper("DELETE")
119
+ GET: factory("GET"),
120
+ POST: factory("POST"),
121
+ PUT: factory("PUT"),
122
+ PATCH: factory("PATCH"),
123
+ DELETE: factory("DELETE")
111
124
  };
112
125
  };
113
- var stringify = (data) => {
114
- return qs.stringify(data, {
115
- arrayFormat: "brackets",
116
- indices: false,
117
- encodeValuesOnly: true
118
- });
119
- };
120
126
  export {
127
+ createHost,
121
128
  index_default as default,
122
- defaults_default as defaults,
129
+ defaults,
130
+ join,
123
131
  stringify
124
132
  };
125
133
  //# sourceMappingURL=index.js.map
package/pkg/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/defaults.ts"],
4
- "sourcesContent": ["import qs from \"qs\";\n\nimport defaults from \"./defaults\";\nimport type {\n FetchMapper,\n FetchMethod,\n HTTPError,\n HTTPMethod,\n Options,\n} from \"./types\";\n\nexport { defaults };\n\nexport * from \"./types\";\n\n// Supported data types for request body\ntype Data = Record<string, unknown> | FormData | ArrayBuffer | Blob | string;\n\n// Path can be a string, number, or array of these\ntype PathEntry = string | number;\n\n// HTTP methods that typically don't include a request body\nconst bodylessMethods = [\"GET\", \"DELETE\"];\n\n// Main factory function that creates a configured fetch client instance\nexport default (base: string | URL, opts?: Options): FetchMapper => {\n // Merge provided options with defaults, extracting specific properties\n const {\n headers: _headers,\n responseMode,\n stringify,\n errorHandler,\n ...fetchOpts // Remaining options passed directly to fetch\n } = {\n ...defaults,\n ...opts,\n };\n\n // Normalize headers to Headers instance for consistent API\n const headers = new Headers({\n ...(_headers instanceof Headers\n ? Object.fromEntries(_headers.entries()) // Convert Headers to plain object\n : _headers), // Use as-is if already a plain object\n });\n\n // Factory function that creates HTTP method implementations\n function wrapper(method: HTTPMethod): FetchMethod {\n // Function overloads for TypeScript type checking\n // No path, no data\n function _wrapper<T>(): Promise<T>;\n // Path without data\n function _wrapper<T>(path: PathEntry | Array<PathEntry>): Promise<T>;\n // Path with data\n function _wrapper<T>(\n path: PathEntry | Array<PathEntry>,\n data: Data,\n ): Promise<T>;\n\n // Main implementation function\n function _wrapper<T>(\n path?: PathEntry | Array<PathEntry>,\n data?: Data,\n ): Promise<T> {\n // Construct URL from base and path segments\n const url = [\n String(base),\n ...(Array.isArray(path)\n ? path // Use array as-is\n : [\"string\", \"number\"].includes(typeof path)\n ? [path] // Wrap single value in array\n : []), // No path provided\n ].join(\"/\");\n\n // Check if content-type was explicitly set in options\n const optedContentType =\n opts?.headers instanceof Headers\n ? opts.headers.get(\"Content-Type\")\n : opts?.headers?.[\"Content-Type\"];\n\n // Auto-set Content-Type header based on response mode if not explicitly set\n if (responseMode !== defaults.responseMode && !optedContentType) {\n const contentType = {\n text: \"text/plain\",\n blob: data instanceof Blob ? data.type : undefined,\n formData: null, // Let browser set multipart boundary\n arrayBuffer: null, // No content-type needed\n raw: undefined, // Don't modify\n }[responseMode];\n\n if (contentType === null) {\n headers.delete(\"Content-Type\");\n } else if (contentType) {\n headers.set(\"Content-Type\", contentType);\n }\n }\n\n let searchParams = \"\";\n\n // Default empty body\n let body: string | FormData | ArrayBuffer | Blob = JSON.stringify({});\n\n // Handle different data types for request body\n if (\n data instanceof Blob ||\n data instanceof FormData ||\n Object.prototype.toString.call(data) === \"[object ArrayBuffer]\"\n ) {\n // Use binary data as-is\n body = data as typeof body;\n } else if (typeof data === \"string\") {\n if (bodylessMethods.includes(method)) {\n // For GET/DELETE, add string data as query params\n searchParams = data;\n } else {\n // For other methods, use as body\n body = data;\n }\n } else if (typeof data === \"object\") {\n if (bodylessMethods.includes(method)) {\n // For GET/DELETE, serialize object to query string\n searchParams = stringify(data as Record<string, string>);\n } else {\n // For other methods, serialize as JSON\n body = JSON.stringify({ ...data });\n }\n }\n\n // Prepare fetch configuration\n const config: Options & { method: HTTPMethod; body?: typeof body } = {\n ...fetchOpts,\n method,\n headers,\n // Only include body for non-bodyless methods\n ...(bodylessMethods.includes(method) ? {} : { body }),\n };\n\n // Execute fetch request and process response\n return fetch([url, searchParams].join(\"?\"), config)\n .then((response) => {\n // Return both response and parsed data based on responseMode\n return Promise.all([\n response,\n responseMode === \"raw\"\n ? response // Return full response object\n : response[responseMode]().catch(() => null), // Parse response body\n ]);\n })\n .then(([response, data]) => {\n if (response.ok) {\n return data; // Return parsed data for successful responses\n }\n // Create enhanced error object for HTTP errors\n const error = new Error(\n data?.error || response.statusText,\n ) as HTTPError;\n error.response = response;\n error.body = data;\n errorHandler?.(error); // Call custom error handler if provided\n throw error;\n });\n }\n\n return _wrapper;\n }\n\n // Return object with HTTP method functions\n return {\n GET: wrapper(\"GET\"),\n POST: wrapper(\"POST\"),\n PUT: wrapper(\"PUT\"),\n PATCH: wrapper(\"PATCH\"),\n DELETE: wrapper(\"DELETE\"),\n };\n};\n\nexport const stringify = (data: Record<string, unknown>) => {\n return qs.stringify(data, {\n arrayFormat: \"brackets\",\n indices: false,\n encodeValuesOnly: true,\n });\n};\n", "export default {\n responseMode: \"json\",\n get headers() {\n return {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n },\n stringify: (o) => new URLSearchParams(o as never).toString(),\n errorHandler: console.error,\n} satisfies import(\"./types\").Defaults;\n"],
5
- "mappings": ";AAAA,OAAO,QAAQ;;;ACAf,IAAO,mBAAQ;AAAA,EACb,cAAc;AAAA,EACd,IAAI,UAAU;AACZ,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,gBAAgB;AAAA,IAClB;AAAA,EACF;AAAA,EACA,WAAW,CAAC,MAAM,IAAI,gBAAgB,CAAU,EAAE,SAAS;AAAA,EAC3D,cAAc,QAAQ;AACxB;;;ADYA,IAAM,kBAAkB,CAAC,OAAO,QAAQ;AAGxC,IAAO,gBAAQ,CAAC,MAAoB,SAAgC;AAElE,QAAM;AAAA,IACJ,SAAS;AAAA,IACT;AAAA,IACA,WAAAA;AAAA,IACA;AAAA,IACA,G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Opt } from \"./types\";\n\nexport const stringify = (data: Record<string, unknown>) => {\n return qs.stringify(data, {\n arrayFormat: \"brackets\",\n indices: false,\n encodeValuesOnly: true,\n });\n};\n\nexport const join = (...args: Array<unknown>): string => {\n for (const a of args) {\n if (typeof a === \"string\" || typeof a === \"number\") {\n continue;\n }\n throw new Error(\n `The \"path\" argument must be of type string or number. Received type ${typeof a} (${JSON.stringify(a)})`,\n );\n }\n return args.join(\"/\").replace(/\\/+/g, \"/\");\n};\n\nexport const createHost = (host: HostOpt): string => {\n if (typeof host === \"string\") {\n return host;\n }\n\n if (typeof host === \"object\") {\n return [\n host.secure ? \"https://\" : \"http://\",\n host.hostname,\n host.port ? `:${host.port}` : \"\",\n ]\n .join(\"\")\n .replace(/\\/+$/, \"\");\n }\n\n throw new Error(\n \"Expected host to be a string or an object like { hostname: string; port?: number; secure?: boolean }\",\n );\n};\n", "import type { Defaults } from \"./types\";\nimport { stringify } from \"./utils\";\n\nexport const defaults = {\n responseMode: \"json\",\n stringify,\n errorHandler: console.error,\n} satisfies Defaults;\n", "import { defaults } from \"./defaults\";\nimport type {\n FetchMapper,\n FetchMethod,\n HTTPError,\n HTTPMethod,\n Options,\n} from \"./types\";\n\nexport * from \"./defaults\";\nexport * from \"./types\";\nexport * from \"./utils\";\n\n// HTTP methods that typically don't include a request body\nconst bodylessMethods = [\"GET\", \"DELETE\"];\n\n// Main factory function that creates a configured fetch client instance\nexport default (base: string | URL, baseOpts?: Options): FetchMapper => {\n // Factory function that creates HTTP method implementations\n function factory(method: HTTPMethod): FetchMethod {\n return async (...args: Partial<Parameters<FetchMethod>>) => {\n const [path, data, opts] = args;\n\n const {\n responseMode,\n stringify,\n errorHandler,\n ...fetchOpts // Remaining options passed directly to fetch\n } = {\n ...defaults,\n ...baseOpts,\n ...opts,\n };\n\n // Construct URL from base and path segments\n const url = [\n String(base),\n ...(Array.isArray(path)\n ? path.flat()\n : [\"string\", \"number\"].includes(typeof path)\n ? [path] // Wrap single value in array\n : []), // No path provided\n ].join(\"/\");\n\n // Normalize headers to Headers instance for consistent API\n const headers = new Headers({\n ...(data?.headers instanceof Headers\n ? Object.fromEntries(data.headers.entries()) // Convert Headers to plain object\n : data?.headers), // Use as-is if already a plain object\n });\n\n let contentType: string | undefined;\n let body: unknown;\n\n // Handle different data types for request body\n if (data?.json) {\n contentType = \"application/json\";\n body = JSON.stringify(data.json);\n } else if (data?.form) {\n if (data.form instanceof FormData) {\n // let fetch set Content-Type, with boundary etc.\n body = data.form;\n } else {\n contentType = \"application/x-www-form-urlencoded\";\n body = stringify(data.form as never);\n }\n } else if (data?.raw) {\n // no Content-Type needed\n body = data.raw;\n }\n\n if (contentType && !headers.get(\"Content-Type\")) {\n headers.set(\"Content-Type\", contentType);\n }\n\n // Prepare fetch configuration\n const config = {\n ...fetchOpts,\n method,\n headers,\n // Only include body for non-bodyless methods\n ...(bodylessMethods.includes(method) ? {} : { body }),\n };\n\n const searchParams = data?.query\n ? `?${stringify(data.query as never)}`\n : \"\";\n\n return fetch(url + searchParams, config as never)\n .then((response) => {\n // Return both response and parsed data based on responseMode\n return Promise.all([\n response,\n responseMode === \"raw\"\n ? response // Return full response object\n : response[responseMode]().catch((e) => e), // Parse response body\n ]);\n })\n .then(([response, data]) => {\n if (response.ok) {\n return data instanceof Error ? undefined : data;\n }\n // Create enhanced error object for HTTP errors\n const error = new Error(\n data?.error || response.statusText,\n ) as HTTPError;\n error.response = response;\n error.body = data;\n if (errorHandler) {\n return errorHandler(error);\n }\n throw error;\n });\n };\n }\n\n return {\n GET: factory(\"GET\"),\n POST: factory(\"POST\"),\n PUT: factory(\"PUT\"),\n PATCH: factory(\"PATCH\"),\n DELETE: factory(\"DELETE\"),\n };\n};\n"],
5
+ "mappings": ";AAAA,OAAO,QAAQ;AAIR,IAAM,YAAY,CAAC,SAAkC;AAC1D,SAAO,GAAG,UAAU,MAAM;AAAA,IACxB,aAAa;AAAA,IACb,SAAS;AAAA,IACT,kBAAkB;AAAA,EACpB,CAAC;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Ac;AAChB,iBAAO,aAAa,KAAK;AAAA,QAC3B;AACA,cAAM;AAAA,MACR,CAAC;AAAA,IACL;AAAA,EACF;AAEA,SAAO;AAAA,IACL,KAAK,QAAQ,KAAK;AAAA,IAClB,MAAM,QAAQ,MAAM;AAAA,IACpB,KAAK,QAAQ,KAAK;AAAA,IAClB,OAAO,QAAQ,OAAO;AAAA,IACtB,QAAQ,QAAQ,QAAQ;AAAA,EAC1B;AACF;",
6
6
  "names": ["stringify", "data"]
7
7
  }
package/pkg/types.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export interface Defaults {
2
+ responseMode: ResponseMode;
3
+ stringify: (d: Record<string, unknown>) => string;
4
+ errorHandler: (e: unknown) => void;
5
+ }
6
+ export type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
7
+ export type ResponseMode = "json" | "text" | "blob" | "formData" | "arrayBuffer" | "raw";
8
+ export type Options = Partial<Defaults> & Pick<RequestInit, "cache" | "credentials" | "integrity" | "keepalive" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window">;
9
+ export type PathEntry = string | number;
10
+ export type Data = Partial<Record<"query" | "json" | "form" | "raw", unknown> & {
11
+ headers: Headers | Record<string, string>;
12
+ }>;
13
+ export type FetchMethod = {
14
+ <T = unknown>(): Promise<T>;
15
+ <T = unknown>(path: PathEntry | Array<PathEntry>): Promise<T>;
16
+ <T = unknown>(path: PathEntry | Array<PathEntry>, data: Data): Promise<T>;
17
+ <T = unknown>(path: PathEntry | Array<PathEntry>, data: Data, opts: Options): Promise<T>;
18
+ };
19
+ export type FetchMapper = Record<HTTPMethod, FetchMethod>;
20
+ export interface HTTPError<T extends object = object> extends Error {
21
+ body: T;
22
+ response: Response;
23
+ }
24
+ export type HostOpt = string | {
25
+ hostname: string;
26
+ port?: number;
27
+ secure?: boolean;
28
+ };
package/pkg/utils.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { HostOpt } from "./types";
2
+ export declare const stringify: (data: Record<string, unknown>) => string;
3
+ export declare const join: (...args: Array<unknown>) => string;
4
+ export declare const createHost: (host: HostOpt) => string;
@@ -1,10 +0,0 @@
1
- declare const _default: {
2
- responseMode: "json";
3
- readonly headers: {
4
- Accept: string;
5
- "Content-Type": string;
6
- };
7
- stringify: (o: Record<string, unknown>) => string;
8
- errorHandler: (...data: any[]) => void;
9
- };
10
- export default _default;
@@ -1,7 +0,0 @@
1
- import defaults from "./defaults";
2
- import type { FetchMapper, Options } from "./types";
3
- export { defaults };
4
- export * from "./types";
5
- declare const _default: (base: string | URL, opts?: Options) => FetchMapper;
6
- export default _default;
7
- export declare const stringify: (data: Record<string, unknown>) => string;
@@ -1,15 +0,0 @@
1
- export interface Defaults {
2
- responseMode: ResponseMode;
3
- headers: Record<string, string> | Headers;
4
- stringify: (d: Record<string, unknown>) => string;
5
- errorHandler: (e: unknown) => void;
6
- }
7
- export type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
8
- export type ResponseMode = "json" | "text" | "blob" | "formData" | "arrayBuffer" | "raw";
9
- export type Options = Partial<Defaults> & Pick<RequestInit, "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window">;
10
- export type FetchMethod = <T = unknown>(...a: Array<unknown>) => Promise<T>;
11
- export type FetchMapper = Record<HTTPMethod, FetchMethod>;
12
- export interface HTTPError<T extends object = object> extends Error {
13
- body: T;
14
- response: Response;
15
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export declare const server: import("msw/node").SetupServerApi;
@@ -1 +0,0 @@
1
- export {};