hoa 0.3.2 → 0.3.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.
@@ -0,0 +1,335 @@
1
+ import { commonTypeMapping, encodeUrl, statusEmptyMapping, statusRedirectMapping, statusTextMapping } from "./lib/utils.mjs";
2
+
3
+ //#region src/response.js
4
+ /**
5
+ * @typedef {Object} ResJSON
6
+ * @property {number} status - Response status code
7
+ * @property {string} statusText - Response status text
8
+ * @property {Record<string, string|string[]>} headers - Response headers
9
+ */
10
+ /**
11
+ * @class HoaResponse
12
+ */
13
+ var HoaResponse = class {
14
+ /**
15
+ * Expose a plain object snapshot of response headers.
16
+ * Uses the Web Standard Headers API internally for proper header handling.
17
+ * Returns a plain object representation where header names are normalized.
18
+ *
19
+ * @returns {Record<string, string>} Object with all response headers
20
+ * @public
21
+ */
22
+ get headers() {
23
+ this._headers = this._headers || new Headers();
24
+ return Object.fromEntries(this._headers.entries());
25
+ }
26
+ /**
27
+ * Set the response headers.
28
+ * Accepts either a Headers object or a plain object/array of header entries.
29
+ * This replaces all existing headers with the new ones.
30
+ *
31
+ * @param {Headers|Record<string, string>|Array<[string, string]>} val - Headers to set
32
+ * @public
33
+ */
34
+ set headers(val) {
35
+ if (val instanceof Headers) this._headers = val;
36
+ else this._headers = new Headers(val);
37
+ }
38
+ /**
39
+ * Get a response header value by name (case-insensitive).
40
+ * Uses the Web Standard Headers API for proper header retrieval.
41
+ * Special-cases "referer/referrer" for compatibility.
42
+ * Returns null for empty or whitespace-only field names.
43
+ *
44
+ * @param {string} field - The header name
45
+ * @returns {string|null} The header value or null if not found
46
+ * @public
47
+ */
48
+ get(field) {
49
+ if (!field) return null;
50
+ this._headers = this._headers || new Headers();
51
+ switch (field = field.toLowerCase()) {
52
+ case "referer":
53
+ case "referrer": return this._headers.get("referrer") ?? this._headers.get("referer");
54
+ default: return this._headers.get(field);
55
+ }
56
+ }
57
+ /**
58
+ * Get all Set-Cookie header values as an array.
59
+ * Returns all Set-Cookie headers that will be sent with the response.
60
+ *
61
+ * @returns {string[]} Array of Set-Cookie header values
62
+ * @public
63
+ */
64
+ getSetCookie() {
65
+ this._headers = this._headers || new Headers();
66
+ return this._headers.getSetCookie();
67
+ }
68
+ /**
69
+ * Check if a response header is present.
70
+ * Uses the Web Standard Headers API for case-insensitive header checking.
71
+ *
72
+ * @param {string} field - The header name to check
73
+ * @returns {boolean} True if the header exists
74
+ * @public
75
+ */
76
+ has(field) {
77
+ if (!field) return false;
78
+ this._headers = this._headers || new Headers();
79
+ return this._headers.has(field);
80
+ }
81
+ /**
82
+ * Set response header(s) using the Web Standard Headers API.
83
+ * Accepts various input formats:
84
+ * - Single key/value pair
85
+ * - Plain object with multiple headers
86
+ * Replaces existing header values.
87
+ *
88
+ * @param {string|Record<string,string>} field - Header name or headers object
89
+ * @param {string} [val] - Header value when field is a string
90
+ * @public
91
+ */
92
+ set(field, val) {
93
+ if (!field) return;
94
+ this._headers = this._headers || new Headers();
95
+ if (typeof field === "string") this._headers.set(field, val);
96
+ else Object.keys(field).forEach((header) => this._headers.set(header, field[header]));
97
+ }
98
+ /**
99
+ * Append a response header value using the Web Standard Headers API.
100
+ * Does not replace existing values, but appends to them.
101
+ * This is useful for headers that can have multiple values like Set-Cookie.
102
+ *
103
+ * @param {string|Record<string,string>} field - The header name or headers object
104
+ * @param {string} [val] - The value to append when field is a string
105
+ * @public
106
+ */
107
+ append(field, val) {
108
+ if (!field) return;
109
+ this._headers = this._headers || new Headers();
110
+ if (typeof field === "string") this._headers.append(field, val);
111
+ else Object.keys(field).forEach((header) => this._headers.append(header, field[header]));
112
+ }
113
+ /**
114
+ * Delete a response header by name using the Web Standard Headers API.
115
+ * Header deletion is case-insensitive.
116
+ *
117
+ * @param {string} field - The header name to delete
118
+ * @public
119
+ */
120
+ delete(field) {
121
+ if (!field) return;
122
+ this._headers = this._headers || new Headers();
123
+ this._headers.delete(field);
124
+ }
125
+ /**
126
+ * Get the response status code.
127
+ * Defaults to 404 if not explicitly set.
128
+ *
129
+ * @returns {number} The HTTP status code
130
+ * @public
131
+ */
132
+ get status() {
133
+ return this._status || 404;
134
+ }
135
+ /**
136
+ * Set the response status code.
137
+ * Automatically clears body for status codes that should not have content.
138
+ *
139
+ * @param {number} val - The HTTP status code (100-599)
140
+ * @throws {TypeError}
141
+ * @public
142
+ */
143
+ set status(val) {
144
+ if (!Number.isInteger(val)) throw new TypeError("status code must be an integer");
145
+ if (val < 100 || val > 1e3) throw new TypeError(`invalid status code: ${val}`);
146
+ this._status = val;
147
+ this._explicitStatus = true;
148
+ if (!this._explicitStatusText) this._statusText = statusTextMapping[val];
149
+ if (this.body && statusEmptyMapping[val]) this.body = null;
150
+ }
151
+ /**
152
+ * Get the response status text.
153
+ *
154
+ * @returns {string} The statusText (e.g., 'OK', 'Not Found')
155
+ * @public
156
+ */
157
+ get statusText() {
158
+ if (this._explicitStatusText) return this._statusText;
159
+ return this._statusText || (this._statusText = statusTextMapping[this.status]);
160
+ }
161
+ /**
162
+ * Set a custom response status text.
163
+ *
164
+ * @param {string} val - The custom status text
165
+ * @public
166
+ */
167
+ set statusText(val) {
168
+ this._statusText = val;
169
+ this._explicitStatusText = true;
170
+ }
171
+ /**
172
+ * Get the response body.
173
+ *
174
+ * @returns {any} The response body content
175
+ * @public
176
+ */
177
+ get body() {
178
+ return this._body;
179
+ }
180
+ /**
181
+ * Set response body with automatic content-type detection.
182
+ * Supports various body types and automatically sets appropriate headers.
183
+ * When set to null/undefined, if current Content-Type is application/json,
184
+ * body becomes the literal string 'null'; otherwise status is set to 204 and
185
+ * Content-Type/Transfer-Encoding are removed.
186
+ *
187
+ * @param {string|Object|ReadableStream|Blob|Response|ArrayBuffer|TypedArray|FormData|URLSearchParams|null} val - The response body
188
+ * @public
189
+ */
190
+ set body(val) {
191
+ this._body = val;
192
+ if (val == null) {
193
+ if (!statusEmptyMapping[this.status]) {
194
+ if (this.type === "application/json") {
195
+ this._body = "null";
196
+ return;
197
+ }
198
+ this.status = 204;
199
+ }
200
+ if (val === null) this._explicitNullBody = true;
201
+ this.delete("Content-Type");
202
+ this.delete("Content-Length");
203
+ this.delete("Transfer-Encoding");
204
+ return;
205
+ }
206
+ if (!this._explicitStatus) this.status = 200;
207
+ const noType = !this.has("Content-Type");
208
+ if (typeof val === "string") {
209
+ if (noType) this.type = /^\s*</.test(val) ? "html" : "text";
210
+ return;
211
+ }
212
+ if (val instanceof Blob || val instanceof ArrayBuffer || ArrayBuffer.isView(val) || val instanceof ReadableStream) {
213
+ if (noType) if (val instanceof Blob && val.type) this.set("Content-Type", val.type);
214
+ else this.type = "bin";
215
+ return;
216
+ }
217
+ if (val instanceof FormData) return;
218
+ if (val instanceof URLSearchParams) {
219
+ if (noType) this.type = "form";
220
+ return;
221
+ }
222
+ if (val instanceof Response) {
223
+ if (noType) this.type = "bin";
224
+ this.status = val.status;
225
+ for (const [k, v] of val.headers) this.set(k, v);
226
+ return;
227
+ }
228
+ if (!this.type || !/\bjson\b/i.test(this.type)) this.type = "json";
229
+ }
230
+ /**
231
+ * Perform an HTTP redirect to the specified URL.
232
+ * Automatically sets the Location header and appropriate status code.
233
+ * Absolute URLs are normalized and Location value is URL-encoded.
234
+ *
235
+ * @param {string} url - The URL to redirect to (absolute or relative)
236
+ * @public
237
+ */
238
+ redirect(url) {
239
+ if (/^https?:\/\//i.test(url)) url = new URL(url).toString();
240
+ this.set("Location", encodeUrl(url));
241
+ if (!statusRedirectMapping[this.status]) this.status = 302;
242
+ this.type = "text";
243
+ this.body = `Redirecting to ${url}.`;
244
+ }
245
+ /**
246
+ * Perform a special-cased "back" redirect using the Referrer header.
247
+ * When Referrer is not present or unsafe, falls back to the provided alternative or "/".
248
+ * Only redirects to same-origin referrers for security.
249
+ * If referrer is an absolute URL with different origin or an invalid URL, falls back.
250
+ *
251
+ * @param {string} [alt='/'] - Alternative URL when referrer is unavailable or unsafe
252
+ * @public
253
+ */
254
+ back(alt) {
255
+ const referrer = this.req.get("Referrer");
256
+ if (referrer) {
257
+ if (referrer.startsWith("/")) {
258
+ this.redirect(referrer);
259
+ return;
260
+ }
261
+ if (new URL(referrer, this.req.href).origin === this.req.origin) {
262
+ this.redirect(referrer);
263
+ return;
264
+ }
265
+ }
266
+ this.redirect(alt || "/");
267
+ }
268
+ /**
269
+ * Get the response Content-Type without parameters.
270
+ * Returns only the media type without parameters (e.g., 'application/json').
271
+ *
272
+ * @returns {string|null} The content type, or null if not set
273
+ * @public
274
+ */
275
+ get type() {
276
+ const type = this.get("Content-Type");
277
+ if (!type) return null;
278
+ return type.split(";", 1)[0];
279
+ }
280
+ /**
281
+ * Set the response Content-Type.
282
+ * Supports both full MIME types and shorthand aliases.
283
+ *
284
+ * @param {string} type - The content type or alias (e.g., 'json', 'html', 'application/json')
285
+ * @public
286
+ */
287
+ set type(val) {
288
+ if (!val) return;
289
+ val = commonTypeMapping[val] || val;
290
+ this.set("Content-Type", val);
291
+ }
292
+ /**
293
+ * Get the response Content-Length as a number.
294
+ * Returns the parsed Content-Length header value, or calculates it from the body if available.
295
+ *
296
+ * @returns {number|null} The content length in bytes, or null if not determinable
297
+ * @public
298
+ */
299
+ get length() {
300
+ if (this.has("Content-Length")) return Number.parseInt(this.get("Content-Length"), 10) || 0;
301
+ if (this.body == null || this.body instanceof ReadableStream || this.body instanceof FormData || this.body instanceof Response) return null;
302
+ if (typeof this.body === "string") return new TextEncoder().encode(this.body).length;
303
+ if (this.body instanceof Blob) return this.body.size;
304
+ if (this.body instanceof ArrayBuffer) return this.body.byteLength;
305
+ if (ArrayBuffer.isView(this.body)) return this.body.byteLength;
306
+ if (this.body instanceof URLSearchParams) return new TextEncoder().encode(this.body.toString()).length;
307
+ return new TextEncoder().encode(JSON.stringify(this.body)).length;
308
+ }
309
+ /**
310
+ * Set the response Content-Length header.
311
+ * Only sets the header if Transfer-Encoding is not present.
312
+ *
313
+ * @param {number|string} val - The content length in bytes
314
+ * @public
315
+ */
316
+ set length(val) {
317
+ if (!this.has("Transfer-Encoding")) this.set("Content-Length", val);
318
+ }
319
+ /**
320
+ * Return JSON representation of the response.
321
+ *
322
+ * @returns {ResJSON} JSON representation of response
323
+ * @public
324
+ */
325
+ toJSON() {
326
+ return {
327
+ status: this.status,
328
+ statusText: this.statusText,
329
+ headers: this.headers
330
+ };
331
+ }
332
+ };
333
+
334
+ //#endregion
335
+ export { HoaResponse as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hoa",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "A minimal web framework built on Web Standards",
5
5
  "main": "./dist/cjs/hoa.js",
6
6
  "type": "module",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "scripts": {
23
23
  "lint": "eslint .",
24
- "build": "tsup",
24
+ "build": "tsdown",
25
25
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
26
26
  "prepublishOnly": "npm run lint && npm run test && npm run build",
27
27
  "prepare": "husky"
@@ -48,14 +48,14 @@
48
48
  "lambda"
49
49
  ],
50
50
  "devDependencies": {
51
- "@commitlint/cli": "20.1.0",
52
- "@commitlint/config-conventional": "20.0.0",
53
- "eslint": "9.39.1",
54
- "globals": "16.5.0",
51
+ "@commitlint/cli": "20.3.1",
52
+ "@commitlint/config-conventional": "20.3.1",
53
+ "eslint": "9.39.2",
54
+ "globals": "17.1.0",
55
55
  "husky": "9.1.7",
56
56
  "jest": "30.2.0",
57
57
  "neostandard": "0.12.2",
58
- "tsup": "8.5.0"
58
+ "tsdown": "0.20.1"
59
59
  },
60
60
  "engines": {
61
61
  "node": ">=20"
package/types/index.d.ts CHANGED
@@ -1,25 +1,32 @@
1
- interface AppJSON {
1
+ interface HoaAppJson {
2
2
  name: string;
3
3
  }
4
4
 
5
- interface CtxJSON {
6
- app: AppJSON;
7
- req: ReqJSON;
8
- res: ResJSON;
5
+ interface HoaContextJson {
6
+ app: HoaAppJson;
7
+ req: HoaRequestJson;
8
+ res: HoaResponseJson;
9
9
  }
10
10
 
11
- interface ReqJSON {
11
+ interface HoaRequestJson {
12
12
  method: string;
13
13
  url: string;
14
14
  headers: Record<string, string>;
15
15
  }
16
16
 
17
- interface ResJSON {
17
+ interface HoaResponseJson {
18
18
  status: number;
19
19
  statusText: string;
20
20
  headers: Record<string, string>;
21
21
  }
22
22
 
23
+ interface HoaError {
24
+ message?: string;
25
+ cause?: unknown;
26
+ expose?: boolean;
27
+ headers?: Headers | Record<string, string> | Iterable<readonly [string, string]>;
28
+ }
29
+
23
30
  export type HoaExtension = (app: Hoa) => void;
24
31
 
25
32
  export type HoaMiddleware = (ctx: HoaContext, next?: () => Promise<void>) => Promise<void> | void;
@@ -40,7 +47,7 @@ export declare class Hoa {
40
47
  protected handleRequest(ctx: HoaContext, middlewareFn: HoaMiddleware): Promise<Response>;
41
48
  protected createContext(request: Request, env?: any, executionCtx?: any): HoaContext;
42
49
  protected onerror(err: unknown, ctx?: HoaContext): void;
43
- toJSON(): AppJSON;
50
+ toJSON(): HoaAppJson;
44
51
 
45
52
  static get default(): typeof Hoa;
46
53
  }
@@ -54,10 +61,10 @@ export declare class HoaContext {
54
61
  env?: any;
55
62
  executionCtx?: any;
56
63
  state: Record<string, any>;
57
- throw(status: number, message?: string | { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> }, options?: { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> }): never;
58
- assert<T>(value: T, status: number, message?: string | { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> }, options?: { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> }): asserts value is NonNullable<T>;
64
+ throw(status: number, message?: string | HoaError, options?: HoaError): never;
65
+ assert<T>(value: T, status: number, message?: string | HoaError, options?: HoaError): asserts value is NonNullable<T>;
59
66
  onerror(err: unknown): Response;
60
- toJSON(): CtxJSON;
67
+ toJSON(): HoaContextJson;
61
68
  readonly response: Response;
62
69
  }
63
70
 
@@ -67,54 +74,54 @@ export declare class HoaRequest {
67
74
  res: HoaResponse;
68
75
 
69
76
  get url(): URL;
70
- set url(value: string | URL);
77
+ set url(val: string | URL);
71
78
 
72
79
  get href(): string;
73
- set href(value: string);
80
+ set href(val: string);
74
81
 
75
82
  get origin(): string;
76
- set origin(value: string);
83
+ set origin(val: string);
77
84
 
78
85
  get protocol(): string;
79
- set protocol(value: string);
86
+ set protocol(val: string);
80
87
 
81
88
  get host(): string;
82
- set host(value: string);
89
+ set host(val: string);
83
90
 
84
91
  get hostname(): string;
85
- set hostname(value: string);
92
+ set hostname(val: string);
86
93
 
87
94
  get port(): string;
88
- set port(value: string);
95
+ set port(val: string);
89
96
 
90
97
  get pathname(): string;
91
- set pathname(value: string);
98
+ set pathname(val: string);
92
99
 
93
100
  get search(): string;
94
- set search(value: string);
101
+ set search(val: string);
95
102
 
96
103
  get hash(): string;
97
- set hash(value: string);
104
+ set hash(val: string);
98
105
 
99
106
  get method(): string;
100
- set method(value: string);
107
+ set method(val: string);
101
108
 
102
109
  get query(): Record<string, string | string[]>;
103
- set query(value: Record<string, string | string[]>);
110
+ set query(val: Record<string, string | string[]>);
104
111
 
105
112
  get headers(): Record<string, string>;
106
- set headers(value: Headers | Record<string, string> | Iterable<readonly [string, string]>);
113
+ set headers(val: Headers | Record<string, string> | Iterable<readonly [string, string]>);
107
114
 
108
115
  get body(): ReadableStream<Uint8Array> | null;
109
- set body(value: any);
116
+ set body(val: any);
110
117
 
111
118
  get(field: string): string | null;
112
119
  getSetCookie(): string[];
113
120
  has(field: string): boolean;
114
- set(field: string, value: string): void;
115
- set(values: Record<string, string>): void;
116
- append(field: string, value: string): void;
117
- append(values: Record<string, string>): void;
121
+ set(field: string, val: string): void;
122
+ set(field: Record<string, string>): void;
123
+ append(field: string, val: string): void;
124
+ append(field: Record<string, string>): void;
118
125
  delete(field: string): void;
119
126
 
120
127
  get ips(): string[];
@@ -129,10 +136,10 @@ export declare class HoaRequest {
129
136
  text(): Promise<string>;
130
137
  json<T = any>(): Promise<T>;
131
138
  formData(): Promise<FormData>;
132
- toJSON(): ReqJSON;
139
+ toJSON(): HoaRequestJson;
133
140
  }
134
141
 
135
- type ResponseBody =
142
+ type HoaResponseBody =
136
143
  | string
137
144
  | Blob
138
145
  | ArrayBuffer
@@ -151,43 +158,43 @@ export declare class HoaResponse {
151
158
  req: HoaRequest;
152
159
 
153
160
  get headers(): Record<string, string>;
154
- set headers(value: Headers | Record<string, string> | Iterable<readonly [string, string]>);
161
+ set headers(val: Headers | Record<string, string> | Iterable<readonly [string, string]>);
155
162
 
156
163
  get(field: string): string | null;
157
164
  getSetCookie(): string[];
158
165
  has(field: string): boolean;
159
- set(field: string, value: string): void;
160
- set(values: Record<string, string>): void;
161
- append(field: string, value: string): void;
162
- append(values: Record<string, string>): void;
166
+ set(field: string, val: string): void;
167
+ set(field: Record<string, string>): void;
168
+ append(field: string, val: string): void;
169
+ append(field: Record<string, string>): void;
163
170
  delete(field: string): void;
164
171
 
165
172
  get status(): number;
166
- set status(value: number);
173
+ set status(val: number);
167
174
 
168
175
  get statusText(): string;
169
- set statusText(value: string);
176
+ set statusText(val: string);
170
177
 
171
- get body(): ResponseBody;
172
- set body(value: ResponseBody);
178
+ get body(): HoaResponseBody;
179
+ set body(val: HoaResponseBody);
173
180
 
174
181
  redirect(url: string): void;
175
182
  back(alt?: string): void;
176
183
 
177
184
  get type(): string | null;
178
- set type(value: string);
185
+ set type(val: string);
179
186
 
180
187
  get length(): number | null;
181
- set length(value: number | string);
188
+ set length(val: number | string);
182
189
 
183
- toJSON(): ResJSON;
190
+ toJSON(): HoaResponseJson;
184
191
  }
185
192
 
186
193
  export declare class HttpError extends Error {
187
194
  constructor(
188
195
  status: number,
189
- message?: string | { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> },
190
- options?: { message?: string; cause?: unknown; expose?: boolean; headers?: Headers | Record<string, string> | Iterable<readonly [string, string]> }
196
+ message?: string | HoaError,
197
+ options?: HoaError
191
198
  );
192
199
  readonly name: string;
193
200
  readonly status: number;