@wooksjs/event-http 0.4.8 → 0.4.10

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