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