@jwn-js/common 1.3.9 → 1.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -5,118 +5,43 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var ApiError = require('./ApiError.js');
6
6
  var Server = require('./Server-77093d28.js');
7
7
  var Jwt = require('./Jwt.js');
8
+ var Memcached = require('./Memcached.js');
9
+ var jsonBody$1 = require('./jsonBody.js');
8
10
  var ApiError$1 = require('./ApiError-b517f53a.js');
9
11
  var stream$1 = require('stream');
10
- var querystring = require('querystring');
11
- var formidable = require('formidable');
12
+ var urlencodedBody$1 = require('./urlencodedBody.js');
13
+ var multipartBody$1 = require('./multipartBody.js');
14
+ var readConfig = require('./readConfig.js');
15
+ var readConfigSync$1 = require('./readConfigSync.js');
16
+ var cookieParse = require('./cookieParse.js');
17
+ var cookieString$1 = require('./cookieString.js');
12
18
  var path = require('path');
13
19
  var fs = require('fs');
14
20
  require('dns');
15
21
  require('uWebSockets.js');
16
22
  var easyAsh = require('easy-ash');
23
+ var querystring = require('querystring');
17
24
  var xmljs = require('xml-js');
25
+ var formidable = require('formidable');
18
26
  require('reflect-metadata');
19
27
  require('crypto');
20
28
 
21
29
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
22
30
 
23
- var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
24
- var formidable__default = /*#__PURE__*/_interopDefaultLegacy(formidable);
25
31
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
26
32
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
33
+ var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
27
34
  var xmljs__default = /*#__PURE__*/_interopDefaultLegacy(xmljs);
35
+ var formidable__default = /*#__PURE__*/_interopDefaultLegacy(formidable);
28
36
 
29
- class Memcached {
30
- constructor(memjs, specialHeaders = { "x-cache": "memcached-js" }, maxKeyLength = 160, debug = 0) {
31
- this.memjs = memjs;
32
- this.specialHeaders = specialHeaders;
33
- this.maxKeyLength = maxKeyLength;
34
- this.debug = debug;
35
- }
36
- async setPage(url, headers, data, expires) {
37
- if ((expires || expires === 0) && url.length <= this.maxKeyLength && this.memjs) {
38
- try {
39
- headers = this.objectKeysToLower(headers);
40
- delete headers["set-cookie"];
41
- const headersString = Object.entries(headers).map((v) => v.join(":")).join("\r\n");
42
- const memjsHeaders = "EXTRACT_HEADERS\r\n" + headersString + "\r\n\r\n";
43
- const toMamcache = Buffer.concat([Buffer.from(memjsHeaders), Buffer.from(data)]);
44
- await this.memjs.set(url, toMamcache, { expires });
45
- } catch (e) {
46
- if (this.debug) {
47
- console.log(e);
48
- }
49
- }
50
- }
51
- }
52
- async getPage(url) {
53
- if (url.length <= this.maxKeyLength && this.memjs) {
54
- try {
55
- let headers = {};
56
- const obj = await this.memjs.get(url);
57
- const result = typeof obj === "object" ? obj?.value : obj;
58
- if (!result) {
59
- return null;
60
- }
61
- const memData = Buffer.from(result);
62
- const start = memData.indexOf(Buffer.from("EXTRACT_HEADERS\r\n"));
63
- const end = memData.indexOf(Buffer.from("\r\n\r\n"));
64
- if (start < 0 || end < 0) {
65
- return null;
66
- }
67
- const arr = memData.subarray(start, end).toString().split("\r\n");
68
- arr.shift();
69
- arr.map((row) => {
70
- const [index, value] = row.split(":");
71
- headers[index] = value;
72
- });
73
- headers = Object.assign(headers, this.specialHeaders);
74
- const data = memData.subarray(end + 4);
75
- return { headers, data };
76
- } catch (e) {
77
- if (this.debug) {
78
- console.log(e);
79
- }
80
- }
81
- }
82
- return null;
83
- }
84
- objectKeysToLower(o) {
85
- return Object.keys(o).reduce((c, k) => (c[k.toLowerCase()] = o[k], c), {});
86
- }
87
- }
88
-
89
- const jsonBody = (res, req) => new Promise((resolve, reject) => {
90
- readJson(res, (obj) => {
91
- resolve(obj);
92
- }, (e) => {
93
- reject(new ApiError$1.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
94
- });
95
- });
96
- function readJson(res, cb, err) {
97
- let buffer = Buffer.from([]);
98
- res.onData((ab, isLast) => {
99
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
100
- if (isLast) {
101
- try {
102
- cb(JSON.parse(buffer.toString()));
103
- } catch (e) {
104
- cb({});
105
- return;
106
- }
107
- }
108
- });
109
- res.onAborted(err);
110
- }
111
-
112
- const rawBody = (res, req) => new Promise((resolve, reject) => {
113
- readRaw(res, (obj) => {
37
+ const rawBody$1 = (res, req) => new Promise((resolve, reject) => {
38
+ readRaw$1(res, (obj) => {
114
39
  resolve(obj);
115
40
  }, (e) => {
116
41
  reject(new ApiError$1.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
117
42
  });
118
43
  });
119
- function readRaw(res, cb, err) {
44
+ function readRaw$1(res, cb, err) {
120
45
  let buffer = Buffer.from([]);
121
46
  res.onData((ab, isLast) => {
122
47
  buffer = Buffer.concat([buffer, Buffer.from(ab)]);
@@ -127,7 +52,7 @@ function readRaw(res, cb, err) {
127
52
  res.onAborted(err);
128
53
  }
129
54
 
130
- const streamBody = (res, req) => {
55
+ const streamBody$1 = (res, req) => {
131
56
  const err = new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
132
57
  res.onAborted(() => err);
133
58
  const stream = new stream$1.PassThrough();
@@ -143,85 +68,6 @@ const streamBody = (res, req) => {
143
68
  return stream;
144
69
  };
145
70
 
146
- const urlencodedBody = (res, req) => new Promise((resolve, reject) => {
147
- readBody(res, (obj) => {
148
- resolve(obj);
149
- }, (e) => {
150
- reject(new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 }));
151
- });
152
- });
153
- function readBody(res, cb, err) {
154
- let buffer = Buffer.from([]);
155
- res.onData((ab, isLast) => {
156
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
157
- if (isLast) {
158
- try {
159
- cb(querystring__default['default'].parse(buffer.toString()));
160
- } catch (e) {
161
- cb(null);
162
- return;
163
- }
164
- }
165
- });
166
- res.onAborted(err);
167
- }
168
-
169
- const multipartBody = (res, req, options = { multiples: true }) => new Promise(async (resolve, reject) => {
170
- const err = new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
171
- res.onAborted(() => err);
172
- try {
173
- const stream = new stream$1.PassThrough();
174
- stream.headers = {};
175
- req.forEach((key, val) => stream.headers[key] = val);
176
- res.onData((chunk, isLast) => {
177
- stream.write(Buffer.from(Buffer.from(chunk)));
178
- stream.resume();
179
- if (isLast) {
180
- stream.end();
181
- }
182
- });
183
- const form = formidable__default['default'](options);
184
- form.parse(stream, (err2, fields, files) => {
185
- if (err2) {
186
- reject(err2);
187
- }
188
- fields.files = files;
189
- resolve(fields);
190
- });
191
- } catch (e) {
192
- reject(err);
193
- }
194
- });
195
-
196
- const readConfig = async (jsonfile) => {
197
- const file = path__default['default'].resolve(jsonfile);
198
- return JSON.parse(await fs.promises.readFile(file, "utf-8"));
199
- };
200
-
201
- const readConfigSync = (jsonfile) => {
202
- const file = path__default['default'].resolve(jsonfile);
203
- return JSON.parse(fs__default['default'].readFileSync(file, "utf-8"));
204
- };
205
-
206
- const cookieString = (name, value, options = {}) => {
207
- options = {
208
- path: "/",
209
- ...options
210
- };
211
- if (options.expires instanceof Date) {
212
- options.expires = options.expires.toUTCString();
213
- }
214
- let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
215
- for (const optionKey in options) {
216
- updatedCookie += "; " + optionKey;
217
- const optionValue = options[optionKey];
218
- if (optionValue !== true) {
219
- updatedCookie += "=" + optionValue;
220
- }
221
- }
222
- return updatedCookie;
223
- };
224
-
225
71
  const exts = {
226
72
  "3gp": "video/3gpp",
227
73
  "a": "application/octet-stream",
@@ -611,6 +457,207 @@ const selectControllerParams = async (db, method, name, subaction) => {
611
457
  };
612
458
  };
613
459
 
460
+ const schemaControllerParams = async (schema, method, name, subaction) => {
461
+ let controllerRow = schema.controllers.find((row) => row.name === name);
462
+ if (!controllerRow) {
463
+ throw new ApiError$1.ApiError({
464
+ statusCode: 404,
465
+ code: 11,
466
+ message: `Controller ${name} not found is site schema`
467
+ });
468
+ }
469
+ controllerRow = Object.assign({
470
+ isActive: true,
471
+ isSitemap: false
472
+ }, controllerRow);
473
+ if (controllerRow.isActive) {
474
+ throw new ApiError$1.ApiError({
475
+ statusCode: 404,
476
+ code: 11,
477
+ message: `Controller ${name} not active is site schema`
478
+ });
479
+ }
480
+ let subactionRow = controllerRow.subactions.find((row) => row.name === subaction);
481
+ if (!subactionRow) {
482
+ throw new ApiError$1.ApiError({
483
+ statusCode: 404,
484
+ code: 11,
485
+ message: `Subaction ${subaction} not found is site schema`
486
+ });
487
+ }
488
+ subactionRow = Object.assign({
489
+ isPermission: false,
490
+ isCheckMethod: false,
491
+ isLog: false,
492
+ isActive: true
493
+ }, subactionRow);
494
+ if (!subactionRow.isActive) {
495
+ throw new ApiError$1.ApiError({
496
+ statusCode: 404,
497
+ code: 11,
498
+ message: `Subaction ${subaction} not active is site schema`
499
+ });
500
+ }
501
+ let actionRow = schema.actions.find((row) => row.name === subactionRow.action);
502
+ if (!actionRow) {
503
+ throw new ApiError$1.ApiError({
504
+ statusCode: 404,
505
+ code: 11,
506
+ message: `Action not found is site schema`
507
+ });
508
+ }
509
+ actionRow = Object.assign({
510
+ isActive: true,
511
+ method: "any"
512
+ }, actionRow);
513
+ if (!actionRow.isActive) {
514
+ throw new ApiError$1.ApiError({
515
+ statusCode: 404,
516
+ code: 11,
517
+ message: `Action ${actionRow.name} not active is site schema`
518
+ });
519
+ }
520
+ const allowMethods = (actionRow?.method || "").split(",").map((method2) => method2.trim());
521
+ if (subactionRow.isCheckMethod) {
522
+ if (actionRow.method !== "any" && !allowMethods.includes(method)) {
523
+ throw new ApiError$1.ApiError({
524
+ statusCode: 404,
525
+ code: 11,
526
+ message: `Controller ${name} action ${actionRow.name} allow only ${actionRow.method} method`
527
+ });
528
+ }
529
+ }
530
+ return {
531
+ controller: {
532
+ id: controllerRow.id,
533
+ name: controllerRow.name,
534
+ isActive: controllerRow.isActive,
535
+ isSitemap: controllerRow.isSitemap
536
+ },
537
+ subaction: {
538
+ id: subactionRow.id,
539
+ name: subactionRow.name,
540
+ isPermission: subactionRow.isPermission,
541
+ isCheckMethod: subactionRow.isCheckMethod,
542
+ isLog: subactionRow.isLog,
543
+ isActive: subactionRow.isActive
544
+ },
545
+ action: {
546
+ id: actionRow.id,
547
+ name: actionRow.name,
548
+ isActive: actionRow.isActive,
549
+ method: actionRow.method
550
+ }
551
+ };
552
+ };
553
+
554
+ const jsonBody = (res, req) => new Promise((resolve, reject) => {
555
+ readJson(res, (obj) => {
556
+ resolve(obj);
557
+ }, (e) => {
558
+ reject(new ApiError$1.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
559
+ });
560
+ });
561
+ function readJson(res, cb, err) {
562
+ let buffer = Buffer.from([]);
563
+ res.onData((ab, isLast) => {
564
+ buffer = Buffer.concat([buffer, Buffer.from(ab)]);
565
+ if (isLast) {
566
+ try {
567
+ cb(JSON.parse(buffer.toString()));
568
+ } catch (e) {
569
+ cb({});
570
+ return;
571
+ }
572
+ }
573
+ });
574
+ res.onAborted(err);
575
+ }
576
+
577
+ const multipartBody = (res, req, options = { multiples: true }) => new Promise(async (resolve, reject) => {
578
+ const err = new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
579
+ res.onAborted(() => err);
580
+ try {
581
+ const stream = new stream$1.PassThrough();
582
+ stream.headers = {};
583
+ req.forEach((key, val) => stream.headers[key] = val);
584
+ res.onData((chunk, isLast) => {
585
+ stream.write(Buffer.from(Buffer.from(chunk)));
586
+ stream.resume();
587
+ if (isLast) {
588
+ stream.end();
589
+ }
590
+ });
591
+ const form = formidable__default['default'](options);
592
+ form.parse(stream, (err2, fields, files) => {
593
+ if (err2) {
594
+ reject(err2);
595
+ }
596
+ fields.files = files;
597
+ resolve(fields);
598
+ });
599
+ } catch (e) {
600
+ reject(err);
601
+ }
602
+ });
603
+
604
+ const urlencodedBody = (res, req) => new Promise((resolve, reject) => {
605
+ readBody(res, (obj) => {
606
+ resolve(obj);
607
+ }, (e) => {
608
+ reject(new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 }));
609
+ });
610
+ });
611
+ function readBody(res, cb, err) {
612
+ let buffer = Buffer.from([]);
613
+ res.onData((ab, isLast) => {
614
+ buffer = Buffer.concat([buffer, Buffer.from(ab)]);
615
+ if (isLast) {
616
+ try {
617
+ cb(querystring__default['default'].parse(buffer.toString()));
618
+ } catch (e) {
619
+ cb(null);
620
+ return;
621
+ }
622
+ }
623
+ });
624
+ res.onAborted(err);
625
+ }
626
+
627
+ const rawBody = (res, req) => new Promise((resolve, reject) => {
628
+ readRaw(res, (obj) => {
629
+ resolve(obj);
630
+ }, (e) => {
631
+ reject(new ApiError$1.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
632
+ });
633
+ });
634
+ function readRaw(res, cb, err) {
635
+ let buffer = Buffer.from([]);
636
+ res.onData((ab, isLast) => {
637
+ buffer = Buffer.concat([buffer, Buffer.from(ab)]);
638
+ if (isLast) {
639
+ cb(buffer);
640
+ }
641
+ });
642
+ res.onAborted(err);
643
+ }
644
+
645
+ const streamBody = (res, req) => {
646
+ const err = new ApiError$1.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
647
+ res.onAborted(() => err);
648
+ const stream = new stream$1.PassThrough();
649
+ stream.headers = {};
650
+ req.forEach((key, val) => stream.headers[key] = val);
651
+ res.onData((chunk, isLast) => {
652
+ stream.write(Buffer.from(Buffer.from(chunk)));
653
+ stream.resume();
654
+ if (isLast) {
655
+ stream.end();
656
+ }
657
+ });
658
+ return stream;
659
+ };
660
+
614
661
  class Web {
615
662
  constructor(res, req, context) {
616
663
  this.defaultRequest = {
@@ -669,7 +716,7 @@ class Web {
669
716
  });
670
717
  }
671
718
  this.route = this.findRoute(request);
672
- Object.assign(this.contextWeb, await selectControllerParams(this.contextWeb.db.home, this.contextWeb.method, this.route.name, request.subaction));
719
+ Object.assign(this.contextWeb, this.context.schema ? await 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));
673
720
  Object.defineProperty(this.contextWeb, "$route", {
674
721
  enumerable: false,
675
722
  configurable: false,
@@ -762,6 +809,11 @@ class Web {
762
809
  }
763
810
  }
764
811
 
812
+ const readConfigSync = (jsonfile) => {
813
+ const file = path__default['default'].resolve(jsonfile);
814
+ return JSON.parse(fs__default['default'].readFileSync(file, "utf-8"));
815
+ };
816
+
765
817
  const config$1 = readConfigSync("./connect.json");
766
818
  const mountWithContext = async ($class, $context, request = {}) => {
767
819
  const initComponent = async (obj2) => {
@@ -799,14 +851,36 @@ const mountWithContext = async ($class, $context, request = {}) => {
799
851
  return obj;
800
852
  };
801
853
 
854
+ const cookieString = (name, value, options = {}) => {
855
+ options = {
856
+ path: "/",
857
+ ...options
858
+ };
859
+ if (options.expires instanceof Date) {
860
+ options.expires = options.expires.toUTCString();
861
+ }
862
+ let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
863
+ for (const optionKey in options) {
864
+ updatedCookie += "; " + optionKey;
865
+ const optionValue = options[optionKey];
866
+ if (optionValue !== true) {
867
+ updatedCookie += "=" + optionValue;
868
+ }
869
+ }
870
+ return updatedCookie;
871
+ };
872
+
802
873
  const xmlOptions = { compact: true, ignoreComment: true, spaces: 4 };
803
874
  class Controller {
875
+ constructor() {
876
+ this.responseHeaders = {};
877
+ }
804
878
  setCookieHeader(name, value, options = {}) {
805
879
  return cookieString(name, value, options);
806
880
  }
807
881
  success(data = {}, options) {
808
882
  return {
809
- headers: options?.headers || { "content-type": "application/json" },
883
+ headers: Object.assign({ "content-type": "application/json" }, this.responseHeaders, options?.headers || {}),
810
884
  body: {
811
885
  isError: false,
812
886
  data
@@ -857,7 +931,7 @@ class Controller {
857
931
  };
858
932
  const response = this.success(data, options);
859
933
  return {
860
- headers: options?.headers || { "content-type": "application/xml" },
934
+ headers: Object.assign({ "content-type": "application/xml" }, this.responseHeaders, options?.headers || {}),
861
935
  body: xmljs__default['default'].js2xml(Object.assign(defaultXml, { body: { ...response.body } }), xmlOptions),
862
936
  memcache: response.memcache
863
937
  };
@@ -889,9 +963,12 @@ class Controller {
889
963
  config: this.$context.config,
890
964
  db: this.$context.db,
891
965
  headers: this.$context.headers,
966
+ cookies: this.$context.cookies,
892
967
  controller: this.$context.controller,
893
968
  action: this.$context.action,
894
- subaction: this.$context.subaction
969
+ subaction: this.$context.subaction,
970
+ setResponseHeader: this.setResponseHeader,
971
+ setCookieHeader: this.setCookieHeader
895
972
  });
896
973
  }
897
974
  const inits = ["init", ...obj.$inits || []];
@@ -956,6 +1033,14 @@ class Controller {
956
1033
  getPool(key = "home") {
957
1034
  return this.getDb()[key];
958
1035
  }
1036
+ setResponseHeader(key, value) {
1037
+ if (this.responseHeaders.hasOwnProperty(key)) {
1038
+ this.responseHeaders[key] = Array.isArray(this.responseHeaders[key]) ? this.responseHeaders[key] : [this.responseHeaders[key]];
1039
+ this.responseHeaders[key].push(value);
1040
+ } else {
1041
+ this.responseHeaders[key] = value;
1042
+ }
1043
+ }
959
1044
  }
960
1045
 
961
1046
  class Model {
@@ -968,9 +1053,12 @@ class Model {
968
1053
  config: this.$context.config,
969
1054
  db: this.$context.db,
970
1055
  headers: this.$context.headers,
1056
+ cookies: this.$context.cookies,
971
1057
  controller: this.$context.controller,
972
1058
  action: this.$context.action,
973
- subaction: this.$context.subaction
1059
+ subaction: this.$context.subaction,
1060
+ setResponseHeader: this.$context.setResponseHeader,
1061
+ setCookieHeader: this.$context.setCookieHeader
974
1062
  });
975
1063
  }
976
1064
  if ("init" in obj) {
@@ -996,6 +1084,9 @@ class Model {
996
1084
  getHeaders() {
997
1085
  return this.$context.headers;
998
1086
  }
1087
+ getCookies() {
1088
+ return this.$context.cookies;
1089
+ }
999
1090
  getController() {
1000
1091
  return this.$context.controller;
1001
1092
  }
@@ -1223,15 +1314,15 @@ function init() {
1223
1314
  }
1224
1315
 
1225
1316
  const helpers = {
1226
- cookieParse: Server.cookieParse,
1227
- cookieString,
1228
- jsonBody,
1229
- rawBody,
1230
- streamBody,
1231
- urlencodedBody,
1232
- multipartBody,
1233
- readConfig,
1234
- readConfigSync,
1317
+ cookieParse: cookieParse.cookieParse,
1318
+ cookieString: cookieString$1.cookieString,
1319
+ jsonBody: jsonBody$1.jsonBody,
1320
+ rawBody: rawBody$1,
1321
+ streamBody: streamBody$1,
1322
+ urlencodedBody: urlencodedBody$1.urlencodedBody,
1323
+ multipartBody: multipartBody$1.multipartBody,
1324
+ readConfig: readConfig.readConfig,
1325
+ readConfigSync: readConfigSync$1.readConfigSync,
1235
1326
  staticBody,
1236
1327
  extensions,
1237
1328
  getExt
@@ -1241,8 +1332,8 @@ exports.ApiError = ApiError.ApiError;
1241
1332
  exports.Server = Server.Server;
1242
1333
  exports.codeToStatus = Server.codeToStatus;
1243
1334
  exports.Jwt = Jwt.Jwt;
1335
+ exports.Memcached = Memcached.Memcached;
1244
1336
  exports.Controller = Controller;
1245
- exports.Memcached = Memcached;
1246
1337
  exports.Model = Model;
1247
1338
  exports.Ssr = Ssr;
1248
1339
  exports.Web = Web;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jwn-js/common",
3
3
  "private": false,
4
- "version": "1.3.9",
4
+ "version": "1.3.13",
5
5
  "description": "@jwn-js/common package",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",