@jwn-js/common 2.1.15 → 2.1.16

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 (97) hide show
  1. package/ApiError.d.ts +1 -29
  2. package/ApiError.js +1 -39
  3. package/ApiError.mjs +1 -0
  4. package/Jwt-7tQL-rwa.js +1 -0
  5. package/Jwt-CDdbxwvH.js +1 -0
  6. package/Jwt.js +1 -44
  7. package/Jwt.mjs +1 -0
  8. package/Memcached.js +9 -124
  9. package/Memcached.mjs +9 -0
  10. package/Server.d.ts +2 -2
  11. package/Server.js +1 -239
  12. package/Server.mjs +1 -0
  13. package/cookieParse.js +1 -27
  14. package/cookieParse.mjs +1 -0
  15. package/cookieString.js +1 -24
  16. package/cookieString.mjs +1 -0
  17. package/docs/assets/highlight.css +19 -5
  18. package/docs/assets/main.js +59 -52
  19. package/docs/assets/navigation.js +1 -0
  20. package/docs/assets/search.js +1 -1
  21. package/docs/assets/style.css +826 -826
  22. package/docs/classes/ApiError.html +22 -17
  23. package/docs/classes/AsyncJwt.html +16 -17
  24. package/docs/classes/Controller.html +42 -24
  25. package/docs/classes/Jwt.html +16 -17
  26. package/docs/classes/Memcached.html +31 -38
  27. package/docs/classes/Model.html +24 -7
  28. package/docs/classes/Server.html +25 -25
  29. package/docs/classes/Ssr.html +13 -11
  30. package/docs/classes/Web.html +10 -3
  31. package/docs/functions/action.html +2 -0
  32. package/docs/functions/body.html +2 -0
  33. package/docs/functions/codeToStatus.html +2 -0
  34. package/docs/functions/config.html +2 -0
  35. package/docs/functions/connection.html +2 -0
  36. package/docs/functions/context.html +2 -0
  37. package/docs/functions/controller-1.html +2 -0
  38. package/docs/functions/cookies.html +2 -0
  39. package/docs/functions/db.html +2 -0
  40. package/docs/functions/headers.html +2 -0
  41. package/docs/functions/home.html +2 -0
  42. package/docs/functions/hostname.html +2 -0
  43. package/docs/functions/http.html +4 -0
  44. package/docs/functions/init.html +2 -0
  45. package/docs/functions/json.html +3 -0
  46. package/docs/functions/logerror.html +3 -0
  47. package/docs/functions/method.html +2 -0
  48. package/docs/functions/mixin.html +5 -0
  49. package/docs/functions/mount.html +2 -0
  50. package/docs/functions/pool.html +2 -0
  51. package/docs/functions/protocol.html +2 -0
  52. package/docs/functions/request.html +2 -0
  53. package/docs/functions/selectControllersSchema.html +1 -0
  54. package/docs/functions/stream.html +2 -0
  55. package/docs/functions/subaction.html +2 -0
  56. package/docs/functions/url.html +2 -0
  57. package/docs/functions/xml.html +3 -0
  58. package/docs/index.html +8 -16
  59. package/docs/interfaces/ApiErrorMessage.html +6 -1
  60. package/docs/interfaces/ContextSsr.html +22 -19
  61. package/docs/interfaces/ContextWeb.html +7 -1
  62. package/docs/interfaces/OptionsSsr.html +3 -1
  63. package/docs/interfaces/OptionsWeb.html +6 -1
  64. package/docs/interfaces/ResponseOptions.html +4 -1
  65. package/docs/interfaces/Route.html +4 -1
  66. package/docs/interfaces/Schema.html +3 -1
  67. package/docs/interfaces/ServerHandler.html +4 -1
  68. package/docs/interfaces/ServerOptions.html +8 -1
  69. package/docs/interfaces/ServerWebsocket.html +4 -1
  70. package/docs/modules.html +50 -85
  71. package/docs/types/ServerRoutes.html +1 -0
  72. package/docs/variables/helpers.html +31 -0
  73. package/index.d.ts +30 -109
  74. package/index.js +4 -1965
  75. package/index.mjs +57 -0
  76. package/jsonBody.js +1 -27
  77. package/jsonBody.mjs +1 -0
  78. package/multipartBody.d.ts +1 -1
  79. package/multipartBody.js +1 -48
  80. package/multipartBody.mjs +1 -0
  81. package/package.json +11 -18
  82. package/readConfig.js +1 -17
  83. package/readConfig.mjs +1 -0
  84. package/readConfigSync.js +1 -18
  85. package/readConfigSync.mjs +1 -0
  86. package/staticBody.js +1 -207
  87. package/staticBody.mjs +1 -0
  88. package/urlencodedBody.js +1 -32
  89. package/urlencodedBody.mjs +1 -0
  90. package/ApiError-b517f53a.js +0 -37
  91. package/cookieParse-49f1da46.js +0 -25
  92. package/decoders-ee9f4396.js +0 -18
  93. package/docs/assets/icons.css +0 -1043
  94. package/docs/assets/icons.png +0 -0
  95. package/docs/assets/icons@2x.png +0 -0
  96. package/docs/assets/widgets.png +0 -0
  97. package/docs/assets/widgets@2x.png +0 -0
package/index.js CHANGED
@@ -1,870 +1,4 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var ApiError = require('./ApiError-b517f53a.js');
6
- var dns = require('dns');
7
- var uws = require('uWebSockets.js');
8
- var cookieParse = require('./cookieParse-49f1da46.js');
9
- var crypto = require('crypto');
10
- var decoders = require('./decoders-ee9f4396.js');
11
- var util = require('util');
12
- var stream$1 = require('stream');
13
- var querystring = require('querystring');
14
- var formidable = require('formidable');
15
- var path = require('path');
16
- var fs = require('fs');
17
- var easyAsh = require('easy-ash');
18
- var xmljs = require('xml-js');
19
- var os = require('os');
20
- require('reflect-metadata');
21
-
22
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
23
-
24
- function _interopNamespace(e) {
25
- if (e && e.__esModule) return e;
26
- var n = Object.create(null);
27
- if (e) {
28
- Object.keys(e).forEach(function (k) {
29
- if (k !== 'default') {
30
- var d = Object.getOwnPropertyDescriptor(e, k);
31
- Object.defineProperty(n, k, d.get ? d : {
32
- enumerable: true,
33
- get: function () { return e[k]; }
34
- });
35
- }
36
- });
37
- }
38
- n["default"] = e;
39
- return Object.freeze(n);
40
- }
41
-
42
- var dns__default = /*#__PURE__*/_interopDefaultLegacy(dns);
43
- var uws__default = /*#__PURE__*/_interopDefaultLegacy(uws);
44
- var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
45
- var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
46
- var formidable__default = /*#__PURE__*/_interopDefaultLegacy(formidable);
47
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
48
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
49
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
50
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
51
- var xmljs__default = /*#__PURE__*/_interopDefaultLegacy(xmljs);
52
- var os__namespace = /*#__PURE__*/_interopNamespace(os);
53
-
54
- const status = {
55
- 100: "100 Continue",
56
- 101: "101 Switching Protocols",
57
- 200: "200 OK",
58
- 201: "201 Created",
59
- 202: "202 Accepted",
60
- 203: "203 Non-Authoritative Information",
61
- 204: "No Content",
62
- 205: "205 Reset Content",
63
- 206: "206 Partial Content",
64
- 300: "300 Multiple Choices",
65
- 301: "301 Moved Permanently",
66
- 302: "302 Found",
67
- 303: "303 See Other",
68
- 304: "304 Not Modified",
69
- 305: "305 Use Proxy",
70
- 306: "306 (Unused)",
71
- 307: "307 Temporary Redirect",
72
- 400: "400 Bad Request",
73
- 401: "401 Unauthorized",
74
- 402: "402 Payment Required",
75
- 403: "403 Forbidden",
76
- 404: "404 Not Found",
77
- 405: "405 Method Not Allowed",
78
- 406: "406 Not Acceptable",
79
- 407: "407 Proxy Authentication Required",
80
- 408: "408 Request Timeout",
81
- 409: "409 Conflict",
82
- 410: "410 Gone",
83
- 411: "411 Length Required",
84
- 412: "412 Precondition Failed",
85
- 413: "413 Request Entity Too Large",
86
- 414: "414 Request-URI Too Long",
87
- 415: "415 Unsupported Media Type",
88
- 416: "416 Requested Range Not Satisfiable",
89
- 417: "417 Expectation Failed",
90
- 500: "500 Internal Server Error",
91
- 501: "501 Not Implemented",
92
- 502: "502 Bad Gateway",
93
- 503: "503 Service Unavailable",
94
- 504: "504 Gateway Timeout",
95
- 505: "505 HTTP Version Not Supported"
96
- };
97
- const codeToStatus = (code) => {
98
- return status.hasOwnProperty(code) ? status[code] : `${code}`;
99
- };
100
- class Server {
101
- constructor(options) {
102
- this._logLevel = "info";
103
- this._socket = null;
104
- this._timeout = 0;
105
- this._routes = [];
106
- this._host = "localhost";
107
- this._port = 3e3;
108
- this._mode = "production";
109
- this._appOptions = {};
110
- this._defaultRoute = {
111
- method: "get",
112
- pattern: "/*",
113
- handler: (res, req, next) => next()
114
- };
115
- this._routes = options.routes || this._routes;
116
- this._host = options.host || this._host;
117
- this._port = options.port || this._port;
118
- this._timeout = options.timeout || this._timeout;
119
- this._mode = options.mode || this._mode;
120
- this._appOptions = options.appOptions || this._appOptions;
121
- this._logLevel = options.logLevel || this._logLevel;
122
- }
123
- getApp() {
124
- return this._app;
125
- }
126
- app() {
127
- this._protocol = "http";
128
- this._app = uws__default["default"].App(this._appOptions);
129
- return this;
130
- }
131
- sslApp() {
132
- this._protocol = "https";
133
- this._app = uws__default["default"].SSLApp(this._appOptions);
134
- return this;
135
- }
136
- push(route) {
137
- this._routes.push(route);
138
- return this;
139
- }
140
- unshift(route) {
141
- this._routes.unshift(route);
142
- return this;
143
- }
144
- listen(host, port, fn = () => {
145
- }) {
146
- if (typeof port === "number") {
147
- this._port = port;
148
- this._host = host;
149
- } else if (typeof host === "number") {
150
- if (typeof port === "function") {
151
- fn = port;
152
- }
153
- this._port = host;
154
- } else if (typeof host === "function") {
155
- fn = host;
156
- }
157
- if (!this._app) {
158
- throw new Error("Create app or sslApp first");
159
- }
160
- this._lookup(this._host, (ip) => {
161
- for (let route of this._routes) {
162
- route = typeof route === "function" ? { handler: route } : route;
163
- route = Object.assign({}, this._defaultRoute, route);
164
- switch (route.method) {
165
- case "ws":
166
- this._app[route.method](route.pattern, route.behavior);
167
- break;
168
- default:
169
- const routeHandler = route;
170
- this._app[routeHandler.method](route.pattern, (res, req) => {
171
- res.redirect = (url, code = 307) => this.constructor._redirect(res, req, url, code);
172
- req.cookies = cookieParse.cookieParse(req.getHeader("cookie"));
173
- Promise.race([
174
- this._abortTimeout(res, req),
175
- this._createHandler(res, req, routeHandler.handler)
176
- ]);
177
- });
178
- }
179
- }
180
- this._app.listen(ip, this._port, (listenSocket) => {
181
- fn(listenSocket);
182
- if (listenSocket) {
183
- this._socket = listenSocket;
184
- if (this._mode === "development") {
185
- ["info"].includes(this._logLevel) && console.log(`Listening ${this._protocol}://${this._host}:${this._port}`);
186
- }
187
- } else {
188
- ["info", "warn", "error"].includes(this._logLevel) && console.error(`Error start server on ${this._protocol}://${this._host}:${this._port}`);
189
- }
190
- });
191
- });
192
- return this;
193
- }
194
- async close() {
195
- if (this._socket) {
196
- await uws__default["default"].us_listen_socket_close(this._socket);
197
- while (true) {
198
- await new Promise((resolve) => setTimeout(resolve, 50));
199
- if (await this.socketPort() < 0) {
200
- break;
201
- }
202
- }
203
- this._socket = null;
204
- }
205
- return this;
206
- }
207
- async socketPort() {
208
- if (!this._socket) {
209
- return -1;
210
- }
211
- return uws__default["default"].us_socket_local_port(this._socket);
212
- }
213
- _createHandler(res, req, fn) {
214
- return new Promise(async (resolve) => {
215
- const end = () => {
216
- clearTimeout(this._timeoutId);
217
- resolve();
218
- };
219
- try {
220
- const next = (param, code = 307) => {
221
- if (typeof param === "boolean") {
222
- req.setYield(param);
223
- }
224
- if (param instanceof Error) {
225
- throw param;
226
- }
227
- if (typeof param === "string") {
228
- res.redirect(param, code);
229
- }
230
- end();
231
- };
232
- const result = fn(res, req, next);
233
- if (result instanceof Promise) {
234
- next(await result);
235
- }
236
- } catch (e) {
237
- ["info", "warn", "error"].includes(this._logLevel) && console.error(e);
238
- const body = this._mode === "development" ? e.message : "";
239
- try {
240
- res.writeStatus("404 Not Found").end(body);
241
- } catch (e2) {
242
- }
243
- end();
244
- }
245
- });
246
- }
247
- static _redirect(res, req, url, code = 307) {
248
- let status2 = "307 Temporary Redirect";
249
- if (code === 301) {
250
- status2 = "301 Moved Permanently";
251
- }
252
- res.writeStatus(status2).writeHeader("location", url).end();
253
- }
254
- _abortTimeout(res, req) {
255
- return new Promise((resolve) => {
256
- if (this._timeout && !req.getHeader("x-no-timeout")) {
257
- this._timeoutId = setTimeout(() => {
258
- try {
259
- res.writeStatus("408 Request Timeout").end();
260
- resolve();
261
- } catch (e) {
262
- }
263
- }, this._timeout);
264
- }
265
- });
266
- }
267
- _lookup(host, resolve) {
268
- dns__default["default"].lookup(this._host, (err, addresses) => {
269
- if (err) {
270
- ["info", "warn", "error"].includes(this._logLevel) && console.log(`${this._host} error: ${err.message}`);
271
- } else {
272
- resolve(Buffer.from(addresses));
273
- }
274
- });
275
- }
276
- }
277
-
278
- class Jwt {
279
- constructor(secret, opt) {
280
- this.algorithm = "SHA256";
281
- this.secret = secret;
282
- this.algorithm = opt?.algorithm || this.algorithm;
283
- this.algorithm = this.algorithm.replace("-", "");
284
- }
285
- verify(jwt) {
286
- if (!jwt) {
287
- return false;
288
- }
289
- const parts = jwt.split(".");
290
- const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${parts[0]}.${parts[1]}`).digest("base64"));
291
- return signature === parts[2];
292
- }
293
- sign(data) {
294
- const head = decoders.toBase64url({
295
- alg: this.algorithm.replace("SHA", "HS"),
296
- typ: "JWT"
297
- });
298
- const body = decoders.toBase64url(data);
299
- const signature = decoders.urlEncode(crypto__default["default"].createHmac(this.algorithm, this.secret).update(`${head}.${body}`).digest("base64"));
300
- return `${head}.${body}.${signature}`;
301
- }
302
- decode(jwt) {
303
- const parts = (jwt || "").split(".");
304
- const head = decoders.fromBase64url(parts[0]);
305
- const body = decoders.fromBase64url(parts[1]);
306
- return { head, body };
307
- }
308
- }
309
-
310
- const { subtle } = crypto.webcrypto;
311
- class AsyncJwt {
312
- constructor(secret, opt) {
313
- this.algorithm = "SHA-256";
314
- this.secret = secret;
315
- this.algorithm = opt?.algorithm || this.algorithm;
316
- this.algorithm = this.algorithm.replace("-", "").replace("SHA", "SHA-");
317
- }
318
- async verify(jwt) {
319
- if (!jwt) {
320
- return false;
321
- }
322
- const parts = jwt.split(".");
323
- const signature = await this.signString(`${parts[0]}.${parts[1]}`);
324
- return signature === parts[2];
325
- }
326
- async sign(data) {
327
- const head = decoders.toBase64url({
328
- alg: this.algorithm.replace("-", "").replace("SHA", "HS"),
329
- typ: "JWT"
330
- });
331
- const body = decoders.toBase64url(data);
332
- const signature = await this.signString(`${head}.${body}`);
333
- return `${head}.${body}.${signature}`;
334
- }
335
- decode(jwt) {
336
- const parts = (jwt || "").split(".");
337
- const head = decoders.fromBase64url(parts[0]);
338
- const body = decoders.fromBase64url(parts[1]);
339
- return { head, body };
340
- }
341
- async signString(str) {
342
- const enc = new util.TextEncoder();
343
- const key = await subtle.importKey("raw", enc.encode(this.secret), {
344
- name: "HMAC",
345
- hash: {
346
- name: this.algorithm
347
- }
348
- }, false, ["sign", "verify"]);
349
- return decoders.urlEncode(Buffer.from(await subtle.sign("HMAC", key, enc.encode(str))).toString("base64"));
350
- }
351
- }
352
-
353
- const jwtDecode = (jwt) => {
354
- const parts = (jwt || "").split(".");
355
- const head = decoders.fromBase64url(parts[0]);
356
- const body = decoders.fromBase64url(parts[1]);
357
- return { head, body };
358
- };
359
-
360
- class Memcached {
361
- constructor(memjs, specialHeaders = { "x-cache": "memcached-js" }, maxKeyLength = 160, debug = 0) {
362
- this.prefix = "";
363
- this.memjs = memjs;
364
- this.specialHeaders = specialHeaders;
365
- this.maxKeyLength = maxKeyLength;
366
- this.debug = debug;
367
- this.prefix = process.env.NODE_ENV !== "production" ? "dev::" : "";
368
- }
369
- isClient() {
370
- return !!this.memjs;
371
- }
372
- isConnectedServers() {
373
- if (!this.isClient()) {
374
- return false;
375
- }
376
- const servers = this.memjs?.servers || [];
377
- for (const server of servers) {
378
- if (server.connected) {
379
- return true;
380
- }
381
- }
382
- return false;
383
- }
384
- async setValue(key, value, expires) {
385
- if ((expires || expires === 0) && key.length <= this.maxKeyLength && this.memjs) {
386
- try {
387
- await this.memjs.set(`${this.prefix}${key}`, Buffer.from(value), { expires });
388
- } catch (e) {
389
- if (this.debug) {
390
- console.log(e);
391
- }
392
- }
393
- }
394
- }
395
- async getValue(key) {
396
- if (key.length <= this.maxKeyLength && this.memjs) {
397
- try {
398
- const obj = await this.memjs.get(`${this.prefix}${key}`);
399
- const result = typeof obj === "object" ? obj?.value : obj;
400
- if (!result) {
401
- return null;
402
- }
403
- return result;
404
- } catch (e) {
405
- if (this.debug) {
406
- console.log(e);
407
- }
408
- }
409
- }
410
- return null;
411
- }
412
- async deleteValue(key) {
413
- if (key.length <= this.maxKeyLength && this.memjs) {
414
- try {
415
- return this.memjs.delete(`${this.prefix}${key}`);
416
- } catch (e) {
417
- if (this.debug) {
418
- console.log(e);
419
- }
420
- }
421
- }
422
- return false;
423
- }
424
- async setPage(url, headers, data, expires) {
425
- if ((expires || expires === 0) && url.length <= this.maxKeyLength && this.memjs) {
426
- try {
427
- headers = this.objectKeysToLower(headers);
428
- delete headers["set-cookie"];
429
- const headersString = Object.entries(headers).map((v) => v.join(":")).join("\r\n");
430
- const memjsHeaders = "EXTRACT_HEADERS\r\n" + headersString + "\r\n\r\n";
431
- const toMamcache = Buffer.concat([Buffer.from(memjsHeaders), Buffer.from(data)]);
432
- const key = /^http/.test(url) ? url : `${this.prefix}${url}`;
433
- await this.memjs.set(key, toMamcache, { expires });
434
- } catch (e) {
435
- if (this.debug) {
436
- console.log(e);
437
- }
438
- }
439
- }
440
- }
441
- async getPage(url) {
442
- if (url.length <= this.maxKeyLength && this.memjs) {
443
- try {
444
- let headers = {};
445
- const key = /^http/.test(url) ? url : `${this.prefix}${url}`;
446
- const obj = await this.memjs.get(key);
447
- const result = typeof obj === "object" ? obj?.value : obj;
448
- if (!result) {
449
- return null;
450
- }
451
- const memData = Buffer.from(result);
452
- const start = memData.indexOf(Buffer.from("EXTRACT_HEADERS\r\n"));
453
- const end = memData.indexOf(Buffer.from("\r\n\r\n"));
454
- if (start < 0 || end < 0) {
455
- return null;
456
- }
457
- const arr = memData.subarray(start, end).toString().split("\r\n");
458
- arr.shift();
459
- arr.map((row) => {
460
- const [index, value] = row.split(":");
461
- headers[index] = value;
462
- });
463
- headers = Object.assign(headers, this.specialHeaders);
464
- const data = memData.subarray(end + 4);
465
- return { headers, data };
466
- } catch (e) {
467
- if (this.debug) {
468
- console.log(e);
469
- }
470
- }
471
- }
472
- return null;
473
- }
474
- objectKeysToLower(o) {
475
- return Object.keys(o).reduce((c, k) => (c[k.toLowerCase()] = o[k], c), {});
476
- }
477
- }
478
-
479
- const jsonBody = (res) => new Promise((resolve, reject) => {
480
- readJson(res, (obj) => resolve(obj), () => {
481
- reject(new ApiError.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
482
- });
483
- });
484
- function readJson(res, cb, err) {
485
- let buffer = Buffer.from([]);
486
- res.onData((ab, isLast) => {
487
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
488
- if (isLast) {
489
- try {
490
- cb(JSON.parse(buffer.toString()));
491
- } catch (e) {
492
- cb({});
493
- }
494
- }
495
- });
496
- res.onAborted(err);
497
- }
498
-
499
- const rawBody = (res) => new Promise((resolve, reject) => {
500
- readRaw(res, (obj) => resolve(obj), () => {
501
- reject(new ApiError.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
502
- });
503
- });
504
- function readRaw(res, cb, err) {
505
- let buffer = Buffer.from([]);
506
- res.onData((ab, isLast) => {
507
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
508
- isLast && cb(buffer);
509
- });
510
- res.onAborted(err);
511
- }
512
-
513
- const streamBody = (res, req, resume = true) => {
514
- res.onAborted(() => new ApiError.ApiError({ message: "Connection aborted", code: 1, statusCode: 404 }));
515
- const stream = new stream$1.PassThrough();
516
- stream.headers = {};
517
- req.forEach((key, val) => stream.headers[key] = val);
518
- res.onData((chunk, isLast) => {
519
- stream.write(Buffer.from(Buffer.from(chunk)));
520
- resume && stream.resume();
521
- isLast && stream.end();
522
- });
523
- return stream;
524
- };
525
-
526
- const urlencodedBody = (res) => new Promise((resolve, reject) => {
527
- readBody(res, (obj) => resolve(obj), () => {
528
- reject(new ApiError.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 }));
529
- });
530
- });
531
- function readBody(res, cb, err) {
532
- let buffer = Buffer.from([]);
533
- res.onData((ab, isLast) => {
534
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
535
- if (isLast) {
536
- try {
537
- cb(querystring__default["default"].parse(buffer.toString()));
538
- } catch (e) {
539
- cb({});
540
- }
541
- }
542
- });
543
- res.onAborted(err);
544
- }
545
-
546
- const multipartBody = (res, req, options = { multiples: true }) => new Promise(async (resolve, reject) => {
547
- const err = new ApiError.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
548
- res.onAborted(() => err);
549
- try {
550
- const stream = new stream$1.PassThrough();
551
- stream.headers = {};
552
- req.forEach((key, val) => stream.headers[key] = val);
553
- res.onData((chunk, isLast) => {
554
- stream.write(Buffer.from(Buffer.from(chunk)));
555
- stream.resume();
556
- isLast && stream.end();
557
- });
558
- const form = formidable__default["default"](options);
559
- const adapter = (row) => ({
560
- size: row.size,
561
- path: row.filepath,
562
- name: row.originalFilename,
563
- type: row.mimetype,
564
- mtime: row.mtime,
565
- newFilename: row.newFilename
566
- });
567
- form.parse(stream, (err2, fields, files) => {
568
- err2 && reject(err2);
569
- const output = {};
570
- Object.keys(files).map((key) => {
571
- output[key] = Array.isArray(files[key]) ? files[key].map((row) => adapter(row)) : adapter(files[key]);
572
- });
573
- fields.files = output;
574
- resolve(fields);
575
- });
576
- } catch (e) {
577
- reject(err);
578
- }
579
- });
580
-
581
- const readConfig = async (jsonfile) => {
582
- const file = path__default["default"].resolve(jsonfile);
583
- return JSON.parse(await fs.promises.readFile(file, "utf-8"));
584
- };
585
-
586
- const readConfigSync = (jsonfile) => {
587
- const file = path__default["default"].resolve(jsonfile);
588
- return JSON.parse(fs__default["default"].readFileSync(file, "utf-8"));
589
- };
590
-
591
- const cookieString = (name, value, options = {}) => {
592
- options = {
593
- path: "/",
594
- ...options
595
- };
596
- if (options.expires instanceof Date) {
597
- options.expires = options.expires.toUTCString();
598
- }
599
- let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
600
- for (const optionKey in options) {
601
- updatedCookie += "; " + optionKey;
602
- const optionValue = options[optionKey];
603
- if (optionValue !== true) {
604
- updatedCookie += "=" + optionValue;
605
- }
606
- }
607
- return updatedCookie;
608
- };
609
-
610
- const exts = {
611
- "3gp": "video/3gpp",
612
- "a": "application/octet-stream",
613
- "ai": "application/postscript",
614
- "aif": "audio/x-aiff",
615
- "aiff": "audio/x-aiff",
616
- "asc": "application/pgp-signature",
617
- "asf": "video/x-ms-asf",
618
- "asm": "text/x-asm",
619
- "asx": "video/x-ms-asf",
620
- "atom": "application/atom+xml",
621
- "au": "audio/basic",
622
- "avi": "video/x-msvideo",
623
- "bat": "application/x-msdownload",
624
- "bin": "application/octet-stream",
625
- "bmp": "image/bmp",
626
- "bz2": "application/x-bzip2",
627
- "c": "text/x-c",
628
- "cab": "application/vnd.ms-cab-compressed",
629
- "cc": "text/x-c",
630
- "chm": "application/vnd.ms-htmlhelp",
631
- "class": "application/octet-stream",
632
- "com": "application/x-msdownload",
633
- "conf": "text/plain",
634
- "cpp": "text/x-c",
635
- "crt": "application/x-x509-ca-cert",
636
- "css": "text/css",
637
- "csv": "text/csv",
638
- "cxx": "text/x-c",
639
- "deb": "application/x-debian-package",
640
- "der": "application/x-x509-ca-cert",
641
- "diff": "text/x-diff",
642
- "djv": "image/vnd.djvu",
643
- "djvu": "image/vnd.djvu",
644
- "dll": "application/x-msdownload",
645
- "dmg": "application/octet-stream",
646
- "doc": "application/msword",
647
- "dot": "application/msword",
648
- "dtd": "application/xml-dtd",
649
- "dvi": "application/x-dvi",
650
- "ear": "application/java-archive",
651
- "eml": "message/rfc822",
652
- "eps": "application/postscript",
653
- "exe": "application/x-msdownload",
654
- "f": "text/x-fortran",
655
- "f77": "text/x-fortran",
656
- "f90": "text/x-fortran",
657
- "flv": "video/x-flv",
658
- "for": "text/x-fortran",
659
- "gem": "application/octet-stream",
660
- "gemspec": "text/x-script.ruby",
661
- "gif": "image/gif",
662
- "gz": "application/x-gzip",
663
- "h": "text/x-c",
664
- "hh": "text/x-c",
665
- "htm": "text/html",
666
- "html": "text/html",
667
- "ico": "image/vnd.microsoft.icon",
668
- "ics": "text/calendar",
669
- "ifb": "text/calendar",
670
- "iso": "application/octet-stream",
671
- "jar": "application/java-archive",
672
- "java": "text/x-java-source",
673
- "jnlp": "application/x-java-jnlp-file",
674
- "jpeg": "image/jpeg",
675
- "jpg": "image/jpeg",
676
- "js": "application/javascript",
677
- "json": "application/json",
678
- "log": "text/plain",
679
- "m3u": "audio/x-mpegurl",
680
- "m4v": "video/mp4",
681
- "man": "text/troff",
682
- "mathml": "application/mathml+xml",
683
- "mbox": "application/mbox",
684
- "mdoc": "text/troff",
685
- "me": "text/troff",
686
- "mid": "audio/midi",
687
- "midi": "audio/midi",
688
- "mime": "message/rfc822",
689
- "mml": "application/mathml+xml",
690
- "mng": "video/x-mng",
691
- "mov": "video/quicktime",
692
- "mp3": "audio/mpeg",
693
- "mp4": "video/mp4",
694
- "mp4v": "video/mp4",
695
- "mpeg": "video/mpeg",
696
- "mpg": "video/mpeg",
697
- "ms": "text/troff",
698
- "msi": "application/x-msdownload",
699
- "odp": "application/vnd.oasis.opendocument.presentation",
700
- "ods": "application/vnd.oasis.opendocument.spreadsheet",
701
- "odt": "application/vnd.oasis.opendocument.text",
702
- "ogg": "application/ogg",
703
- "p": "text/x-pascal",
704
- "pas": "text/x-pascal",
705
- "pbm": "image/x-portable-bitmap",
706
- "pdf": "application/pdf",
707
- "pem": "application/x-x509-ca-cert",
708
- "pgm": "image/x-portable-graymap",
709
- "pgp": "application/pgp-encrypted",
710
- "pkg": "application/octet-stream",
711
- "pl": "text/x-script.perl",
712
- "pm": "text/x-script.perl-module",
713
- "png": "image/png",
714
- "pnm": "image/x-portable-anymap",
715
- "ppm": "image/x-portable-pixmap",
716
- "pps": "application/vnd.ms-powerpoint",
717
- "ppt": "application/vnd.ms-powerpoint",
718
- "ps": "application/postscript",
719
- "psd": "image/vnd.adobe.photoshop",
720
- "py": "text/x-script.python",
721
- "qt": "video/quicktime",
722
- "ra": "audio/x-pn-realaudio",
723
- "rake": "text/x-script.ruby",
724
- "ram": "audio/x-pn-realaudio",
725
- "rar": "application/x-rar-compressed",
726
- "rb": "text/x-script.ruby",
727
- "rdf": "application/rdf+xml",
728
- "roff": "text/troff",
729
- "rpm": "application/x-redhat-package-manager",
730
- "rss": "application/rss+xml",
731
- "rtf": "application/rtf",
732
- "ru": "text/x-script.ruby",
733
- "s": "text/x-asm",
734
- "sgm": "text/sgml",
735
- "sgml": "text/sgml",
736
- "sh": "application/x-sh",
737
- "sig": "application/pgp-signature",
738
- "snd": "audio/basic",
739
- "so": "application/octet-stream",
740
- "svg": "image/svg+xml",
741
- "svgz": "image/svg+xml",
742
- "swf": "application/x-shockwave-flash",
743
- "t": "text/troff",
744
- "tar": "application/x-tar",
745
- "tbz": "application/x-bzip-compressed-tar",
746
- "tcl": "application/x-tcl",
747
- "tex": "application/x-tex",
748
- "texi": "application/x-texinfo",
749
- "texinfo": "application/x-texinfo",
750
- "text": "text/plain",
751
- "tif": "image/tiff",
752
- "tiff": "image/tiff",
753
- "torrent": "application/x-bittorrent",
754
- "tr": "text/troff",
755
- "txt": "text/plain",
756
- "vcf": "text/x-vcard",
757
- "vcs": "text/x-vcalendar",
758
- "vrml": "model/vrml",
759
- "war": "application/java-archive",
760
- "wav": "audio/x-wav",
761
- "webp": "image/webp",
762
- "wma": "audio/x-ms-wma",
763
- "wmv": "video/x-ms-wmv",
764
- "wmx": "video/x-ms-wmx",
765
- "wrl": "model/vrml",
766
- "wsdl": "application/wsdl+xml",
767
- "xbm": "image/x-xbitmap",
768
- "xhtml": "application/xhtml+xml",
769
- "xls": "application/vnd.ms-excel",
770
- "xml": "application/xml",
771
- "xpm": "image/x-xpixmap",
772
- "xsl": "application/xml",
773
- "xslt": "application/xslt+xml",
774
- "yaml": "text/yaml",
775
- "yml": "text/yaml",
776
- "zip": "application/zip",
777
- "ttf": "application/x-font-ttf",
778
- "woff": "application/x-font-woff",
779
- "woff2": "application/x-font-woff2"
780
- };
781
- const extensions = Object.keys(exts);
782
- const getExt = (path2) => path2.split(".").pop();
783
- const getContentType = (ext) => exts[ext.toLowerCase()] || "application/octet-stream";
784
- async function staticBody(res, req, base) {
785
- try {
786
- res.onAborted(() => new ApiError.ApiError({
787
- message: "Requers is aborted",
788
- code: 1,
789
- statusCode: 404
790
- }));
791
- let url = req.getUrl().replace(/\.\.\//ig, "").replace(/^\.\/?/, "");
792
- url = `./${url}`;
793
- const file = path__default["default"].resolve(base, url);
794
- const content = await fs.promises.readFile(file);
795
- res.writeStatus("200 OK").writeHeader("content-type", getContentType(getExt(url))).end(content);
796
- } catch (e) {
797
- res.writeStatus("404 Not Found").end(e.message);
798
- }
799
- }
800
-
801
- const readJsonConfigsSync = (configs, input = {}) => {
802
- for (const config of configs) {
803
- const filePath = path__namespace.resolve(config);
804
- Object.assign(input, JSON.parse(fs__namespace.readFileSync(filePath).toString()));
805
- }
806
- return input;
807
- };
808
-
809
- class Ssr {
810
- constructor(res, req, context, entry) {
811
- this.res = res;
812
- this.req = req;
813
- this.context = context;
814
- this.entry = entry;
815
- }
816
- async request(request = {}) {
817
- this.res.onAborted(() => {
818
- console.log("Abort is SSR handler");
819
- });
820
- const query = this.req.getQuery();
821
- const url = this.req.getUrl() + (query ? `?${query}` : "");
822
- const extension = getExt(url);
823
- if (extensions.includes(extension)) {
824
- await staticBody(this.res, this.req, "./dist/client");
825
- return;
826
- }
827
- const contextSsr = {
828
- hostname: this.req.getHeader("host"),
829
- protocol: this.req.getHeader("x-forwarded-proto") || "http",
830
- url: this.req.getUrl(),
831
- cookies: cookieParse.cookieParse(this.req.getHeader("cookie")),
832
- ip: this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],
833
- memcache: null,
834
- statusCode: 200,
835
- headers: {},
836
- responseHeaders: {
837
- "content-type": "text/html; charset=utf-8"
838
- }
839
- };
840
- this.req.forEach((key2, value) => contextSsr.headers[key2] = value);
841
- const key = `${contextSsr.protocol}://${contextSsr.hostname}${contextSsr.url}`;
842
- let html, page = null;
843
- if (this.context.memcached) {
844
- page = await this.context.memcached.getPage(key);
845
- }
846
- if (page) {
847
- html = page.data.toString();
848
- contextSsr.headers = page.headers;
849
- } else {
850
- ({ html } = await this.entry(url, {
851
- manifest: this.context.manifest,
852
- res: this.res,
853
- req: this.req,
854
- context: contextSsr
855
- }));
856
- if (contextSsr.statusCode === 200 && this.context.memcached) {
857
- await this.context.memcached.setPage(key, contextSsr.headers, html, contextSsr.memcache);
858
- }
859
- }
860
- this.res.writeStatus(codeToStatus(contextSsr.statusCode));
861
- Object.keys(contextSsr.headers).map((key2) => this.res.writeHeader(key2, contextSsr.headers[key2]));
862
- this.res.end(html);
863
- }
864
- }
865
-
866
- const selectRouteController = async (db, name, subaction) => {
867
- return (await db.poolQuery({ sql: `
1
+ "use strict";var h=require("./ApiError.js"),_=require("./Server.js"),g=require("./Jwt-CDdbxwvH.js"),k=require("crypto"),Q=require("util"),v=require("./Memcached.js"),E=require("./jsonBody.js"),$=require("stream"),H=require("./urlencodedBody.js"),R=require("./multipartBody.js"),U=require("./readConfig.js"),V=require("./readConfigSync.js"),P=require("./cookieParse.js"),W=require("./cookieString.js"),y=require("./staticBody.js"),X=require("fs"),B=require("path"),S=require("easy-ash"),z=require("querystring"),C=require("xml-js"),G=require("os");require("reflect-metadata"),require("dns"),require("uWebSockets.js"),require("formidable");function O(o){var t=Object.create(null);return o&&Object.keys(o).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return o[e]}})}}),t.default=o,Object.freeze(t)}var M=O(X),Y=O(B),Z=O(G);const{subtle:N}=k.webcrypto;class ee{constructor(t,e){this.algorithm="SHA-256",this.secret=t,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(t){if(!t)return!1;const e=t.split(".");return await this.signString(`${e[0]}.${e[1]}`)===e[2]}async sign(t){const e=g.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=g.toBase64url(t),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=g.fromBase64url(e[0]),i=g.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new Q.TextEncoder,s=await N.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return g.urlEncode(Buffer.from(await N.sign("HMAC",s,e.encode(t))).toString("base64"))}}const te=o=>{const t=(o||"").split("."),e=g.fromBase64url(t[0]),s=g.fromBase64url(t[1]);return{head:e,body:s}},j=o=>new Promise((t,e)=>{se(o,s=>t(s),()=>{e(new h.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function se(o,t,e){let s=Buffer.from([]);o.onData((i,n)=>{s=Buffer.concat([s,Buffer.from(i)]),n&&t(s)}),o.onAborted(e)}const A=(o,t,e=!0)=>{o.onAborted(()=>new h.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new $.PassThrough;return s.headers={},t.forEach((i,n)=>s.headers[i]=n),o.onData((i,n)=>{s.write(Buffer.from(Buffer.from(i))),e&&s.resume(),n&&s.end()}),s},oe=(o,t={})=>{for(const e of o){const s=Y.resolve(e);Object.assign(t,JSON.parse(M.readFileSync(s).toString()))}return t};class ie{constructor(t,e,s,i){this.res=t,this.req=e,this.context=s,this.entry=i}async request(t={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),i=y.getExt(s);if(y.extensions.includes(i)){await y.staticBody(this.res,this.req,"./dist/client");return}const n={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:P.cookieParse(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,m)=>n.headers[c]=m);const a=`${n.protocol}://${n.hostname}${n.url}`;let r,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(a)),u?(r=u.data.toString(),n.headers=u.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:n}),n.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,n.headers,r,n.memcache)),this.res.writeStatus(_.codeToStatus(n.statusCode)),Object.keys(n.headers).map(c=>this.res.writeHeader(c,n.headers[c])),this.res.end(r)}}const ne=async(o,t,e)=>(await o.poolQuery({sql:`
868
2
  SELECT c.id AS controller_id,
869
3
  c.name AS controller_name,
870
4
  c.is_active AS controller_is_active,
@@ -883,10 +17,7 @@ const selectRouteController = async (db, name, subaction) => {
883
17
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
884
18
  LEFT JOIN app_actions a ON a.id = s.app_actions_id
885
19
  WHERE c.name = :name AND s.name = :subaction
886
- `, namedPlaceholders: true }, { name, subaction }))?.[0];
887
- };
888
- const selectAll = async (db) => {
889
- const rows = await db.poolQuery(`
20
+ `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],re=async o=>(await o.poolQuery(`
890
21
  SELECT c.id AS controller_id,
891
22
  c.name AS controller_name,
892
23
  c.is_active AS controller_is_active,
@@ -904,799 +35,7 @@ const selectAll = async (db) => {
904
35
  FROM app_controllers c
905
36
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
906
37
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
907
- `);
908
- return rows.reduce((ac, row) => {
909
- ac[`${row.controller_name}::${row.subaction_name}`] = row;
910
- return ac;
911
- }, {});
912
- };
913
- const selectRouteControllerMemcached = async (db, name, subaction, memcached, memcachedPrefix = "", expires = 3600) => {
914
- const key = `${memcachedPrefix}::routes::controllers`;
915
- const index = `${name}::${subaction}`;
916
- const schema = await memcached.getValue(key);
917
- if (schema) {
918
- const json = JSON.parse(schema.toString());
919
- return (json || {}).hasOwnProperty(index) ? json[index] : void 0;
920
- } else {
921
- const all = await selectAll(db);
922
- await memcached.setValue(key, Buffer.from(JSON.stringify(all)), expires);
923
- return (all || {}).hasOwnProperty(index) ? all[index] : void 0;
924
- }
925
- };
926
- const selectControllerParams = async (db, method, name, subaction, memcached, memcachedPrefix = "", expires = 3600) => {
927
- let row;
928
- if (memcached && memcached.isClient() && memcached.isConnectedServers()) {
929
- row = await selectRouteControllerMemcached(db, name, subaction, memcached, memcachedPrefix, expires);
930
- } else {
931
- row = await selectRouteController(db, name, subaction);
932
- }
933
- if (!row) {
934
- throw new ApiError.ApiError({
935
- statusCode: 404,
936
- code: 11,
937
- message: `Controller ${name} not found in site schema`
938
- });
939
- }
940
- const allowMethods = (row?.action_method || "").split(",").map((method2) => method2.trim());
941
- if (row.controller_is_active !== 1) {
942
- throw new ApiError.ApiError({
943
- statusCode: 404,
944
- code: 11,
945
- message: `Controller ${name} not active in site schema`
946
- });
947
- }
948
- if (!row.action_id) {
949
- throw new ApiError.ApiError({
950
- statusCode: 404,
951
- code: 11,
952
- message: `Action not found in site schema`
953
- });
954
- }
955
- if (row.action_is_active !== 1) {
956
- throw new ApiError.ApiError({
957
- statusCode: 404,
958
- code: 11,
959
- message: `Action ${row.action_name} not active in site schema`
960
- });
961
- }
962
- if (!row.subaction_id) {
963
- throw new ApiError.ApiError({
964
- statusCode: 404,
965
- code: 11,
966
- message: `Subaction ${subaction} not found in site schema`
967
- });
968
- }
969
- if (row.subaction_is_active !== 1) {
970
- throw new ApiError.ApiError({
971
- statusCode: 404,
972
- code: 11,
973
- message: `Subaction ${subaction} not active in site schema`
974
- });
975
- }
976
- if (row.subaction_is_check_method !== 0) {
977
- if (row.action_method !== "any" && !allowMethods.includes(method)) {
978
- throw new ApiError.ApiError({
979
- statusCode: 404,
980
- code: 11,
981
- message: `Controller ${name} action ${row.action_name} allow only ${row.action_method} method`
982
- });
983
- }
984
- }
985
- return {
986
- controller: {
987
- id: +row.controller_id,
988
- name: row.controller_name,
989
- isActive: !!row.controller_is_active,
990
- isSitemap: !!row.controller_is_sitemap
991
- },
992
- action: {
993
- id: +row.action_id,
994
- name: row.action_name,
995
- isActive: !!row.action_is_active,
996
- method: row.action_method
997
- },
998
- subaction: {
999
- id: +row.subaction_id,
1000
- name: row.subaction_name,
1001
- isPermission: !!row.subaction_is_permission,
1002
- isCheckMethod: !!row.subaction_is_check_method,
1003
- isLog: !!row.subaction_is_log,
1004
- isActive: !!row.subaction_is_active,
1005
- isSync: false
1006
- }
1007
- };
1008
- };
1009
-
1010
- const schemaControllerParams = (schema, method, name, subaction) => {
1011
- let controllerRow = schema.controllers.find((row) => row.name === name);
1012
- if (!controllerRow) {
1013
- throw new ApiError.ApiError({
1014
- statusCode: 404,
1015
- code: 11,
1016
- message: `Controller ${name} not found is site schema`
1017
- });
1018
- }
1019
- controllerRow = Object.assign({
1020
- isActive: true,
1021
- isSitemap: false
1022
- }, controllerRow);
1023
- if (!controllerRow.isActive) {
1024
- throw new ApiError.ApiError({
1025
- statusCode: 404,
1026
- code: 11,
1027
- message: `Controller ${name} not active is site schema`
1028
- });
1029
- }
1030
- let subactionRow = controllerRow.subactions.find((row) => row.name === subaction);
1031
- if (!subactionRow) {
1032
- throw new ApiError.ApiError({
1033
- statusCode: 404,
1034
- code: 11,
1035
- message: `Subaction ${subaction} not found is site schema`
1036
- });
1037
- }
1038
- subactionRow = Object.assign({
1039
- isPermission: false,
1040
- isCheckMethod: false,
1041
- isLog: false,
1042
- isActive: true
1043
- }, subactionRow);
1044
- if (!subactionRow.isActive) {
1045
- throw new ApiError.ApiError({
1046
- statusCode: 404,
1047
- code: 11,
1048
- message: `Subaction ${subaction} not active is site schema`
1049
- });
1050
- }
1051
- let actionRow = schema.actions.find((row) => row.name === subactionRow.action);
1052
- if (!actionRow) {
1053
- throw new ApiError.ApiError({
1054
- statusCode: 404,
1055
- code: 11,
1056
- message: `Action not found is site schema`
1057
- });
1058
- }
1059
- actionRow = Object.assign({
1060
- isActive: true,
1061
- method: "any"
1062
- }, actionRow);
1063
- if (!actionRow.isActive) {
1064
- throw new ApiError.ApiError({
1065
- statusCode: 404,
1066
- code: 11,
1067
- message: `Action ${actionRow.name} not active is site schema`
1068
- });
1069
- }
1070
- const allowMethods = (actionRow?.method || "").split(",").map((method2) => method2.trim());
1071
- if (subactionRow.isCheckMethod) {
1072
- if (actionRow.method !== "any" && !allowMethods.includes(method)) {
1073
- throw new ApiError.ApiError({
1074
- statusCode: 404,
1075
- code: 11,
1076
- message: `Controller ${name} action ${actionRow.name} allow only ${actionRow.method} method`
1077
- });
1078
- }
1079
- }
1080
- return {
1081
- controller: {
1082
- id: controllerRow.id,
1083
- name: controllerRow.name,
1084
- isActive: controllerRow.isActive,
1085
- isSitemap: controllerRow.isSitemap
1086
- },
1087
- subaction: {
1088
- id: subactionRow.id,
1089
- name: subactionRow.name,
1090
- isPermission: subactionRow.isPermission,
1091
- isCheckMethod: subactionRow.isCheckMethod,
1092
- isLog: subactionRow.isLog,
1093
- isActive: subactionRow.isActive,
1094
- isSync: !!subactionRow.isSync
1095
- },
1096
- action: {
1097
- id: actionRow.id,
1098
- name: actionRow.name,
1099
- isActive: actionRow.isActive,
1100
- method: actionRow.method
1101
- }
1102
- };
1103
- };
1104
-
1105
- class Web {
1106
- constructor(res, req, context) {
1107
- this.defaultRequest = {
1108
- lang: "ru"
1109
- };
1110
- this.defaultResponse = {
1111
- statusCode: 200,
1112
- headers: { "content-type": "application/json" },
1113
- body: {}
1114
- };
1115
- this.defaultControllerSubaction = {
1116
- controller: "Index",
1117
- subaction: "index"
1118
- };
1119
- this.res = res;
1120
- this.req = req;
1121
- this.res.onAborted(() => new ApiError.ApiError({ message: "The connection was close", code: 1, statusCode: 404 }));
1122
- this.context = context;
1123
- }
1124
- setDefaultRequest(params) {
1125
- Object.assign(this.defaultRequest, params);
1126
- return this;
1127
- }
1128
- async request(input = {}) {
1129
- let response = {};
1130
- try {
1131
- const query = this.req.getQuery();
1132
- const request = Object.assign({}, this.defaultRequest, input, querystring__default["default"].parse(this.req.getQuery()));
1133
- this.contextWeb = {
1134
- config: this.context.config,
1135
- db: this.context.db,
1136
- method: this.req.getMethod(),
1137
- cookies: this.req.cookies,
1138
- hostname: this.req.getHeader("host"),
1139
- protocol: this.req.getHeader("x-forwarded-proto") || "http",
1140
- url: this.req.getUrl() + (query ? `?${query}` : ""),
1141
- headers: {},
1142
- stack: this.context.stack || {},
1143
- getRequest: () => request
1144
- };
1145
- this.memcachedKey = `${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`;
1146
- this.req.forEach((key, value) => this.contextWeb.headers[key] = value);
1147
- const type = this.contextWeb.headers["content-type"] || "application/json";
1148
- if (request.controller && request.subaction && this.context.schema) {
1149
- this.route = this.findRoute(request.controller);
1150
- Object.defineProperty(this.contextWeb, "$route", {
1151
- enumerable: false,
1152
- configurable: false,
1153
- writable: false,
1154
- value: this.route
1155
- });
1156
- Object.assign(this.contextWeb, schemaControllerParams(this.context.schema, this.contextWeb.method, this.route.name, request.subaction));
1157
- if (this.contextWeb.subaction.isSync) {
1158
- if (!["get", "head"].includes(this.contextWeb.method)) {
1159
- Object.defineProperty(this.contextWeb, "$stream", {
1160
- enumerable: false,
1161
- configurable: false,
1162
- writable: false,
1163
- value: streamBody(this.res, this.req, false)
1164
- });
1165
- }
1166
- const controllerClass2 = this.importControllerSync(request.controller);
1167
- const controller2 = new controllerClass2();
1168
- this.injectContext(controller2);
1169
- if (request.subaction in controller2) {
1170
- response = await controller2[request.subaction]();
1171
- } else {
1172
- throw new ApiError.ApiError({
1173
- statusCode: 404,
1174
- code: 13,
1175
- message: `Method ${request.subaction} not found in ${request.controller} route`
1176
- });
1177
- }
1178
- response = Object.assign({}, this.defaultResponse, response);
1179
- this.success(response);
1180
- return;
1181
- }
1182
- }
1183
- if (["get", "head"].includes(this.contextWeb.method) && this.contextWeb?.stack?.memcached instanceof Memcached) {
1184
- const memcached = this.contextWeb.stack.memcached;
1185
- if (memcached.isConnectedServers()) {
1186
- const cache = await memcached.getPage(this.memcachedKey);
1187
- if (cache) {
1188
- const { data, headers } = cache;
1189
- this.success({
1190
- body: data.toString(),
1191
- headers,
1192
- statusCode: 200
1193
- });
1194
- }
1195
- }
1196
- }
1197
- request.controller = request.controller || this.defaultControllerSubaction.controller;
1198
- request.subaction = request.subaction || this.defaultControllerSubaction.subaction;
1199
- if (!["get", "head"].includes(this.contextWeb.method)) {
1200
- if (type.indexOf("application/json") !== -1 || type.indexOf("text/json") !== -1) {
1201
- Object.assign(request, await jsonBody(this.res));
1202
- } else if (type.indexOf("multipart/form-data") !== -1) {
1203
- Object.assign(request, await multipartBody(this.res, this.req));
1204
- Object.defineProperty(this.contextWeb, "$files", {
1205
- enumerable: false,
1206
- configurable: false,
1207
- writable: false,
1208
- value: request.files
1209
- });
1210
- } else if (type.indexOf("application/x-www-form-urlencoded") !== -1) {
1211
- Object.assign(request, await urlencodedBody(this.res));
1212
- } else if (type.indexOf("application/xml") !== -1 || type.indexOf("text/xml") !== -1) {
1213
- const raw = (await rawBody(this.res)).toString();
1214
- const records = xmljs__default["default"].xml2js(raw, { compact: true, cdataKey: "_value", textKey: "_value" });
1215
- Object.assign(request, records || {});
1216
- } else if (type.indexOf("stream") !== -1) {
1217
- Object.defineProperty(this.contextWeb, "$stream", {
1218
- enumerable: false,
1219
- configurable: false,
1220
- writable: false,
1221
- value: streamBody(this.res, this.req, false)
1222
- });
1223
- } else if (type.indexOf("binary") !== -1) {
1224
- await new Promise((resolve) => {
1225
- const stream = streamBody(this.res, this.req);
1226
- const temp = os__namespace.tmpdir();
1227
- const name = "./body_" + crypto__default["default"].randomBytes(32).toString("hex");
1228
- const pathToFile = path__default["default"].resolve(temp, name);
1229
- const writer = fs__namespace.createWriteStream(pathToFile);
1230
- stream.pipe(writer);
1231
- Object.defineProperty(this.contextWeb, "$files", {
1232
- enumerable: false,
1233
- configurable: false,
1234
- writable: false,
1235
- value: { body: { path: pathToFile } }
1236
- });
1237
- stream.on("end", () => resolve(true));
1238
- });
1239
- } else {
1240
- Object.defineProperty(this.contextWeb, "$body", {
1241
- enumerable: false,
1242
- configurable: false,
1243
- writable: false,
1244
- value: await rawBody(this.res)
1245
- });
1246
- }
1247
- }
1248
- this.route = this.findRoute(request.controller);
1249
- Object.assign(this.contextWeb, this.context.schema ? schemaControllerParams(this.context.schema, this.contextWeb.method, this.route.name, request.subaction) : await selectControllerParams(this.contextWeb.db.home, this.contextWeb.method, this.route.name, request.subaction, this.context.stack?.memcached, this.context.stack?.memcachedPrefix, this.context.stack?.memcachedExpiry));
1250
- Object.defineProperty(this.contextWeb, "$route", {
1251
- enumerable: false,
1252
- configurable: false,
1253
- writable: false,
1254
- value: this.route
1255
- });
1256
- const controllerClass = await this.importController(request.controller);
1257
- const controller = new controllerClass();
1258
- this.injectContext(controller);
1259
- const initResponse = await this.initComponent(controller);
1260
- if (typeof initResponse === "undefined") {
1261
- if (request.subaction in controller) {
1262
- response = await controller[request.subaction]();
1263
- } else {
1264
- throw new ApiError.ApiError({
1265
- statusCode: 404,
1266
- code: 13,
1267
- message: `Method ${request.subaction} not found in ${request.controller} route`
1268
- });
1269
- }
1270
- } else {
1271
- response = initResponse;
1272
- }
1273
- response = Object.assign({}, this.defaultResponse, response);
1274
- this.success(response);
1275
- } catch (e) {
1276
- this.error(e);
1277
- }
1278
- }
1279
- async importController(controllerName) {
1280
- let controllerClass = this.route.component.default || this.route.component;
1281
- if (!easyAsh.isClass(controllerClass)) {
1282
- controllerClass = (await this.route.component()).default;
1283
- }
1284
- if (typeof controllerClass !== "function") {
1285
- throw new ApiError.ApiError({
1286
- statusCode: 404,
1287
- code: 12,
1288
- message: `Class not found for ${controllerName} route`
1289
- });
1290
- }
1291
- return controllerClass;
1292
- }
1293
- importControllerSync(controllerName) {
1294
- const controllerClass = this.route.component.default || this.route.component;
1295
- if (typeof controllerClass !== "function") {
1296
- throw new ApiError.ApiError({
1297
- statusCode: 404,
1298
- code: 12,
1299
- message: `Class not found for ${controllerName} route`
1300
- });
1301
- }
1302
- return controllerClass;
1303
- }
1304
- findRoute(controllerName) {
1305
- const route = this.context.routes.filter((v) => v.name === controllerName && (v.method === this.contextWeb.method || v.method === "any" || Array.isArray(v.method) && v.method.includes(this.contextWeb.method) || typeof v.method === "undefined"))?.[0];
1306
- if (!route) {
1307
- throw new ApiError.ApiError({
1308
- statusCode: 404,
1309
- code: 11,
1310
- message: `Route ${controllerName} not found`
1311
- });
1312
- }
1313
- return route;
1314
- }
1315
- injectContext(obj) {
1316
- if ("$inject" in obj) {
1317
- obj.$inject(this.contextWeb);
1318
- }
1319
- }
1320
- async initComponent(obj) {
1321
- const inits = [.../* @__PURE__ */ new Set(["init", ...obj.$inits || []])];
1322
- for (const method of inits) {
1323
- if (obj[method]) {
1324
- const out = await obj[method]();
1325
- if (out) {
1326
- return out;
1327
- }
1328
- }
1329
- }
1330
- }
1331
- success(response) {
1332
- const isStream = response.body instanceof stream$1.Stream;
1333
- const code = response.statusCode || 200;
1334
- const status = codeToStatus(code);
1335
- const body = !isStream && easyAsh.isObject(response.body) ? JSON.stringify(response.body) : response.body;
1336
- if (!isStream && ["get", "head"].includes(this.contextWeb.method) && code === 200 && response.memcache && this.contextWeb?.stack?.memcached instanceof Memcached) {
1337
- const memcached = this.contextWeb.stack.memcached;
1338
- memcached.setPage(this.memcachedKey, response.headers, body, response.memcache).then();
1339
- }
1340
- if (!isStream) {
1341
- this.res.cork(() => {
1342
- this.res.writeStatus(status);
1343
- this.writeHeaders(response.headers);
1344
- this.res.end(body);
1345
- });
1346
- } else {
1347
- this.res.cork(() => {
1348
- this.res.writeStatus(status);
1349
- this.writeHeaders(response.headers);
1350
- body.on("data", (chunk) => {
1351
- this.res.write(chunk);
1352
- }).on("end", () => {
1353
- this.res.end();
1354
- });
1355
- });
1356
- }
1357
- }
1358
- error(e) {
1359
- const isStream = e instanceof ApiError.ApiError && e.getData() instanceof stream$1.Stream;
1360
- let status = codeToStatus(404), headers = this.defaultResponse.headers, body = e.message;
1361
- if (e instanceof ApiError.ApiError) {
1362
- const data = { isError: true, code: e.getCode(), error: e.getMessage() };
1363
- status = codeToStatus(e.getStatusCode());
1364
- headers = e.getHeaders() || this.defaultResponse.headers;
1365
- if (isStream) {
1366
- body = e.getData();
1367
- } else {
1368
- body = easyAsh.isObject(e.getData()) && Object.keys(e.getData()).length > 0 ? JSON.stringify(e.getData()) : JSON.stringify(data);
1369
- }
1370
- }
1371
- if (!isStream) {
1372
- this.res.cork(() => {
1373
- this.res.writeStatus(status);
1374
- this.writeHeaders(headers);
1375
- this.res.end(body);
1376
- });
1377
- } else {
1378
- this.res.cork(() => {
1379
- this.res.writeStatus(status);
1380
- this.writeHeaders(headers);
1381
- body.on("data", (chunk) => {
1382
- this.res.write(chunk);
1383
- }).on("end", () => {
1384
- this.res.end();
1385
- });
1386
- });
1387
- }
1388
- }
1389
- writeHeaders(headers) {
1390
- Object.entries(headers).forEach(([key, value]) => {
1391
- if (Array.isArray(value)) {
1392
- value.forEach((v) => this.res.writeHeader(key, v));
1393
- } else {
1394
- this.res.writeHeader(key, value);
1395
- }
1396
- });
1397
- }
1398
- }
1399
-
1400
- const mountWithContext = async ($class, $context, request = {}) => {
1401
- const initComponent = async (obj2) => {
1402
- let out;
1403
- if ("init" in obj2) {
1404
- out = await obj2.init();
1405
- }
1406
- return out;
1407
- };
1408
- const injectContext = (obj2, $context2) => {
1409
- if ("$inject" in obj2) {
1410
- obj2.$inject($context2);
1411
- }
1412
- };
1413
- $context = Object.assign({
1414
- config: {},
1415
- getRequest: () => request,
1416
- method: "get",
1417
- ...request.controller && request.subaction && $context.db?.home ? await selectControllerParams($context.db.home, $context.method || "get", request.controller, request.subaction) : {},
1418
- cookies: {},
1419
- hostname: $context.config?.server?.development?.host,
1420
- protocol: "http",
1421
- headers: {}
1422
- }, $context);
1423
- const obj = new $class();
1424
- injectContext(obj, $context);
1425
- const initResponse = await initComponent(obj);
1426
- if (initResponse) {
1427
- throw new ApiError.ApiError({
1428
- statusCode: 404,
1429
- code: 13,
1430
- message: `init method response value`
1431
- });
1432
- }
1433
- return obj;
1434
- };
1435
-
1436
- const xmlOptions = { compact: true, ignoreComment: true, spaces: 4 };
1437
- class Controller {
1438
- constructor() {
1439
- this.responseHeaders = {};
1440
- }
1441
- setCookieHeader(name, value, options = {}) {
1442
- return cookieString(name, value, options);
1443
- }
1444
- success(data = {}, options) {
1445
- return {
1446
- headers: Object.assign({ "content-type": "application/json" }, this.responseHeaders, options?.headers || {}),
1447
- body: {
1448
- isError: false,
1449
- data
1450
- },
1451
- memcache: options?.memcache || null,
1452
- statusCode: options?.statusCode || 200
1453
- };
1454
- }
1455
- error(err) {
1456
- const e = err;
1457
- const code = e.code ? e.code : 0;
1458
- const message = e.message ? e.message : "Api request error";
1459
- const statusCode = e.statusCode ? e.statusCode : 404;
1460
- const data = e.data ? e.data : {};
1461
- const response = e.response ? {
1462
- status: e.response.status,
1463
- headers: e.response.headers,
1464
- config: {
1465
- url: e.response.url,
1466
- method: e.response.method,
1467
- params: e.response.params,
1468
- headers: e.response.headers
1469
- },
1470
- data: e.response.data
1471
- } : {};
1472
- const headers = Object.assign({ "content-type": "application/json" }, e.headers);
1473
- return {
1474
- headers,
1475
- body: {
1476
- isError: true,
1477
- error: message,
1478
- code,
1479
- data,
1480
- stack: process.env.NODE_ENV !== "production" ? e.stack : "",
1481
- response: process.env.NODE_ENV !== "production" ? response : {}
1482
- },
1483
- statusCode
1484
- };
1485
- }
1486
- successXml(data = {}, options) {
1487
- const defaultXml = {
1488
- _declaration: {
1489
- _attributes: {
1490
- version: "1.0",
1491
- encoding: "utf-8"
1492
- }
1493
- }
1494
- };
1495
- const response = this.success(data, options);
1496
- return {
1497
- headers: Object.assign({ "content-type": "application/xml" }, this.responseHeaders, options?.headers || {}),
1498
- body: xmljs__default["default"].js2xml(Object.assign(defaultXml, { body: { ...response.body } }), xmlOptions),
1499
- memcache: response.memcache
1500
- };
1501
- }
1502
- errorXml(err) {
1503
- const e = err;
1504
- const defaultXml = {
1505
- _declaration: {
1506
- _attributes: {
1507
- version: "1.0",
1508
- encoding: "utf-8"
1509
- }
1510
- }
1511
- };
1512
- const response = this.error(e);
1513
- const headers = Object.assign({ "content-type": "application/json" }, e.headers);
1514
- return {
1515
- headers,
1516
- body: xmljs__default["default"].js2xml(Object.assign(defaultXml, { body: { ...response.body } }), xmlOptions),
1517
- statusCode: response.statusCode
1518
- };
1519
- }
1520
- async $create(model, ...args) {
1521
- const obj = new model(...args);
1522
- if ("$inject" in obj) {
1523
- obj.$inject({
1524
- method: this.$context.method,
1525
- getRequest: this.$context.getRequest,
1526
- config: this.$context.config,
1527
- db: this.$context.db,
1528
- stack: this.$context.stack,
1529
- headers: this.$context.headers,
1530
- cookies: this.$context.cookies,
1531
- controller: this.$context.controller,
1532
- action: this.$context.action,
1533
- subaction: this.$context.subaction,
1534
- setResponseHeader: (key, value) => this.setResponseHeader(key, value),
1535
- setCookieHeader: this.setCookieHeader
1536
- });
1537
- }
1538
- const inits = ["init", ...obj.$inits || []];
1539
- for (const method of inits) {
1540
- if (obj[method]) {
1541
- await obj[method]();
1542
- }
1543
- }
1544
- return obj;
1545
- }
1546
- async $createAll(models) {
1547
- return Promise.all(models.map((params) => this.$create(...params)));
1548
- }
1549
- $inject(context) {
1550
- this.$context = context;
1551
- }
1552
- getContext() {
1553
- return this.$context;
1554
- }
1555
- getRequest() {
1556
- return this.$context.getRequest();
1557
- }
1558
- getBody() {
1559
- return this.$context["$body"] || Buffer.from("");
1560
- }
1561
- getFiles() {
1562
- return this.$context["$files"] || {};
1563
- }
1564
- getStream() {
1565
- return this.$context["$stream"] || new stream$1.PassThrough().end();
1566
- }
1567
- getConfig() {
1568
- return this.$context.config;
1569
- }
1570
- getMethod() {
1571
- return this.$context.method;
1572
- }
1573
- getCookies() {
1574
- return this.$context.cookies;
1575
- }
1576
- getHostname() {
1577
- return this.$context.hostname;
1578
- }
1579
- getUrl() {
1580
- return this.$context.url;
1581
- }
1582
- getProtocol() {
1583
- return this.$context.protocol;
1584
- }
1585
- getDb() {
1586
- return this.$context.db;
1587
- }
1588
- getHeaders() {
1589
- return this.$context.headers;
1590
- }
1591
- getController() {
1592
- return this.$context.controller;
1593
- }
1594
- getAction() {
1595
- return this.$context.action;
1596
- }
1597
- getSubaction() {
1598
- return this.$context.subaction;
1599
- }
1600
- getHome() {
1601
- return this.getDb().home;
1602
- }
1603
- getPool(key = "home") {
1604
- return this.getDb()[key];
1605
- }
1606
- getStack() {
1607
- return this.$context.stack;
1608
- }
1609
- setResponseHeader(key, value) {
1610
- if (this.responseHeaders.hasOwnProperty(key)) {
1611
- this.responseHeaders[key] = Array.isArray(this.responseHeaders[key]) ? this.responseHeaders[key] : [this.responseHeaders[key]];
1612
- this.responseHeaders[key].push(value);
1613
- } else {
1614
- this.responseHeaders[key] = value;
1615
- }
1616
- }
1617
- }
1618
-
1619
- class Model {
1620
- async $create(model, ...args) {
1621
- const obj = new model(...args);
1622
- if ("$inject" in obj) {
1623
- obj.$inject({
1624
- method: this.$context.method,
1625
- getRequest: this.$context.getRequest,
1626
- config: this.$context.config,
1627
- db: this.$context.db,
1628
- stack: this.$context.stack,
1629
- headers: this.$context.headers,
1630
- cookies: this.$context.cookies,
1631
- controller: this.$context.controller,
1632
- action: this.$context.action,
1633
- subaction: this.$context.subaction,
1634
- setResponseHeader: this.$context.setResponseHeader,
1635
- setCookieHeader: this.$context.setCookieHeader
1636
- });
1637
- }
1638
- if ("init" in obj) {
1639
- await obj.init();
1640
- }
1641
- return obj;
1642
- }
1643
- async $createAll(models) {
1644
- return Promise.all(models.map((params) => this.$create(...params)));
1645
- }
1646
- $inject(context) {
1647
- this.$context = context;
1648
- }
1649
- getContext() {
1650
- return this.$context;
1651
- }
1652
- getRequest() {
1653
- return this.$context.getRequest();
1654
- }
1655
- getConfig() {
1656
- return this.$context.config;
1657
- }
1658
- getMethod() {
1659
- return this.$context.method;
1660
- }
1661
- getHeaders() {
1662
- return this.$context.headers;
1663
- }
1664
- getCookies() {
1665
- return this.$context.cookies;
1666
- }
1667
- getController() {
1668
- return this.$context.controller;
1669
- }
1670
- getAction() {
1671
- return this.$context.action;
1672
- }
1673
- getSubaction() {
1674
- return this.$context.subaction;
1675
- }
1676
- getDb() {
1677
- return this.$context.db;
1678
- }
1679
- getHome() {
1680
- return this.$context.db.home;
1681
- }
1682
- getPool(key = "home") {
1683
- return this.getDb()[key];
1684
- }
1685
- getStack() {
1686
- return this.$context.stack;
1687
- }
1688
- setResponseHeader(key, value) {
1689
- return this.$context.setResponseHeader(key, value);
1690
- }
1691
- setCookieHeader(name, value, options = {}) {
1692
- return this.$context.setCookieHeader(name, value, options);
1693
- }
1694
- }
1695
-
1696
- const selectControllersSchema = async (pool) => {
1697
- const actions = {};
1698
- const controllers = {};
1699
- const rows = await pool.poolQuery(`
38
+ `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),ae=async(o,t,e,s,i="",n=3600)=>{const a=`${i}::routes::controllers`,r=`${t}::${e}`,u=await s.getValue(a);if(u){const c=JSON.parse(u.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await re(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),n),(c||{}).hasOwnProperty(r)?c[r]:void 0}},D=async(o,t,e,s,i,n="",a=3600)=>{let r;if(i&&i.isClient()&&i.isConnectedServers()?r=await ae(o,e,s,i,n,a):r=await ne(o,e,s),!r)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const u=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new h.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!u.includes(t))throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},ce=async o=>{const t={},e={};return(await o.poolQuery(`
1700
39
  SELECT c.id AS controller_id,
1701
40
  c.name AS controller_name,
1702
41
  c.is_active AS controller_is_active,
@@ -1715,304 +54,4 @@ const selectControllersSchema = async (pool) => {
1715
54
  FROM app_controllers c
1716
55
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
1717
56
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
1718
- `);
1719
- rows.forEach((row) => {
1720
- actions[row.action_name] = {
1721
- id: row.action_id,
1722
- name: row.action_name,
1723
- isActive: !!row.action_is_active,
1724
- method: row.action_method
1725
- };
1726
- controllers[row.controller_name] = controllers[row.controller_name] || {
1727
- id: row.controller_id,
1728
- name: row.controller_name,
1729
- isActive: !!row.controller_is_active,
1730
- isSitemap: !!row.controller_is_sitemap,
1731
- subactions: []
1732
- };
1733
- controllers[row.controller_name].subactions.push({
1734
- id: row.subaction_id,
1735
- action: row.action_name,
1736
- name: row.subaction_name,
1737
- isPermission: !!row.subaction_is_permission,
1738
- isCheckMethod: !!row.subaction_is_check_method,
1739
- isLog: !!row.subaction_is_log,
1740
- isActive: !!row.subaction_is_active,
1741
- isSync: !!row.subaction_is_sync
1742
- });
1743
- });
1744
- return {
1745
- controllers: Object.values(controllers),
1746
- actions: Object.values(actions)
1747
- };
1748
- };
1749
-
1750
- const argumentsSubactionsKey = Symbol("arguments");
1751
- const argumentsConnectionsKey = Symbol("connections");
1752
- const responseSubactionsKey = Symbol("response");
1753
- const responseInitKey = Symbol("init");
1754
- const responseLoggerKey = Symbol("logger");
1755
- const upperCaseFirstLetter = (str) => str.charAt(0).toUpperCase() + str.slice(1);
1756
- function mixin(behaviour, sharedBehaviour = {}) {
1757
- const instanceKeys = Reflect.ownKeys(behaviour);
1758
- const sharedKeys = Reflect.ownKeys(sharedBehaviour);
1759
- const typeTag = Symbol("isa");
1760
- function _mixin(clazz) {
1761
- for (const property of instanceKeys) {
1762
- Object.defineProperty(clazz.prototype, property, { value: behaviour[property] });
1763
- }
1764
- Object.defineProperty(clazz.prototype, typeTag, { value: true });
1765
- return clazz;
1766
- }
1767
- for (const property of sharedKeys) {
1768
- Object.defineProperty(_mixin, property, {
1769
- value: sharedBehaviour[property],
1770
- enumerable: sharedBehaviour.propertyIsEnumerable(property)
1771
- });
1772
- }
1773
- Object.defineProperty(_mixin, Symbol.hasInstance, {
1774
- value: (i) => !!i[typeTag]
1775
- });
1776
- return _mixin;
1777
- }
1778
- const defineMetadataArgument = (key, target, propertyKey, parameterIndex, argumentType, params) => {
1779
- const existingArguments = Reflect.getOwnMetadata(key, target, propertyKey) || {};
1780
- existingArguments[parameterIndex] = {
1781
- type: argumentType,
1782
- params
1783
- };
1784
- Reflect.defineMetadata(key, existingArguments, target, propertyKey);
1785
- };
1786
- function request() {
1787
- return function(target, propertyKey, parameterIndex) {
1788
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "request");
1789
- };
1790
- }
1791
- function context() {
1792
- return function(target, propertyKey, parameterIndex) {
1793
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "context");
1794
- };
1795
- }
1796
- function config() {
1797
- return function(target, propertyKey, parameterIndex) {
1798
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "config");
1799
- };
1800
- }
1801
- function method() {
1802
- return function(target, propertyKey, parameterIndex) {
1803
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "method");
1804
- };
1805
- }
1806
- function cookies() {
1807
- return function(target, propertyKey, parameterIndex) {
1808
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "cookies");
1809
- };
1810
- }
1811
- function hostname() {
1812
- return function(target, propertyKey, parameterIndex) {
1813
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "hostname");
1814
- };
1815
- }
1816
- function url() {
1817
- return function(target, propertyKey, parameterIndex) {
1818
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "url");
1819
- };
1820
- }
1821
- function protocol() {
1822
- return function(target, propertyKey, parameterIndex) {
1823
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "protocol");
1824
- };
1825
- }
1826
- function db() {
1827
- return function(target, propertyKey, parameterIndex) {
1828
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "db");
1829
- };
1830
- }
1831
- function headers() {
1832
- return function(target, propertyKey, parameterIndex) {
1833
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "headers");
1834
- };
1835
- }
1836
- function controller() {
1837
- return function(target, propertyKey, parameterIndex) {
1838
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "controller");
1839
- };
1840
- }
1841
- function action() {
1842
- return function(target, propertyKey, parameterIndex) {
1843
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "action");
1844
- };
1845
- }
1846
- function subaction() {
1847
- return function(target, propertyKey, parameterIndex) {
1848
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "subaction");
1849
- };
1850
- }
1851
- function body() {
1852
- return function(target, propertyKey, parameterIndex) {
1853
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "body");
1854
- };
1855
- }
1856
- function stream() {
1857
- return function(target, propertyKey, parameterIndex) {
1858
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "stream");
1859
- };
1860
- }
1861
- function home() {
1862
- return function(target, propertyKey, parameterIndex) {
1863
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "home");
1864
- };
1865
- }
1866
- function pool(name = "home") {
1867
- return function(target, propertyKey, parameterIndex) {
1868
- defineMetadataArgument(argumentsSubactionsKey, target, propertyKey, parameterIndex, "pool", name);
1869
- };
1870
- }
1871
- function connection(name = "home") {
1872
- return function(target, propertyKey, parameterIndex) {
1873
- defineMetadataArgument(argumentsConnectionsKey, target, propertyKey, parameterIndex, "connection", name);
1874
- };
1875
- }
1876
- function json(opt = {}) {
1877
- return function(target, propertyKey, descriptor) {
1878
- defineMetadataArgument(responseSubactionsKey, target, propertyKey, 0, "json", opt);
1879
- };
1880
- }
1881
- function xml(opt = {}) {
1882
- return function(target, propertyKey, descriptor) {
1883
- defineMetadataArgument(responseSubactionsKey, target, propertyKey, 0, "xml", opt);
1884
- };
1885
- }
1886
- function logerror(name) {
1887
- return function(target, propertyKey, descriptor) {
1888
- defineMetadataArgument(responseLoggerKey, target, propertyKey, name, "logger", name);
1889
- };
1890
- }
1891
- function http(beforeCreate) {
1892
- return function(target, propertyKey, descriptor) {
1893
- const opts = {
1894
- format: "json"
1895
- };
1896
- const method2 = descriptor.value;
1897
- descriptor.value = async function() {
1898
- if (beforeCreate) {
1899
- Object.assign(opts, await beforeCreate.apply(this) || {});
1900
- }
1901
- const args = [];
1902
- const connections = [];
1903
- const existingArguments = Reflect.getOwnMetadata(argumentsSubactionsKey, target, propertyKey) || {};
1904
- const existingConnections = Reflect.getOwnMetadata(argumentsConnectionsKey, target, propertyKey) || {};
1905
- const existingLoggers = Reflect.getOwnMetadata(responseLoggerKey, target, propertyKey) || {};
1906
- const response = Reflect.getOwnMetadata(responseSubactionsKey, target, propertyKey)?.[0] || { type: "json", params: {} };
1907
- const responseInit = Reflect.getOwnMetadata(responseInitKey, target, propertyKey)?.[0] || { type: "", params: {} };
1908
- for (const key in existingArguments) {
1909
- if (!existingArguments.hasOwnProperty(key)) {
1910
- continue;
1911
- }
1912
- const getterName = `get${upperCaseFirstLetter(existingArguments[key].type)}`;
1913
- args[+key] = this[getterName](existingArguments[key].params);
1914
- }
1915
- for (const key in existingConnections) {
1916
- if (!existingConnections.hasOwnProperty(key)) {
1917
- continue;
1918
- }
1919
- existingConnections[key].type;
1920
- args[+key] = await this.getDb()[existingConnections[key].params].getConnection();
1921
- connections.push(args[+key]);
1922
- }
1923
- try {
1924
- let out = await method2.apply(this, args), opt;
1925
- Array.isArray(out) && ([out, opt] = out);
1926
- if (responseInit.type !== "init") {
1927
- if (opts.format === "xml" || response.type === "xml") {
1928
- return this.successXml(out, Object.assign(response.params, opt || {}));
1929
- }
1930
- return this.success(out, Object.assign(response.params, opt || {}));
1931
- }
1932
- } catch (e) {
1933
- await Promise.all([...connections.map((connection2) => connection2.rollback())]);
1934
- let output;
1935
- if (opts.format === "xml" || response.type === "xml") {
1936
- output = this.errorXml(e);
1937
- } else {
1938
- output = this.error(e);
1939
- }
1940
- for (const key in existingLoggers) {
1941
- if (!existingLoggers.hasOwnProperty(key)) {
1942
- continue;
1943
- }
1944
- const logger = existingLoggers[key].params;
1945
- await this[logger].error(e, { response: easyAsh.omit(output?.body || {}, ["stack"]) });
1946
- }
1947
- return output;
1948
- } finally {
1949
- await Promise.all([...connections.map((connection2) => connection2.release())]);
1950
- }
1951
- };
1952
- };
1953
- }
1954
- function init() {
1955
- return function(target, propertyKey, descriptor) {
1956
- defineMetadataArgument(responseInitKey, target, propertyKey, 0, "init");
1957
- descriptor.value;
1958
- if (!("$inits" in target)) {
1959
- Object.defineProperty(target, "$inits", { value: [] });
1960
- }
1961
- target.$inits.push(propertyKey);
1962
- };
1963
- }
1964
-
1965
- const helpers = {
1966
- cookieParse: cookieParse.cookieParse,
1967
- cookieString,
1968
- jsonBody,
1969
- rawBody,
1970
- streamBody,
1971
- urlencodedBody,
1972
- multipartBody,
1973
- readConfig,
1974
- readConfigSync,
1975
- staticBody,
1976
- extensions,
1977
- getExt,
1978
- jwtDecode,
1979
- readJsonConfigsSync
1980
- };
1981
-
1982
- exports.ApiError = ApiError.ApiError;
1983
- exports.AsyncJwt = AsyncJwt;
1984
- exports.Controller = Controller;
1985
- exports.Jwt = Jwt;
1986
- exports.Memcached = Memcached;
1987
- exports.Model = Model;
1988
- exports.Server = Server;
1989
- exports.Ssr = Ssr;
1990
- exports.Web = Web;
1991
- exports.action = action;
1992
- exports.body = body;
1993
- exports.codeToStatus = codeToStatus;
1994
- exports.config = config;
1995
- exports.connection = connection;
1996
- exports.context = context;
1997
- exports.controller = controller;
1998
- exports.cookies = cookies;
1999
- exports.db = db;
2000
- exports.headers = headers;
2001
- exports.helpers = helpers;
2002
- exports.home = home;
2003
- exports.hostname = hostname;
2004
- exports.http = http;
2005
- exports.init = init;
2006
- exports.json = json;
2007
- exports.logerror = logerror;
2008
- exports.method = method;
2009
- exports.mixin = mixin;
2010
- exports.mount = mountWithContext;
2011
- exports.pool = pool;
2012
- exports.protocol = protocol;
2013
- exports.request = request;
2014
- exports.selectControllersSchema = selectControllersSchema;
2015
- exports.stream = stream;
2016
- exports.subaction = subaction;
2017
- exports.url = url;
2018
- exports.xml = xml;
57
+ `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},J=(o,t,e,s)=>{let i=o.controllers.find(u=>u.name===e);if(!i)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let n=i.subactions.find(u=>u.name===s);if(!n)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(n=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},n),!n.isActive)throw new h.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(u=>u.name===n.action);if(!a)throw new h.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new h.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(u=>u.trim());if(n.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new h.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:n.id,name:n.name,isPermission:n.isPermission,isCheckMethod:n.isCheckMethod,isLog:n.isLog,isActive:n.isActive,isSync:!!n.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class he{constructor(t,e,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=t,this.req=e,this.res.onAborted(()=>new h.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,z.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>i},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,m)=>this.contextWeb.headers[c]=m);const n=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,J(this.context.schema,this.contextWeb.method,this.route.name,i.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:A(this.res,this.req,!1)});const c=this.importControllerSync(i.controller),m=new c;if(this.injectContext(m),i.subaction in m)e=await m[i.subaction]();else throw new h.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof v.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const m=await c.getPage(this.memcachedKey);if(m){const{data:b,headers:x}=m;this.success({body:b.toString(),headers:x,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(n.indexOf("application/json")!==-1||n.indexOf("text/json")!==-1)Object.assign(i,await E.jsonBody(this.res));else if(n.indexOf("multipart/form-data")!==-1)Object.assign(i,await R.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(n.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await H.urlencodedBody(this.res));else if(n.indexOf("application/xml")!==-1||n.indexOf("text/xml")!==-1){const c=(await j(this.res)).toString(),m=C.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,m||{})}else n.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:A(this.res,this.req,!1)}):n.indexOf("binary")!==-1?await new Promise(c=>{const m=A(this.res,this.req),b=Z.tmpdir(),x="./body_"+k.randomBytes(32).toString("hex"),d=B.resolve(b,x),p=M.createWriteStream(d);m.pipe(p),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:d}}}),m.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await j(this.res)});this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?J(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await D(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(i.controller),r=new a;this.injectContext(r);const u=await this.initComponent(r);if(typeof u>"u")if(i.subaction in r)e=await r[i.subaction]();else throw new h.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=u;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importController(t){let e=this.route.component.default||this.route.component;if(S.isClass(e)||(e=(await this.route.component()).default),typeof e!="function")throw new h.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}importControllerSync(t){const e=this.route.component.default||this.route.component;if(typeof e!="function")throw new h.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new h.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof $.Stream,s=t.statusCode||200,i=_.codeToStatus(s),n=!e&&S.isObject(t.body)?JSON.stringify(t.body):t.body;!e&&["get","head"].includes(this.contextWeb.method)&&s===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof v.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,n,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),this.res.end(n)})}error(t){const e=t instanceof h.ApiError&&t.getData()instanceof $.Stream;let s=_.codeToStatus(404),i=this.defaultResponse.headers,n=t.message;if(t instanceof h.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=_.codeToStatus(t.getStatusCode()),i=t.getHeaders()||this.defaultResponse.headers,e?n=t.getData():n=S.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),n.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(n)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const ue=async(o,t,e={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},i=(a,r)=>{"$inject"in a&&a.$inject(r)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home?await D(t.db.home,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:t.config?.server?.development?.host,protocol:"http",headers:{}},t);const n=new o;if(i(n,t),await s(n))throw new h.ApiError({statusCode:404,code:13,message:"init method response value"});return n},T={compact:!0,ignoreComment:!0,spaces:4};class de{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return W.cookieString(t,e,s)}success(t={},e){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,data:t},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,i=e.message?e.message:"Api request error",n=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:n}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:C.js2xml(Object.assign(s,{body:{...i.body}}),T),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/json"},e.headers),body:C.js2xml(Object.assign(s,{body:{...i.body}}),T),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,setResponseHeader:(n,a)=>this.setResponseHeader(n,a),setCookieHeader:this.setCookieHeader});const i=["init",...s.$inits||[]];for(const n of i)s[n]&&await s[n]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new $.PassThrough().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class le{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}const f=Symbol("arguments"),I=Symbol("connections"),q=Symbol("response"),L=Symbol("init"),F=Symbol("logger"),me=o=>o.charAt(0).toUpperCase()+o.slice(1);function fe(o,t={}){const e=Reflect.ownKeys(o),s=Reflect.ownKeys(t),i=Symbol("isa");function n(a){for(const r of e)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,i,{value:!0}),a}for(const a of s)Object.defineProperty(n,a,{value:t[a],enumerable:t.propertyIsEnumerable(a)});return Object.defineProperty(n,Symbol.hasInstance,{value:a=>!!a[i]}),n}const l=(o,t,e,s,i,n)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:n},Reflect.defineMetadata(o,a,t,e)};function pe(){return function(o,t,e){l(f,o,t,e,"request")}}function be(){return function(o,t,e){l(f,o,t,e,"context")}}function ge(){return function(o,t,e){l(f,o,t,e,"config")}}function _e(){return function(o,t,e){l(f,o,t,e,"method")}}function ye(){return function(o,t,e){l(f,o,t,e,"cookies")}}function xe(){return function(o,t,e){l(f,o,t,e,"hostname")}}function we(){return function(o,t,e){l(f,o,t,e,"url")}}function $e(){return function(o,t,e){l(f,o,t,e,"protocol")}}function Se(){return function(o,t,e){l(f,o,t,e,"db")}}function Ae(){return function(o,t,e){l(f,o,t,e,"headers")}}function ve(){return function(o,t,e){l(f,o,t,e,"controller")}}function Ce(){return function(o,t,e){l(f,o,t,e,"action")}}function Oe(){return function(o,t,e){l(f,o,t,e,"subaction")}}function je(){return function(o,t,e){l(f,o,t,e,"body")}}function qe(){return function(o,t,e){l(f,o,t,e,"stream")}}function ke(){return function(o,t,e){l(f,o,t,e,"home")}}function Ee(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function He(o="home"){return function(t,e,s){l(I,t,e,s,"connection",o)}}function Re(o={}){return function(t,e,s){l(q,t,e,0,"json",o)}}function Pe(o={}){return function(t,e,s){l(q,t,e,0,"xml",o)}}function We(o){return function(t,e,s){l(F,t,e,o,"logger",o)}}function Be(o){return function(t,e,s){const i={format:"json"},n=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],r=[],u=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(I,t,e)||{},m=Reflect.getOwnMetadata(F,t,e)||{},b=Reflect.getOwnMetadata(q,t,e)?.[0]||{type:"json",params:{}},x=Reflect.getOwnMetadata(L,t,e)?.[0]||{type:"",params:{}};for(const d in u){if(!u.hasOwnProperty(d))continue;const p=`get${me(u[d].type)}`;a[+d]=this[p](u[d].params)}for(const d in c)c.hasOwnProperty(d)&&(c[d].type,a[+d]=await this.getDb()[c[d].params].getConnection(),r.push(a[+d]));try{let d=await n.apply(this,a),p;if(Array.isArray(d)&&([d,p]=d),x.type!=="init")return i.format==="xml"||b.type==="xml"?this.successXml(d,Object.assign(b.params,p||{})):this.success(d,Object.assign(b.params,p||{}))}catch(d){await Promise.all([...r.map(w=>w.rollback())]);let p;i.format==="xml"||b.type==="xml"?p=this.errorXml(d):p=this.error(d);for(const w in m){if(!m.hasOwnProperty(w))continue;const K=m[w].params;await this[K].error(d,{response:S.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(d=>d.release())])}}}}function Me(){return function(o,t,e){l(L,o,t,0,"init"),e.value,"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}const Ne={cookieParse:P.cookieParse,cookieString:W.cookieString,jsonBody:E.jsonBody,rawBody:j,streamBody:A,urlencodedBody:H.urlencodedBody,multipartBody:R.multipartBody,readConfig:U.readConfig,readConfigSync:V.readConfigSync,staticBody:y.staticBody,extensions:y.extensions,getExt:y.getExt,jwtDecode:te,readJsonConfigsSync:oe};exports.ApiError=h.ApiError,exports.Server=_.Server,exports.codeToStatus=_.codeToStatus,exports.Jwt=g.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=ee,exports.Controller=de,exports.Model=le,exports.Ssr=ie,exports.Web=he,exports.action=Ce,exports.body=je,exports.config=ge,exports.connection=He,exports.context=be,exports.controller=ve,exports.cookies=ye,exports.db=Se,exports.headers=Ae,exports.helpers=Ne,exports.home=ke,exports.hostname=xe,exports.http=Be,exports.init=Me,exports.json=Re,exports.logerror=We,exports.method=_e,exports.mixin=fe,exports.mount=ue,exports.pool=Ee,exports.protocol=$e,exports.request=pe,exports.selectControllersSchema=ce,exports.stream=qe,exports.subaction=Oe,exports.url=we,exports.xml=Pe;