@wooksjs/event-http 0.5.20 → 0.5.25

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/dist/index.mjs CHANGED
@@ -1,1001 +1,970 @@
1
- import { createAsyncEventContext, useAsyncEventContext, useEventId, attachHook, useEventLogger } from '@wooksjs/event-core';
2
- export { useEventLogger, useRouteParams } from '@wooksjs/event-core';
3
- import { URLSearchParams } from 'url';
4
- import http from 'http';
5
- import { WooksAdapterBase } from 'wooks';
6
- import { Readable } from 'stream';
1
+ import { attachHook, createAsyncEventContext, useAsyncEventContext, useEventId, useEventLogger, useRouteParams } from "@wooksjs/event-core";
2
+ import { Buffer as Buffer$1 } from "buffer";
3
+ import { URLSearchParams } from "url";
4
+ import http from "http";
5
+ import { WooksAdapterBase } from "wooks";
6
+ import { Readable } from "stream";
7
7
 
8
+ //#region packages/event-http/src/event-http.ts
8
9
  function createHttpContext(data, options) {
9
- return createAsyncEventContext({
10
- event: {
11
- ...data,
12
- type: 'HTTP',
13
- },
14
- options,
15
- });
10
+ return createAsyncEventContext({
11
+ event: {
12
+ ...data,
13
+ type: "HTTP"
14
+ },
15
+ options
16
+ });
16
17
  }
17
18
  function useHttpContext() {
18
- return useAsyncEventContext('HTTP');
19
+ return useAsyncEventContext("HTTP");
19
20
  }
20
21
 
22
+ //#endregion
23
+ //#region packages/event-http/src/utils/helpers.ts
21
24
  function escapeRegex(s) {
22
- return s.replace(/[$()*+./?[\\\]^{|}-]/g, '\\$&');
25
+ return s.replace(/[$()*+\-./?[\\\]^{|}]/gu, "\\$&");
23
26
  }
24
27
  function safeDecode(f, v) {
25
- try {
26
- return f(v);
27
- }
28
- catch (error) {
29
- return v;
30
- }
28
+ try {
29
+ return f(v);
30
+ } catch (error) {
31
+ return v;
32
+ }
31
33
  }
32
34
  function safeDecodeURIComponent(uri) {
33
- if (!uri.includes('%')) {
34
- return uri;
35
- }
36
- return safeDecode(decodeURIComponent, uri);
35
+ if (!uri.includes("%")) return uri;
36
+ return safeDecode(decodeURIComponent, uri);
37
37
  }
38
38
 
39
- function convertTime(time, unit = 'ms') {
40
- if (typeof time === 'number') {
41
- return time / units[unit];
42
- }
43
- const rg = /(\d+)(\w+)/g;
44
- let t = 0;
45
- let r;
46
- while ((r = rg.exec(time))) {
47
- t += Number(r[1]) * (units[r[2]] || 0);
48
- }
49
- return t / units[unit];
39
+ //#endregion
40
+ //#region packages/event-http/src/utils/time.ts
41
+ function convertTime(time, unit = "ms") {
42
+ if (typeof time === "number") return time / units[unit];
43
+ const rg = /(\d+)(\w+)/gu;
44
+ let t = 0;
45
+ let r;
46
+ while (r = rg.exec(time)) t += Number(r[1]) * (units[r[2]] || 0);
47
+ return t / units[unit];
50
48
  }
51
49
  const units = {
52
- ms: 1,
53
- s: 1000,
54
- m: 1000 * 60,
55
- h: 1000 * 60 * 60,
56
- d: 1000 * 60 * 60 * 24,
57
- w: 1000 * 60 * 60 * 24 * 7,
58
- M: 1000 * 60 * 60 * 24 * 30,
59
- Y: 1000 * 60 * 60 * 24 * 365,
50
+ ms: 1,
51
+ s: 1e3,
52
+ m: 6e4,
53
+ h: 36e5,
54
+ d: 864e5,
55
+ w: 6048e5,
56
+ M: 2592e6,
57
+ Y: 31536e6
60
58
  };
61
59
 
60
+ //#endregion
61
+ //#region packages/event-http/src/utils/set-cookie.ts
62
62
  function renderCookie(key, data) {
63
- let attrs = '';
64
- for (const [a, v] of Object.entries(data.attrs)) {
65
- const func = cookieAttrFunc[a];
66
- if (typeof func === 'function') {
67
- const val = func(v);
68
- attrs += val ? `; ${val}` : '';
69
- }
70
- else {
71
- throw new TypeError(`Unknown Set-Cookie attribute ${a}`);
72
- }
73
- }
74
- return `${key}=${encodeURIComponent(data.value)}${attrs}`;
63
+ let attrs = "";
64
+ for (const [a, v] of Object.entries(data.attrs)) {
65
+ const func = cookieAttrFunc[a];
66
+ if (typeof func === "function") {
67
+ const val = func(v);
68
+ attrs += val ? `; ${val}` : "";
69
+ } else throw new TypeError(`Unknown Set-Cookie attribute ${a}`);
70
+ }
71
+ return `${key}=${encodeURIComponent(data.value)}${attrs}`;
75
72
  }
76
73
  const cookieAttrFunc = {
77
- expires: (v) => `Expires=${typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString()}`,
78
- maxAge: (v) => `Max-Age=${convertTime(v, 's').toString()}`,
79
- domain: (v) => `Domain=${v}`,
80
- path: (v) => `Path=${v}`,
81
- secure: (v) => (v ? 'Secure' : ''),
82
- httpOnly: (v) => (v ? 'HttpOnly' : ''),
83
- sameSite: (v) => v ? `SameSite=${typeof v === 'string' ? v : 'Strict'}` : '',
74
+ expires: (v) => `Expires=${typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString()}`,
75
+ maxAge: (v) => `Max-Age=${convertTime(v, "s").toString()}`,
76
+ domain: (v) => `Domain=${v}`,
77
+ path: (v) => `Path=${v}`,
78
+ secure: (v) => v ? "Secure" : "",
79
+ httpOnly: (v) => v ? "HttpOnly" : "",
80
+ sameSite: (v) => v ? `SameSite=${typeof v === "string" ? v : "Strict"}` : ""
84
81
  };
85
82
 
86
- const xForwardedFor = 'x-forwarded-for';
83
+ //#endregion
84
+ //#region packages/event-http/src/composables/request.ts
85
+ const xForwardedFor = "x-forwarded-for";
87
86
  function useRequest() {
88
- const { store } = useHttpContext();
89
- const { init } = store('request');
90
- const event = store('event');
91
- const req = event.get('req');
92
- const rawBody = () => init('rawBody', () => new Promise((resolve, reject) => {
93
- let body = Buffer.from('');
94
- req.on('data', chunk => {
95
- body = Buffer.concat([body, chunk]);
96
- });
97
- req.on('error', err => {
98
- reject(err);
99
- });
100
- req.on('end', () => {
101
- resolve(body);
102
- });
103
- }));
104
- const reqId = useEventId().getId;
105
- const forwardedIp = () => init('forwardedIp', () => {
106
- if (typeof req.headers[xForwardedFor] === 'string' && req.headers[xForwardedFor]) {
107
- return req.headers[xForwardedFor].split(',').shift()?.trim();
108
- }
109
- else {
110
- return '';
111
- }
112
- });
113
- const remoteIp = () => init('remoteIp', () => req.socket.remoteAddress || req.connection.remoteAddress || '');
114
- function getIp(options) {
115
- if (options?.trustProxy) {
116
- return forwardedIp() || getIp();
117
- }
118
- else {
119
- return remoteIp();
120
- }
121
- }
122
- const getIpList = () => init('ipList', () => ({
123
- remoteIp: req.socket.remoteAddress || req.connection.remoteAddress || '',
124
- forwarded: (req.headers[xForwardedFor] || '').split(',').map(s => s.trim()),
125
- }));
126
- return {
127
- rawRequest: req,
128
- url: req.url,
129
- method: req.method,
130
- headers: req.headers,
131
- rawBody,
132
- reqId,
133
- getIp,
134
- getIpList,
135
- };
87
+ const { store } = useHttpContext();
88
+ const { init } = store("request");
89
+ const event = store("event");
90
+ const req = event.get("req");
91
+ const rawBody = () => init("rawBody", () => new Promise((resolve, reject) => {
92
+ let body = Buffer$1.from("");
93
+ req.on("data", (chunk) => {
94
+ body = Buffer$1.concat([body, chunk]);
95
+ });
96
+ req.on("error", (err) => {
97
+ reject(err);
98
+ });
99
+ req.on("end", () => {
100
+ resolve(body);
101
+ });
102
+ }));
103
+ const reqId = useEventId().getId;
104
+ const forwardedIp = () => init("forwardedIp", () => {
105
+ if (typeof req.headers[xForwardedFor] === "string" && req.headers[xForwardedFor]) return req.headers[xForwardedFor].split(",").shift()?.trim();
106
+ else return "";
107
+ });
108
+ const remoteIp = () => init("remoteIp", () => req.socket.remoteAddress || req.connection.remoteAddress || "");
109
+ function getIp(options) {
110
+ if (options?.trustProxy) return forwardedIp() || getIp();
111
+ else return remoteIp();
112
+ }
113
+ const getIpList = () => init("ipList", () => ({
114
+ remoteIp: req.socket.remoteAddress || req.connection.remoteAddress || "",
115
+ forwarded: (req.headers[xForwardedFor] || "").split(",").map((s) => s.trim())
116
+ }));
117
+ return {
118
+ rawRequest: req,
119
+ url: req.url,
120
+ method: req.method,
121
+ headers: req.headers,
122
+ rawBody,
123
+ reqId,
124
+ getIp,
125
+ getIpList
126
+ };
136
127
  }
137
128
 
129
+ //#endregion
130
+ //#region packages/event-http/src/composables/headers.ts
138
131
  function useHeaders() {
139
- return useRequest().headers;
132
+ return useRequest().headers;
140
133
  }
141
134
  function useSetHeaders() {
142
- const { store } = useHttpContext();
143
- const setHeaderStore = store('setHeader');
144
- function setHeader(name, value) {
145
- setHeaderStore.set(name, value.toString());
146
- }
147
- function setContentType(value) {
148
- setHeader('content-type', value);
149
- }
150
- function enableCors(origin = '*') {
151
- setHeader('access-control-allow-origin', origin);
152
- }
153
- return {
154
- setHeader,
155
- getHeader: setHeaderStore.get,
156
- removeHeader: setHeaderStore.del,
157
- setContentType,
158
- headers: () => setHeaderStore.value || {},
159
- enableCors,
160
- };
135
+ const { store } = useHttpContext();
136
+ const setHeaderStore = store("setHeader");
137
+ function setHeader(name, value) {
138
+ setHeaderStore.set(name, value.toString());
139
+ }
140
+ function setContentType(value) {
141
+ setHeader("content-type", value);
142
+ }
143
+ function enableCors(origin = "*") {
144
+ setHeader("access-control-allow-origin", origin);
145
+ }
146
+ return {
147
+ setHeader,
148
+ getHeader: setHeaderStore.get,
149
+ removeHeader: setHeaderStore.del,
150
+ setContentType,
151
+ headers: () => setHeaderStore.value || {},
152
+ enableCors
153
+ };
161
154
  }
162
155
  function useSetHeader(name) {
163
- const { store } = useHttpContext();
164
- const { hook } = store('setHeader');
165
- return hook(name);
156
+ const { store } = useHttpContext();
157
+ const { hook } = store("setHeader");
158
+ return hook(name);
166
159
  }
167
160
 
161
+ //#endregion
162
+ //#region packages/event-http/src/composables/cookies.ts
168
163
  function useCookies() {
169
- const { store } = useHttpContext();
170
- const { cookie } = useHeaders();
171
- const { init } = store('cookies');
172
- const getCookie = (name) => init(name, () => {
173
- if (cookie) {
174
- const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, 'i').exec(cookie);
175
- return result?.[1] ? safeDecodeURIComponent(result[1]) : null;
176
- }
177
- else {
178
- return null;
179
- }
180
- });
181
- return {
182
- rawCookies: cookie,
183
- getCookie,
184
- };
164
+ const { store } = useHttpContext();
165
+ const { cookie } = useHeaders();
166
+ const { init } = store("cookies");
167
+ const getCookie = (name) => init(name, () => {
168
+ if (cookie) {
169
+ const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, "i").exec(cookie);
170
+ return result?.[1] ? safeDecodeURIComponent(result[1]) : null;
171
+ } else return null;
172
+ });
173
+ return {
174
+ rawCookies: cookie,
175
+ getCookie
176
+ };
185
177
  }
186
178
  function useSetCookies() {
187
- const { store } = useHttpContext();
188
- const cookiesStore = store('setCookies');
189
- function setCookie(name, value, attrs) {
190
- cookiesStore.set(name, {
191
- value,
192
- attrs: attrs || {},
193
- });
194
- }
195
- function cookies() {
196
- return cookiesStore
197
- .entries()
198
- .filter(a => !!a[1])
199
- .map(([key, value]) => renderCookie(key, value));
200
- }
201
- return {
202
- setCookie,
203
- getCookie: cookiesStore.get,
204
- removeCookie: cookiesStore.del,
205
- clearCookies: cookiesStore.clear,
206
- cookies,
207
- };
179
+ const { store } = useHttpContext();
180
+ const cookiesStore = store("setCookies");
181
+ function setCookie(name, value, attrs) {
182
+ cookiesStore.set(name, {
183
+ value,
184
+ attrs: attrs || {}
185
+ });
186
+ }
187
+ function cookies() {
188
+ return cookiesStore.entries().filter((a) => !!a[1]).map(([key, value]) => renderCookie(key, value));
189
+ }
190
+ return {
191
+ setCookie,
192
+ getCookie: cookiesStore.get,
193
+ removeCookie: cookiesStore.del,
194
+ clearCookies: cookiesStore.clear,
195
+ cookies
196
+ };
208
197
  }
209
198
  function useSetCookie(name) {
210
- const { setCookie, getCookie } = useSetCookies();
211
- const valueHook = attachHook({
212
- name,
213
- type: 'cookie',
214
- }, {
215
- get: () => getCookie(name)?.value,
216
- set: (value) => {
217
- setCookie(name, value, getCookie(name)?.attrs);
218
- },
219
- });
220
- return attachHook(valueHook, {
221
- get: () => getCookie(name)?.attrs,
222
- set: (attrs) => {
223
- setCookie(name, getCookie(name)?.value || '', attrs);
224
- },
225
- }, 'attrs');
199
+ const { setCookie, getCookie } = useSetCookies();
200
+ const valueHook = attachHook({
201
+ name,
202
+ type: "cookie"
203
+ }, {
204
+ get: () => getCookie(name)?.value,
205
+ set: (value) => {
206
+ setCookie(name, value, getCookie(name)?.attrs);
207
+ }
208
+ });
209
+ return attachHook(valueHook, {
210
+ get: () => getCookie(name)?.attrs,
211
+ set: (attrs) => {
212
+ setCookie(name, getCookie(name)?.value || "", attrs);
213
+ }
214
+ }, "attrs");
226
215
  }
227
216
 
217
+ //#endregion
218
+ //#region packages/event-http/src/composables/header-accept.ts
228
219
  function useAccept() {
229
- const { store } = useHttpContext();
230
- const { accept } = useHeaders();
231
- const accepts = (mime) => {
232
- const { set, get, has } = store('accept');
233
- if (!has(mime)) {
234
- return set(mime, !!(accept && (accept === '*/*' || accept.includes(mime))));
235
- }
236
- return get(mime);
237
- };
238
- return {
239
- accept,
240
- accepts,
241
- acceptsJson: () => accepts('application/json'),
242
- acceptsXml: () => accepts('application/xml'),
243
- acceptsText: () => accepts('text/plain'),
244
- acceptsHtml: () => accepts('text/html'),
245
- };
220
+ const { store } = useHttpContext();
221
+ const { accept } = useHeaders();
222
+ const accepts = (mime) => {
223
+ const { set, get, has } = store("accept");
224
+ if (!has(mime)) return set(mime, !!(accept && (accept === "*/*" || accept.includes(mime))));
225
+ return get(mime);
226
+ };
227
+ return {
228
+ accept,
229
+ accepts,
230
+ acceptsJson: () => accepts("application/json"),
231
+ acceptsXml: () => accepts("application/xml"),
232
+ acceptsText: () => accepts("text/plain"),
233
+ acceptsHtml: () => accepts("text/html")
234
+ };
246
235
  }
247
236
 
237
+ //#endregion
238
+ //#region packages/event-http/src/composables/header-authorization.ts
248
239
  function useAuthorization() {
249
- const { store } = useHttpContext();
250
- const { authorization } = useHeaders();
251
- const { init } = store('authorization');
252
- const authType = () => init('type', () => {
253
- if (authorization) {
254
- const space = authorization.indexOf(' ');
255
- return authorization.slice(0, space);
256
- }
257
- return null;
258
- });
259
- const authRawCredentials = () => init('credentials', () => {
260
- if (authorization) {
261
- const space = authorization.indexOf(' ');
262
- return authorization.slice(space + 1);
263
- }
264
- return null;
265
- });
266
- return {
267
- authorization,
268
- authType,
269
- authRawCredentials,
270
- isBasic: () => authType()?.toLocaleLowerCase() === 'basic',
271
- isBearer: () => authType()?.toLocaleLowerCase() === 'bearer',
272
- basicCredentials: () => init('basicCredentials', () => {
273
- if (authorization) {
274
- const type = authType();
275
- if (type?.toLocaleLowerCase() === 'basic') {
276
- const creds = Buffer.from(authRawCredentials() || '', 'base64').toString('ascii');
277
- const [username, password] = creds.split(':');
278
- return { username, password };
279
- }
280
- }
281
- return null;
282
- }),
283
- };
240
+ const { store } = useHttpContext();
241
+ const { authorization } = useHeaders();
242
+ const { init } = store("authorization");
243
+ const authType = () => init("type", () => {
244
+ if (authorization) {
245
+ const space = authorization.indexOf(" ");
246
+ return authorization.slice(0, space);
247
+ }
248
+ return null;
249
+ });
250
+ const authRawCredentials = () => init("credentials", () => {
251
+ if (authorization) {
252
+ const space = authorization.indexOf(" ");
253
+ return authorization.slice(space + 1);
254
+ }
255
+ return null;
256
+ });
257
+ return {
258
+ authorization,
259
+ authType,
260
+ authRawCredentials,
261
+ isBasic: () => authType()?.toLocaleLowerCase() === "basic",
262
+ isBearer: () => authType()?.toLocaleLowerCase() === "bearer",
263
+ basicCredentials: () => init("basicCredentials", () => {
264
+ if (authorization) {
265
+ const type = authType();
266
+ if (type?.toLocaleLowerCase() === "basic") {
267
+ const creds = Buffer$1.from(authRawCredentials() || "", "base64").toString("ascii");
268
+ const [username, password] = creds.split(":");
269
+ return {
270
+ username,
271
+ password
272
+ };
273
+ }
274
+ }
275
+ return null;
276
+ })
277
+ };
284
278
  }
285
279
 
280
+ //#endregion
281
+ //#region packages/event-http/src/utils/cache-control.ts
286
282
  function renderCacheControl(data) {
287
- let attrs = '';
288
- for (const [a, v] of Object.entries(data)) {
289
- if (v === undefined) {
290
- continue;
291
- }
292
- const func = cacheControlFunc[a];
293
- if (typeof func === 'function') {
294
- const val = func(v);
295
- if (val) {
296
- attrs += attrs ? `, ${val}` : val;
297
- }
298
- }
299
- else {
300
- throw new TypeError(`Unknown Cache-Control attribute ${a}`);
301
- }
302
- }
303
- return attrs;
283
+ let attrs = "";
284
+ for (const [a, v] of Object.entries(data)) {
285
+ if (v === undefined) continue;
286
+ const func = cacheControlFunc[a];
287
+ if (typeof func === "function") {
288
+ const val = func(v);
289
+ if (val) attrs += attrs ? `, ${val}` : val;
290
+ } else throw new TypeError(`Unknown Cache-Control attribute ${a}`);
291
+ }
292
+ return attrs;
304
293
  }
305
294
  const cacheControlFunc = {
306
- mustRevalidate: (v) => (v ? 'must-revalidate' : ''),
307
- noCache: (v) => v ? (typeof v === 'string' ? `no-cache="${v}"` : 'no-cache') : '',
308
- noStore: (v) => (v ? 'no-store' : ''),
309
- noTransform: (v) => (v ? 'no-transform' : ''),
310
- public: (v) => (v ? 'public' : ''),
311
- private: (v) => v ? (typeof v === 'string' ? `private="${v}"` : 'private') : '',
312
- proxyRevalidate: (v) => (v ? 'proxy-revalidate' : ''),
313
- maxAge: (v) => `max-age=${convertTime(v, 's').toString()}`,
314
- sMaxage: (v) => `s-maxage=${convertTime(v, 's').toString()}`,
295
+ mustRevalidate: (v) => v ? "must-revalidate" : "",
296
+ noCache: (v) => v ? typeof v === "string" ? `no-cache="${v}"` : "no-cache" : "",
297
+ noStore: (v) => v ? "no-store" : "",
298
+ noTransform: (v) => v ? "no-transform" : "",
299
+ public: (v) => v ? "public" : "",
300
+ private: (v) => v ? typeof v === "string" ? `private="${v}"` : "private" : "",
301
+ proxyRevalidate: (v) => v ? "proxy-revalidate" : "",
302
+ maxAge: (v) => `max-age=${convertTime(v, "s").toString()}`,
303
+ sMaxage: (v) => `s-maxage=${convertTime(v, "s").toString()}`
315
304
  };
316
305
 
317
- const renderAge = (v) => convertTime(v, 's').toString();
318
- const renderExpires = (v) => typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString();
319
- const renderPragmaNoCache = (v) => (v ? 'no-cache' : '');
306
+ //#endregion
307
+ //#region packages/event-http/src/composables/header-set-cache-control.ts
308
+ const renderAge = (v) => convertTime(v, "s").toString();
309
+ const renderExpires = (v) => typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString();
310
+ const renderPragmaNoCache = (v) => v ? "no-cache" : "";
320
311
  function useSetCacheControl() {
321
- const { setHeader } = useSetHeaders();
322
- const setAge = (value) => {
323
- setHeader('age', renderAge(value));
324
- };
325
- const setExpires = (value) => {
326
- setHeader('expires', renderExpires(value));
327
- };
328
- const setPragmaNoCache = (value = true) => {
329
- setHeader('pragma', renderPragmaNoCache(value));
330
- };
331
- const setCacheControl = (data) => {
332
- setHeader('cache-control', renderCacheControl(data));
333
- };
334
- return {
335
- setExpires,
336
- setAge,
337
- setPragmaNoCache,
338
- setCacheControl,
339
- };
312
+ const { setHeader } = useSetHeaders();
313
+ const setAge = (value) => {
314
+ setHeader("age", renderAge(value));
315
+ };
316
+ const setExpires = (value) => {
317
+ setHeader("expires", renderExpires(value));
318
+ };
319
+ const setPragmaNoCache = (value = true) => {
320
+ setHeader("pragma", renderPragmaNoCache(value));
321
+ };
322
+ const setCacheControl = (data) => {
323
+ setHeader("cache-control", renderCacheControl(data));
324
+ };
325
+ return {
326
+ setExpires,
327
+ setAge,
328
+ setPragmaNoCache,
329
+ setCacheControl
330
+ };
340
331
  }
341
332
 
333
+ //#endregion
334
+ //#region packages/event-http/src/composables/response.ts
342
335
  function useResponse() {
343
- const { store } = useHttpContext();
344
- const event = store('event');
345
- const res = event.get('res');
346
- const responded = store('response').hook('responded');
347
- const statusCode = store('status').hook('code');
348
- function status(code) {
349
- return (statusCode.value = code ? code : statusCode.value);
350
- }
351
- const rawResponse = (options) => {
352
- if (!options || !options.passthrough) {
353
- responded.value = true;
354
- }
355
- return res;
356
- };
357
- return {
358
- rawResponse,
359
- hasResponded: () => responded.value || !res.writable || res.writableEnded,
360
- status: attachHook(status, {
361
- get: () => statusCode.value,
362
- set: (code) => (statusCode.value = code),
363
- }),
364
- };
336
+ const { store } = useHttpContext();
337
+ const event = store("event");
338
+ const res = event.get("res");
339
+ const responded = store("response").hook("responded");
340
+ const statusCode = store("status").hook("code");
341
+ function status(code) {
342
+ return statusCode.value = code ? code : statusCode.value;
343
+ }
344
+ const rawResponse = (options) => {
345
+ if (!options || !options.passthrough) responded.value = true;
346
+ return res;
347
+ };
348
+ return {
349
+ rawResponse,
350
+ hasResponded: () => responded.value || !res.writable || res.writableEnded,
351
+ status: attachHook(status, {
352
+ get: () => statusCode.value,
353
+ set: (code) => statusCode.value = code
354
+ })
355
+ };
365
356
  }
366
357
  function useStatus() {
367
- const { store } = useHttpContext();
368
- return store('status').hook('code');
358
+ const { store } = useHttpContext();
359
+ return store("status").hook("code");
369
360
  }
370
361
 
371
- class WooksURLSearchParams extends URLSearchParams {
372
- toJson() {
373
- const json = {};
374
- for (const [key, value] of this.entries()) {
375
- if (isArrayParam(key)) {
376
- const a = (json[key] = (json[key] || []));
377
- a.push(value);
378
- }
379
- else {
380
- json[key] = value;
381
- }
382
- }
383
- return json;
384
- }
385
- }
362
+ //#endregion
363
+ //#region packages/event-http/src/utils/url-search-params.ts
364
+ var WooksURLSearchParams = class extends URLSearchParams {
365
+ toJson() {
366
+ const json = {};
367
+ for (const [key, value] of this.entries()) if (isArrayParam(key)) {
368
+ const a = json[key] = json[key] || [];
369
+ a.push(value);
370
+ } else json[key] = value;
371
+ return json;
372
+ }
373
+ };
386
374
  function isArrayParam(name) {
387
- return name.endsWith('[]');
375
+ return name.endsWith("[]");
388
376
  }
389
377
 
378
+ //#endregion
379
+ //#region packages/event-http/src/composables/search-params.ts
390
380
  function useSearchParams() {
391
- const { store } = useHttpContext();
392
- const url = useRequest().url || '';
393
- const { init } = store('searchParams');
394
- const rawSearchParams = () => init('raw', () => {
395
- const i = url.indexOf('?');
396
- return i >= 0 ? url.slice(i) : '';
397
- });
398
- const urlSearchParams = () => init('urlSearchParams', () => new WooksURLSearchParams(rawSearchParams()));
399
- return {
400
- rawSearchParams,
401
- urlSearchParams,
402
- jsonSearchParams: () => urlSearchParams().toJson(),
403
- };
381
+ const { store } = useHttpContext();
382
+ const url = useRequest().url || "";
383
+ const { init } = store("searchParams");
384
+ const rawSearchParams = () => init("raw", () => {
385
+ const i = url.indexOf("?");
386
+ return i >= 0 ? url.slice(i) : "";
387
+ });
388
+ const urlSearchParams = () => init("urlSearchParams", () => new WooksURLSearchParams(rawSearchParams()));
389
+ return {
390
+ rawSearchParams,
391
+ urlSearchParams,
392
+ jsonSearchParams: () => urlSearchParams().toJson()
393
+ };
404
394
  }
405
395
 
406
- class BaseHttpResponseRenderer {
407
- render(response) {
408
- if (typeof response.body === 'string' ||
409
- typeof response.body === 'boolean' ||
410
- typeof response.body === 'number') {
411
- if (!response.getContentType()) {
412
- response.setContentType('text/plain');
413
- }
414
- return response.body.toString();
415
- }
416
- if (response.body === undefined) {
417
- return '';
418
- }
419
- if (response.body instanceof Uint8Array) {
420
- return response.body;
421
- }
422
- if (typeof response.body === 'object') {
423
- if (!response.getContentType()) {
424
- response.setContentType('application/json');
425
- }
426
- return JSON.stringify(response.body);
427
- }
428
- throw new Error(`Unsupported body format "${typeof response.body}"`);
429
- }
430
- }
396
+ //#endregion
397
+ //#region packages/event-http/src/response/renderer.ts
398
+ var BaseHttpResponseRenderer = class {
399
+ render(response) {
400
+ if (typeof response.body === "string" || typeof response.body === "boolean" || typeof response.body === "number") {
401
+ if (!response.getContentType()) response.setContentType("text/plain");
402
+ return response.body.toString();
403
+ }
404
+ if (response.body === undefined) return "";
405
+ if (response.body instanceof Uint8Array) return response.body;
406
+ if (typeof response.body === "object") {
407
+ if (!response.getContentType()) response.setContentType("application/json");
408
+ return JSON.stringify(response.body);
409
+ }
410
+ throw new Error(`Unsupported body format "${typeof response.body}"`);
411
+ }
412
+ };
431
413
 
414
+ //#endregion
415
+ //#region packages/event-http/src/utils/status-codes.ts
432
416
  const httpStatusCodes = {
433
- 100: 'Continue',
434
- 101: 'Switching protocols',
435
- 102: 'Processing',
436
- 103: 'Early Hints',
437
- 200: 'OK',
438
- 201: 'Created',
439
- 202: 'Accepted',
440
- 203: 'Non-Authoritative Information',
441
- 204: 'No Content',
442
- 205: 'Reset Content',
443
- 206: 'Partial Content',
444
- 207: 'Multi-Status',
445
- 208: 'Already Reported',
446
- 226: 'IM Used',
447
- 300: 'Multiple Choices',
448
- 301: 'Moved Permanently',
449
- 302: 'Found (Previously "Moved Temporarily")',
450
- 303: 'See Other',
451
- 304: 'Not Modified',
452
- 305: 'Use Proxy',
453
- 306: 'Switch Proxy',
454
- 307: 'Temporary Redirect',
455
- 308: 'Permanent Redirect',
456
- 400: 'Bad Request',
457
- 401: 'Unauthorized',
458
- 402: 'Payment Required',
459
- 403: 'Forbidden',
460
- 404: 'Not Found',
461
- 405: 'Method Not Allowed',
462
- 406: 'Not Acceptable',
463
- 407: 'Proxy Authentication Required',
464
- 408: 'Request Timeout',
465
- 409: 'Conflict',
466
- 410: 'Gone',
467
- 411: 'Length Required',
468
- 412: 'Precondition Failed',
469
- 413: 'Payload Too Large',
470
- 414: 'URI Too Long',
471
- 415: 'Unsupported Media Type',
472
- 416: 'Range Not Satisfiable',
473
- 417: 'Expectation Failed',
474
- 418: "I'm a Teapot",
475
- 421: 'Misdirected Request',
476
- 422: 'Unprocessable Entity',
477
- 423: 'Locked',
478
- 424: 'Failed Dependency',
479
- 425: 'Too Early',
480
- 426: 'Upgrade Required',
481
- 428: 'Precondition Required',
482
- 429: 'Too Many Requests',
483
- 431: 'Request Header Fields Too Large',
484
- 451: 'Unavailable For Legal Reasons',
485
- 500: 'Internal Server Error',
486
- 501: 'Not Implemented',
487
- 502: 'Bad Gateway',
488
- 503: 'Service Unavailable',
489
- 504: 'Gateway Timeout',
490
- 505: 'HTTP Version Not Supported',
491
- 506: 'Variant Also Negotiates',
492
- 507: 'Insufficient Storage',
493
- 508: 'Loop Detected',
494
- 510: 'Not Extended',
495
- 511: 'Network Authentication Required',
417
+ 100: "Continue",
418
+ 101: "Switching protocols",
419
+ 102: "Processing",
420
+ 103: "Early Hints",
421
+ 200: "OK",
422
+ 201: "Created",
423
+ 202: "Accepted",
424
+ 203: "Non-Authoritative Information",
425
+ 204: "No Content",
426
+ 205: "Reset Content",
427
+ 206: "Partial Content",
428
+ 207: "Multi-Status",
429
+ 208: "Already Reported",
430
+ 226: "IM Used",
431
+ 300: "Multiple Choices",
432
+ 301: "Moved Permanently",
433
+ 302: "Found (Previously \"Moved Temporarily\")",
434
+ 303: "See Other",
435
+ 304: "Not Modified",
436
+ 305: "Use Proxy",
437
+ 306: "Switch Proxy",
438
+ 307: "Temporary Redirect",
439
+ 308: "Permanent Redirect",
440
+ 400: "Bad Request",
441
+ 401: "Unauthorized",
442
+ 402: "Payment Required",
443
+ 403: "Forbidden",
444
+ 404: "Not Found",
445
+ 405: "Method Not Allowed",
446
+ 406: "Not Acceptable",
447
+ 407: "Proxy Authentication Required",
448
+ 408: "Request Timeout",
449
+ 409: "Conflict",
450
+ 410: "Gone",
451
+ 411: "Length Required",
452
+ 412: "Precondition Failed",
453
+ 413: "Payload Too Large",
454
+ 414: "URI Too Long",
455
+ 415: "Unsupported Media Type",
456
+ 416: "Range Not Satisfiable",
457
+ 417: "Expectation Failed",
458
+ 418: "I'm a Teapot",
459
+ 421: "Misdirected Request",
460
+ 422: "Unprocessable Entity",
461
+ 423: "Locked",
462
+ 424: "Failed Dependency",
463
+ 425: "Too Early",
464
+ 426: "Upgrade Required",
465
+ 428: "Precondition Required",
466
+ 429: "Too Many Requests",
467
+ 431: "Request Header Fields Too Large",
468
+ 451: "Unavailable For Legal Reasons",
469
+ 500: "Internal Server Error",
470
+ 501: "Not Implemented",
471
+ 502: "Bad Gateway",
472
+ 503: "Service Unavailable",
473
+ 504: "Gateway Timeout",
474
+ 505: "HTTP Version Not Supported",
475
+ 506: "Variant Also Negotiates",
476
+ 507: "Insufficient Storage",
477
+ 508: "Loop Detected",
478
+ 510: "Not Extended",
479
+ 511: "Network Authentication Required"
496
480
  };
497
- var EHttpStatusCode;
498
- (function (EHttpStatusCode) {
499
- EHttpStatusCode[EHttpStatusCode["Continue"] = 100] = "Continue";
500
- EHttpStatusCode[EHttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
501
- EHttpStatusCode[EHttpStatusCode["Processing"] = 102] = "Processing";
502
- EHttpStatusCode[EHttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
503
- EHttpStatusCode[EHttpStatusCode["OK"] = 200] = "OK";
504
- EHttpStatusCode[EHttpStatusCode["Created"] = 201] = "Created";
505
- EHttpStatusCode[EHttpStatusCode["Accepted"] = 202] = "Accepted";
506
- EHttpStatusCode[EHttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
507
- EHttpStatusCode[EHttpStatusCode["NoContent"] = 204] = "NoContent";
508
- EHttpStatusCode[EHttpStatusCode["ResetContent"] = 205] = "ResetContent";
509
- EHttpStatusCode[EHttpStatusCode["PartialContent"] = 206] = "PartialContent";
510
- EHttpStatusCode[EHttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
511
- EHttpStatusCode[EHttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
512
- EHttpStatusCode[EHttpStatusCode["IMUsed"] = 226] = "IMUsed";
513
- EHttpStatusCode[EHttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
514
- EHttpStatusCode[EHttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
515
- EHttpStatusCode[EHttpStatusCode["Found"] = 302] = "Found";
516
- EHttpStatusCode[EHttpStatusCode["SeeOther"] = 303] = "SeeOther";
517
- EHttpStatusCode[EHttpStatusCode["NotModified"] = 304] = "NotModified";
518
- EHttpStatusCode[EHttpStatusCode["UseProxy"] = 305] = "UseProxy";
519
- EHttpStatusCode[EHttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy";
520
- EHttpStatusCode[EHttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
521
- EHttpStatusCode[EHttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
522
- EHttpStatusCode[EHttpStatusCode["BadRequest"] = 400] = "BadRequest";
523
- EHttpStatusCode[EHttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
524
- EHttpStatusCode[EHttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
525
- EHttpStatusCode[EHttpStatusCode["Forbidden"] = 403] = "Forbidden";
526
- EHttpStatusCode[EHttpStatusCode["NotFound"] = 404] = "NotFound";
527
- EHttpStatusCode[EHttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
528
- EHttpStatusCode[EHttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
529
- EHttpStatusCode[EHttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
530
- EHttpStatusCode[EHttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
531
- EHttpStatusCode[EHttpStatusCode["Conflict"] = 409] = "Conflict";
532
- EHttpStatusCode[EHttpStatusCode["Gone"] = 410] = "Gone";
533
- EHttpStatusCode[EHttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
534
- EHttpStatusCode[EHttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
535
- EHttpStatusCode[EHttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
536
- EHttpStatusCode[EHttpStatusCode["URITooLong"] = 414] = "URITooLong";
537
- EHttpStatusCode[EHttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
538
- EHttpStatusCode[EHttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
539
- EHttpStatusCode[EHttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
540
- EHttpStatusCode[EHttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
541
- EHttpStatusCode[EHttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
542
- EHttpStatusCode[EHttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
543
- EHttpStatusCode[EHttpStatusCode["Locked"] = 423] = "Locked";
544
- EHttpStatusCode[EHttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
545
- EHttpStatusCode[EHttpStatusCode["TooEarly"] = 425] = "TooEarly";
546
- EHttpStatusCode[EHttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
547
- EHttpStatusCode[EHttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
548
- EHttpStatusCode[EHttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
549
- EHttpStatusCode[EHttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
550
- EHttpStatusCode[EHttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
551
- EHttpStatusCode[EHttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
552
- EHttpStatusCode[EHttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
553
- EHttpStatusCode[EHttpStatusCode["BadGateway"] = 502] = "BadGateway";
554
- EHttpStatusCode[EHttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
555
- EHttpStatusCode[EHttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
556
- EHttpStatusCode[EHttpStatusCode["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
557
- EHttpStatusCode[EHttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
558
- EHttpStatusCode[EHttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
559
- EHttpStatusCode[EHttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
560
- EHttpStatusCode[EHttpStatusCode["NotExtended"] = 510] = "NotExtended";
561
- EHttpStatusCode[EHttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
562
- })(EHttpStatusCode || (EHttpStatusCode = {}));
481
+ let EHttpStatusCode = function(EHttpStatusCode$1) {
482
+ EHttpStatusCode$1[EHttpStatusCode$1["Continue"] = 100] = "Continue";
483
+ EHttpStatusCode$1[EHttpStatusCode$1["SwitchingProtocols"] = 101] = "SwitchingProtocols";
484
+ EHttpStatusCode$1[EHttpStatusCode$1["Processing"] = 102] = "Processing";
485
+ EHttpStatusCode$1[EHttpStatusCode$1["EarlyHints"] = 103] = "EarlyHints";
486
+ EHttpStatusCode$1[EHttpStatusCode$1["OK"] = 200] = "OK";
487
+ EHttpStatusCode$1[EHttpStatusCode$1["Created"] = 201] = "Created";
488
+ EHttpStatusCode$1[EHttpStatusCode$1["Accepted"] = 202] = "Accepted";
489
+ EHttpStatusCode$1[EHttpStatusCode$1["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
490
+ EHttpStatusCode$1[EHttpStatusCode$1["NoContent"] = 204] = "NoContent";
491
+ EHttpStatusCode$1[EHttpStatusCode$1["ResetContent"] = 205] = "ResetContent";
492
+ EHttpStatusCode$1[EHttpStatusCode$1["PartialContent"] = 206] = "PartialContent";
493
+ EHttpStatusCode$1[EHttpStatusCode$1["MultiStatus"] = 207] = "MultiStatus";
494
+ EHttpStatusCode$1[EHttpStatusCode$1["AlreadyReported"] = 208] = "AlreadyReported";
495
+ EHttpStatusCode$1[EHttpStatusCode$1["IMUsed"] = 226] = "IMUsed";
496
+ EHttpStatusCode$1[EHttpStatusCode$1["MultipleChoices"] = 300] = "MultipleChoices";
497
+ EHttpStatusCode$1[EHttpStatusCode$1["MovedPermanently"] = 301] = "MovedPermanently";
498
+ EHttpStatusCode$1[EHttpStatusCode$1["Found"] = 302] = "Found";
499
+ EHttpStatusCode$1[EHttpStatusCode$1["SeeOther"] = 303] = "SeeOther";
500
+ EHttpStatusCode$1[EHttpStatusCode$1["NotModified"] = 304] = "NotModified";
501
+ EHttpStatusCode$1[EHttpStatusCode$1["UseProxy"] = 305] = "UseProxy";
502
+ EHttpStatusCode$1[EHttpStatusCode$1["SwitchProxy"] = 306] = "SwitchProxy";
503
+ EHttpStatusCode$1[EHttpStatusCode$1["TemporaryRedirect"] = 307] = "TemporaryRedirect";
504
+ EHttpStatusCode$1[EHttpStatusCode$1["PermanentRedirect"] = 308] = "PermanentRedirect";
505
+ EHttpStatusCode$1[EHttpStatusCode$1["BadRequest"] = 400] = "BadRequest";
506
+ EHttpStatusCode$1[EHttpStatusCode$1["Unauthorized"] = 401] = "Unauthorized";
507
+ EHttpStatusCode$1[EHttpStatusCode$1["PaymentRequired"] = 402] = "PaymentRequired";
508
+ EHttpStatusCode$1[EHttpStatusCode$1["Forbidden"] = 403] = "Forbidden";
509
+ EHttpStatusCode$1[EHttpStatusCode$1["NotFound"] = 404] = "NotFound";
510
+ EHttpStatusCode$1[EHttpStatusCode$1["MethodNotAllowed"] = 405] = "MethodNotAllowed";
511
+ EHttpStatusCode$1[EHttpStatusCode$1["NotAcceptable"] = 406] = "NotAcceptable";
512
+ EHttpStatusCode$1[EHttpStatusCode$1["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
513
+ EHttpStatusCode$1[EHttpStatusCode$1["RequestTimeout"] = 408] = "RequestTimeout";
514
+ EHttpStatusCode$1[EHttpStatusCode$1["Conflict"] = 409] = "Conflict";
515
+ EHttpStatusCode$1[EHttpStatusCode$1["Gone"] = 410] = "Gone";
516
+ EHttpStatusCode$1[EHttpStatusCode$1["LengthRequired"] = 411] = "LengthRequired";
517
+ EHttpStatusCode$1[EHttpStatusCode$1["PreconditionFailed"] = 412] = "PreconditionFailed";
518
+ EHttpStatusCode$1[EHttpStatusCode$1["PayloadTooLarge"] = 413] = "PayloadTooLarge";
519
+ EHttpStatusCode$1[EHttpStatusCode$1["URITooLong"] = 414] = "URITooLong";
520
+ EHttpStatusCode$1[EHttpStatusCode$1["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
521
+ EHttpStatusCode$1[EHttpStatusCode$1["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
522
+ EHttpStatusCode$1[EHttpStatusCode$1["ExpectationFailed"] = 417] = "ExpectationFailed";
523
+ EHttpStatusCode$1[EHttpStatusCode$1["ImATeapot"] = 418] = "ImATeapot";
524
+ EHttpStatusCode$1[EHttpStatusCode$1["MisdirectedRequest"] = 421] = "MisdirectedRequest";
525
+ EHttpStatusCode$1[EHttpStatusCode$1["UnprocessableEntity"] = 422] = "UnprocessableEntity";
526
+ EHttpStatusCode$1[EHttpStatusCode$1["Locked"] = 423] = "Locked";
527
+ EHttpStatusCode$1[EHttpStatusCode$1["FailedDependency"] = 424] = "FailedDependency";
528
+ EHttpStatusCode$1[EHttpStatusCode$1["TooEarly"] = 425] = "TooEarly";
529
+ EHttpStatusCode$1[EHttpStatusCode$1["UpgradeRequired"] = 426] = "UpgradeRequired";
530
+ EHttpStatusCode$1[EHttpStatusCode$1["PreconditionRequired"] = 428] = "PreconditionRequired";
531
+ EHttpStatusCode$1[EHttpStatusCode$1["TooManyRequests"] = 429] = "TooManyRequests";
532
+ EHttpStatusCode$1[EHttpStatusCode$1["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
533
+ EHttpStatusCode$1[EHttpStatusCode$1["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
534
+ EHttpStatusCode$1[EHttpStatusCode$1["InternalServerError"] = 500] = "InternalServerError";
535
+ EHttpStatusCode$1[EHttpStatusCode$1["NotImplemented"] = 501] = "NotImplemented";
536
+ EHttpStatusCode$1[EHttpStatusCode$1["BadGateway"] = 502] = "BadGateway";
537
+ EHttpStatusCode$1[EHttpStatusCode$1["ServiceUnavailable"] = 503] = "ServiceUnavailable";
538
+ EHttpStatusCode$1[EHttpStatusCode$1["GatewayTimeout"] = 504] = "GatewayTimeout";
539
+ EHttpStatusCode$1[EHttpStatusCode$1["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
540
+ EHttpStatusCode$1[EHttpStatusCode$1["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
541
+ EHttpStatusCode$1[EHttpStatusCode$1["InsufficientStorage"] = 507] = "InsufficientStorage";
542
+ EHttpStatusCode$1[EHttpStatusCode$1["LoopDetected"] = 508] = "LoopDetected";
543
+ EHttpStatusCode$1[EHttpStatusCode$1["NotExtended"] = 510] = "NotExtended";
544
+ EHttpStatusCode$1[EHttpStatusCode$1["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
545
+ return EHttpStatusCode$1;
546
+ }({});
563
547
 
564
- const preStyles = 'font-family: monospace;' +
565
- 'width: 100%;' +
566
- 'max-width: 900px;' +
567
- 'padding: 10px;' +
568
- 'margin: 20px auto;' +
569
- 'border-radius: 8px;' +
570
- 'background-color: #494949;' +
571
- 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
572
- class HttpErrorRenderer extends BaseHttpResponseRenderer {
573
- renderHtml(response) {
574
- const data = response.body || {};
575
- response.setContentType('text/html');
576
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
577
- return ('<html style="background-color: #333; color: #bbb;">' +
578
- `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
579
- `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
580
- `<center><h4>${data.message}</h1></center><hr color="#666">` +
581
- `<center style="color: #666;"> Wooks v${"0.5.20"} </center>` +
582
- `${keys.length > 0
583
- ? `<pre style="${preStyles}">${JSON.stringify({
584
- ...data,
585
- statusCode: undefined,
586
- message: undefined,
587
- error: undefined,
588
- }, null, ' ')}</pre>`
589
- : ''}` +
590
- '</body></html>');
591
- }
592
- renderText(response) {
593
- const data = response.body || {};
594
- response.setContentType('text/plain');
595
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
596
- return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
597
- `\n\n${keys.length > 0
598
- ? `${JSON.stringify({
599
- ...data,
600
- statusCode: undefined,
601
- message: undefined,
602
- error: undefined,
603
- }, null, ' ')}`
604
- : ''}`);
605
- }
606
- renderJson(response) {
607
- const data = response.body || {};
608
- response.setContentType('application/json');
609
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
610
- return (`{"statusCode":${escapeQuotes(data.statusCode)},` +
611
- `"error":"${escapeQuotes(data.error)}",` +
612
- `"message":"${escapeQuotes(data.message)}"` +
613
- `${keys.length > 0
614
- ? `,${keys.map(k => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(',')}`
615
- : ''}}`);
616
- }
617
- render(response) {
618
- const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
619
- response.status = response.body?.statusCode || 500;
620
- if (acceptsJson()) {
621
- return this.renderJson(response);
622
- }
623
- else if (acceptsHtml()) {
624
- return this.renderHtml(response);
625
- }
626
- else if (acceptsText()) {
627
- return this.renderText(response);
628
- }
629
- else {
630
- return this.renderJson(response);
631
- }
632
- }
633
- }
548
+ //#endregion
549
+ //#region packages/event-http/src/errors/error-renderer.ts
550
+ const preStyles = "font-family: monospace;width: 100%;max-width: 900px;padding: 10px;margin: 20px auto;border-radius: 8px;background-color: #494949;box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);";
551
+ var HttpErrorRenderer = class extends BaseHttpResponseRenderer {
552
+ renderHtml(response) {
553
+ const data = response.body || {};
554
+ response.setContentType("text/html");
555
+ const keys = Object.keys(data).filter((key) => ![
556
+ "statusCode",
557
+ "error",
558
+ "message"
559
+ ].includes(key));
560
+ return "<html style=\"background-color: #333; color: #bbb;\">" + `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` + `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` + `<center><h4>${data.message}</h1></center><hr color="#666">` + `<center style="color: #666;"> Wooks v${"0.5.24"} </center>` + `${keys.length > 0 ? `<pre style="${preStyles}">${JSON.stringify({
561
+ ...data,
562
+ statusCode: undefined,
563
+ message: undefined,
564
+ error: undefined
565
+ }, null, " ")}</pre>` : ""}` + "</body></html>";
566
+ }
567
+ renderText(response) {
568
+ const data = response.body || {};
569
+ response.setContentType("text/plain");
570
+ const keys = Object.keys(data).filter((key) => ![
571
+ "statusCode",
572
+ "error",
573
+ "message"
574
+ ].includes(key));
575
+ return `${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` + `\n\n${keys.length > 0 ? `${JSON.stringify({
576
+ ...data,
577
+ statusCode: undefined,
578
+ message: undefined,
579
+ error: undefined
580
+ }, null, " ")}` : ""}`;
581
+ }
582
+ renderJson(response) {
583
+ const data = response.body || {};
584
+ response.setContentType("application/json");
585
+ const keys = Object.keys(data).filter((key) => ![
586
+ "statusCode",
587
+ "error",
588
+ "message"
589
+ ].includes(key));
590
+ return `{"statusCode":${escapeQuotes(data.statusCode)},` + `"error":"${escapeQuotes(data.error)}",` + `"message":"${escapeQuotes(data.message)}"` + `${keys.length > 0 ? `,${keys.map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(",")}` : ""}}`;
591
+ }
592
+ render(response) {
593
+ const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
594
+ response.status = response.body?.statusCode || 500;
595
+ if (acceptsJson()) return this.renderJson(response);
596
+ else if (acceptsHtml()) return this.renderHtml(response);
597
+ else if (acceptsText()) return this.renderText(response);
598
+ else return this.renderJson(response);
599
+ }
600
+ };
634
601
  function escapeQuotes(s) {
635
- return (typeof s === 'number' ? s : s || '').toString().replace(/"/g, '\\"');
602
+ return (typeof s === "number" ? s : s || "").toString().replace(/"/gu, "\\\"");
636
603
  }
637
604
 
638
- class HttpError extends Error {
639
- constructor(code = 500, _body = '') {
640
- super(typeof _body === 'string' ? _body : _body.message);
641
- this.code = code;
642
- this._body = _body;
643
- this.name = 'HttpError';
644
- }
645
- get body() {
646
- return typeof this._body === 'string'
647
- ? {
648
- statusCode: this.code,
649
- message: this.message,
650
- error: httpStatusCodes[this.code],
651
- }
652
- : {
653
- ...this._body,
654
- statusCode: this.code,
655
- message: this.message,
656
- error: httpStatusCodes[this.code],
657
- };
658
- }
659
- attachRenderer(renderer) {
660
- this.renderer = renderer;
661
- }
662
- getRenderer() {
663
- return this.renderer;
664
- }
665
- }
605
+ //#endregion
606
+ //#region packages/event-http/src/errors/http-error.ts
607
+ var HttpError = class extends Error {
608
+ name = "HttpError";
609
+ constructor(code = 500, _body = "") {
610
+ super(typeof _body === "string" ? _body : _body.message);
611
+ this.code = code;
612
+ this._body = _body;
613
+ }
614
+ get body() {
615
+ return typeof this._body === "string" ? {
616
+ statusCode: this.code,
617
+ message: this.message,
618
+ error: httpStatusCodes[this.code]
619
+ } : {
620
+ ...this._body,
621
+ statusCode: this.code,
622
+ message: this.message,
623
+ error: httpStatusCodes[this.code]
624
+ };
625
+ }
626
+ renderer;
627
+ attachRenderer(renderer) {
628
+ this.renderer = renderer;
629
+ }
630
+ getRenderer() {
631
+ return this.renderer;
632
+ }
633
+ };
666
634
 
635
+ //#endregion
636
+ //#region packages/event-http/src/response/core.ts
667
637
  const defaultStatus = {
668
- GET: EHttpStatusCode.OK,
669
- POST: EHttpStatusCode.Created,
670
- PUT: EHttpStatusCode.Created,
671
- PATCH: EHttpStatusCode.Accepted,
672
- DELETE: EHttpStatusCode.Accepted,
638
+ GET: EHttpStatusCode.OK,
639
+ POST: EHttpStatusCode.Created,
640
+ PUT: EHttpStatusCode.Created,
641
+ PATCH: EHttpStatusCode.Accepted,
642
+ DELETE: EHttpStatusCode.Accepted
673
643
  };
674
644
  const baseRenderer = new BaseHttpResponseRenderer();
675
- class BaseHttpResponse {
676
- constructor(renderer = baseRenderer) {
677
- this.renderer = renderer;
678
- this._status = 0;
679
- this._headers = {};
680
- }
681
- get status() {
682
- return this._status;
683
- }
684
- set status(value) {
685
- this._status = value;
686
- }
687
- get body() {
688
- return this._body;
689
- }
690
- set body(value) {
691
- this._body = value;
692
- }
693
- setStatus(value) {
694
- this.status = value;
695
- return this;
696
- }
697
- setBody(value) {
698
- this.body = value;
699
- return this;
700
- }
701
- getContentType() {
702
- return this._headers['content-type'];
703
- }
704
- setContentType(value) {
705
- this._headers['content-type'] = value;
706
- return this;
707
- }
708
- enableCors(origin = '*') {
709
- this._headers['Access-Control-Allow-Origin'] = origin;
710
- return this;
711
- }
712
- setCookie(name, value, attrs) {
713
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
714
- cookies.push(renderCookie(name, { value, attrs: attrs || {} }));
715
- return this;
716
- }
717
- setCacheControl(data) {
718
- this.setHeader('cache-control', renderCacheControl(data));
719
- }
720
- setCookieRaw(rawValue) {
721
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
722
- cookies.push(rawValue);
723
- return this;
724
- }
725
- header(name, value) {
726
- this._headers[name] = value;
727
- return this;
728
- }
729
- setHeader(name, value) {
730
- return this.header(name, value);
731
- }
732
- getHeader(name) {
733
- return this._headers[name];
734
- }
735
- mergeHeaders() {
736
- const { headers } = useSetHeaders();
737
- const { cookies, removeCookie } = useSetCookies();
738
- const newCookies = this._headers['set-cookie'] || [];
739
- for (const cookie of newCookies) {
740
- removeCookie(cookie.slice(0, cookie.indexOf('=')));
741
- }
742
- this._headers = {
743
- ...headers(),
744
- ...this._headers,
745
- };
746
- const setCookie = [...newCookies, ...cookies()];
747
- if (setCookie.length > 0) {
748
- this._headers['set-cookie'] = setCookie;
749
- }
750
- return this;
751
- }
752
- mergeStatus(renderedBody) {
753
- this.status = this.status || useResponse().status();
754
- if (!this.status) {
755
- const { method } = useRequest();
756
- this.status = renderedBody
757
- ? defaultStatus[method] || EHttpStatusCode.OK
758
- : EHttpStatusCode.NoContent;
759
- }
760
- return this;
761
- }
762
- mergeFetchStatus(fetchStatus) {
763
- this.status = this.status || useResponse().status() || fetchStatus;
764
- }
765
- panic(text, logger) {
766
- const error = new Error(text);
767
- logger.error(error);
768
- throw error;
769
- }
770
- async respond() {
771
- const { rawResponse, hasResponded } = useResponse();
772
- const { method, rawRequest } = useRequest();
773
- const logger = useEventLogger('http-response') || console;
774
- if (hasResponded()) {
775
- this.panic('The response was already sent.', logger);
776
- }
777
- this.mergeHeaders();
778
- const res = rawResponse();
779
- if (this.body instanceof Readable) {
780
- const stream = this.body;
781
- this.mergeStatus('ok');
782
- res.writeHead(this.status, {
783
- ...this._headers,
784
- });
785
- rawRequest.once('close', () => {
786
- stream.destroy();
787
- });
788
- if (method === 'HEAD') {
789
- stream.destroy();
790
- res.end();
791
- }
792
- else {
793
- return new Promise((resolve, reject) => {
794
- stream.on('error', e => {
795
- stream.destroy();
796
- res.end();
797
- reject(e);
798
- });
799
- stream.on('close', () => {
800
- stream.destroy();
801
- resolve(undefined);
802
- });
803
- stream.pipe(res);
804
- });
805
- }
806
- }
807
- else if (globalThis.Response && this.body instanceof Response) {
808
- this.mergeFetchStatus(this.body.status);
809
- if (method === 'HEAD') {
810
- res.end();
811
- }
812
- else {
813
- const additionalHeaders = {};
814
- if (this.body.headers.get('content-length')) {
815
- additionalHeaders['content-length'] = this.body.headers.get('content-length');
816
- }
817
- if (this.body.headers.get('content-type')) {
818
- additionalHeaders['content-type'] = this.body.headers.get('content-type');
819
- }
820
- res.writeHead(this.status, {
821
- ...additionalHeaders,
822
- ...this._headers,
823
- });
824
- await respondWithFetch(this.body.body, res);
825
- }
826
- }
827
- else {
828
- const renderedBody = this.renderer.render(this);
829
- this.mergeStatus(renderedBody);
830
- res
831
- .writeHead(this.status, {
832
- 'content-length': Buffer.byteLength(renderedBody),
833
- ...this._headers,
834
- })
835
- .end(method === 'HEAD' ? '' : renderedBody);
836
- }
837
- }
838
- }
645
+ var BaseHttpResponse = class {
646
+ constructor(renderer = baseRenderer) {
647
+ this.renderer = renderer;
648
+ }
649
+ _status = 0;
650
+ _body;
651
+ _headers = {};
652
+ get status() {
653
+ return this._status;
654
+ }
655
+ set status(value) {
656
+ this._status = value;
657
+ }
658
+ get body() {
659
+ return this._body;
660
+ }
661
+ set body(value) {
662
+ this._body = value;
663
+ }
664
+ setStatus(value) {
665
+ this.status = value;
666
+ return this;
667
+ }
668
+ setBody(value) {
669
+ this.body = value;
670
+ return this;
671
+ }
672
+ getContentType() {
673
+ return this._headers["content-type"];
674
+ }
675
+ setContentType(value) {
676
+ this._headers["content-type"] = value;
677
+ return this;
678
+ }
679
+ enableCors(origin = "*") {
680
+ this._headers["Access-Control-Allow-Origin"] = origin;
681
+ return this;
682
+ }
683
+ setCookie(name, value, attrs) {
684
+ const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
685
+ cookies.push(renderCookie(name, {
686
+ value,
687
+ attrs: attrs || {}
688
+ }));
689
+ return this;
690
+ }
691
+ setCacheControl(data) {
692
+ this.setHeader("cache-control", renderCacheControl(data));
693
+ }
694
+ setCookieRaw(rawValue) {
695
+ const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
696
+ cookies.push(rawValue);
697
+ return this;
698
+ }
699
+ header(name, value) {
700
+ this._headers[name] = value;
701
+ return this;
702
+ }
703
+ setHeader(name, value) {
704
+ return this.header(name, value);
705
+ }
706
+ getHeader(name) {
707
+ return this._headers[name];
708
+ }
709
+ mergeHeaders() {
710
+ const { headers } = useSetHeaders();
711
+ const { cookies, removeCookie } = useSetCookies();
712
+ const newCookies = this._headers["set-cookie"] || [];
713
+ for (const cookie of newCookies) removeCookie(cookie.slice(0, cookie.indexOf("=")));
714
+ this._headers = {
715
+ ...headers(),
716
+ ...this._headers
717
+ };
718
+ const setCookie = [...newCookies, ...cookies()];
719
+ if (setCookie.length > 0) this._headers["set-cookie"] = setCookie;
720
+ return this;
721
+ }
722
+ mergeStatus(renderedBody) {
723
+ this.status = this.status || useResponse().status();
724
+ if (!this.status) {
725
+ const { method } = useRequest();
726
+ this.status = renderedBody ? defaultStatus[method] || EHttpStatusCode.OK : EHttpStatusCode.NoContent;
727
+ }
728
+ return this;
729
+ }
730
+ mergeFetchStatus(fetchStatus) {
731
+ this.status = this.status || useResponse().status() || fetchStatus;
732
+ }
733
+ panic(text, logger) {
734
+ const error = new Error(text);
735
+ logger.error(error);
736
+ throw error;
737
+ }
738
+ async respond() {
739
+ const { rawResponse, hasResponded } = useResponse();
740
+ const { method, rawRequest } = useRequest();
741
+ const logger = useEventLogger("http-response") || console;
742
+ if (hasResponded()) this.panic("The response was already sent.", logger);
743
+ this.mergeHeaders();
744
+ const res = rawResponse();
745
+ if (this.body instanceof Readable) {
746
+ const stream = this.body;
747
+ this.mergeStatus("ok");
748
+ res.writeHead(this.status, { ...this._headers });
749
+ rawRequest.once("close", () => {
750
+ stream.destroy();
751
+ });
752
+ if (method === "HEAD") {
753
+ stream.destroy();
754
+ res.end();
755
+ } else return new Promise((resolve, reject) => {
756
+ stream.on("error", (e) => {
757
+ stream.destroy();
758
+ res.end();
759
+ reject(e);
760
+ });
761
+ stream.on("close", () => {
762
+ stream.destroy();
763
+ resolve(undefined);
764
+ });
765
+ stream.pipe(res);
766
+ });
767
+ } else if (globalThis.Response && this.body instanceof Response) {
768
+ this.mergeFetchStatus(this.body.status);
769
+ if (method === "HEAD") res.end();
770
+ else {
771
+ const additionalHeaders = {};
772
+ if (this.body.headers.get("content-length")) additionalHeaders["content-length"] = this.body.headers.get("content-length");
773
+ if (this.body.headers.get("content-type")) additionalHeaders["content-type"] = this.body.headers.get("content-type");
774
+ res.writeHead(this.status, {
775
+ ...additionalHeaders,
776
+ ...this._headers
777
+ });
778
+ await respondWithFetch(this.body.body, res);
779
+ }
780
+ } else {
781
+ const renderedBody = this.renderer.render(this);
782
+ this.mergeStatus(renderedBody);
783
+ res.writeHead(this.status, {
784
+ "content-length": Buffer.byteLength(renderedBody),
785
+ ...this._headers
786
+ }).end(method === "HEAD" ? "" : renderedBody);
787
+ }
788
+ }
789
+ };
839
790
  async function respondWithFetch(fetchBody, res) {
840
- if (fetchBody) {
841
- try {
842
- for await (const chunk of fetchBody) {
843
- res.write(chunk);
844
- }
845
- }
846
- catch (error) {
847
- }
848
- }
849
- res.end();
791
+ if (fetchBody) try {
792
+ for await (const chunk of fetchBody) res.write(chunk);
793
+ } catch (error) {}
794
+ res.end();
850
795
  }
851
796
 
797
+ //#endregion
798
+ //#region packages/event-http/src/response/factory.ts
852
799
  function createWooksResponder(renderer = new BaseHttpResponseRenderer(), errorRenderer = new HttpErrorRenderer()) {
853
- function createResponse(data) {
854
- const { hasResponded } = useResponse();
855
- if (hasResponded()) {
856
- return null;
857
- }
858
- if (data instanceof Error) {
859
- const r = new BaseHttpResponse(errorRenderer);
860
- let httpError;
861
- if (data instanceof HttpError) {
862
- httpError = data;
863
- }
864
- else {
865
- httpError = new HttpError(500, data.message);
866
- }
867
- r.setBody(httpError.body);
868
- return r;
869
- }
870
- else if (data instanceof BaseHttpResponse) {
871
- return data;
872
- }
873
- else {
874
- return new BaseHttpResponse(renderer).setBody(data);
875
- }
876
- }
877
- return {
878
- createResponse,
879
- respond: (data) => createResponse(data)?.respond(),
880
- };
800
+ function createResponse(data) {
801
+ const { hasResponded } = useResponse();
802
+ if (hasResponded()) return null;
803
+ if (data instanceof Error) {
804
+ const r = new BaseHttpResponse(errorRenderer);
805
+ let httpError;
806
+ if (data instanceof HttpError) httpError = data;
807
+ else httpError = new HttpError(500, data.message);
808
+ r.setBody(httpError.body);
809
+ return r;
810
+ } else if (data instanceof BaseHttpResponse) return data;
811
+ else return new BaseHttpResponse(renderer).setBody(data);
812
+ }
813
+ return {
814
+ createResponse,
815
+ respond: (data) => createResponse(data)?.respond()
816
+ };
881
817
  }
882
818
 
883
- class WooksHttp extends WooksAdapterBase {
884
- constructor(opts, wooks) {
885
- super(wooks, opts?.logger, opts?.router);
886
- this.opts = opts;
887
- this.responder = createWooksResponder();
888
- this.logger = opts?.logger || this.getLogger(`${''}[wooks-http]`);
889
- }
890
- all(path, handler) {
891
- return this.on('*', path, handler);
892
- }
893
- get(path, handler) {
894
- return this.on('GET', path, handler);
895
- }
896
- post(path, handler) {
897
- return this.on('POST', path, handler);
898
- }
899
- put(path, handler) {
900
- return this.on('PUT', path, handler);
901
- }
902
- patch(path, handler) {
903
- return this.on('PATCH', path, handler);
904
- }
905
- delete(path, handler) {
906
- return this.on('DELETE', path, handler);
907
- }
908
- head(path, handler) {
909
- return this.on('HEAD', path, handler);
910
- }
911
- options(path, handler) {
912
- return this.on('OPTIONS', path, handler);
913
- }
914
- async listen(port, hostname, backlog, listeningListener) {
915
- const server = (this.server = http.createServer(this.getServerCb()));
916
- return new Promise((resolve, reject) => {
917
- server.once('listening', resolve);
918
- server.once('error', reject);
919
- let args = [port, hostname, backlog, listeningListener];
920
- const ui = args.indexOf(undefined);
921
- if (ui >= 0) {
922
- args = args.slice(0, ui);
923
- }
924
- server.listen(...args);
925
- });
926
- }
927
- close(server) {
928
- const srv = server || this.server;
929
- return new Promise((resolve, reject) => {
930
- srv?.close(err => {
931
- if (err) {
932
- reject(err);
933
- return;
934
- }
935
- resolve(srv);
936
- });
937
- });
938
- }
939
- getServer() {
940
- return this.server;
941
- }
942
- attachServer(server) {
943
- this.server = server;
944
- }
945
- respond(data) {
946
- void this.responder.respond(data)?.catch(e => {
947
- this.logger.error('Uncaught response exception', e);
948
- });
949
- }
950
- getServerCb() {
951
- return (req, res) => {
952
- const runInContext = createHttpContext({ req, res }, this.mergeEventOptions(this.opts?.eventOptions));
953
- runInContext(async () => {
954
- const { handlers } = this.wooks.lookup(req.method, req.url);
955
- if (handlers || this.opts?.onNotFound) {
956
- try {
957
- return await this.processHandlers(handlers || [this.opts?.onNotFound]);
958
- }
959
- catch (error) {
960
- this.logger.error('Internal error, please report', error);
961
- this.respond(error);
962
- return error;
963
- }
964
- }
965
- else {
966
- this.logger.debug(`404 Not found (${req.method})${req.url}`);
967
- const error = new HttpError(404);
968
- this.respond(error);
969
- return error;
970
- }
971
- });
972
- };
973
- }
974
- async processHandlers(handlers) {
975
- const { store } = useHttpContext();
976
- for (const [i, handler] of handlers.entries()) {
977
- const isLastHandler = handlers.length === i + 1;
978
- try {
979
- const promise = handler();
980
- const result = await promise;
981
- this.respond(result);
982
- return result;
983
- }
984
- catch (error) {
985
- if (error instanceof HttpError) ;
986
- else {
987
- this.logger.error(`Uncaught route handler exception: ${store('event').get('req')?.url || ''}`, error);
988
- }
989
- if (isLastHandler) {
990
- this.respond(error);
991
- return error;
992
- }
993
- }
994
- }
995
- }
996
- }
819
+ //#endregion
820
+ //#region packages/event-http/src/http-adapter.ts
821
+ var WooksHttp = class extends WooksAdapterBase {
822
+ logger;
823
+ constructor(opts, wooks) {
824
+ super(wooks, opts?.logger, opts?.router);
825
+ this.opts = opts;
826
+ this.logger = opts?.logger || this.getLogger(`${"\x1B[96m"}[wooks-http]`);
827
+ }
828
+ all(path, handler) {
829
+ return this.on("*", path, handler);
830
+ }
831
+ get(path, handler) {
832
+ return this.on("GET", path, handler);
833
+ }
834
+ post(path, handler) {
835
+ return this.on("POST", path, handler);
836
+ }
837
+ put(path, handler) {
838
+ return this.on("PUT", path, handler);
839
+ }
840
+ patch(path, handler) {
841
+ return this.on("PATCH", path, handler);
842
+ }
843
+ delete(path, handler) {
844
+ return this.on("DELETE", path, handler);
845
+ }
846
+ head(path, handler) {
847
+ return this.on("HEAD", path, handler);
848
+ }
849
+ options(path, handler) {
850
+ return this.on("OPTIONS", path, handler);
851
+ }
852
+ server;
853
+ async listen(port, hostname, backlog, listeningListener) {
854
+ const server = this.server = http.createServer(this.getServerCb());
855
+ return new Promise((resolve, reject) => {
856
+ server.once("listening", resolve);
857
+ server.once("error", reject);
858
+ let args = [
859
+ port,
860
+ hostname,
861
+ backlog,
862
+ listeningListener
863
+ ];
864
+ const ui = args.indexOf(undefined);
865
+ if (ui >= 0) args = args.slice(0, ui);
866
+ server.listen(...args);
867
+ });
868
+ }
869
+ /**
870
+ * Stops the server if it was attached or passed via argument
871
+ * @param server
872
+ */
873
+ close(server) {
874
+ const srv = server || this.server;
875
+ return new Promise((resolve, reject) => {
876
+ srv?.close((err) => {
877
+ if (err) {
878
+ reject(err);
879
+ return;
880
+ }
881
+ resolve(srv);
882
+ });
883
+ });
884
+ }
885
+ /**
886
+ * Returns http(s) server that was attached to Wooks
887
+ *
888
+ * See attachServer method docs
889
+ * @returns Server
890
+ */
891
+ getServer() {
892
+ return this.server;
893
+ }
894
+ /**
895
+ * Attaches http(s) server instance
896
+ * to Wooks.
897
+ *
898
+ * Use it only if you want to `close` method to stop the server.
899
+ * @param server Server
900
+ */
901
+ attachServer(server) {
902
+ this.server = server;
903
+ }
904
+ responder = createWooksResponder();
905
+ respond(data) {
906
+ void this.responder.respond(data)?.catch((e) => {
907
+ this.logger.error("Uncaught response exception", e);
908
+ });
909
+ }
910
+ /**
911
+ * Returns server callback function
912
+ * that can be passed to any node server:
913
+ * ```js
914
+ * import { createHttpApp } from '@wooksjs/event-http'
915
+ * import http from 'http'
916
+ *
917
+ * const app = createHttpApp()
918
+ * const server = http.createServer(app.getServerCb())
919
+ * server.listen(3000)
920
+ * ```
921
+ */
922
+ getServerCb() {
923
+ return (req, res) => {
924
+ const runInContext = createHttpContext({
925
+ req,
926
+ res
927
+ }, this.mergeEventOptions(this.opts?.eventOptions));
928
+ runInContext(async () => {
929
+ const { handlers } = this.wooks.lookup(req.method, req.url);
930
+ if (handlers || this.opts?.onNotFound) try {
931
+ return await this.processHandlers(handlers || [this.opts?.onNotFound]);
932
+ } catch (error) {
933
+ this.logger.error("Internal error, please report", error);
934
+ this.respond(error);
935
+ return error;
936
+ }
937
+ else {
938
+ this.logger.debug(`404 Not found (${req.method})${req.url}`);
939
+ const error = new HttpError(404);
940
+ this.respond(error);
941
+ return error;
942
+ }
943
+ });
944
+ };
945
+ }
946
+ async processHandlers(handlers) {
947
+ const { store } = useHttpContext();
948
+ for (const [i, handler] of handlers.entries()) {
949
+ const isLastHandler = handlers.length === i + 1;
950
+ try {
951
+ const promise = handler();
952
+ const result = await promise;
953
+ this.respond(result);
954
+ return result;
955
+ } catch (error) {
956
+ if (error instanceof HttpError) {} else this.logger.error(`Uncaught route handler exception: ${store("event").get("req")?.url || ""}`, error);
957
+ if (isLastHandler) {
958
+ this.respond(error);
959
+ return error;
960
+ }
961
+ }
962
+ }
963
+ }
964
+ };
997
965
  function createHttpApp(opts, wooks) {
998
- return new WooksHttp(opts, wooks);
966
+ return new WooksHttp(opts, wooks);
999
967
  }
1000
968
 
1001
- export { BaseHttpResponse, BaseHttpResponseRenderer, EHttpStatusCode, HttpError, HttpErrorRenderer, WooksHttp, WooksURLSearchParams, createHttpApp, createHttpContext, createWooksResponder, httpStatusCodes, renderCacheControl, useAccept, useAuthorization, useCookies, useHeaders, useHttpContext, useRequest, useResponse, useSearchParams, useSetCacheControl, useSetCookie, useSetCookies, useSetHeader, useSetHeaders, useStatus };
969
+ //#endregion
970
+ export { BaseHttpResponse, BaseHttpResponseRenderer, EHttpStatusCode, HttpError, HttpErrorRenderer, WooksHttp, WooksURLSearchParams, createHttpApp, createHttpContext, createWooksResponder, httpStatusCodes, renderCacheControl, useAccept, useAuthorization, useCookies, useEventLogger, useHeaders, useHttpContext, useRequest, useResponse, useRouteParams, useSearchParams, useSetCacheControl, useSetCookie, useSetCookies, useSetHeader, useSetHeaders, useStatus };