unfee 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Ayoub Chaaoui <ayoubchaaoui02@gmail.com>
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/README.md ADDED
File without changes
@@ -0,0 +1,67 @@
1
+ //#region src/http-error.d.ts
2
+ declare class HTTPError extends Error {
3
+ readonly response: Response;
4
+ readonly request: Request;
5
+ readonly options: FetchOptions;
6
+ readonly status: number;
7
+ readonly statusText: string;
8
+ constructor(response: Response, request: Request, options: FetchOptions);
9
+ }
10
+ //#endregion
11
+ //#region src/types.d.ts
12
+ type Input = string | URL;
13
+ interface Fetch {
14
+ <T = any>(input: Input, options?: FetchOptions): Promise<FetchResponse<T>>;
15
+ extend: (options: ExtendOptions) => Fetch;
16
+ }
17
+ interface FetchResponse<T> {
18
+ headers: Headers;
19
+ data: T;
20
+ status: number;
21
+ statusText: string;
22
+ }
23
+ interface ExtendOptions {
24
+ baseUrl?: string;
25
+ headers?: HeadersInit;
26
+ query?: Record<string, any>;
27
+ hooks?: Hooks;
28
+ }
29
+ interface FetchOptions {
30
+ method?: RequestHttpVerbs;
31
+ query?: Record<string, any>;
32
+ headers?: HeadersInit;
33
+ data?: string | FormData | URLSearchParams | object;
34
+ hooks?: Hooks;
35
+ }
36
+ interface Hooks {
37
+ beforeRequest?: (options: Omit<FetchOptions, "hooks">) => void;
38
+ afterResponse?: (request: Request, response: Response, options: Readonly<FetchOptions>) => void;
39
+ onRequestError?: (error: unknown, request: Request, options: Readonly<FetchOptions>) => void;
40
+ onResponseError?: (error: HTTPError, response: Response, request: Request, options: Readonly<FetchOptions>) => void;
41
+ onResponseParseError?: (error: unknown, response: Response, request: Request, options: Readonly<FetchOptions>) => void;
42
+ }
43
+ interface Context {
44
+ method: string;
45
+ url: string;
46
+ headers: HeadersInit;
47
+ query: URLSearchParams;
48
+ data: BodyInit | undefined;
49
+ options: FetchOptions;
50
+ hooks: {
51
+ beforeRequest: Hooks["beforeRequest"][];
52
+ afterResponse: Hooks["afterResponse"][];
53
+ onRequestError: Hooks["onRequestError"][];
54
+ onResponseError: Hooks["onResponseError"][];
55
+ onResponseParseError: Hooks["onResponseParseError"][];
56
+ };
57
+ }
58
+ type RequestHttpVerbs = "get" | "post" | "put" | "patch" | "head" | "delete" | "options" | "trace";
59
+ declare enum ResponseType {
60
+ text = 0,
61
+ json = 1
62
+ }
63
+ //#endregion
64
+ //#region src/index.d.ts
65
+ declare const bfetch: Fetch;
66
+ //#endregion
67
+ export { Context, ExtendOptions, Fetch, FetchOptions, FetchResponse, Hooks, Input, RequestHttpVerbs, ResponseType, bfetch };
package/dist/index.js ADDED
@@ -0,0 +1,167 @@
1
+ //#region src/http-error.ts
2
+ var HTTPError = class extends Error {
3
+ status;
4
+ statusText;
5
+ constructor(response, request, options) {
6
+ super(`Request failed: [${request.method} ${request.url}]`);
7
+ this.response = response;
8
+ this.request = request;
9
+ this.options = options;
10
+ this.name = "fetch-error";
11
+ this.status = response.status;
12
+ this.statusText = response.statusText;
13
+ }
14
+ };
15
+
16
+ //#endregion
17
+ //#region src/types.ts
18
+ let ResponseType = /* @__PURE__ */ function(ResponseType) {
19
+ ResponseType[ResponseType["text"] = 0] = "text";
20
+ ResponseType[ResponseType["json"] = 1] = "json";
21
+ return ResponseType;
22
+ }({});
23
+
24
+ //#endregion
25
+ //#region src/http.ts
26
+ function constructRequest(ctx) {
27
+ const query = ctx.query.toString();
28
+ return new Request(ctx.url + (query ? `?${query}` : ""), {
29
+ method: ctx.method,
30
+ headers: ctx.headers,
31
+ body: ctx.data
32
+ });
33
+ }
34
+ function detectResponseType(responseTypeHeader) {
35
+ const JSON_RESPONSE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i;
36
+ responseTypeHeader = responseTypeHeader.split(";").shift() || "";
37
+ if (JSON_RESPONSE.test(responseTypeHeader)) return ResponseType.json;
38
+ return ResponseType.text;
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/merge.ts
43
+ function mergeURL(path, baseUrl) {
44
+ if (path instanceof URL) return path.toString();
45
+ if (!baseUrl) return path;
46
+ if (path.startsWith(baseUrl)) return path;
47
+ if (!baseUrl.endsWith("/") && !path.startsWith("/")) return `${baseUrl}/${path}`;
48
+ if (baseUrl.endsWith("/") && path.startsWith("/")) return `${baseUrl.slice(0, -1)}${path}`;
49
+ return `${baseUrl}${path}`;
50
+ }
51
+ function mergeParams(...params) {
52
+ const result = new URLSearchParams();
53
+ function normalizeQueryValue(value) {
54
+ if (value == null) return "";
55
+ if (typeof value === "object") return JSON.stringify(value);
56
+ return String(value);
57
+ }
58
+ params.forEach((queries) => {
59
+ for (const [key, value] of Object.entries(queries)) if (value === void 0) result.delete(key);
60
+ else if (Array.isArray(value)) value.forEach((val) => result.append(key, val));
61
+ else result.set(key, normalizeQueryValue(value));
62
+ });
63
+ return result;
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/parse-error.ts
68
+ var ParseError = class extends Error {
69
+ constructor(response, request, options, cause) {
70
+ super("Failed to parse response", { cause });
71
+ this.response = response;
72
+ this.request = request;
73
+ this.options = options;
74
+ this.name = "parse-error";
75
+ }
76
+ };
77
+
78
+ //#endregion
79
+ //#region src/fetch.ts
80
+ function createContext(input, options, extendOption) {
81
+ let method = "get";
82
+ let data;
83
+ let headers = { Accept: "application/json, text/plain, */*" };
84
+ if (options.method) method = options.method;
85
+ if (options.data instanceof URLSearchParams) {
86
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
87
+ data = options.data.toString();
88
+ } else if (options.data instanceof FormData) data = options.data;
89
+ else if (typeof options.data === "string") {
90
+ headers["Content-Type"] = "text/plain;charset=UTF-8";
91
+ data = options.data;
92
+ } else if (typeof options.data === "object") {
93
+ headers["Content-Type"] = "application/json";
94
+ data = JSON.stringify(options.data);
95
+ } else data = options.data;
96
+ headers = {
97
+ ...headers,
98
+ ...options.headers ?? {}
99
+ };
100
+ return {
101
+ method: method.toUpperCase(),
102
+ url: mergeURL(input, extendOption.baseUrl),
103
+ query: mergeParams(extendOption.query ?? {}, options.query ?? {}),
104
+ headers,
105
+ data,
106
+ options,
107
+ hooks: {
108
+ onRequestError: [extendOption.hooks?.onRequestError, options.hooks?.onRequestError],
109
+ onResponseError: [extendOption.hooks?.onResponseError, options.hooks?.onResponseError],
110
+ beforeRequest: [extendOption.hooks?.beforeRequest, options.hooks?.beforeRequest],
111
+ afterResponse: [extendOption.hooks?.afterResponse, options.hooks?.afterResponse],
112
+ onResponseParseError: [extendOption.hooks?.onResponseParseError, options.hooks?.onResponseParseError]
113
+ }
114
+ };
115
+ }
116
+ async function createFetchResponse(response, request, ctx) {
117
+ const contentType = detectResponseType(response.headers.get("content-type") ?? "application/json");
118
+ let data;
119
+ try {
120
+ if (contentType === ResponseType.json) data = await response.json();
121
+ else data = await response.text();
122
+ } catch (error) {
123
+ throw new ParseError(response, request, ctx.options, error);
124
+ }
125
+ return {
126
+ data,
127
+ status: response.status,
128
+ headers: response.headers,
129
+ statusText: response.statusText
130
+ };
131
+ }
132
+ function createFetch(extendOptions) {
133
+ const $fetch = async function(input, options = {}) {
134
+ extendOptions.hooks?.beforeRequest?.(options);
135
+ options.hooks?.beforeRequest?.(options);
136
+ const context = createContext(input, options, extendOptions);
137
+ const request = constructRequest(context);
138
+ let inflight;
139
+ try {
140
+ inflight = await fetch(request);
141
+ if (!inflight.ok) throw new HTTPError(inflight, request, context.options);
142
+ context.hooks.afterResponse[0]?.(request, inflight, options);
143
+ context.hooks.afterResponse[1]?.(request, inflight, options);
144
+ return await createFetchResponse(inflight, request, context);
145
+ } catch (error) {
146
+ if (error instanceof ParseError) {
147
+ context.hooks.onResponseParseError[0]?.(error, inflight, request, options);
148
+ context.hooks.onResponseParseError[1]?.(error, inflight, request, options);
149
+ } else if (error instanceof HTTPError) {
150
+ context.hooks.onResponseError[0]?.(error, inflight, request, options);
151
+ context.hooks.onResponseError[1]?.(error, inflight, request, options);
152
+ } else {
153
+ context.hooks.onRequestError[0]?.(error, request, options);
154
+ context.hooks.onRequestError[1]?.(error, request, options);
155
+ }
156
+ throw error;
157
+ }
158
+ };
159
+ return Object.assign($fetch, { extend: createFetch });
160
+ }
161
+
162
+ //#endregion
163
+ //#region src/index.ts
164
+ const bfetch = createFetch({});
165
+
166
+ //#endregion
167
+ export { ResponseType, bfetch };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "unfee",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "packageManager": "pnpm@10.20.0",
6
+ "description": "Fetch API with sensible defaults",
7
+ "license": "MIT",
8
+ "repository": "ayb-cha/unfee",
9
+ "sideEffects": false,
10
+ "exports": "./dist/index.js",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsc --noEmit && rolldown -c",
18
+ "lint": "eslint",
19
+ "lint:fix": "eslint --fix",
20
+ "prepare": "pnpm simple-git-hooks",
21
+ "test": "vitest run --coverage",
22
+ "release": "release-it"
23
+ },
24
+ "devDependencies": {
25
+ "@antfu/eslint-config": "^7.2.0",
26
+ "@commitlint/cli": "^19.6.1",
27
+ "@commitlint/config-conventional": "^19.6.0",
28
+ "@types/node": "^24.9.2",
29
+ "@vitest/coverage-v8": "^4.0.5",
30
+ "changelogen": "^0.6.2",
31
+ "eslint": "^9.39.2",
32
+ "h3": "2.0.1-rc.11",
33
+ "lint-staged": "^16.2.7",
34
+ "release-it": "^19.2.4",
35
+ "release-it-pnpm": "^4.6.6",
36
+ "rolldown": "1.0.0-rc.3",
37
+ "rolldown-plugin-dts": "^0.22.1",
38
+ "simple-git-hooks": "^2.13.1",
39
+ "typescript": "^5.9.3",
40
+ "vitest": "^4.0.5"
41
+ }
42
+ }