@wooksjs/event-http 0.4.9 → 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 +1014 -1012
  2. package/dist/index.mjs +1014 -1012
  3. package/package.json +3 -3
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,6 +431,8 @@ 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, SuppressedError, Symbol */
435
+
434
436
 
435
437
  function __awaiter(thisArg, _arguments, P, generator) {
436
438
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -460,646 +462,646 @@ function __asyncValues(o) {
460
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);
461
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); }); }; }
462
464
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
463
- }
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
+ };
464
471
 
465
- class BaseHttpResponseRenderer {
466
- render(response) {
467
- if (typeof response.body === 'string' ||
468
- typeof response.body === 'boolean' ||
469
- typeof response.body === 'number') {
470
- if (!response.getContentType())
471
- response.setContentType('text/plain');
472
- return response.body.toString();
473
- }
474
- if (typeof response.body === 'undefined') {
475
- return '';
476
- }
477
- if (response.body instanceof Uint8Array) {
478
- return response.body;
479
- }
480
- if (typeof response.body === 'object') {
481
- if (!response.getContentType())
482
- response.setContentType('application/json');
483
- return JSON.stringify(response.body);
484
- }
485
- throw new Error('Unsupported body format "' + typeof response.body + '"');
486
- }
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
+ }
487
494
  }
488
495
 
489
- const httpStatusCodes = {
490
- [100]: 'Continue',
491
- [101]: 'Switching protocols',
492
- [102]: 'Processing',
493
- [103]: 'Early Hints',
494
- [200]: 'OK',
495
- [201]: 'Created',
496
- [202]: 'Accepted',
497
- [203]: 'Non-Authoritative Information',
498
- [204]: 'No Content',
499
- [205]: 'Reset Content',
500
- [206]: 'Partial Content',
501
- [207]: 'Multi-Status',
502
- [208]: 'Already Reported',
503
- [226]: 'IM Used',
504
- [300]: 'Multiple Choices',
505
- [301]: 'Moved Permanently',
506
- [302]: 'Found (Previously "Moved Temporarily")',
507
- [303]: 'See Other',
508
- [304]: 'Not Modified',
509
- [305]: 'Use Proxy',
510
- [306]: 'Switch Proxy',
511
- [307]: 'Temporary Redirect',
512
- [308]: 'Permanent Redirect',
513
- [400]: 'Bad Request',
514
- [401]: 'Unauthorized',
515
- [402]: 'Payment Required',
516
- [403]: 'Forbidden',
517
- [404]: 'Not Found',
518
- [405]: 'Method Not Allowed',
519
- [406]: 'Not Acceptable',
520
- [407]: 'Proxy Authentication Required',
521
- [408]: 'Request Timeout',
522
- [409]: 'Conflict',
523
- [410]: 'Gone',
524
- [411]: 'Length Required',
525
- [412]: 'Precondition Failed',
526
- [413]: 'Payload Too Large',
527
- [414]: 'URI Too Long',
528
- [415]: 'Unsupported Media Type',
529
- [416]: 'Range Not Satisfiable',
530
- [417]: 'Expectation Failed',
531
- [418]: 'I\'m a Teapot',
532
- [421]: 'Misdirected Request',
533
- [422]: 'Unprocessable Entity',
534
- [423]: 'Locked',
535
- [424]: 'Failed Dependency',
536
- [425]: 'Too Early',
537
- [426]: 'Upgrade Required',
538
- [428]: 'Precondition Required',
539
- [429]: 'Too Many Requests',
540
- [431]: 'Request Header Fields Too Large',
541
- [451]: 'Unavailable For Legal Reasons',
542
- [500]: 'Internal Server Error',
543
- [501]: 'Not Implemented',
544
- [502]: 'Bad Gateway',
545
- [503]: 'Service Unavailable',
546
- [504]: 'Gateway Timeout',
547
- [505]: 'HTTP Version Not Supported',
548
- [506]: 'Variant Also Negotiates',
549
- [507]: 'Insufficient Storage',
550
- [508]: 'Loop Detected',
551
- [510]: 'Not Extended',
552
- [511]: 'Network Authentication Required',
553
- };
554
- var EHttpStatusCode;
555
- (function (EHttpStatusCode) {
556
- EHttpStatusCode[EHttpStatusCode["Continue"] = 100] = "Continue";
557
- EHttpStatusCode[EHttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
558
- EHttpStatusCode[EHttpStatusCode["Processing"] = 102] = "Processing";
559
- EHttpStatusCode[EHttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
560
- EHttpStatusCode[EHttpStatusCode["OK"] = 200] = "OK";
561
- EHttpStatusCode[EHttpStatusCode["Created"] = 201] = "Created";
562
- EHttpStatusCode[EHttpStatusCode["Accepted"] = 202] = "Accepted";
563
- EHttpStatusCode[EHttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
564
- EHttpStatusCode[EHttpStatusCode["NoContent"] = 204] = "NoContent";
565
- EHttpStatusCode[EHttpStatusCode["ResetContent"] = 205] = "ResetContent";
566
- EHttpStatusCode[EHttpStatusCode["PartialContent"] = 206] = "PartialContent";
567
- EHttpStatusCode[EHttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
568
- EHttpStatusCode[EHttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
569
- EHttpStatusCode[EHttpStatusCode["IMUsed"] = 226] = "IMUsed";
570
- EHttpStatusCode[EHttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
571
- EHttpStatusCode[EHttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
572
- EHttpStatusCode[EHttpStatusCode["Found"] = 302] = "Found";
573
- EHttpStatusCode[EHttpStatusCode["SeeOther"] = 303] = "SeeOther";
574
- EHttpStatusCode[EHttpStatusCode["NotModified"] = 304] = "NotModified";
575
- EHttpStatusCode[EHttpStatusCode["UseProxy"] = 305] = "UseProxy";
576
- EHttpStatusCode[EHttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy";
577
- EHttpStatusCode[EHttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
578
- EHttpStatusCode[EHttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
579
- EHttpStatusCode[EHttpStatusCode["BadRequest"] = 400] = "BadRequest";
580
- EHttpStatusCode[EHttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
581
- EHttpStatusCode[EHttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
582
- EHttpStatusCode[EHttpStatusCode["Forbidden"] = 403] = "Forbidden";
583
- EHttpStatusCode[EHttpStatusCode["NotFound"] = 404] = "NotFound";
584
- EHttpStatusCode[EHttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
585
- EHttpStatusCode[EHttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
586
- EHttpStatusCode[EHttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
587
- EHttpStatusCode[EHttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
588
- EHttpStatusCode[EHttpStatusCode["Conflict"] = 409] = "Conflict";
589
- EHttpStatusCode[EHttpStatusCode["Gone"] = 410] = "Gone";
590
- EHttpStatusCode[EHttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
591
- EHttpStatusCode[EHttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
592
- EHttpStatusCode[EHttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
593
- EHttpStatusCode[EHttpStatusCode["URITooLong"] = 414] = "URITooLong";
594
- EHttpStatusCode[EHttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
595
- EHttpStatusCode[EHttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
596
- EHttpStatusCode[EHttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
597
- EHttpStatusCode[EHttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
598
- EHttpStatusCode[EHttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
599
- EHttpStatusCode[EHttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
600
- EHttpStatusCode[EHttpStatusCode["Locked"] = 423] = "Locked";
601
- EHttpStatusCode[EHttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
602
- EHttpStatusCode[EHttpStatusCode["TooEarly"] = 425] = "TooEarly";
603
- EHttpStatusCode[EHttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
604
- EHttpStatusCode[EHttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
605
- EHttpStatusCode[EHttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
606
- EHttpStatusCode[EHttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
607
- EHttpStatusCode[EHttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
608
- EHttpStatusCode[EHttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
609
- EHttpStatusCode[EHttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
610
- EHttpStatusCode[EHttpStatusCode["BadGateway"] = 502] = "BadGateway";
611
- EHttpStatusCode[EHttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
612
- EHttpStatusCode[EHttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
613
- EHttpStatusCode[EHttpStatusCode["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
614
- EHttpStatusCode[EHttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
615
- EHttpStatusCode[EHttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
616
- EHttpStatusCode[EHttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
617
- EHttpStatusCode[EHttpStatusCode["NotExtended"] = 510] = "NotExtended";
618
- 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";
619
626
  })(EHttpStatusCode || (EHttpStatusCode = {}));
620
627
 
621
- const defaultStatus = {
622
- GET: EHttpStatusCode.OK,
623
- POST: EHttpStatusCode.Created,
624
- PUT: EHttpStatusCode.Created,
625
- PATCH: EHttpStatusCode.Accepted,
626
- DELETE: EHttpStatusCode.Accepted,
627
- };
628
- const baseRenderer = new BaseHttpResponseRenderer();
629
- class BaseHttpResponse {
630
- constructor(renderer = baseRenderer) {
631
- this.renderer = renderer;
632
- this._status = 0;
633
- this._headers = {};
634
- }
635
- get status() {
636
- return this._status;
637
- }
638
- set status(value) {
639
- this._status = value;
640
- }
641
- get body() {
642
- return this._body;
643
- }
644
- set body(value) {
645
- this._body = value;
646
- }
647
- setStatus(value) {
648
- this.status = value;
649
- return this;
650
- }
651
- setBody(value) {
652
- this.body = value;
653
- return this;
654
- }
655
- getContentType() {
656
- return this._headers['content-type'];
657
- }
658
- setContentType(value) {
659
- this._headers['content-type'] = value;
660
- return this;
661
- }
662
- enableCors(origin = '*') {
663
- this._headers['Access-Control-Allow-Origin'] = origin;
664
- return this;
665
- }
666
- setCookie(name, value, attrs) {
667
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
668
- cookies.push(renderCookie(name, { value, attrs: attrs || {} }));
669
- return this;
670
- }
671
- setCacheControl(data) {
672
- this.setHeader('cache-control', renderCacheControl(data));
673
- }
674
- setCookieRaw(rawValue) {
675
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
676
- cookies.push(rawValue);
677
- return this;
678
- }
679
- header(name, value) {
680
- this._headers[name] = value;
681
- return this;
682
- }
683
- setHeader(name, value) {
684
- return this.header(name, value);
685
- }
686
- getHeader(name) {
687
- return this._headers[name];
688
- }
689
- mergeHeaders() {
690
- const { headers } = useSetHeaders();
691
- const { cookies, removeCookie } = useSetCookies();
692
- const newCookies = this._headers['set-cookie'] || [];
693
- for (const cookie of newCookies) {
694
- removeCookie(cookie.slice(0, cookie.indexOf('=')));
695
- }
696
- this._headers = Object.assign(Object.assign({}, headers()), this._headers);
697
- const setCookie = [...newCookies, ...cookies()];
698
- if (setCookie && setCookie.length) {
699
- this._headers['set-cookie'] = setCookie;
700
- }
701
- return this;
702
- }
703
- mergeStatus(renderedBody) {
704
- this.status = this.status || useResponse().status();
705
- if (!this.status) {
706
- const { method } = useRequest();
707
- this.status = renderedBody
708
- ? defaultStatus[method] || EHttpStatusCode.OK
709
- : EHttpStatusCode.NoContent;
710
- }
711
- return this;
712
- }
713
- mergeFetchStatus(fetchStatus) {
714
- this.status = this.status || useResponse().status() || fetchStatus;
715
- }
716
- panic(text, logger) {
717
- const error = new Error(text);
718
- logger.error(error);
719
- throw error;
720
- }
721
- respond() {
722
- return __awaiter(this, void 0, void 0, function* () {
723
- const { rawResponse, hasResponded } = useResponse();
724
- const { method, rawRequest } = useRequest();
725
- const logger = useEventLogger('http-response');
726
- if (hasResponded()) {
727
- this.panic('The response was already sent.', logger);
728
- }
729
- this.mergeHeaders();
730
- const res = rawResponse();
731
- if (this.body instanceof Readable) {
732
- // responding with readable stream
733
- const stream = this.body;
734
- this.mergeStatus('ok');
735
- res.writeHead(this.status, Object.assign({}, this._headers));
736
- rawRequest.once('close', () => {
737
- stream.destroy();
738
- });
739
- if (method === 'HEAD') {
740
- stream.destroy();
741
- res.end();
742
- }
743
- else {
744
- return new Promise((resolve, reject) => {
745
- stream.on('error', (e) => {
746
- stream.destroy();
747
- res.end();
748
- reject(e);
749
- });
750
- stream.on('close', () => {
751
- stream.destroy();
752
- resolve(undefined);
753
- });
754
- stream.pipe(res);
755
- });
756
- }
757
- }
758
- else if (globalThis.Response &&
759
- this.body instanceof Response /* Fetch Response */) {
760
- this.mergeFetchStatus(this.body.status);
761
- if (method === 'HEAD') {
762
- res.end();
763
- }
764
- else {
765
- const additionalHeaders = {};
766
- if (this.body.headers.get('content-length')) {
767
- additionalHeaders['content-length'] = this.body.headers.get('content-length');
768
- }
769
- if (this.body.headers.get('content-type')) {
770
- additionalHeaders['content-type'] = this.body.headers.get('content-type');
771
- }
772
- res.writeHead(this.status, Object.assign(Object.assign({}, additionalHeaders), this._headers));
773
- yield respondWithFetch(this.body.body, res);
774
- }
775
- }
776
- else {
777
- const renderedBody = this.renderer.render(this);
778
- this.mergeStatus(renderedBody);
779
- res.writeHead(this.status, Object.assign({ 'content-length': Buffer.byteLength(renderedBody) }, this._headers)).end(method !== 'HEAD' ? renderedBody : '');
780
- }
781
- });
782
- }
783
- }
784
- function respondWithFetch(fetchBody, res) {
785
- var _a, e_1, _b, _c;
786
- return __awaiter(this, void 0, void 0, function* () {
787
- if (fetchBody) {
788
- try {
789
- try {
790
- for (var _d = true, _e = __asyncValues(fetchBody), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
791
- _c = _f.value;
792
- _d = false;
793
- try {
794
- const chunk = _c;
795
- res.write(chunk);
796
- }
797
- finally {
798
- _d = true;
799
- }
800
- }
801
- }
802
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
803
- finally {
804
- try {
805
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
806
- }
807
- finally { if (e_1) throw e_1.error; }
808
- }
809
- }
810
- catch (e) {
811
- // ?
812
- }
813
- }
814
- res.end();
815
- });
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
+ });
816
818
  }
817
819
 
818
- const preStyles = 'font-family: monospace;' +
819
- 'width: 100%;' +
820
- 'max-width: 900px;' +
821
- 'padding: 10px;' +
822
- 'margin: 20px auto;' +
823
- 'border-radius: 8px;' +
824
- 'background-color: #494949;' +
825
- 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
826
- class HttpErrorRenderer extends BaseHttpResponseRenderer {
827
- renderHtml(response) {
828
- const data = response.body || {};
829
- response.setContentType('text/html');
830
- const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
831
- return ('<html style="background-color: #333; color: #bbb;">' +
832
- `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
833
- `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
834
- `<center><h4>${data.message}</h1></center><hr color="#666">` +
835
- `<center style="color: #666;"> Wooks v${"0.4.9"} </center>` +
836
- `${keys.length
837
- ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>`
838
- : ''}` +
839
- '</body></html>');
840
- }
841
- renderText(response) {
842
- const data = response.body || {};
843
- response.setContentType('text/plain');
844
- const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
845
- return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
846
- `\n\n${keys.length
847
- ? `${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}`
848
- : ''}`);
849
- }
850
- renderJson(response) {
851
- const data = response.body || {};
852
- response.setContentType('application/json');
853
- const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
854
- return (`{"statusCode":${escapeQuotes(data.statusCode)},` +
855
- `"error":"${escapeQuotes(data.error)}",` +
856
- `"message":"${escapeQuotes(data.message)}"` +
857
- `${keys.length
858
- ? ',' +
859
- keys
860
- .map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`)
861
- .join(',')
862
- : ''}}`);
863
- }
864
- render(response) {
865
- var _a;
866
- const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
867
- response.status = ((_a = response.body) === null || _a === void 0 ? void 0 : _a.statusCode) || 500;
868
- if (acceptsJson()) {
869
- return this.renderJson(response);
870
- }
871
- else if (acceptsHtml()) {
872
- return this.renderHtml(response);
873
- }
874
- else if (acceptsText()) {
875
- return this.renderText(response);
876
- }
877
- else {
878
- return this.renderJson(response);
879
- }
880
- }
881
- }
882
- function escapeQuotes(s) {
883
- return (typeof s === 'number' ? s : s || '')
884
- .toString()
885
- .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, '\\"');
886
888
  }
887
889
 
888
- class HttpError extends Error {
889
- constructor(code = 500, _body = '') {
890
- super(typeof _body === 'string' ? _body : _body.message);
891
- this.code = code;
892
- this._body = _body;
893
- }
894
- get body() {
895
- return typeof this._body === 'string'
896
- ? {
897
- statusCode: this.code,
898
- message: this.message,
899
- error: httpStatusCodes[this.code],
900
- }
901
- : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
902
- }
903
- attachRenderer(renderer) {
904
- this.renderer = renderer;
905
- }
906
- getRenderer() {
907
- return this.renderer;
908
- }
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
+ }
909
911
  }
910
912
 
911
- function createWooksResponder(
912
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
913
- renderer = new BaseHttpResponseRenderer(),
914
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
915
- errorRenderer = new HttpErrorRenderer()) {
916
- function createResponse(data) {
917
- const { hasResponded } = useResponse();
918
- if (hasResponded())
919
- return null;
920
- if (data instanceof Error) {
921
- const r = new BaseHttpResponse(errorRenderer);
922
- let httpError;
923
- if (data instanceof HttpError) {
924
- httpError = data;
925
- }
926
- else {
927
- httpError = new HttpError(500, data.message);
928
- }
929
- r.setBody(httpError.body);
930
- return r;
931
- }
932
- else if (data instanceof BaseHttpResponse) {
933
- return data;
934
- }
935
- else {
936
- return new BaseHttpResponse(renderer).setBody(data);
937
- }
938
- }
939
- return {
940
- createResponse,
941
- respond: (data) => { var _a; return (_a = createResponse(data)) === null || _a === void 0 ? void 0 : _a.respond(); },
942
- };
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
+ };
943
945
  }
944
946
 
945
- class WooksHttp extends WooksAdapterBase {
946
- constructor(opts, wooks) {
947
- super(wooks, opts === null || opts === void 0 ? void 0 : opts.logger, opts === null || opts === void 0 ? void 0 : opts.router);
948
- this.opts = opts;
949
- this.responder = createWooksResponder();
950
- this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-http');
951
- }
952
- all(path, handler) {
953
- return this.on('*', path, handler);
954
- }
955
- get(path, handler) {
956
- return this.on('GET', path, handler);
957
- }
958
- post(path, handler) {
959
- return this.on('POST', path, handler);
960
- }
961
- put(path, handler) {
962
- return this.on('PUT', path, handler);
963
- }
964
- patch(path, handler) {
965
- return this.on('PATCH', path, handler);
966
- }
967
- delete(path, handler) {
968
- return this.on('DELETE', path, handler);
969
- }
970
- head(path, handler) {
971
- return this.on('HEAD', path, handler);
972
- }
973
- options(path, handler) {
974
- return this.on('OPTIONS', path, handler);
975
- }
976
- /**
977
- * Starts the http(s) server.
978
- *
979
- * Use this only if you rely on Wooks server.
980
- */
981
- listen(...args) {
982
- return __awaiter(this, void 0, void 0, function* () {
983
- const server = (this.server = http.createServer(this.getServerCb()));
984
- return new Promise((resolve, reject) => {
985
- server.once('listening', resolve);
986
- server.once('error', reject);
987
- server.listen(...args);
988
- });
989
- });
990
- }
991
- /**
992
- * Stops the server if it was attached or passed via argument
993
- * @param server
994
- */
995
- close(server) {
996
- const srv = server || this.server;
997
- return new Promise((resolve, reject) => {
998
- srv === null || srv === void 0 ? void 0 : srv.close((err) => {
999
- if (err)
1000
- return reject(err);
1001
- resolve(srv);
1002
- });
1003
- });
1004
- }
1005
- /**
1006
- * Returns http(s) server that was attached to Wooks
1007
- *
1008
- * See attachServer method docs
1009
- * @returns Server
1010
- */
1011
- getServer() {
1012
- return this.server;
1013
- }
1014
- /**
1015
- * Attaches http(s) server instance
1016
- * to Wooks.
1017
- *
1018
- * Use it only if you want to `close` method to stop the server.
1019
- * @param server Server
1020
- */
1021
- attachServer(server) {
1022
- this.server = server;
1023
- }
1024
- respond(data) {
1025
- var _a;
1026
- void ((_a = this.responder.respond(data)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
1027
- this.logger.error('Uncought response exception', e);
1028
- }));
1029
- }
1030
- /**
1031
- * Returns server callback function
1032
- * that can be passed to any node server:
1033
- * ```js
1034
- * import { createHttpApp } from '@wooksjs/event-http'
1035
- * import http from 'http'
1036
- *
1037
- * const app = createHttpApp()
1038
- * const server = http.createServer(app.getServerCb())
1039
- * server.listen(3000)
1040
- * ```
1041
- */
1042
- getServerCb() {
1043
- return (req, res) => __awaiter(this, void 0, void 0, function* () {
1044
- var _a, _b, _c;
1045
- const { restoreCtx, clearCtx } = createHttpContext({ req, res }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
1046
- const { handlers } = this.wooks.lookup(req.method, req.url);
1047
- if (handlers || ((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound)) {
1048
- try {
1049
- yield this.processHandlers(handlers || [(_c = this.opts) === null || _c === void 0 ? void 0 : _c.onNotFound]);
1050
- }
1051
- catch (e) {
1052
- this.logger.error('Internal error, please report', e);
1053
- restoreCtx();
1054
- this.respond(e);
1055
- clearCtx();
1056
- }
1057
- }
1058
- else {
1059
- // not found
1060
- this.logger.debug(`404 Not found (${req.method})${req.url}`);
1061
- this.respond(new HttpError(404));
1062
- clearCtx();
1063
- }
1064
- });
1065
- }
1066
- processHandlers(handlers) {
1067
- return __awaiter(this, void 0, void 0, function* () {
1068
- const { restoreCtx, clearCtx, store } = useHttpContext();
1069
- for (const [i, handler] of handlers.entries()) {
1070
- const isLastHandler = handlers.length === i + 1;
1071
- try {
1072
- restoreCtx();
1073
- const promise = handler();
1074
- clearCtx();
1075
- const result = yield promise;
1076
- // even if the returned value is an Error instance
1077
- // we still want to process it as a response
1078
- restoreCtx();
1079
- this.respond(result);
1080
- clearCtx();
1081
- break;
1082
- }
1083
- catch (e) {
1084
- this.logger.error(`Uncought route handler exception: ${store('event').get('req').url || ''}`, e);
1085
- if (isLastHandler) {
1086
- restoreCtx();
1087
- this.respond(e);
1088
- clearCtx();
1089
- }
1090
- }
1091
- }
1092
- });
1093
- }
1094
- }
1095
- /**
1096
- * Factory for WooksHttp App
1097
- * @param opts TWooksHttpOptions
1098
- * @param wooks Wooks | WooksAdapterBase
1099
- * @returns WooksHttp
1100
- */
1101
- function createHttpApp(opts, wooks) {
1102
- 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);
1103
1105
  }
1104
1106
 
1105
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 };