moost 0.0.1 → 0.2.0

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 (129) hide show
  1. package/README.md +14 -8
  2. package/dist/index.cjs +2093 -0
  3. package/dist/{moost.d.ts → index.d.ts} +43 -158
  4. package/dist/index.mjs +2063 -0
  5. package/package.json +13 -69
  6. package/LICENSE +0 -21
  7. package/dist/moost.cjs.prod.js +0 -923
  8. package/dist/moost.esm-bundler.js +0 -870
  9. package/dist/src/binding/bind-controller.d.ts +0 -13
  10. package/dist/src/binding/bind-controller.d.ts.map +0 -1
  11. package/dist/src/binding/bind-handler.d.ts +0 -18
  12. package/dist/src/binding/bind-handler.d.ts.map +0 -1
  13. package/dist/src/binding/index.d.ts +0 -3
  14. package/dist/src/binding/index.d.ts.map +0 -1
  15. package/dist/src/binding/tests/binding.spec.d.ts +0 -2
  16. package/dist/src/binding/tests/binding.spec.d.ts.map +0 -1
  17. package/dist/src/binding/utils.d.ts +0 -3
  18. package/dist/src/binding/utils.d.ts.map +0 -1
  19. package/dist/src/class-function/class-function.d.ts +0 -4
  20. package/dist/src/class-function/class-function.d.ts.map +0 -1
  21. package/dist/src/class-function/index.d.ts +0 -2
  22. package/dist/src/class-function/index.d.ts.map +0 -1
  23. package/dist/src/class-function/types.d.ts +0 -9
  24. package/dist/src/class-function/types.d.ts.map +0 -1
  25. package/dist/src/composables/controller-meta.d.ts +0 -13
  26. package/dist/src/composables/controller-meta.d.ts.map +0 -1
  27. package/dist/src/composables/index.d.ts +0 -2
  28. package/dist/src/composables/index.d.ts.map +0 -1
  29. package/dist/src/decorators/circular.decorator.d.ts +0 -3
  30. package/dist/src/decorators/circular.decorator.d.ts.map +0 -1
  31. package/dist/src/decorators/common.decorator.d.ts +0 -4
  32. package/dist/src/decorators/common.decorator.d.ts.map +0 -1
  33. package/dist/src/decorators/controller.decorator.d.ts +0 -24
  34. package/dist/src/decorators/controller.decorator.d.ts.map +0 -1
  35. package/dist/src/decorators/http-method.decorator.d.ts +0 -8
  36. package/dist/src/decorators/http-method.decorator.d.ts.map +0 -1
  37. package/dist/src/decorators/index.d.ts +0 -10
  38. package/dist/src/decorators/index.d.ts.map +0 -1
  39. package/dist/src/decorators/injectable.decorator.d.ts +0 -12
  40. package/dist/src/decorators/injectable.decorator.d.ts.map +0 -1
  41. package/dist/src/decorators/intercept.decorator.d.ts +0 -20
  42. package/dist/src/decorators/intercept.decorator.d.ts.map +0 -1
  43. package/dist/src/decorators/pipe.decorator.d.ts +0 -3
  44. package/dist/src/decorators/pipe.decorator.d.ts.map +0 -1
  45. package/dist/src/decorators/provide.decorator.d.ts +0 -5
  46. package/dist/src/decorators/provide.decorator.d.ts.map +0 -1
  47. package/dist/src/decorators/resolve.decorator.d.ts +0 -137
  48. package/dist/src/decorators/resolve.decorator.d.ts.map +0 -1
  49. package/dist/src/decorators/tests/circular.artifacts.d.ts +0 -7
  50. package/dist/src/decorators/tests/circular.artifacts.d.ts.map +0 -1
  51. package/dist/src/decorators/tests/circular.spec.d.ts +0 -2
  52. package/dist/src/decorators/tests/circular.spec.d.ts.map +0 -1
  53. package/dist/src/decorators/tests/common.artifacts.d.ts +0 -4
  54. package/dist/src/decorators/tests/common.artifacts.d.ts.map +0 -1
  55. package/dist/src/decorators/tests/common.spec.d.ts +0 -2
  56. package/dist/src/decorators/tests/common.spec.d.ts.map +0 -1
  57. package/dist/src/decorators/tests/controller.spec.d.ts +0 -2
  58. package/dist/src/decorators/tests/controller.spec.d.ts.map +0 -1
  59. package/dist/src/decorators/tests/http-method.artifacts.d.ts +0 -12
  60. package/dist/src/decorators/tests/http-method.artifacts.d.ts.map +0 -1
  61. package/dist/src/decorators/tests/http-method.spec.d.ts +0 -2
  62. package/dist/src/decorators/tests/http-method.spec.d.ts.map +0 -1
  63. package/dist/src/decorators/tests/injectable.spec.d.ts +0 -2
  64. package/dist/src/decorators/tests/injectable.spec.d.ts.map +0 -1
  65. package/dist/src/decorators/tests/intercept.spec.d.ts +0 -2
  66. package/dist/src/decorators/tests/intercept.spec.d.ts.map +0 -1
  67. package/dist/src/decorators/tests/pipe.artifacts.d.ts +0 -4
  68. package/dist/src/decorators/tests/pipe.artifacts.d.ts.map +0 -1
  69. package/dist/src/decorators/tests/pipe.spec.d.ts +0 -2
  70. package/dist/src/decorators/tests/pipe.spec.d.ts.map +0 -1
  71. package/dist/src/decorators/tests/provide.artifacts.d.ts +0 -9
  72. package/dist/src/decorators/tests/provide.artifacts.d.ts.map +0 -1
  73. package/dist/src/decorators/tests/provide.spec.d.ts +0 -2
  74. package/dist/src/decorators/tests/provide.spec.d.ts.map +0 -1
  75. package/dist/src/decorators/tests/resolve.artifacts.d.ts +0 -4
  76. package/dist/src/decorators/tests/resolve.artifacts.d.ts.map +0 -1
  77. package/dist/src/decorators/tests/resolve.spec.d.ts +0 -2
  78. package/dist/src/decorators/tests/resolve.spec.d.ts.map +0 -1
  79. package/dist/src/decorators/tests/validate.artifacts.d.ts +0 -21
  80. package/dist/src/decorators/tests/validate.artifacts.d.ts.map +0 -1
  81. package/dist/src/decorators/tests/validate.spec.d.ts +0 -2
  82. package/dist/src/decorators/tests/validate.spec.d.ts.map +0 -1
  83. package/dist/src/decorators/validate.decorator.d.ts +0 -10
  84. package/dist/src/decorators/validate.decorator.d.ts.map +0 -1
  85. package/dist/src/index.d.ts +0 -7
  86. package/dist/src/index.d.ts.map +0 -1
  87. package/dist/src/metadata/index.d.ts +0 -2
  88. package/dist/src/metadata/index.d.ts.map +0 -1
  89. package/dist/src/metadata/infact.d.ts +0 -7
  90. package/dist/src/metadata/infact.d.ts.map +0 -1
  91. package/dist/src/metadata/moost-metadata.d.ts +0 -62
  92. package/dist/src/metadata/moost-metadata.d.ts.map +0 -1
  93. package/dist/src/metadata/valido.d.ts +0 -3
  94. package/dist/src/metadata/valido.d.ts.map +0 -1
  95. package/dist/src/moost.d.ts +0 -46
  96. package/dist/src/moost.d.ts.map +0 -1
  97. package/dist/src/moost.spec.d.ts +0 -2
  98. package/dist/src/moost.spec.d.ts.map +0 -1
  99. package/dist/src/pipes/generic-types-cast.pipe.d.ts +0 -3
  100. package/dist/src/pipes/generic-types-cast.pipe.d.ts.map +0 -1
  101. package/dist/src/pipes/index.d.ts +0 -5
  102. package/dist/src/pipes/index.d.ts.map +0 -1
  103. package/dist/src/pipes/resolve.pipe.d.ts +0 -3
  104. package/dist/src/pipes/resolve.pipe.d.ts.map +0 -1
  105. package/dist/src/pipes/run-pipes.d.ts +0 -5
  106. package/dist/src/pipes/run-pipes.d.ts.map +0 -1
  107. package/dist/src/pipes/shared-pipes.d.ts +0 -3
  108. package/dist/src/pipes/shared-pipes.d.ts.map +0 -1
  109. package/dist/src/pipes/types.d.ts +0 -21
  110. package/dist/src/pipes/types.d.ts.map +0 -1
  111. package/dist/src/pipes/validate.pipe.d.ts +0 -7
  112. package/dist/src/pipes/validate.pipe.d.ts.map +0 -1
  113. package/dist/src/pipes/validation.spec.d.ts +0 -2
  114. package/dist/src/pipes/validation.spec.d.ts.map +0 -1
  115. package/dist/src/tests/e2e.artifacts.d.ts +0 -17
  116. package/dist/src/tests/e2e.artifacts.d.ts.map +0 -1
  117. package/dist/src/tests/e2e.spec.d.ts +0 -2
  118. package/dist/src/tests/e2e.spec.d.ts.map +0 -1
  119. package/dist/src/tests/request.artifacts.d.ts +0 -10
  120. package/dist/src/tests/request.artifacts.d.ts.map +0 -1
  121. package/dist/src/types.d.ts +0 -8
  122. package/dist/src/types.d.ts.map +0 -1
  123. package/dist/src/utils/banner.d.ts +0 -2
  124. package/dist/src/utils/banner.d.ts.map +0 -1
  125. package/dist/src/utils/log.d.ts +0 -5
  126. package/dist/src/utils/log.d.ts.map +0 -1
  127. package/dist/src/utils/panic.d.ts +0 -2
  128. package/dist/src/utils/panic.d.ts.map +0 -1
  129. package/index.js +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,2093 @@
1
+ 'use strict';
2
+
3
+ var eventCore = require('@wooksjs/event-core');
4
+ require('url');
5
+ require('stream');
6
+ require('http');
7
+ var mate = require('@prostojs/mate');
8
+ var infact = require('@prostojs/infact');
9
+ var valido$1 = require('@prostojs/valido');
10
+
11
+ /******************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+
26
+ function __awaiter(thisArg, _arguments, P, generator) {
27
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
+ return new (P || (P = Promise))(function (resolve, reject) {
29
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
33
+ });
34
+ }
35
+
36
+ const dim = '';
37
+ const reset = '';
38
+ class ProstoTree {
39
+ constructor(options) {
40
+ var _a, _b, _c, _d;
41
+ const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
42
+ const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
43
+ const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
44
+ const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
45
+ const branches = {
46
+ end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
47
+ middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
48
+ vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
49
+ hLine,
50
+ };
51
+ this.options = {
52
+ label: label,
53
+ children: children,
54
+ renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
55
+ branches,
56
+ branchWidth,
57
+ };
58
+ }
59
+ _render(root, opts) {
60
+ const { children, renderLabel } = this.options;
61
+ let s = `${renderLabel(root, '')}\n`;
62
+ const { end, middle, vLine, hLine } = this.options.branches;
63
+ const endBranch = end + hLine + reset + ' ';
64
+ const middleBranch = middle + hLine + reset + ' ';
65
+ const { branchWidth } = this.options;
66
+ if (root) {
67
+ treeNode(root);
68
+ }
69
+ function treeNode(node, behind = '', level = 1) {
70
+ const items = (node && node[children]);
71
+ const count = items && items.length || 0;
72
+ if (items) {
73
+ if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
74
+ s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
75
+ }
76
+ else {
77
+ let itemsToRender = items;
78
+ const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
79
+ if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
80
+ itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
81
+ }
82
+ if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
83
+ s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
84
+ itemsToRender.forEach((childNode, i) => {
85
+ const last = i + 1 === count;
86
+ const branch = last ? endBranch : middleBranch;
87
+ const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
88
+ s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
89
+ if (typeof childNode === 'object') {
90
+ treeNode(childNode, nextBehind, level + 1);
91
+ }
92
+ });
93
+ if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
94
+ s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
95
+ }
96
+ }
97
+ }
98
+ return s;
99
+ }
100
+ render(root, opts) {
101
+ return this._render(root, opts);
102
+ }
103
+ print(root, opts) {
104
+ const s = this.render(root, opts);
105
+ console.log(s);
106
+ return s;
107
+ }
108
+ }
109
+ function renderCollapsedChildren(count) {
110
+ return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
111
+ }
112
+
113
+ function renderCodeFragment(lines, options) {
114
+ const row = (options.row || 1) - 1;
115
+ const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
116
+ const limit = Math.min(options.limit || 6, lines.length);
117
+ const offset = Math.min(options.offset || 3, lines.length);
118
+ const error = options.error;
119
+ const errorEnd = options.errorEnd;
120
+ let output = '';
121
+ const delta = rowEnd - row;
122
+ const maxIndex = lines.length;
123
+ if (delta > limit) {
124
+ let longestLine = 0;
125
+ const newLimit = Math.floor(limit / 2);
126
+ for (let i = 0; i < newLimit + offset; i++) {
127
+ const index = row + i - offset;
128
+ const line = lines[index] || '';
129
+ longestLine = Math.max(line.length, longestLine);
130
+ output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
131
+ }
132
+ let output2 = '';
133
+ for (let i = newLimit + offset; i > 0; i--) {
134
+ const index = rowEnd - i + offset;
135
+ const line = lines[index] || '';
136
+ longestLine = Math.max(line.length, longestLine);
137
+ output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
138
+ }
139
+ output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
140
+ }
141
+ else {
142
+ for (let i = 0; i < limit + offset; i++) {
143
+ const index = row + i - offset;
144
+ if (index <= lines.length + 1) {
145
+ const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
146
+ output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
147
+ }
148
+ }
149
+ }
150
+ return output;
151
+ }
152
+ function lineStyles(s) {
153
+ return '' + (s || '')
154
+ .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
155
+ .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
156
+ }
157
+ function lineStylesError(s) {
158
+ return '' + (s || '') + '';
159
+ }
160
+ function renderLine(line, index, error, style = '') {
161
+ const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
162
+ if (typeof error === 'number') {
163
+ const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
164
+ return renderLineNumber(index, true) +
165
+ st +
166
+ lineStyles(line.slice(0, error)) +
167
+ lineStylesError(line.slice(error, error + errorLength)) +
168
+ lineStyles(line.slice(error + errorLength)) +
169
+ renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
170
+ }
171
+ return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
172
+ }
173
+ function renderLineNumber(i, isError = false, bold = false) {
174
+ let s = ' ';
175
+ const sep = i === '———';
176
+ if (i && i > 0 || typeof i === 'string') {
177
+ s = ' ' + String(i);
178
+ }
179
+ s = s.slice(s.length - 5);
180
+ return '\n' + '' + (sep ? '' : '') +
181
+ (isError ? '' + '' : (bold ? '' : '')) +
182
+ s + (sep ? i : ' | ') + '';
183
+ }
184
+
185
+ function escapeRegex(s) {
186
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
187
+ }
188
+
189
+ class ProstoParserNodeBase {
190
+ addRecognizes(...args) {
191
+ for (const node of args) {
192
+ if (!this.options.recognizes)
193
+ this.options.recognizes = [];
194
+ if (!this.options.recognizes.includes(node)) {
195
+ this.options.recognizes.push(node);
196
+ }
197
+ }
198
+ return this;
199
+ }
200
+ addAbsorbs(node, rule = 'append') {
201
+ this.options.absorbs = this.options.absorbs || {};
202
+ if (Array.isArray(node)) {
203
+ node.forEach(n => {
204
+ this.options.absorbs[n.id] = rule;
205
+ this.addRecognizes(n);
206
+ });
207
+ }
208
+ else {
209
+ this.options.absorbs[node.id] = rule;
210
+ this.addRecognizes(node);
211
+ }
212
+ return this;
213
+ }
214
+ addPopsAfterNode(...args) {
215
+ for (const node of args) {
216
+ if (!this.options.popsAfterNode)
217
+ this.options.popsAfterNode = [];
218
+ if (!this.options.popsAfterNode.includes(node)) {
219
+ this.options.popsAfterNode.push(node);
220
+ }
221
+ }
222
+ this.addRecognizes(...args);
223
+ return this;
224
+ }
225
+ addHoistChildren(...args) {
226
+ if (!this.options.hoistChildren)
227
+ this.options.hoistChildren = [];
228
+ this.options.hoistChildren.push(...args);
229
+ return this;
230
+ }
231
+ set icon(value) {
232
+ this.options.icon = value;
233
+ }
234
+ set label(value) {
235
+ this.options.label = value;
236
+ }
237
+ get startsWith() {
238
+ return this.options.startsWith;
239
+ }
240
+ set startsWith(value) {
241
+ this.options.startsWith = value;
242
+ }
243
+ get endsWith() {
244
+ return this.options.endsWith;
245
+ }
246
+ set endsWith(value) {
247
+ this.options.endsWith = value;
248
+ }
249
+ getPopsAtEOFSource() {
250
+ return this.options.popsAtEOFSource;
251
+ }
252
+ popsAtEOFSource(value) {
253
+ this.options.popsAtEOFSource = value;
254
+ return this;
255
+ }
256
+ get absorbs() {
257
+ return this.options.absorbs;
258
+ }
259
+ get badToken() {
260
+ return this.options.badToken;
261
+ }
262
+ set badToken(value) {
263
+ this.options.badToken = value;
264
+ }
265
+ get skipToken() {
266
+ return this.options.skipToken;
267
+ }
268
+ set skipToken(value) {
269
+ this.options.skipToken = value;
270
+ }
271
+ get recognizes() {
272
+ return this.options.recognizes || [];
273
+ }
274
+ set recognizes(value) {
275
+ this.options.recognizes = value;
276
+ }
277
+ get hoistChildren() {
278
+ return this.options.hoistChildren || [];
279
+ }
280
+ set hoistChildren(value) {
281
+ this.options.hoistChildren = value;
282
+ }
283
+ getMapContent() {
284
+ return this.options.mapContent;
285
+ }
286
+ mapContent(key, value = 'copy') {
287
+ this.options.mapContent = this.options.mapContent || {};
288
+ this.options.mapContent[key] = value;
289
+ return this;
290
+ }
291
+ onMatch(value) {
292
+ this.options.onMatch = value;
293
+ return this;
294
+ }
295
+ onAppendContent(value) {
296
+ this.options.onAppendContent = value;
297
+ return this;
298
+ }
299
+ onAfterChildParse(value) {
300
+ this.options.onAfterChildParse = value;
301
+ return this;
302
+ }
303
+ onBeforeChildParse(value) {
304
+ this.options.onBeforeChildParse = value;
305
+ return this;
306
+ }
307
+ onMatchStartToken(value) {
308
+ if (this.options.startsWith) {
309
+ this.options.startsWith.onMatchToken = value;
310
+ }
311
+ return this;
312
+ }
313
+ onMatchEndToken(value) {
314
+ if (this.options.endsWith) {
315
+ this.options.endsWith.onMatchToken = value;
316
+ }
317
+ return this;
318
+ }
319
+ initCustomData(value) {
320
+ this.options.initCustomData = value;
321
+ return this;
322
+ }
323
+ onPop(value) {
324
+ this.options.onPop = value;
325
+ return this;
326
+ }
327
+ get popsAfterNode() {
328
+ return this.options.popsAfterNode || [];
329
+ }
330
+ set popsAfterNode(nodes) {
331
+ this.options.popsAfterNode = nodes;
332
+ }
333
+ clearStartsWith() {
334
+ delete this.options.startsWith;
335
+ return this;
336
+ }
337
+ clearEndsWith() {
338
+ delete this.options.endsWith;
339
+ return this;
340
+ }
341
+ clearPopsAtEOFSource() {
342
+ delete this.options.popsAtEOFSource;
343
+ return this;
344
+ }
345
+ clearBadToken() {
346
+ delete this.options.badToken;
347
+ return this;
348
+ }
349
+ clearSkipToken() {
350
+ delete this.options.skipToken;
351
+ return this;
352
+ }
353
+ clearAbsorbs(node) {
354
+ if (this.options.absorbs) {
355
+ if (node && Array.isArray(node)) {
356
+ for (const n of node) {
357
+ delete this.options.absorbs[n.id];
358
+ }
359
+ }
360
+ else if (node) {
361
+ delete this.options.absorbs[node.id];
362
+ }
363
+ else {
364
+ this.options.absorbs = {};
365
+ }
366
+ }
367
+ return this;
368
+ }
369
+ clearRecognizes(...args) {
370
+ var _a;
371
+ if (args.length) {
372
+ this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
373
+ }
374
+ else {
375
+ this.options.recognizes = [];
376
+ }
377
+ return this;
378
+ }
379
+ clearHoistChildren() {
380
+ delete this.options.hoistChildren;
381
+ return this;
382
+ }
383
+ clearMapContent() {
384
+ delete this.options.mapContent;
385
+ return this;
386
+ }
387
+ removeOnPop() {
388
+ delete this.options.onPop;
389
+ return this;
390
+ }
391
+ removeOnMatch() {
392
+ delete this.options.onMatch;
393
+ return this;
394
+ }
395
+ removeOnAppendContent() {
396
+ delete this.options.onAppendContent;
397
+ return this;
398
+ }
399
+ removeOnBeforeChildParse() {
400
+ delete this.options.onBeforeChildParse;
401
+ return this;
402
+ }
403
+ removeOnAfterChildParse() {
404
+ delete this.options.onAfterChildParse;
405
+ return this;
406
+ }
407
+ fireNodeMatched(matched, cbData) {
408
+ return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
409
+ }
410
+ fireNodeEndMatched(matched, cbData) {
411
+ return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
412
+ }
413
+ fireMatched(descr, matched, cbData) {
414
+ const { omit, eject, onMatchToken } = descr;
415
+ let cbResult = true;
416
+ if (onMatchToken) {
417
+ cbResult = onMatchToken({
418
+ ...cbData,
419
+ matched,
420
+ });
421
+ }
422
+ const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
423
+ const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
424
+ return {
425
+ omit: cbOmit !== undefined ? cbOmit : omit,
426
+ eject: cbEject !== undefined ? cbEject : eject,
427
+ confirmed: cbResult !== false,
428
+ };
429
+ }
430
+ getStartTokenRg() {
431
+ return this.getRgOutOfTokenDescriptor(this.options.startsWith);
432
+ }
433
+ getEndTokenRg() {
434
+ return this.getRgOutOfTokenDescriptor(this.options.endsWith);
435
+ }
436
+ getConstraintTokens() {
437
+ return {
438
+ skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
439
+ bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
440
+ };
441
+ }
442
+ getRgOutOfTokenDescriptor(descr) {
443
+ if (descr) {
444
+ const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
445
+ let token;
446
+ if (typeof descr.token === 'function') {
447
+ token = descr.token(this);
448
+ }
449
+ else {
450
+ token = descr.token;
451
+ }
452
+ if (token instanceof RegExp) {
453
+ return new RegExp(prefix + token.source, token.flags);
454
+ }
455
+ else {
456
+ return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex(t)).join('|')})`);
457
+ }
458
+ }
459
+ }
460
+ }
461
+
462
+ class ProstoHoistManager {
463
+ constructor() {
464
+ this.data = {};
465
+ }
466
+ addHoistOptions(ctx) {
467
+ if (ctx.hoistChildren) {
468
+ ctx.hoistChildren.forEach(options => {
469
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
470
+ const hoist = this.data[nodeId] = (this.data[nodeId] || {});
471
+ if (hoist) {
472
+ hoist[ctx.index] = {
473
+ options,
474
+ context: ctx,
475
+ };
476
+ }
477
+ });
478
+ }
479
+ }
480
+ removeHoistOptions(ctx) {
481
+ if (ctx.hoistChildren) {
482
+ ctx.hoistChildren.forEach(options => {
483
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
484
+ const hoist = this.data[nodeId];
485
+ if (hoist) {
486
+ delete hoist[ctx.index];
487
+ }
488
+ });
489
+ }
490
+ }
491
+ processHoistOptions(ctx) {
492
+ const id = ctx.node.id;
493
+ const hoist = this.data[id];
494
+ if (hoist) {
495
+ Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
496
+ const customData = context.getCustomData();
497
+ if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
498
+ if (options.asArray) {
499
+ const hoisted = customData[options.as] = (customData[options.as] || []);
500
+ if (!Array.isArray(hoisted)) {
501
+ if (!options.onConflict || options.onConflict === 'error') {
502
+ throw new Error(`Can not hoist "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists and it is not an Array Type.`);
503
+ }
504
+ else if (options.onConflict === 'overwrite') {
505
+ customData[options.as] = [doTheMapRule(options, ctx)];
506
+ }
507
+ else if (options.onConflict !== 'ignore') {
508
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
509
+ }
510
+ }
511
+ else {
512
+ hoisted.push(doTheMapRule(options, ctx));
513
+ }
514
+ }
515
+ else {
516
+ if (customData[options.as]) {
517
+ if (!options.onConflict || options.onConflict === 'error') {
518
+ throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
519
+ }
520
+ else if (options.onConflict === 'overwrite') {
521
+ customData[options.as] = doTheMapRule(options, ctx);
522
+ }
523
+ else if (options.onConflict !== 'ignore') {
524
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
525
+ }
526
+ }
527
+ else {
528
+ customData[options.as] = doTheMapRule(options, ctx);
529
+ }
530
+ }
531
+ if (options.removeChildFromContent) {
532
+ context.content = context.content.filter(c => c !== ctx);
533
+ }
534
+ }
535
+ });
536
+ }
537
+ function doTheMapRule(options, ctx) {
538
+ var _a;
539
+ if (typeof options.mapRule === 'function') {
540
+ return options.mapRule(ctx);
541
+ }
542
+ if (options.mapRule === 'content.join') {
543
+ return ctx.content.join('');
544
+ }
545
+ if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
546
+ const key = options.mapRule.slice(11);
547
+ if (key) {
548
+ return ctx.getCustomData()[key];
549
+ }
550
+ else {
551
+ return ctx.getCustomData();
552
+ }
553
+ }
554
+ return ctx;
555
+ }
556
+ }
557
+ }
558
+
559
+ const banner$1 = '' + '[parser]' + '';
560
+ class ProstoParserContext {
561
+ constructor(root) {
562
+ this.root = root;
563
+ this.nodes = {};
564
+ this.pos = 0;
565
+ this.index = 0;
566
+ this.behind = '';
567
+ this.here = '';
568
+ this.src = '';
569
+ this.stack = [];
570
+ this.l = 0;
571
+ this.hoistManager = new ProstoHoistManager();
572
+ this.context = root;
573
+ }
574
+ parse(src) {
575
+ this.src = src,
576
+ this.here = src,
577
+ this.l = src.length;
578
+ const cache = {};
579
+ while (this.pos < this.l) {
580
+ const searchTokens = this.context.getSearchTokens();
581
+ let closestIndex = Number.MAX_SAFE_INTEGER;
582
+ let closestToken;
583
+ let matched;
584
+ for (const t of searchTokens) {
585
+ const key = t.g.source;
586
+ t.g.lastIndex = this.pos;
587
+ let cached = cache[key];
588
+ if (cached === null)
589
+ continue;
590
+ if (cached && cached.index < this.pos) {
591
+ cached = null;
592
+ delete cache[key];
593
+ }
594
+ if (!cached) {
595
+ cached = t.g.exec(this.src);
596
+ if (cached || (this.pos === 0 && !cached)) {
597
+ cache[key] = cached;
598
+ }
599
+ }
600
+ if (cached && cached.index < closestIndex) {
601
+ closestIndex = cached.index;
602
+ matched = cached;
603
+ closestToken = t;
604
+ if (closestIndex === this.pos)
605
+ break;
606
+ }
607
+ }
608
+ if (closestToken && matched) {
609
+ const toAppend = this.src.slice(this.pos, closestIndex);
610
+ if (toAppend) {
611
+ this.context.appendContent(toAppend);
612
+ this.jump(toAppend.length);
613
+ }
614
+ const matchedToken = matched[0];
615
+ if (closestToken.node) {
616
+ const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
617
+ if (!confirmed)
618
+ continue;
619
+ let toAppend = '';
620
+ if (eject) {
621
+ this.context.appendContent(matchedToken);
622
+ }
623
+ else if (!omit) {
624
+ toAppend = matchedToken;
625
+ }
626
+ this.jump(matchedToken.length);
627
+ this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
628
+ this.context.fireOnMatch(matched);
629
+ continue;
630
+ }
631
+ else {
632
+ const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
633
+ if (!confirmed)
634
+ continue;
635
+ if (!eject && !omit) {
636
+ this.context.appendContent(matchedToken);
637
+ }
638
+ if (!eject) {
639
+ this.jump(matchedToken.length);
640
+ }
641
+ this.context.mapNamedGroups(matched);
642
+ this.pop();
643
+ continue;
644
+ }
645
+ }
646
+ else {
647
+ this.context.appendContent(this.here);
648
+ this.jump(this.here.length);
649
+ }
650
+ }
651
+ if (this.context !== this.root) {
652
+ while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
653
+ this.pop();
654
+ }
655
+ if (this.context !== this.root) {
656
+ this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
657
+ }
658
+ return this.root;
659
+ }
660
+ pop() {
661
+ const parentContext = this.stack.pop();
662
+ this.context.fireOnPop();
663
+ if (parentContext) {
664
+ parentContext.fireAfterChildParse(this.context);
665
+ parentContext.fireAbsorb(this.context);
666
+ this.context.cleanup();
667
+ const node = this.context.node;
668
+ this.context = parentContext;
669
+ if (parentContext.popsAfterNode.includes(node)) {
670
+ this.pop();
671
+ }
672
+ }
673
+ else {
674
+ this.context.cleanup();
675
+ }
676
+ }
677
+ pushNewContext(newNode, content) {
678
+ this.index++;
679
+ const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
680
+ ctx.content = content;
681
+ this.context.fireBeforeChildParse(ctx);
682
+ this.context.pushChild(ctx);
683
+ this.stack.push(this.context);
684
+ this.hoistManager.addHoistOptions(this.context);
685
+ this.context = ctx;
686
+ return ctx;
687
+ }
688
+ fromStack(depth = 0) {
689
+ return this.stack[this.stack.length - depth - 1];
690
+ }
691
+ jump(n = 1) {
692
+ this.pos += n;
693
+ this.behind = this.src.slice(0, this.pos);
694
+ this.here = this.src.slice(this.pos, this.l);
695
+ return this.pos;
696
+ }
697
+ getCallbackData(matched) {
698
+ return {
699
+ parserContext: this,
700
+ context: this.context,
701
+ matched,
702
+ customData: this.context.getCustomData(),
703
+ };
704
+ }
705
+ getPosition(offset = 0) {
706
+ var _a;
707
+ const past = this.src.slice(0, this.pos + offset).split('\n');
708
+ const row = past.length;
709
+ const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
710
+ return {
711
+ row, col, pos: this.pos,
712
+ };
713
+ }
714
+ panic(message, errorBackOffset = 0) {
715
+ if (this.pos > 0) {
716
+ const { row, col } = this.getPosition(-errorBackOffset);
717
+ console.error(banner$1 + '', message, '');
718
+ console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
719
+ console.error(renderCodeFragment(this.src.split('\n'), {
720
+ row: row,
721
+ error: col,
722
+ }));
723
+ }
724
+ throw new Error(message);
725
+ }
726
+ panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
727
+ if (this.pos > 0) {
728
+ const { row, col } = this.getPosition(-bottomBackOffset);
729
+ console.error(banner$1 + '', message, '');
730
+ console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
731
+ console.error(renderCodeFragment(this.src.split('\n'), {
732
+ row: this.context.startPos.row,
733
+ error: this.context.startPos.col - topBackOffset,
734
+ rowEnd: row,
735
+ errorEnd: col,
736
+ }));
737
+ }
738
+ throw new Error(message);
739
+ }
740
+ }
741
+
742
+ const styles = {
743
+ banner: (s) => '' + s + '',
744
+ text: (s) => '' + s + '',
745
+ valuesDim: (s) => '' + '' + s + '' + '',
746
+ boolean: (s) => '' + s + '',
747
+ booleanDim: (s) => '' + '' + s + '' + '',
748
+ underscore: (s) => '' + s + '',
749
+ values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
750
+ nodeDim: (s) => '' + '' + s + '' + '',
751
+ node: (s) => '' + s + '',
752
+ };
753
+ const stringOutputLimit = 70;
754
+ const parserTree = new ProstoTree({
755
+ children: 'content',
756
+ renderLabel: (context) => {
757
+ if (typeof context === 'string') {
758
+ return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
759
+ }
760
+ else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
761
+ let keys = '';
762
+ const data = context.getCustomData();
763
+ Object.keys(data).forEach(key => {
764
+ const val = data[key];
765
+ if (typeof val === 'string' || typeof val === 'number') {
766
+ keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
767
+ }
768
+ else if (Array.isArray(val)) {
769
+ keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
770
+ }
771
+ else if (typeof val === 'object') {
772
+ keys += ' ' + styles.valuesDim(`{ ${key} }`);
773
+ }
774
+ else if (typeof val === 'boolean' && val) {
775
+ const st = key ? styles.boolean : styles.booleanDim;
776
+ keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
777
+ }
778
+ });
779
+ return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
780
+ }
781
+ return '';
782
+ },
783
+ });
784
+ function cut(s, n) {
785
+ const c = s.replace(/\n/g, '\\n');
786
+ if (c.length <= n)
787
+ return c;
788
+ return c.slice(0, n) + '' + '…';
789
+ }
790
+
791
+ class ProstoParserNodeContext extends ProstoParserNodeBase {
792
+ constructor(_node, index, level, parserContext) {
793
+ super();
794
+ this._node = _node;
795
+ this.index = index;
796
+ this.level = level;
797
+ this.content = [];
798
+ this._customData = {};
799
+ this.hasNodes = [];
800
+ this.count = {};
801
+ this.mapContentRules = {
802
+ 'first': (content) => content[0],
803
+ 'shift': (content) => content.shift(),
804
+ 'pop': (content) => content.pop(),
805
+ 'last': (content) => content[content.length - 1],
806
+ 'join': (content) => content.join(''),
807
+ 'join-clear': (content) => content.splice(0).join(''),
808
+ 'copy': (content) => content,
809
+ };
810
+ this.options = _node.getOptions();
811
+ if (this.options.initCustomData) {
812
+ this._customData = this.options.initCustomData();
813
+ }
814
+ this._label = this.options.label || '';
815
+ this._icon = this.options.icon || '◦';
816
+ this.parserContext = parserContext || new ProstoParserContext(this);
817
+ if (parserContext) {
818
+ this.parent = parserContext.context || parserContext.root;
819
+ }
820
+ this.startPos = this.parserContext.getPosition();
821
+ this.endPos = this.parserContext.getPosition();
822
+ }
823
+ getOptions() {
824
+ return this.options;
825
+ }
826
+ extractCustomDataTree() {
827
+ let content = this.content;
828
+ if (this.contentCopiedTo) {
829
+ content = this.customData[this.contentCopiedTo];
830
+ }
831
+ if (Array.isArray(content)) {
832
+ return content.map(c => {
833
+ if (typeof c === 'string') {
834
+ return c;
835
+ }
836
+ else {
837
+ return extract(c);
838
+ }
839
+ });
840
+ }
841
+ else {
842
+ const c = content;
843
+ if (c instanceof ProstoParserNodeContext) {
844
+ return extract(c);
845
+ }
846
+ else {
847
+ return content;
848
+ }
849
+ }
850
+ function extract(c) {
851
+ const cd = { ...c.getCustomData() };
852
+ if (c.contentCopiedTo) {
853
+ cd[c.contentCopiedTo] = c.extractCustomDataTree();
854
+ }
855
+ return cd;
856
+ }
857
+ }
858
+ getPrevNode(n = 1) {
859
+ if (this.parent) {
860
+ const index = this.parent.content.findIndex(n => n === this) - n;
861
+ if (index >= 0)
862
+ return this.parent.content[index];
863
+ }
864
+ }
865
+ getPrevContext(n = 1) {
866
+ if (this.parent) {
867
+ const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
868
+ const index = contexts.findIndex(n => n === this) - n;
869
+ if (index >= 0)
870
+ return contexts[index];
871
+ }
872
+ }
873
+ set icon(value) {
874
+ this._icon = value;
875
+ }
876
+ get icon() {
877
+ return this._icon;
878
+ }
879
+ set label(value) {
880
+ this._label = value;
881
+ }
882
+ get label() {
883
+ return this._label;
884
+ }
885
+ getCustomData() {
886
+ return this._customData;
887
+ }
888
+ get customData() {
889
+ return this._customData;
890
+ }
891
+ get nodeId() {
892
+ return this._node.id;
893
+ }
894
+ get node() {
895
+ return this._node;
896
+ }
897
+ toTree(options) {
898
+ return parserTree.render(this, options);
899
+ }
900
+ getSearchTokens() {
901
+ var _a;
902
+ const rg = this.getEndTokenRg();
903
+ const tokens = rg ? [{
904
+ rg,
905
+ y: addFlag(rg, 'y'),
906
+ g: addFlag(rg, 'g'),
907
+ }] : [];
908
+ (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
909
+ const rg = node.getStartTokenRg();
910
+ if (rg) {
911
+ tokens.push({
912
+ rg,
913
+ y: addFlag(rg, 'y'),
914
+ g: addFlag(rg, 'g'),
915
+ node,
916
+ });
917
+ }
918
+ });
919
+ function addFlag(rg, f) {
920
+ return new RegExp(rg.source, rg.flags + f);
921
+ }
922
+ return tokens;
923
+ }
924
+ appendContent(input) {
925
+ let s = input;
926
+ this.endPos = this.parserContext.getPosition();
927
+ let { skip, bad } = this.getConstraintTokens();
928
+ skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
929
+ bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
930
+ if (skip) {
931
+ s = s.replace(skip, '');
932
+ }
933
+ if (bad) {
934
+ const m = bad.exec(s);
935
+ if (m) {
936
+ this.parserContext.jump(m.index);
937
+ this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
938
+ }
939
+ }
940
+ s = this.fireOnAppendContent(s);
941
+ if (s) {
942
+ this.content.push(s);
943
+ }
944
+ }
945
+ cleanup() {
946
+ this.options = null;
947
+ }
948
+ pushChild(child) {
949
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
950
+ if (!absorbRule) {
951
+ this.content.push(child);
952
+ }
953
+ }
954
+ fireAbsorb(child) {
955
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
956
+ if (absorbRule) {
957
+ switch (absorbRule) {
958
+ case 'append':
959
+ this.content.push(...child.content);
960
+ break;
961
+ case 'join':
962
+ this.appendContent(child.content.join(''));
963
+ break;
964
+ default:
965
+ const [action, target] = absorbRule.split('->');
966
+ const cd = this.getCustomData();
967
+ if (action === 'copy') {
968
+ cd[target] = child.content;
969
+ }
970
+ else if (action === 'join') {
971
+ cd[target] = child.content.join('');
972
+ }
973
+ else {
974
+ this.parserContext.panic(`Absorb action "${action}" is not supported.`);
975
+ }
976
+ }
977
+ }
978
+ }
979
+ has(node) {
980
+ return this.hasNodes.includes(node);
981
+ }
982
+ countOf(node) {
983
+ return this.count[node.id] || 0;
984
+ }
985
+ mapNamedGroups(matched) {
986
+ if (matched.groups) {
987
+ const cd = this.getCustomData();
988
+ for (const [key, value] of Object.entries(matched.groups)) {
989
+ if (key === 'content') {
990
+ this.appendContent(value);
991
+ }
992
+ else {
993
+ cd[key] = value;
994
+ }
995
+ }
996
+ }
997
+ }
998
+ fireOnPop() {
999
+ this.endPos = this.parserContext.getPosition();
1000
+ this.processMappings();
1001
+ const data = this.parserContext.getCallbackData();
1002
+ this.node.beforeOnPop(data);
1003
+ if (this.options.onPop) {
1004
+ this.options.onPop(data);
1005
+ }
1006
+ }
1007
+ fireOnMatch(matched) {
1008
+ this.mapNamedGroups(matched);
1009
+ const data = this.parserContext.getCallbackData(matched);
1010
+ this.node.beforeOnMatch(data);
1011
+ if (this.options.onMatch) {
1012
+ return this.options.onMatch(data);
1013
+ }
1014
+ }
1015
+ fireBeforeChildParse(child) {
1016
+ const data = this.parserContext.getCallbackData();
1017
+ this.node.beforeOnBeforeChildParse(child, data);
1018
+ if (this.options.onBeforeChildParse) {
1019
+ return this.options.onBeforeChildParse(child, data);
1020
+ }
1021
+ }
1022
+ fireAfterChildParse(child) {
1023
+ if (!this.hasNodes.includes(child.node)) {
1024
+ this.hasNodes.push(child.node);
1025
+ }
1026
+ this.count[child.node.id] = this.count[child.node.id] || 0;
1027
+ this.count[child.node.id]++;
1028
+ const data = this.parserContext.getCallbackData();
1029
+ this.node.beforeOnAfterChildParse(child, data);
1030
+ if (this.options.onAfterChildParse) {
1031
+ return this.options.onAfterChildParse(child, data);
1032
+ }
1033
+ }
1034
+ fireOnAppendContent(s) {
1035
+ let _s = s;
1036
+ const data = this.parserContext.getCallbackData();
1037
+ _s = this.node.beforeOnAppendContent(_s, data);
1038
+ if (this.options.onAppendContent) {
1039
+ _s = this.options.onAppendContent(_s, data);
1040
+ }
1041
+ return _s;
1042
+ }
1043
+ processMappings() {
1044
+ this.parserContext.hoistManager.removeHoistOptions(this);
1045
+ this.parserContext.hoistManager.processHoistOptions(this);
1046
+ this.processMapContent();
1047
+ }
1048
+ processMapContent() {
1049
+ const targetNodeOptions = this.options;
1050
+ if (targetNodeOptions.mapContent) {
1051
+ Object.keys(targetNodeOptions.mapContent).forEach((key) => {
1052
+ const keyOfT = key;
1053
+ if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
1054
+ const mapRule = targetNodeOptions.mapContent[keyOfT];
1055
+ if (typeof mapRule === 'function') {
1056
+ this._customData[keyOfT] = mapRule(this.content);
1057
+ }
1058
+ else {
1059
+ const ruleKey = mapRule;
1060
+ if (ruleKey === 'copy')
1061
+ this.contentCopiedTo = keyOfT;
1062
+ this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
1063
+ }
1064
+ if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
1065
+ this.contentCopiedTo = keyOfT;
1066
+ }
1067
+ }
1068
+ });
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ let idCounter = 0;
1074
+ class ProstoParserNode extends ProstoParserNodeBase {
1075
+ constructor(options) {
1076
+ super();
1077
+ this.options = options;
1078
+ this.id = idCounter++;
1079
+ }
1080
+ getOptions() {
1081
+ return {
1082
+ label: this.options.label || '',
1083
+ icon: this.options.icon || '',
1084
+ startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
1085
+ endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
1086
+ popsAfterNode: [...(this.options.popsAfterNode || [])],
1087
+ popsAtEOFSource: this.options.popsAtEOFSource || false,
1088
+ badToken: this.options.badToken || '',
1089
+ skipToken: this.options.skipToken || '',
1090
+ recognizes: [...(this.options.recognizes || [])],
1091
+ hoistChildren: [...(this.options.hoistChildren || [])],
1092
+ mapContent: {
1093
+ ...this.options.mapContent,
1094
+ },
1095
+ onPop: this.options.onPop,
1096
+ onMatch: this.options.onMatch,
1097
+ onAppendContent: this.options.onAppendContent,
1098
+ onAfterChildParse: this.options.onAfterChildParse,
1099
+ onBeforeChildParse: this.options.onBeforeChildParse,
1100
+ initCustomData: this.options.initCustomData,
1101
+ absorbs: this.options.absorbs,
1102
+ };
1103
+ }
1104
+ createContext(index, level, rootContext) {
1105
+ return new ProstoParserNodeContext(this, index, level, rootContext);
1106
+ }
1107
+ get name() {
1108
+ return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
1109
+ }
1110
+ parse(source) {
1111
+ return this.createContext(0, 0).parserContext.parse(source);
1112
+ }
1113
+ beforeOnPop(data) {
1114
+ }
1115
+ beforeOnMatch(data) {
1116
+ }
1117
+ beforeOnAppendContent(s, data) {
1118
+ return s;
1119
+ }
1120
+ beforeOnAfterChildParse(child, data) {
1121
+ }
1122
+ beforeOnBeforeChildParse(child, data) {
1123
+ }
1124
+ }
1125
+
1126
+ class BasicNode extends ProstoParserNode {
1127
+ constructor(options) {
1128
+ var _a, _b;
1129
+ const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
1130
+ const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
1131
+ const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
1132
+ const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
1133
+ if (startsWith) {
1134
+ startsWith.omit = startOption === 'omit';
1135
+ startsWith.eject = startOption === 'eject';
1136
+ startsWith.ignoreBackSlashed = startBSlash === 'ignore';
1137
+ }
1138
+ if (endsWith) {
1139
+ endsWith.omit = endOption === 'omit';
1140
+ endsWith.eject = endOption === 'eject';
1141
+ endsWith.ignoreBackSlashed = endBSlash === 'ignore';
1142
+ }
1143
+ super({
1144
+ icon: options.icon || '',
1145
+ label: typeof options.label === 'string' ? options.label : '',
1146
+ startsWith,
1147
+ endsWith,
1148
+ badToken: options.badToken,
1149
+ skipToken: options.skipToken,
1150
+ });
1151
+ if (options.recursive) {
1152
+ this.addAbsorbs(this, 'join');
1153
+ }
1154
+ }
1155
+ }
1156
+
1157
+ class ParametricNodeWithRegex extends BasicNode {
1158
+ constructor(options, rgNode) {
1159
+ super(options);
1160
+ const hoistRegex = {
1161
+ as: 'regex',
1162
+ node: regexNode,
1163
+ onConflict: 'overwrite',
1164
+ removeChildFromContent: true,
1165
+ deep: 1,
1166
+ mapRule: ({ content }) => content.join('').replace(/^\(\^/, '(').replace(/\$\)$/, ')'),
1167
+ };
1168
+ this.mapContent('value', content => content.shift())
1169
+ .popsAtEOFSource(true)
1170
+ .addRecognizes(rgNode)
1171
+ .addPopsAfterNode(rgNode)
1172
+ .addHoistChildren(hoistRegex);
1173
+ }
1174
+ }
1175
+ const regexNode = new BasicNode({
1176
+ label: 'RegEx',
1177
+ tokens: ['(', ')'],
1178
+ backSlash: 'ignore-ignore',
1179
+ recursive: true,
1180
+ }).onMatch(({ parserContext, context }) => {
1181
+ var _a;
1182
+ if (((_a = parserContext.fromStack()) === null || _a === void 0 ? void 0 : _a.node) === context.node) {
1183
+ if (!parserContext.here.startsWith('?:')) {
1184
+ context.content[0] += '?:';
1185
+ }
1186
+ }
1187
+ });
1188
+ const paramNode = new ParametricNodeWithRegex({
1189
+ label: 'Parameter',
1190
+ tokens: [':', /[\/\-]/],
1191
+ tokenOE: 'omit-eject',
1192
+ backSlash: 'ignore-',
1193
+ }, regexNode).initCustomData(() => ({ type: EPathSegmentType.VARIABLE, value: '', regex: '([^\\/]*)' }));
1194
+ const wildcardNode = new ParametricNodeWithRegex({
1195
+ label: 'Wildcard',
1196
+ tokens: ['*', /[^*\()]/],
1197
+ tokenOE: '-eject',
1198
+ }, regexNode).initCustomData(() => ({ type: EPathSegmentType.WILDCARD, value: '*', regex: '(.*)' }));
1199
+ const staticNode = new BasicNode({
1200
+ label: 'Static',
1201
+ tokens: [/[^:\*]/, /[:\*]/],
1202
+ backSlash: '-ignore',
1203
+ tokenOE: '-eject',
1204
+ }).initCustomData(() => ({ type: EPathSegmentType.STATIC, value: '' }))
1205
+ .mapContent('value', content => content.splice(0).join('').replace(/\\:/g, ':'))
1206
+ .popsAtEOFSource(true);
1207
+ new BasicNode({}).addRecognizes(staticNode, paramNode, wildcardNode);
1208
+
1209
+ var EPathSegmentType;
1210
+ (function (EPathSegmentType) {
1211
+ EPathSegmentType[EPathSegmentType["STATIC"] = 0] = "STATIC";
1212
+ EPathSegmentType[EPathSegmentType["VARIABLE"] = 1] = "VARIABLE";
1213
+ EPathSegmentType[EPathSegmentType["REGEX"] = 2] = "REGEX";
1214
+ EPathSegmentType[EPathSegmentType["WILDCARD"] = 3] = "WILDCARD";
1215
+ })(EPathSegmentType || (EPathSegmentType = {}));
1216
+
1217
+ function useHttpContext() {
1218
+ return eventCore.useEventContext('HTTP');
1219
+ }
1220
+
1221
+ const httpStatusCodes = {
1222
+ [100]: 'Continue',
1223
+ [101]: 'Switching protocols',
1224
+ [102]: 'Processing',
1225
+ [103]: 'Early Hints',
1226
+ [200]: 'OK',
1227
+ [201]: 'Created',
1228
+ [202]: 'Accepted',
1229
+ [203]: 'Non-Authoritative Information',
1230
+ [204]: 'No Content',
1231
+ [205]: 'Reset Content',
1232
+ [206]: 'Partial Content',
1233
+ [207]: 'Multi-Status',
1234
+ [208]: 'Already Reported',
1235
+ [226]: 'IM Used',
1236
+ [300]: 'Multiple Choices',
1237
+ [301]: 'Moved Permanently',
1238
+ [302]: 'Found (Previously "Moved Temporarily")',
1239
+ [303]: 'See Other',
1240
+ [304]: 'Not Modified',
1241
+ [305]: 'Use Proxy',
1242
+ [306]: 'Switch Proxy',
1243
+ [307]: 'Temporary Redirect',
1244
+ [308]: 'Permanent Redirect',
1245
+ [400]: 'Bad Request',
1246
+ [401]: 'Unauthorized',
1247
+ [402]: 'Payment Required',
1248
+ [403]: 'Forbidden',
1249
+ [404]: 'Not Found',
1250
+ [405]: 'Method Not Allowed',
1251
+ [406]: 'Not Acceptable',
1252
+ [407]: 'Proxy Authentication Required',
1253
+ [408]: 'Request Timeout',
1254
+ [409]: 'Conflict',
1255
+ [410]: 'Gone',
1256
+ [411]: 'Length Required',
1257
+ [412]: 'Precondition Failed',
1258
+ [413]: 'Payload Too Large',
1259
+ [414]: 'URI Too Long',
1260
+ [415]: 'Unsupported Media Type',
1261
+ [416]: 'Range Not Satisfiable',
1262
+ [417]: 'Expectation Failed',
1263
+ [418]: 'I\'m a Teapot',
1264
+ [421]: 'Misdirected Request',
1265
+ [422]: 'Unprocessable Entity',
1266
+ [423]: 'Locked',
1267
+ [424]: 'Failed Dependency',
1268
+ [425]: 'Too Early',
1269
+ [426]: 'Upgrade Required',
1270
+ [428]: 'Precondition Required',
1271
+ [429]: 'Too Many Requests',
1272
+ [431]: 'Request Header Fields Too Large',
1273
+ [451]: 'Unavailable For Legal Reasons',
1274
+ [500]: 'Internal Server Error',
1275
+ [501]: 'Not Implemented',
1276
+ [502]: 'Bad Gateway',
1277
+ [503]: 'Service Unavailable',
1278
+ [504]: 'Gateway Timeout',
1279
+ [505]: 'HTTP Version Not Supported',
1280
+ [506]: 'Variant Also Negotiates',
1281
+ [507]: 'Insufficient Storage',
1282
+ [508]: 'Loop Detected',
1283
+ [510]: 'Not Extended',
1284
+ [511]: 'Network Authentication Required',
1285
+ };
1286
+ var EHttpStatusCode;
1287
+ (function (EHttpStatusCode) {
1288
+ EHttpStatusCode[EHttpStatusCode["Continue"] = 100] = "Continue";
1289
+ EHttpStatusCode[EHttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
1290
+ EHttpStatusCode[EHttpStatusCode["Processing"] = 102] = "Processing";
1291
+ EHttpStatusCode[EHttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
1292
+ EHttpStatusCode[EHttpStatusCode["OK"] = 200] = "OK";
1293
+ EHttpStatusCode[EHttpStatusCode["Created"] = 201] = "Created";
1294
+ EHttpStatusCode[EHttpStatusCode["Accepted"] = 202] = "Accepted";
1295
+ EHttpStatusCode[EHttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
1296
+ EHttpStatusCode[EHttpStatusCode["NoContent"] = 204] = "NoContent";
1297
+ EHttpStatusCode[EHttpStatusCode["ResetContent"] = 205] = "ResetContent";
1298
+ EHttpStatusCode[EHttpStatusCode["PartialContent"] = 206] = "PartialContent";
1299
+ EHttpStatusCode[EHttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
1300
+ EHttpStatusCode[EHttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
1301
+ EHttpStatusCode[EHttpStatusCode["IMUsed"] = 226] = "IMUsed";
1302
+ EHttpStatusCode[EHttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
1303
+ EHttpStatusCode[EHttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
1304
+ EHttpStatusCode[EHttpStatusCode["Found"] = 302] = "Found";
1305
+ EHttpStatusCode[EHttpStatusCode["SeeOther"] = 303] = "SeeOther";
1306
+ EHttpStatusCode[EHttpStatusCode["NotModified"] = 304] = "NotModified";
1307
+ EHttpStatusCode[EHttpStatusCode["UseProxy"] = 305] = "UseProxy";
1308
+ EHttpStatusCode[EHttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy";
1309
+ EHttpStatusCode[EHttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
1310
+ EHttpStatusCode[EHttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
1311
+ EHttpStatusCode[EHttpStatusCode["BadRequest"] = 400] = "BadRequest";
1312
+ EHttpStatusCode[EHttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
1313
+ EHttpStatusCode[EHttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
1314
+ EHttpStatusCode[EHttpStatusCode["Forbidden"] = 403] = "Forbidden";
1315
+ EHttpStatusCode[EHttpStatusCode["NotFound"] = 404] = "NotFound";
1316
+ EHttpStatusCode[EHttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
1317
+ EHttpStatusCode[EHttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
1318
+ EHttpStatusCode[EHttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
1319
+ EHttpStatusCode[EHttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
1320
+ EHttpStatusCode[EHttpStatusCode["Conflict"] = 409] = "Conflict";
1321
+ EHttpStatusCode[EHttpStatusCode["Gone"] = 410] = "Gone";
1322
+ EHttpStatusCode[EHttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
1323
+ EHttpStatusCode[EHttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
1324
+ EHttpStatusCode[EHttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
1325
+ EHttpStatusCode[EHttpStatusCode["URITooLong"] = 414] = "URITooLong";
1326
+ EHttpStatusCode[EHttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
1327
+ EHttpStatusCode[EHttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
1328
+ EHttpStatusCode[EHttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
1329
+ EHttpStatusCode[EHttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
1330
+ EHttpStatusCode[EHttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
1331
+ EHttpStatusCode[EHttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
1332
+ EHttpStatusCode[EHttpStatusCode["Locked"] = 423] = "Locked";
1333
+ EHttpStatusCode[EHttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
1334
+ EHttpStatusCode[EHttpStatusCode["TooEarly"] = 425] = "TooEarly";
1335
+ EHttpStatusCode[EHttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
1336
+ EHttpStatusCode[EHttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
1337
+ EHttpStatusCode[EHttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
1338
+ EHttpStatusCode[EHttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
1339
+ EHttpStatusCode[EHttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
1340
+ EHttpStatusCode[EHttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
1341
+ EHttpStatusCode[EHttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
1342
+ EHttpStatusCode[EHttpStatusCode["BadGateway"] = 502] = "BadGateway";
1343
+ EHttpStatusCode[EHttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
1344
+ EHttpStatusCode[EHttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
1345
+ EHttpStatusCode[EHttpStatusCode["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
1346
+ EHttpStatusCode[EHttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
1347
+ EHttpStatusCode[EHttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
1348
+ EHttpStatusCode[EHttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
1349
+ EHttpStatusCode[EHttpStatusCode["NotExtended"] = 510] = "NotExtended";
1350
+ EHttpStatusCode[EHttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
1351
+ })(EHttpStatusCode || (EHttpStatusCode = {}));
1352
+
1353
+ ({
1354
+ GET: EHttpStatusCode.OK,
1355
+ POST: EHttpStatusCode.Created,
1356
+ PUT: EHttpStatusCode.Created,
1357
+ PATCH: EHttpStatusCode.Accepted,
1358
+ DELETE: EHttpStatusCode.Accepted,
1359
+ });
1360
+
1361
+ class WooksError extends Error {
1362
+ constructor(code = 500, _body = '') {
1363
+ super(typeof _body === 'string' ? _body : _body.message);
1364
+ this.code = code;
1365
+ this._body = _body;
1366
+ }
1367
+ get body() {
1368
+ return typeof this._body === 'string' ? {
1369
+ statusCode: this.code,
1370
+ message: this.message,
1371
+ error: httpStatusCodes[this.code],
1372
+ } : Object.assign(Object.assign({}, this._body), { statusCode: this.code, message: this.message, error: httpStatusCodes[this.code] });
1373
+ }
1374
+ attachRenderer(renderer) {
1375
+ this.renderer = renderer;
1376
+ }
1377
+ getRenderer() {
1378
+ return this.renderer;
1379
+ }
1380
+ }
1381
+
1382
+ const METADATA_WORKSPACE = 'moost';
1383
+ const moostMate = new mate.Mate(METADATA_WORKSPACE, {
1384
+ readType: true,
1385
+ readReturnType: true,
1386
+ });
1387
+ function getMoostMate() {
1388
+ return moostMate;
1389
+ }
1390
+
1391
+ function getInstanceOwnMethods(instance) {
1392
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1393
+ const proto = Object.getPrototypeOf(instance);
1394
+ return [
1395
+ ...Object.getOwnPropertyNames(proto),
1396
+ ...Object.getOwnPropertyNames(instance),
1397
+ ].filter(m => typeof instance[m] === 'function');
1398
+ }
1399
+
1400
+ const banner = () => `[${"moost"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
1401
+
1402
+ /* istanbul ignore file */
1403
+ function log(text) {
1404
+ console.log('' + '' + banner() + text + '');
1405
+ }
1406
+ function logError(error) {
1407
+ console.error('' + '' + banner() + error + '');
1408
+ }
1409
+
1410
+ function panic(error) {
1411
+ logError(error);
1412
+ return new Error(error);
1413
+ }
1414
+
1415
+ function runPipes(pipes, meta, restoreCtx) {
1416
+ return __awaiter(this, void 0, void 0, function* () {
1417
+ let v = undefined;
1418
+ for (const pipe of pipes) {
1419
+ restoreCtx && restoreCtx();
1420
+ v = yield pipe.handler(v, meta);
1421
+ }
1422
+ return v;
1423
+ });
1424
+ }
1425
+
1426
+ exports.TPipePriority = void 0;
1427
+ (function (TPipePriority) {
1428
+ TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
1429
+ TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
1430
+ TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
1431
+ TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
1432
+ TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
1433
+ TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
1434
+ TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
1435
+ TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
1436
+ TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
1437
+ })(exports.TPipePriority || (exports.TPipePriority = {}));
1438
+
1439
+ const resolvePipe = (_value, meta) => {
1440
+ if (meta === null || meta === void 0 ? void 0 : meta.resolver) {
1441
+ return meta.resolver();
1442
+ }
1443
+ return undefined;
1444
+ };
1445
+ resolvePipe.priority = exports.TPipePriority.RESOLVE;
1446
+
1447
+ const sharedPipes = [
1448
+ {
1449
+ handler: resolvePipe,
1450
+ priority: exports.TPipePriority.RESOLVE,
1451
+ },
1452
+ ];
1453
+
1454
+ const sharedMoostInfact = getNewMoostInfact();
1455
+ function getMoostInfact() {
1456
+ return sharedMoostInfact;
1457
+ }
1458
+ function getNewMoostInfact() {
1459
+ return new infact.Infact({
1460
+ describeClass(classConstructor) {
1461
+ const meta = getMoostMate().read(classConstructor);
1462
+ const infactMeta = {
1463
+ injectable: !!(meta === null || meta === void 0 ? void 0 : meta.injectable),
1464
+ global: false,
1465
+ constructorParams: (meta === null || meta === void 0 ? void 0 : meta.params) || [],
1466
+ provide: meta === null || meta === void 0 ? void 0 : meta.provide,
1467
+ scopeId: (meta === null || meta === void 0 ? void 0 : meta.injectable) === 'FOR_EVENT' ? eventCore.useEventId().getId() : undefined,
1468
+ };
1469
+ return infactMeta;
1470
+ },
1471
+ resolveParam(paramMeta) {
1472
+ if (paramMeta.resolver) {
1473
+ return runPipes(sharedPipes, paramMeta);
1474
+ }
1475
+ },
1476
+ storeProvideRegByInstance: true,
1477
+ });
1478
+ }
1479
+
1480
+ function getCallableFn(targetInstance, fn, restoreCtx) {
1481
+ return __awaiter(this, void 0, void 0, function* () {
1482
+ const mate$1 = getMoostMate();
1483
+ const meta = mate$1.read(fn);
1484
+ if (meta === null || meta === void 0 ? void 0 : meta.injectable) {
1485
+ const infact = getMoostInfact();
1486
+ infact.silent(meta.injectable === 'FOR_EVENT');
1487
+ const instance = yield infact.getForInstance(targetInstance, fn, [], () => { restoreCtx && restoreCtx(); });
1488
+ infact.silent(false);
1489
+ return ((...args) => {
1490
+ return instance.handler(...args);
1491
+ });
1492
+ }
1493
+ if (typeof fn === 'function') {
1494
+ return fn;
1495
+ }
1496
+ throw panic(`getCallableFn failed for "${mate.getConstructor(targetInstance).name}" because the passed arg is not a Function nor TClassFunction`);
1497
+ });
1498
+ }
1499
+
1500
+ class InterceptorHandler {
1501
+ constructor(handlers) {
1502
+ this.handlers = handlers;
1503
+ this.before = [];
1504
+ this.after = [];
1505
+ this.onError = [];
1506
+ this.responseOverwritten = false;
1507
+ }
1508
+ replyFn(reply) {
1509
+ this.response = reply;
1510
+ this.responseOverwritten = true;
1511
+ }
1512
+ init() {
1513
+ return __awaiter(this, void 0, void 0, function* () {
1514
+ const { restoreCtx } = eventCore.useEventContext();
1515
+ for (const handler of this.handlers) {
1516
+ restoreCtx();
1517
+ yield handler((fn) => { this.before.push(fn); }, (fn) => { this.after.unshift(fn); }, (fn) => { this.onError.unshift(fn); });
1518
+ }
1519
+ });
1520
+ }
1521
+ fireBefore(response) {
1522
+ return __awaiter(this, void 0, void 0, function* () {
1523
+ const { restoreCtx } = eventCore.useEventContext();
1524
+ this.response = response;
1525
+ for (const handler of this.before) {
1526
+ restoreCtx();
1527
+ yield handler(this.replyFn.bind(this));
1528
+ if (this.responseOverwritten)
1529
+ break;
1530
+ }
1531
+ return this.response;
1532
+ });
1533
+ }
1534
+ fireAfter(response) {
1535
+ return __awaiter(this, void 0, void 0, function* () {
1536
+ const { restoreCtx } = eventCore.useEventContext();
1537
+ this.response = response;
1538
+ if (response instanceof Error) {
1539
+ for (const handler of this.onError) {
1540
+ restoreCtx();
1541
+ yield handler(response, this.replyFn.bind(this));
1542
+ }
1543
+ }
1544
+ else {
1545
+ for (const handler of this.after) {
1546
+ restoreCtx();
1547
+ yield handler(response, this.replyFn.bind(this));
1548
+ }
1549
+ }
1550
+ return this.response;
1551
+ });
1552
+ }
1553
+ }
1554
+
1555
+ function bindControllerMethods(options) {
1556
+ var _a;
1557
+ return __awaiter(this, void 0, void 0, function* () {
1558
+ const opts = options || {};
1559
+ const { getInstance } = opts;
1560
+ const { classConstructor } = opts;
1561
+ const { adapters } = opts;
1562
+ opts.globalPrefix = opts.globalPrefix || '';
1563
+ opts.provide = opts.provide || {};
1564
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1565
+ const fakeInstance = Object.create(classConstructor.prototype);
1566
+ const methods = getInstanceOwnMethods(fakeInstance);
1567
+ const mate = getMoostMate();
1568
+ const meta = mate.read(classConstructor) || {};
1569
+ const ownPrefix = typeof opts.replaceOwnPrefix === 'string' ? opts.replaceOwnPrefix : (((_a = meta.controller) === null || _a === void 0 ? void 0 : _a.prefix) || '');
1570
+ const prefix = `${opts.globalPrefix}/${ownPrefix}`;
1571
+ for (const method of methods) {
1572
+ const methodMeta = getMoostMate().read(fakeInstance, method) || {};
1573
+ if (!methodMeta.handlers || !methodMeta.handlers.length)
1574
+ continue;
1575
+ // preparing interceptors
1576
+ const interceptors = [...(opts.interceptors || []), ...(meta.interceptors || []), ...(methodMeta.interceptors || [])].sort((a, b) => a.priority - b.priority);
1577
+ const getIterceptorHandler = () => __awaiter(this, void 0, void 0, function* () {
1578
+ const interceptorHandlers = [];
1579
+ for (const { handler } of interceptors) {
1580
+ const interceptorMeta = mate.read(handler);
1581
+ if (interceptorMeta === null || interceptorMeta === void 0 ? void 0 : interceptorMeta.injectable) {
1582
+ interceptorHandlers.push((...args) => __awaiter(this, void 0, void 0, function* () {
1583
+ const { restoreCtx } = useHttpContext();
1584
+ const targetInstance = yield getInstance();
1585
+ restoreCtx();
1586
+ return (yield getCallableFn(targetInstance, handler, restoreCtx))(...args);
1587
+ }));
1588
+ }
1589
+ else {
1590
+ interceptorHandlers.push(handler);
1591
+ }
1592
+ }
1593
+ return new InterceptorHandler(interceptorHandlers);
1594
+ });
1595
+ // preparing pipes
1596
+ const pipes = [...(opts.pipes || []), ...(meta.pipes || []), ...(methodMeta.pipes || [])];
1597
+ const argsPipes = [];
1598
+ for (const p of methodMeta.params || []) {
1599
+ argsPipes.push({
1600
+ meta: p,
1601
+ pipes: [...pipes, ...(p.pipes || [])].sort((a, b) => a.priority - b.priority),
1602
+ });
1603
+ }
1604
+ const resolveArgs = () => __awaiter(this, void 0, void 0, function* () {
1605
+ const args = [];
1606
+ const { restoreCtx } = eventCore.useEventContext();
1607
+ for (let i = 0; i < argsPipes.length; i++) {
1608
+ const { pipes, meta } = argsPipes[i];
1609
+ args[i] = yield runPipes(pipes, meta, restoreCtx);
1610
+ }
1611
+ return args;
1612
+ });
1613
+ // preparing provide
1614
+ // const provide = {...(opts.provide || {}), ...(meta.provide || {})}
1615
+ for (const adapter of adapters) {
1616
+ yield adapter.bindHandler({
1617
+ prefix,
1618
+ fakeInstance,
1619
+ getInstance,
1620
+ registerEventScope: (scopeId) => {
1621
+ const infact = getMoostInfact();
1622
+ infact.registerScope(scopeId);
1623
+ return () => infact.unregisterScope(scopeId);
1624
+ },
1625
+ method,
1626
+ handlers: methodMeta.handlers,
1627
+ getIterceptorHandler,
1628
+ resolveArgs,
1629
+ logHandler: (eventName) => log(`• ${eventName} ${'' + '' + ''}→ ${classConstructor.name}.${''}${method}${''}()`),
1630
+ });
1631
+ }
1632
+ }
1633
+ });
1634
+ }
1635
+
1636
+ function Label(value) {
1637
+ return getMoostMate().decorate('label', value);
1638
+ }
1639
+ function Id(value) {
1640
+ return getMoostMate().decorate('id', value);
1641
+ }
1642
+ function Optional() {
1643
+ return getMoostMate().decorate('optional', true);
1644
+ }
1645
+ function Required() {
1646
+ const mate = getMoostMate();
1647
+ return mate.apply(mate.decorate('required', true),
1648
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
1649
+ mate.decorateClass((meta, key, index) => {
1650
+ if (typeof index !== 'number' && meta && ['string', 'symbol'].includes(typeof key)) {
1651
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
1652
+ meta.requiredProps = meta.requiredProps || [];
1653
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
1654
+ meta.requiredProps.push(key);
1655
+ }
1656
+ return meta;
1657
+ }));
1658
+ }
1659
+
1660
+ /**
1661
+ * Hook to the Response Status
1662
+ * @decorator
1663
+ * @param resolver - resolver function
1664
+ * @param label - field label
1665
+ * @paramType unknown
1666
+ */
1667
+ function Resolve(resolver, label) {
1668
+ return (target, key, index) => {
1669
+ fillLabel(target, key, index, label);
1670
+ getMoostMate().decorate('resolver', resolver)(target, key, index);
1671
+ };
1672
+ }
1673
+ /**
1674
+ * Get Param Value from url parh
1675
+ * @decorator
1676
+ * @param name - param name
1677
+ * @paramType string
1678
+ */
1679
+ function Param(name) {
1680
+ return Resolve(() => eventCore.useRouteParams().get(name), name);
1681
+ }
1682
+ /**
1683
+ * Get Parsed Params from url parh
1684
+ * @decorator
1685
+ * @paramType object
1686
+ */
1687
+ function Params() {
1688
+ return Resolve(() => eventCore.useRouteParams().params, 'params');
1689
+ }
1690
+ /**
1691
+ * Provide Const Value
1692
+ * @decorator
1693
+ * @param value - provided value
1694
+ * @param label - label of the field
1695
+ * @paramType unknown
1696
+ */
1697
+ function Const(value, label) {
1698
+ return Resolve(() => value, label);
1699
+ }
1700
+ function fillLabel(target, key, index, name) {
1701
+ if (name) {
1702
+ const meta = getMoostMate().read(target, key);
1703
+ if (!(meta === null || meta === void 0 ? void 0 : meta.params) || !(meta === null || meta === void 0 ? void 0 : meta.params[index]) || !(meta === null || meta === void 0 ? void 0 : meta.params[index].label)) {
1704
+ Label(name)(target, key, index);
1705
+ }
1706
+ }
1707
+ }
1708
+
1709
+ /**
1710
+ * Mark the Class as Injectable to enable it to be used in dependency injection
1711
+ * @decorator
1712
+ * @param scope - Scope for injection ("FOR_EVENT" | "SINGLETON" | true)
1713
+ * FOR_EVENT - will create a new instance for each incoming request
1714
+ * SINGLETON | true - will create a new instance only once
1715
+ * @param label - field label
1716
+ */
1717
+ function Injectable(scope = true) {
1718
+ return getMoostMate().decorate('injectable', scope);
1719
+ }
1720
+ const insureInjectable = getMoostMate().decorate((meta) => {
1721
+ if (!meta.injectable)
1722
+ meta.injectable = true;
1723
+ return meta;
1724
+ });
1725
+
1726
+ /**
1727
+ * Set Class as a Controller
1728
+ * @decorator
1729
+ * @param prefix - define the prefix for all the paths of this controller
1730
+ */
1731
+ function Controller(prefix) {
1732
+ const mate = getMoostMate();
1733
+ return mate.apply(insureInjectable, mate.decorate('controller', { prefix: prefix || '' }));
1734
+ }
1735
+ function ImportController(prefix, controller, provide) {
1736
+ return getMoostMate().decorate('importController', {
1737
+ prefix: typeof prefix === 'string' ? prefix : undefined,
1738
+ typeResolver: typeof prefix === 'string' ? controller : prefix,
1739
+ provide: typeof prefix === 'string' ? provide || undefined : controller || undefined,
1740
+ }, true);
1741
+ }
1742
+
1743
+ function Circular(resolver) {
1744
+ return getMoostMate().decorate('circular', resolver);
1745
+ }
1746
+
1747
+ exports.TInterceptorPriority = void 0;
1748
+ (function (TInterceptorPriority) {
1749
+ TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
1750
+ TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
1751
+ TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
1752
+ TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
1753
+ TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
1754
+ TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
1755
+ TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
1756
+ })(exports.TInterceptorPriority || (exports.TInterceptorPriority = {}));
1757
+ function Intercept(handler, priority) {
1758
+ return getMoostMate().decorate('interceptors', {
1759
+ handler,
1760
+ priority: priority || handler.priority || exports.TInterceptorPriority.INTERCEPTOR,
1761
+ }, true);
1762
+ }
1763
+
1764
+ function Provide(type, fn) {
1765
+ return getMoostMate().decorate(meta => {
1766
+ meta.provide = meta.provide || {};
1767
+ Object.assign(meta.provide, infact.createProvideRegistry([type, fn]));
1768
+ return meta;
1769
+ });
1770
+ }
1771
+ function Inject(type) {
1772
+ return getMoostMate().decorate('inject', type);
1773
+ }
1774
+
1775
+ function Dto(dtoOptions = {}) {
1776
+ return getMoostMate().decorate('dto', dtoOptions || {});
1777
+ }
1778
+ let isArrayItemValidator = false;
1779
+ function Validate(validator) {
1780
+ return getMoostMate().decorate(isArrayItemValidator ? 'validatorsOfItem' : 'validators', validator, true);
1781
+ }
1782
+ function IsArray(opts) {
1783
+ const mate = getMoostMate();
1784
+ const decorators = [mate.decorate('arrayType', opts || true)];
1785
+ if ((opts === null || opts === void 0 ? void 0 : opts.itemValidators) && !isArrayItemValidator) {
1786
+ isArrayItemValidator = true;
1787
+ decorators.push(...opts.itemValidators());
1788
+ isArrayItemValidator = false;
1789
+ }
1790
+ else if ((opts === null || opts === void 0 ? void 0 : opts.itemValidators) && isArrayItemValidator) {
1791
+ throw new Error('IsArray validator is not supported inside of array type');
1792
+ }
1793
+ const decorator = mate.apply(...decorators);
1794
+ return decorator;
1795
+ }
1796
+ function IsTypeOf(type, errorText) {
1797
+ return Validate(valido$1.validoIsTypeOf(type, errorText));
1798
+ }
1799
+ function IsString(...args) {
1800
+ return Validate(valido$1.validoIsString(...args));
1801
+ }
1802
+ function IsNumber(...args) {
1803
+ return Validate(valido$1.validoIsNumber(...args));
1804
+ }
1805
+ function IsBoolean(...args) {
1806
+ return Validate(valido$1.validoIsBoolean(...args));
1807
+ }
1808
+
1809
+ const valido = new valido$1.Valido({
1810
+ getDtoMeta(value, _type) {
1811
+ let type = _type;
1812
+ if (!type) {
1813
+ type = mate.getConstructor(value);
1814
+ }
1815
+ const mate$1 = getMoostMate();
1816
+ return mate$1.read(type);
1817
+ },
1818
+ getDtoParamMeta(value, type, key) {
1819
+ const mate = getMoostMate();
1820
+ return mate.read(type, key);
1821
+ },
1822
+ });
1823
+ function getMoostValido() {
1824
+ return valido;
1825
+ }
1826
+
1827
+ class Moost {
1828
+ constructor(options) {
1829
+ this.options = options;
1830
+ this.pipes = [...sharedPipes];
1831
+ this.interceptors = [];
1832
+ this.adapters = [];
1833
+ this.provide = infact.createProvideRegistry([infact.Infact, getMoostInfact], [mate.Mate, getMoostMate], [valido$1.Valido, getMoostValido]);
1834
+ this.unregisteredControllers = [];
1835
+ }
1836
+ adapter(a) {
1837
+ this.adapters.push(a);
1838
+ return a;
1839
+ }
1840
+ init() {
1841
+ return __awaiter(this, void 0, void 0, function* () {
1842
+ this.setProvideRegistry(infact.createProvideRegistry([Moost, () => this]));
1843
+ this.unregisteredControllers.unshift(this);
1844
+ yield this.bindControllers();
1845
+ for (const a of this.adapters) {
1846
+ yield (a.onInit && a.onInit());
1847
+ }
1848
+ });
1849
+ }
1850
+ bindControllers() {
1851
+ var _a;
1852
+ return __awaiter(this, void 0, void 0, function* () {
1853
+ const meta = getMoostMate();
1854
+ const thisMeta = meta.read(this);
1855
+ const provide = Object.assign(Object.assign({}, ((thisMeta === null || thisMeta === void 0 ? void 0 : thisMeta.provide) || {})), this.provide);
1856
+ for (const controller of this.unregisteredControllers) {
1857
+ yield this.bindController(controller, provide, ((_a = this.options) === null || _a === void 0 ? void 0 : _a.globalPrefix) || '');
1858
+ }
1859
+ this.unregisteredControllers = [];
1860
+ });
1861
+ }
1862
+ bindController(controller, provide, globalPrefix, replaceOwnPrefix) {
1863
+ var _a;
1864
+ return __awaiter(this, void 0, void 0, function* () {
1865
+ const meta = getMoostMate();
1866
+ const classMeta = meta.read(controller);
1867
+ const infact = getMoostInfact();
1868
+ const isControllerConsructor = mate.isConstructor(controller);
1869
+ let instance;
1870
+ if (isControllerConsructor && (classMeta === null || classMeta === void 0 ? void 0 : classMeta.injectable) === 'SINGLETON') {
1871
+ instance = (yield infact.get(controller, provide));
1872
+ }
1873
+ else if (!isControllerConsructor) {
1874
+ instance = controller;
1875
+ infact.setProvideRegByInstance(instance, provide);
1876
+ }
1877
+ // getInstance - instance factory for resolving SINGLETON and FOR_EVENT instance
1878
+ const getInstance = instance ? () => Promise.resolve(instance) : () => __awaiter(this, void 0, void 0, function* () {
1879
+ // if (!instance) {
1880
+ infact.silent();
1881
+ const instance = yield infact.get(controller, provide);
1882
+ infact.silent(false);
1883
+ // }
1884
+ return instance;
1885
+ });
1886
+ const classConstructor = mate.isConstructor(controller) ? controller : mate.getConstructor(controller);
1887
+ yield bindControllerMethods({
1888
+ getInstance,
1889
+ classConstructor,
1890
+ adapters: this.adapters,
1891
+ globalPrefix,
1892
+ replaceOwnPrefix,
1893
+ interceptors: [...this.interceptors],
1894
+ pipes: [...this.pipes],
1895
+ provide: (classMeta === null || classMeta === void 0 ? void 0 : classMeta.provide) || {},
1896
+ });
1897
+ if (classMeta && classMeta.importController) {
1898
+ const prefix = typeof replaceOwnPrefix === 'string' ? replaceOwnPrefix : (_a = classMeta === null || classMeta === void 0 ? void 0 : classMeta.controller) === null || _a === void 0 ? void 0 : _a.prefix;
1899
+ const mergedProvide = Object.assign(Object.assign({}, provide), ((classMeta === null || classMeta === void 0 ? void 0 : classMeta.provide) || {}));
1900
+ for (const ic of classMeta.importController) {
1901
+ if (ic.typeResolver) {
1902
+ const isConstr = mate.isConstructor(ic.typeResolver);
1903
+ const isFunc = typeof ic.typeResolver === 'function';
1904
+ yield this.bindController(
1905
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1906
+ isConstr ? ic.typeResolver : isFunc ? yield ic.typeResolver() : ic.typeResolver, ic.provide ? Object.assign(Object.assign({}, mergedProvide), ic.provide) : mergedProvide, `${globalPrefix}/${(prefix || '')}`, ic.prefix);
1907
+ }
1908
+ }
1909
+ }
1910
+ });
1911
+ }
1912
+ applyGlobalPipes(...items) {
1913
+ for (const item of items) {
1914
+ if (typeof item === 'function') {
1915
+ this.pipes.push({
1916
+ handler: item,
1917
+ priority: typeof item.priority === 'number' ? item.priority : exports.TPipePriority.TRANSFORM,
1918
+ });
1919
+ }
1920
+ else {
1921
+ this.pipes.push({
1922
+ handler: item.handler,
1923
+ priority: item.priority,
1924
+ });
1925
+ }
1926
+ }
1927
+ return this;
1928
+ }
1929
+ applyGlobalInterceptors(...items) {
1930
+ for (const item of items) {
1931
+ if (typeof item === 'function') {
1932
+ this.interceptors.push({
1933
+ handler: item,
1934
+ priority: typeof item.priority === 'number' ? item.priority : exports.TInterceptorPriority.INTERCEPTOR,
1935
+ });
1936
+ }
1937
+ else {
1938
+ this.interceptors.push({
1939
+ handler: item.handler,
1940
+ priority: item.priority,
1941
+ });
1942
+ }
1943
+ }
1944
+ return this;
1945
+ }
1946
+ /**
1947
+ * Register new entried to provide as dependency injections
1948
+ * @param provide - Provide Registry (use createProvideRegistry from '\@prostojs/infact')
1949
+ * @returns
1950
+ */
1951
+ setProvideRegistry(provide) {
1952
+ this.provide = Object.assign(Object.assign({}, this.provide), provide);
1953
+ return this;
1954
+ }
1955
+ /**
1956
+ * Register controllers (similar to @ImportController decorator)
1957
+ * @param controllers - list of target controllers (instances)
1958
+ * @returns
1959
+ */
1960
+ registerControllers(...controllers) {
1961
+ this.unregisteredControllers.push(...controllers);
1962
+ return this;
1963
+ }
1964
+ }
1965
+
1966
+ function useControllerMeta() {
1967
+ const moostStore = useMoostStore();
1968
+ return {
1969
+ getClassMeta: () => getMoostMate().read(moostStore.value.controller),
1970
+ getMethodMeta: () => getMoostMate().read(moostStore.value.controller, moostStore.value.method),
1971
+ };
1972
+ }
1973
+ function useMoostStore() {
1974
+ return useHttpContext().store('moost');
1975
+ }
1976
+
1977
+ const genericTypesCastPipe = (strict) => {
1978
+ const handler = (value, meta) => {
1979
+ if (meta === null || meta === void 0 ? void 0 : meta.type) {
1980
+ if ((value === undefined || value === null || (meta.type !== String && value === '')) && meta.optional) {
1981
+ return undefined;
1982
+ }
1983
+ switch (meta.type) {
1984
+ case Date: {
1985
+ let d;
1986
+ if (typeof value === 'string') {
1987
+ d = new Date(/^\d+$/.test(value) ? Number(value) : value);
1988
+ }
1989
+ else {
1990
+ d = new Date(value);
1991
+ }
1992
+ if (strict && Number.isNaN(d.getTime())) {
1993
+ typeError(value, 'Date', meta.label);
1994
+ }
1995
+ return Number.isNaN(d.getTime()) ? value : d;
1996
+ }
1997
+ case Boolean:
1998
+ if ([true, 'true', 'TRUE', 'True', 1, '1', 'X', 'x'].includes(value)) {
1999
+ return true;
2000
+ }
2001
+ if ([false, 'false', 'FALSE', 'False', 0, '0', '', ' ', null, undefined].includes(value)) {
2002
+ return false;
2003
+ }
2004
+ if (strict) {
2005
+ typeError(value, 'boolean', meta.label);
2006
+ }
2007
+ return value;
2008
+ case Number: {
2009
+ if (strict && !value && value !== 0) {
2010
+ typeError(value, 'numeric', meta.label);
2011
+ }
2012
+ const n = typeof value === 'string' && value.length > 0 ? Number(value) : NaN;
2013
+ if (strict && Number.isNaN(n)) {
2014
+ typeError(value, 'numeric', meta.label);
2015
+ }
2016
+ return Number.isNaN(n) ? value : n;
2017
+ }
2018
+ case String:
2019
+ if (strict && ['object', 'function'].includes(typeof value)) {
2020
+ typeError(value, 'string', meta.label);
2021
+ }
2022
+ return value && String(value) || value;
2023
+ default:
2024
+ return value;
2025
+ }
2026
+ }
2027
+ };
2028
+ handler.priority = exports.TPipePriority.AFTER_TRANSFORM;
2029
+ return handler;
2030
+ };
2031
+ function typeError(value, targetType, label) {
2032
+ const prefix = label ? `Argument "${label}" with value ` : '';
2033
+ throw new WooksError(400, `${prefix}${JSON.stringify(value)} is not a ${targetType} type`);
2034
+ }
2035
+
2036
+ const DEFAULT_ERROR_LIMIT = 10;
2037
+ function firstString(errors) {
2038
+ const keys = Object.keys(errors);
2039
+ for (const key of keys) {
2040
+ if (typeof errors[key] === 'string')
2041
+ return errors[key];
2042
+ return firstString(errors[key]);
2043
+ }
2044
+ return '';
2045
+ }
2046
+ const validatePipe = (opts) => {
2047
+ const pipe = (_value, meta) => __awaiter(void 0, void 0, void 0, function* () {
2048
+ const { restoreCtx } = useHttpContext();
2049
+ const valido = getMoostValido();
2050
+ const result = yield valido.validateParam(_value, meta, undefined, undefined, undefined, undefined, 0, 0, (opts === null || opts === void 0 ? void 0 : opts.errorLimit) || DEFAULT_ERROR_LIMIT, restoreCtx);
2051
+ if (result !== true) {
2052
+ throw new WooksError(400, {
2053
+ statusCode: 400,
2054
+ message: typeof result === 'string' ? result : firstString(result),
2055
+ error: 'Validation Error',
2056
+ details: result,
2057
+ });
2058
+ }
2059
+ return _value;
2060
+ });
2061
+ pipe.priority = exports.TPipePriority.VALIDATE;
2062
+ return pipe;
2063
+ };
2064
+
2065
+ exports.Circular = Circular;
2066
+ exports.Const = Const;
2067
+ exports.Controller = Controller;
2068
+ exports.Dto = Dto;
2069
+ exports.Id = Id;
2070
+ exports.ImportController = ImportController;
2071
+ exports.Inject = Inject;
2072
+ exports.Injectable = Injectable;
2073
+ exports.Intercept = Intercept;
2074
+ exports.InterceptorHandler = InterceptorHandler;
2075
+ exports.IsArray = IsArray;
2076
+ exports.IsBoolean = IsBoolean;
2077
+ exports.IsNumber = IsNumber;
2078
+ exports.IsString = IsString;
2079
+ exports.IsTypeOf = IsTypeOf;
2080
+ exports.Label = Label;
2081
+ exports.Moost = Moost;
2082
+ exports.Optional = Optional;
2083
+ exports.Param = Param;
2084
+ exports.Params = Params;
2085
+ exports.Provide = Provide;
2086
+ exports.Required = Required;
2087
+ exports.Resolve = Resolve;
2088
+ exports.Validate = Validate;
2089
+ exports.genericTypesCastPipe = genericTypesCastPipe;
2090
+ exports.getMoostMate = getMoostMate;
2091
+ exports.resolvePipe = resolvePipe;
2092
+ exports.useControllerMeta = useControllerMeta;
2093
+ exports.validatePipe = validatePipe;