@moostjs/event-cli 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.cjs +33 -2675
  2. package/dist/index.mjs +26 -2668
  3. package/package.json +9 -2
package/dist/index.mjs CHANGED
@@ -1,2283 +1,6 @@
1
+ import { WooksCli, createCliApp, useCliContext, useFlags } from '@wooksjs/event-cli';
1
2
  import { randomUUID } from 'crypto';
2
- import 'url';
3
- import 'stream';
4
- import 'http';
5
-
6
- /******************************************************************************
7
- Copyright (c) Microsoft Corporation.
8
-
9
- Permission to use, copy, modify, and/or distribute this software for any
10
- purpose with or without fee is hereby granted.
11
-
12
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
- PERFORMANCE OF THIS SOFTWARE.
19
- ***************************************************************************** */
20
-
21
- function __awaiter$1(thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- }
30
-
31
- const banner$4 = () => `[${"@wooksjs/event-core"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
32
-
33
- /* istanbul ignore file */
34
- function logError$2(error) {
35
- console.error('' + '' + banner$4() + error + '');
36
- }
37
-
38
- function panic$1(error) {
39
- logError$2(error);
40
- return new Error(error);
41
- }
42
-
43
- // eslint-disable-next-line @typescript-eslint/ban-types
44
- function attachHook(target, opts, name) {
45
- Object.defineProperty(target, name || 'value', {
46
- get: opts.get,
47
- set: opts.set,
48
- });
49
- return target;
50
- }
51
-
52
- let currentContext = null;
53
- /**
54
- * Create a new event context
55
- *
56
- * @param data
57
- * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
58
- */
59
- function createEventContext(data) {
60
- const newContext = Object.assign({}, data);
61
- currentContext = newContext;
62
- return _getCtxHelpers(newContext);
63
- }
64
- /**
65
- * Use existing event context
66
- *
67
- * !Must be called syncronously while context is reachable
68
- *
69
- * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
70
- */
71
- function useEventContext(expectedTypes) {
72
- var _a;
73
- if (!currentContext) {
74
- throw panic$1('Event context does not exist. Use event context synchronously within the runtime of the event.');
75
- }
76
- const cc = currentContext;
77
- if (expectedTypes || typeof expectedTypes === 'string') {
78
- const type = (_a = cc.event) === null || _a === void 0 ? void 0 : _a.type;
79
- const types = typeof expectedTypes === 'string' ? [expectedTypes] : expectedTypes;
80
- if (!types.includes(type))
81
- panic$1(`Event context type mismatch: expected ${types.map(t => `"${t}"`).join(', ')}, received "${type}"`);
82
- }
83
- return _getCtxHelpers(cc);
84
- }
85
- function _getCtxHelpers(cc) {
86
- /**
87
- * Hook to an event store property
88
- *
89
- * @param key store property key
90
- * @returns a hook { value: <prop value>, hook: (key2: keyof <prop value>) => { value: <nested prop value> }, ... }
91
- */
92
- function store(key) {
93
- const obj = {
94
- value: null,
95
- hook,
96
- init,
97
- set: setNested,
98
- get: getNested,
99
- has: hasNested,
100
- del: delNested,
101
- entries,
102
- clear,
103
- };
104
- attachHook(obj, {
105
- set: v => set(key, v),
106
- get: () => get(key),
107
- });
108
- function init(key2, getter) {
109
- if (hasNested(key2))
110
- return getNested(key2);
111
- return setNested(key2, getter());
112
- }
113
- function hook(key2) {
114
- const obj = {
115
- value: null,
116
- isDefined: null,
117
- };
118
- attachHook(obj, {
119
- set: v => setNested(key2, v),
120
- get: () => getNested(key2),
121
- });
122
- attachHook(obj, {
123
- get: () => hasNested(key2),
124
- }, 'isDefined');
125
- return obj;
126
- }
127
- function setNested(key2, v) {
128
- if (typeof obj.value === 'undefined') {
129
- obj.value = {};
130
- }
131
- obj.value[key2] = v;
132
- return v;
133
- }
134
- function delNested(key2) {
135
- setNested(key2, undefined);
136
- }
137
- function getNested(key2) { return (obj.value || {})[key2]; }
138
- function hasNested(key2) { return typeof (obj.value || {})[key2] !== 'undefined'; }
139
- function entries() { return Object.entries((obj.value || {})); }
140
- function clear() { obj.value = {}; }
141
- return obj;
142
- }
143
- /**
144
- * Get event context object
145
- *
146
- * @returns whole context object
147
- */
148
- function getCtx() { return cc; }
149
- /**
150
- * Get value of event store property
151
- *
152
- * @param key property name
153
- * @returns value of property by name
154
- */
155
- function get(key) { return getCtx()[key]; }
156
- /**
157
- * Set value of event store property
158
- *
159
- * @param key property name
160
- * @param v property value
161
- */
162
- function set(key, v) {
163
- (getCtx())[key] = v;
164
- }
165
- return {
166
- getCtx,
167
- restoreCtx: () => currentContext = cc,
168
- clearCtx: () => cc === currentContext ? currentContext = null : null,
169
- store,
170
- getStore: get,
171
- setStore: set,
172
- };
173
- }
174
-
175
- function useEventId() {
176
- const { store } = useEventContext();
177
- const { init } = store('event');
178
- const getId = () => init('id', () => randomUUID());
179
- return { getId };
180
- }
181
-
182
- class ProstoCache {
183
- constructor(options) {
184
- this.data = {};
185
- this.limits = [];
186
- this.expireOrder = [];
187
- this.expireSeries = {};
188
- this.options = {
189
- limit: 1000,
190
- ...options,
191
- };
192
- }
193
- set(key, value) {
194
- var _a, _b, _c;
195
- if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.limit) === 0)
196
- return;
197
- const expires = ((_b = this.options) === null || _b === void 0 ? void 0 : _b.ttl) ? Math.round(new Date().getTime() / 1) + ((_c = this.options) === null || _c === void 0 ? void 0 : _c.ttl) : null;
198
- if (expires) {
199
- this.del(key);
200
- }
201
- this.data[key] = {
202
- value: value,
203
- expires,
204
- };
205
- if (expires) {
206
- this.pushExpires(key, expires);
207
- }
208
- this.pushLimit(key);
209
- }
210
- get(key) {
211
- var _a;
212
- return (_a = this.data[key]) === null || _a === void 0 ? void 0 : _a.value;
213
- }
214
- del(key) {
215
- const entry = this.data[key];
216
- if (entry) {
217
- delete this.data[key];
218
- if (entry.expires) {
219
- let es = this.expireSeries[entry.expires];
220
- if (es) {
221
- es = this.expireSeries[entry.expires] = es.filter(k => k !== key);
222
- }
223
- if (!es || !es.length) {
224
- delete this.expireSeries[entry.expires];
225
- const { found, index } = this.searchExpireOrder(entry.expires);
226
- if (found) {
227
- this.expireOrder.splice(index, 1);
228
- if (index === 0) {
229
- console.log('calling prepareTimeout');
230
- this.prepareTimeout();
231
- }
232
- }
233
- }
234
- }
235
- }
236
- }
237
- reset() {
238
- this.data = {};
239
- if (this.nextTimeout) {
240
- clearTimeout(this.nextTimeout);
241
- }
242
- this.expireOrder = [];
243
- this.expireSeries = {};
244
- this.limits = [];
245
- }
246
- searchExpireOrder(time) {
247
- return binarySearch(this.expireOrder, time);
248
- }
249
- pushLimit(key) {
250
- var _a;
251
- const limit = (_a = this.options) === null || _a === void 0 ? void 0 : _a.limit;
252
- if (limit) {
253
- const newObj = [key, ...(this.limits.filter(item => item !== key && this.data[item]))];
254
- const tail = newObj.slice(limit);
255
- this.limits = newObj.slice(0, limit);
256
- if (tail.length) {
257
- tail.forEach(tailItem => {
258
- this.del(tailItem);
259
- });
260
- }
261
- }
262
- }
263
- prepareTimeout() {
264
- if (this.nextTimeout) {
265
- clearTimeout(this.nextTimeout);
266
- }
267
- const time = this.expireOrder[0];
268
- const del = (time) => {
269
- for (const key of (this.expireSeries[time] || [])) {
270
- delete this.data[key];
271
- }
272
- delete this.expireSeries[time];
273
- this.expireOrder = this.expireOrder.slice(1);
274
- this.prepareTimeout();
275
- };
276
- if (time) {
277
- const delta = time - Math.round(new Date().getTime() / 1);
278
- if (delta > 0) {
279
- this.nextTimeout = setTimeout(() => {
280
- del(time);
281
- }, delta);
282
- }
283
- else {
284
- del(time);
285
- }
286
- }
287
- }
288
- pushExpires(key, time) {
289
- const { found, index } = this.searchExpireOrder(time);
290
- if (!found) {
291
- this.expireOrder.splice(index, 0, time);
292
- }
293
- const e = this.expireSeries[time] = this.expireSeries[time] || [];
294
- e.push(key);
295
- if (!found && index === 0) {
296
- this.prepareTimeout();
297
- }
298
- }
299
- }
300
- function binarySearch(a, n) {
301
- let start = 0;
302
- let end = a.length - 1;
303
- let mid = 0;
304
- while (start <= end) {
305
- mid = Math.floor((start + end) / 2);
306
- if (a[mid] === n) {
307
- return {
308
- found: true,
309
- index: mid,
310
- };
311
- }
312
- if (n < a[mid]) {
313
- end = mid - 1;
314
- mid--;
315
- }
316
- else {
317
- start = mid + 1;
318
- mid++;
319
- }
320
- }
321
- return {
322
- found: false,
323
- index: mid,
324
- };
325
- }
326
-
327
- const dim = '';
328
- const reset = '';
329
- class ProstoTree {
330
- constructor(options) {
331
- var _a, _b, _c, _d;
332
- const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
333
- const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
334
- const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
335
- const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
336
- const branches = {
337
- end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
338
- middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
339
- vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
340
- hLine,
341
- };
342
- this.options = {
343
- label: label,
344
- children: children,
345
- renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
346
- branches,
347
- branchWidth,
348
- };
349
- }
350
- _render(root, opts) {
351
- const { children, renderLabel } = this.options;
352
- let s = `${renderLabel(root, '')}\n`;
353
- const { end, middle, vLine, hLine } = this.options.branches;
354
- const endBranch = end + hLine + reset + ' ';
355
- const middleBranch = middle + hLine + reset + ' ';
356
- const { branchWidth } = this.options;
357
- if (root) {
358
- treeNode(root);
359
- }
360
- function treeNode(node, behind = '', level = 1) {
361
- const items = (node && node[children]);
362
- const count = items && items.length || 0;
363
- if (items) {
364
- if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
365
- s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
366
- }
367
- else {
368
- let itemsToRender = items;
369
- const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
370
- if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
371
- itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
372
- }
373
- if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
374
- s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
375
- itemsToRender.forEach((childNode, i) => {
376
- const last = i + 1 === count;
377
- const branch = last ? endBranch : middleBranch;
378
- const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
379
- s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
380
- if (typeof childNode === 'object') {
381
- treeNode(childNode, nextBehind, level + 1);
382
- }
383
- });
384
- if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
385
- s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
386
- }
387
- }
388
- }
389
- return s;
390
- }
391
- render(root, opts) {
392
- return this._render(root, opts);
393
- }
394
- print(root, opts) {
395
- const s = this.render(root, opts);
396
- console.log(s);
397
- return s;
398
- }
399
- }
400
- function renderCollapsedChildren(count) {
401
- return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
402
- }
403
-
404
- function renderCodeFragment(lines, options) {
405
- const row = (options.row || 1) - 1;
406
- const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
407
- const limit = Math.min(options.limit || 6, lines.length);
408
- const offset = Math.min(options.offset || 3, lines.length);
409
- const error = options.error;
410
- const errorEnd = options.errorEnd;
411
- let output = '';
412
- const delta = rowEnd - row;
413
- const maxIndex = lines.length;
414
- if (delta > limit) {
415
- let longestLine = 0;
416
- const newLimit = Math.floor(limit / 2);
417
- for (let i = 0; i < newLimit + offset; i++) {
418
- const index = row + i - offset;
419
- const line = lines[index] || '';
420
- longestLine = Math.max(line.length, longestLine);
421
- output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
422
- }
423
- let output2 = '';
424
- for (let i = newLimit + offset; i > 0; i--) {
425
- const index = rowEnd - i + offset;
426
- const line = lines[index] || '';
427
- longestLine = Math.max(line.length, longestLine);
428
- output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
429
- }
430
- output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
431
- }
432
- else {
433
- for (let i = 0; i < limit + offset; i++) {
434
- const index = row + i - offset;
435
- if (index <= lines.length + 1) {
436
- const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
437
- output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
438
- }
439
- }
440
- }
441
- return output;
442
- }
443
- function lineStyles(s) {
444
- return '' + (s || '')
445
- .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
446
- .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
447
- }
448
- function lineStylesError(s) {
449
- return '' + (s || '') + '';
450
- }
451
- function renderLine(line, index, error, style = '') {
452
- const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
453
- if (typeof error === 'number') {
454
- const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
455
- return renderLineNumber(index, true) +
456
- st +
457
- lineStyles(line.slice(0, error)) +
458
- lineStylesError(line.slice(error, error + errorLength)) +
459
- lineStyles(line.slice(error + errorLength)) +
460
- renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
461
- }
462
- return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
463
- }
464
- function renderLineNumber(i, isError = false, bold = false) {
465
- let s = ' ';
466
- const sep = i === '———';
467
- if (i && i > 0 || typeof i === 'string') {
468
- s = ' ' + String(i);
469
- }
470
- s = s.slice(s.length - 5);
471
- return '\n' + '' + (sep ? '' : '') +
472
- (isError ? '' + '' : (bold ? '' : '')) +
473
- s + (sep ? i : ' | ') + '';
474
- }
475
-
476
- function escapeRegex$1(s) {
477
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
478
- }
479
-
480
- class ProstoParserNodeBase {
481
- addRecognizes(...args) {
482
- for (const node of args) {
483
- if (!this.options.recognizes)
484
- this.options.recognizes = [];
485
- if (!this.options.recognizes.includes(node)) {
486
- this.options.recognizes.push(node);
487
- }
488
- }
489
- return this;
490
- }
491
- addAbsorbs(node, rule = 'append') {
492
- this.options.absorbs = this.options.absorbs || {};
493
- if (Array.isArray(node)) {
494
- node.forEach(n => {
495
- this.options.absorbs[n.id] = rule;
496
- this.addRecognizes(n);
497
- });
498
- }
499
- else {
500
- this.options.absorbs[node.id] = rule;
501
- this.addRecognizes(node);
502
- }
503
- return this;
504
- }
505
- addPopsAfterNode(...args) {
506
- for (const node of args) {
507
- if (!this.options.popsAfterNode)
508
- this.options.popsAfterNode = [];
509
- if (!this.options.popsAfterNode.includes(node)) {
510
- this.options.popsAfterNode.push(node);
511
- }
512
- }
513
- this.addRecognizes(...args);
514
- return this;
515
- }
516
- addHoistChildren(...args) {
517
- if (!this.options.hoistChildren)
518
- this.options.hoistChildren = [];
519
- this.options.hoistChildren.push(...args);
520
- return this;
521
- }
522
- set icon(value) {
523
- this.options.icon = value;
524
- }
525
- set label(value) {
526
- this.options.label = value;
527
- }
528
- get startsWith() {
529
- return this.options.startsWith;
530
- }
531
- set startsWith(value) {
532
- this.options.startsWith = value;
533
- }
534
- get endsWith() {
535
- return this.options.endsWith;
536
- }
537
- set endsWith(value) {
538
- this.options.endsWith = value;
539
- }
540
- getPopsAtEOFSource() {
541
- return this.options.popsAtEOFSource;
542
- }
543
- popsAtEOFSource(value) {
544
- this.options.popsAtEOFSource = value;
545
- return this;
546
- }
547
- get absorbs() {
548
- return this.options.absorbs;
549
- }
550
- get badToken() {
551
- return this.options.badToken;
552
- }
553
- set badToken(value) {
554
- this.options.badToken = value;
555
- }
556
- get skipToken() {
557
- return this.options.skipToken;
558
- }
559
- set skipToken(value) {
560
- this.options.skipToken = value;
561
- }
562
- get recognizes() {
563
- return this.options.recognizes || [];
564
- }
565
- set recognizes(value) {
566
- this.options.recognizes = value;
567
- }
568
- get hoistChildren() {
569
- return this.options.hoistChildren || [];
570
- }
571
- set hoistChildren(value) {
572
- this.options.hoistChildren = value;
573
- }
574
- getMapContent() {
575
- return this.options.mapContent;
576
- }
577
- mapContent(key, value = 'copy') {
578
- this.options.mapContent = this.options.mapContent || {};
579
- this.options.mapContent[key] = value;
580
- return this;
581
- }
582
- onMatch(value) {
583
- this.options.onMatch = value;
584
- return this;
585
- }
586
- onAppendContent(value) {
587
- this.options.onAppendContent = value;
588
- return this;
589
- }
590
- onAfterChildParse(value) {
591
- this.options.onAfterChildParse = value;
592
- return this;
593
- }
594
- onBeforeChildParse(value) {
595
- this.options.onBeforeChildParse = value;
596
- return this;
597
- }
598
- onMatchStartToken(value) {
599
- if (this.options.startsWith) {
600
- this.options.startsWith.onMatchToken = value;
601
- }
602
- return this;
603
- }
604
- onMatchEndToken(value) {
605
- if (this.options.endsWith) {
606
- this.options.endsWith.onMatchToken = value;
607
- }
608
- return this;
609
- }
610
- initCustomData(value) {
611
- this.options.initCustomData = value;
612
- return this;
613
- }
614
- onPop(value) {
615
- this.options.onPop = value;
616
- return this;
617
- }
618
- get popsAfterNode() {
619
- return this.options.popsAfterNode || [];
620
- }
621
- set popsAfterNode(nodes) {
622
- this.options.popsAfterNode = nodes;
623
- }
624
- clearStartsWith() {
625
- delete this.options.startsWith;
626
- return this;
627
- }
628
- clearEndsWith() {
629
- delete this.options.endsWith;
630
- return this;
631
- }
632
- clearPopsAtEOFSource() {
633
- delete this.options.popsAtEOFSource;
634
- return this;
635
- }
636
- clearBadToken() {
637
- delete this.options.badToken;
638
- return this;
639
- }
640
- clearSkipToken() {
641
- delete this.options.skipToken;
642
- return this;
643
- }
644
- clearAbsorbs(node) {
645
- if (this.options.absorbs) {
646
- if (node && Array.isArray(node)) {
647
- for (const n of node) {
648
- delete this.options.absorbs[n.id];
649
- }
650
- }
651
- else if (node) {
652
- delete this.options.absorbs[node.id];
653
- }
654
- else {
655
- this.options.absorbs = {};
656
- }
657
- }
658
- return this;
659
- }
660
- clearRecognizes(...args) {
661
- var _a;
662
- if (args.length) {
663
- this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
664
- }
665
- else {
666
- this.options.recognizes = [];
667
- }
668
- return this;
669
- }
670
- clearHoistChildren() {
671
- delete this.options.hoistChildren;
672
- return this;
673
- }
674
- clearMapContent() {
675
- delete this.options.mapContent;
676
- return this;
677
- }
678
- removeOnPop() {
679
- delete this.options.onPop;
680
- return this;
681
- }
682
- removeOnMatch() {
683
- delete this.options.onMatch;
684
- return this;
685
- }
686
- removeOnAppendContent() {
687
- delete this.options.onAppendContent;
688
- return this;
689
- }
690
- removeOnBeforeChildParse() {
691
- delete this.options.onBeforeChildParse;
692
- return this;
693
- }
694
- removeOnAfterChildParse() {
695
- delete this.options.onAfterChildParse;
696
- return this;
697
- }
698
- fireNodeMatched(matched, cbData) {
699
- return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
700
- }
701
- fireNodeEndMatched(matched, cbData) {
702
- return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
703
- }
704
- fireMatched(descr, matched, cbData) {
705
- const { omit, eject, onMatchToken } = descr;
706
- let cbResult = true;
707
- if (onMatchToken) {
708
- cbResult = onMatchToken({
709
- ...cbData,
710
- matched,
711
- });
712
- }
713
- const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
714
- const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
715
- return {
716
- omit: cbOmit !== undefined ? cbOmit : omit,
717
- eject: cbEject !== undefined ? cbEject : eject,
718
- confirmed: cbResult !== false,
719
- };
720
- }
721
- getStartTokenRg() {
722
- return this.getRgOutOfTokenDescriptor(this.options.startsWith);
723
- }
724
- getEndTokenRg() {
725
- return this.getRgOutOfTokenDescriptor(this.options.endsWith);
726
- }
727
- getConstraintTokens() {
728
- return {
729
- skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
730
- bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
731
- };
732
- }
733
- getRgOutOfTokenDescriptor(descr) {
734
- if (descr) {
735
- const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
736
- let token;
737
- if (typeof descr.token === 'function') {
738
- token = descr.token(this);
739
- }
740
- else {
741
- token = descr.token;
742
- }
743
- if (token instanceof RegExp) {
744
- return new RegExp(prefix + token.source, token.flags);
745
- }
746
- else {
747
- return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex$1(t)).join('|')})`);
748
- }
749
- }
750
- }
751
- }
752
-
753
- class ProstoHoistManager {
754
- constructor() {
755
- this.data = {};
756
- }
757
- addHoistOptions(ctx) {
758
- if (ctx.hoistChildren) {
759
- ctx.hoistChildren.forEach(options => {
760
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
761
- const hoist = this.data[nodeId] = (this.data[nodeId] || {});
762
- if (hoist) {
763
- hoist[ctx.index] = {
764
- options,
765
- context: ctx,
766
- };
767
- }
768
- });
769
- }
770
- }
771
- removeHoistOptions(ctx) {
772
- if (ctx.hoistChildren) {
773
- ctx.hoistChildren.forEach(options => {
774
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
775
- const hoist = this.data[nodeId];
776
- if (hoist) {
777
- delete hoist[ctx.index];
778
- }
779
- });
780
- }
781
- }
782
- processHoistOptions(ctx) {
783
- const id = ctx.node.id;
784
- const hoist = this.data[id];
785
- if (hoist) {
786
- Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
787
- const customData = context.getCustomData();
788
- if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
789
- if (options.asArray) {
790
- const hoisted = customData[options.as] = (customData[options.as] || []);
791
- if (!Array.isArray(hoisted)) {
792
- if (!options.onConflict || options.onConflict === 'error') {
793
- 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.`);
794
- }
795
- else if (options.onConflict === 'overwrite') {
796
- customData[options.as] = [doTheMapRule(options, ctx)];
797
- }
798
- else if (options.onConflict !== 'ignore') {
799
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
800
- }
801
- }
802
- else {
803
- hoisted.push(doTheMapRule(options, ctx));
804
- }
805
- }
806
- else {
807
- if (customData[options.as]) {
808
- if (!options.onConflict || options.onConflict === 'error') {
809
- throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
810
- }
811
- else if (options.onConflict === 'overwrite') {
812
- customData[options.as] = doTheMapRule(options, ctx);
813
- }
814
- else if (options.onConflict !== 'ignore') {
815
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
816
- }
817
- }
818
- else {
819
- customData[options.as] = doTheMapRule(options, ctx);
820
- }
821
- }
822
- if (options.removeChildFromContent) {
823
- context.content = context.content.filter(c => c !== ctx);
824
- }
825
- }
826
- });
827
- }
828
- function doTheMapRule(options, ctx) {
829
- var _a;
830
- if (typeof options.mapRule === 'function') {
831
- return options.mapRule(ctx);
832
- }
833
- if (options.mapRule === 'content.join') {
834
- return ctx.content.join('');
835
- }
836
- if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
837
- const key = options.mapRule.slice(11);
838
- if (key) {
839
- return ctx.getCustomData()[key];
840
- }
841
- else {
842
- return ctx.getCustomData();
843
- }
844
- }
845
- return ctx;
846
- }
847
- }
848
- }
849
-
850
- const banner$3 = '' + '[parser]' + '';
851
- class ProstoParserContext {
852
- constructor(root) {
853
- this.root = root;
854
- this.nodes = {};
855
- this.pos = 0;
856
- this.index = 0;
857
- this.behind = '';
858
- this.here = '';
859
- this.src = '';
860
- this.stack = [];
861
- this.l = 0;
862
- this.hoistManager = new ProstoHoistManager();
863
- this.context = root;
864
- }
865
- parse(src) {
866
- this.src = src,
867
- this.here = src,
868
- this.l = src.length;
869
- const cache = {};
870
- while (this.pos < this.l) {
871
- const searchTokens = this.context.getSearchTokens();
872
- let closestIndex = Number.MAX_SAFE_INTEGER;
873
- let closestToken;
874
- let matched;
875
- for (const t of searchTokens) {
876
- const key = t.g.source;
877
- t.g.lastIndex = this.pos;
878
- let cached = cache[key];
879
- if (cached === null)
880
- continue;
881
- if (cached && cached.index < this.pos) {
882
- cached = null;
883
- delete cache[key];
884
- }
885
- if (!cached) {
886
- cached = t.g.exec(this.src);
887
- if (cached || (this.pos === 0 && !cached)) {
888
- cache[key] = cached;
889
- }
890
- }
891
- if (cached && cached.index < closestIndex) {
892
- closestIndex = cached.index;
893
- matched = cached;
894
- closestToken = t;
895
- if (closestIndex === this.pos)
896
- break;
897
- }
898
- }
899
- if (closestToken && matched) {
900
- const toAppend = this.src.slice(this.pos, closestIndex);
901
- if (toAppend) {
902
- this.context.appendContent(toAppend);
903
- this.jump(toAppend.length);
904
- }
905
- const matchedToken = matched[0];
906
- if (closestToken.node) {
907
- const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
908
- if (!confirmed)
909
- continue;
910
- let toAppend = '';
911
- if (eject) {
912
- this.context.appendContent(matchedToken);
913
- }
914
- else if (!omit) {
915
- toAppend = matchedToken;
916
- }
917
- this.jump(matchedToken.length);
918
- this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
919
- this.context.fireOnMatch(matched);
920
- continue;
921
- }
922
- else {
923
- const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
924
- if (!confirmed)
925
- continue;
926
- if (!eject && !omit) {
927
- this.context.appendContent(matchedToken);
928
- }
929
- if (!eject) {
930
- this.jump(matchedToken.length);
931
- }
932
- this.context.mapNamedGroups(matched);
933
- this.pop();
934
- continue;
935
- }
936
- }
937
- else {
938
- this.context.appendContent(this.here);
939
- this.jump(this.here.length);
940
- }
941
- }
942
- if (this.context !== this.root) {
943
- while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
944
- this.pop();
945
- }
946
- if (this.context !== this.root) {
947
- this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
948
- }
949
- return this.root;
950
- }
951
- pop() {
952
- const parentContext = this.stack.pop();
953
- this.context.fireOnPop();
954
- if (parentContext) {
955
- parentContext.fireAfterChildParse(this.context);
956
- parentContext.fireAbsorb(this.context);
957
- this.context.cleanup();
958
- const node = this.context.node;
959
- this.context = parentContext;
960
- if (parentContext.popsAfterNode.includes(node)) {
961
- this.pop();
962
- }
963
- }
964
- else {
965
- this.context.cleanup();
966
- }
967
- }
968
- pushNewContext(newNode, content) {
969
- this.index++;
970
- const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
971
- ctx.content = content;
972
- this.context.fireBeforeChildParse(ctx);
973
- this.context.pushChild(ctx);
974
- this.stack.push(this.context);
975
- this.hoistManager.addHoistOptions(this.context);
976
- this.context = ctx;
977
- return ctx;
978
- }
979
- fromStack(depth = 0) {
980
- return this.stack[this.stack.length - depth - 1];
981
- }
982
- jump(n = 1) {
983
- this.pos += n;
984
- this.behind = this.src.slice(0, this.pos);
985
- this.here = this.src.slice(this.pos, this.l);
986
- return this.pos;
987
- }
988
- getCallbackData(matched) {
989
- return {
990
- parserContext: this,
991
- context: this.context,
992
- matched,
993
- customData: this.context.getCustomData(),
994
- };
995
- }
996
- getPosition(offset = 0) {
997
- var _a;
998
- const past = this.src.slice(0, this.pos + offset).split('\n');
999
- const row = past.length;
1000
- const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
1001
- return {
1002
- row, col, pos: this.pos,
1003
- };
1004
- }
1005
- panic(message, errorBackOffset = 0) {
1006
- if (this.pos > 0) {
1007
- const { row, col } = this.getPosition(-errorBackOffset);
1008
- console.error(banner$3 + '', message, '');
1009
- console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
1010
- console.error(renderCodeFragment(this.src.split('\n'), {
1011
- row: row,
1012
- error: col,
1013
- }));
1014
- }
1015
- throw new Error(message);
1016
- }
1017
- panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
1018
- if (this.pos > 0) {
1019
- const { row, col } = this.getPosition(-bottomBackOffset);
1020
- console.error(banner$3 + '', message, '');
1021
- console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
1022
- console.error(renderCodeFragment(this.src.split('\n'), {
1023
- row: this.context.startPos.row,
1024
- error: this.context.startPos.col - topBackOffset,
1025
- rowEnd: row,
1026
- errorEnd: col,
1027
- }));
1028
- }
1029
- throw new Error(message);
1030
- }
1031
- }
1032
-
1033
- const styles = {
1034
- banner: (s) => '' + s + '',
1035
- text: (s) => '' + s + '',
1036
- valuesDim: (s) => '' + '' + s + '' + '',
1037
- boolean: (s) => '' + s + '',
1038
- booleanDim: (s) => '' + '' + s + '' + '',
1039
- underscore: (s) => '' + s + '',
1040
- values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
1041
- nodeDim: (s) => '' + '' + s + '' + '',
1042
- node: (s) => '' + s + '',
1043
- };
1044
- const stringOutputLimit = 70;
1045
- const parserTree = new ProstoTree({
1046
- children: 'content',
1047
- renderLabel: (context) => {
1048
- if (typeof context === 'string') {
1049
- return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
1050
- }
1051
- else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
1052
- let keys = '';
1053
- const data = context.getCustomData();
1054
- Object.keys(data).forEach(key => {
1055
- const val = data[key];
1056
- if (typeof val === 'string' || typeof val === 'number') {
1057
- keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
1058
- }
1059
- else if (Array.isArray(val)) {
1060
- keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
1061
- }
1062
- else if (typeof val === 'object') {
1063
- keys += ' ' + styles.valuesDim(`{ ${key} }`);
1064
- }
1065
- else if (typeof val === 'boolean' && val) {
1066
- const st = key ? styles.boolean : styles.booleanDim;
1067
- keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
1068
- }
1069
- });
1070
- return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
1071
- }
1072
- return '';
1073
- },
1074
- });
1075
- function cut(s, n) {
1076
- const c = s.replace(/\n/g, '\\n');
1077
- if (c.length <= n)
1078
- return c;
1079
- return c.slice(0, n) + '' + '…';
1080
- }
1081
-
1082
- class ProstoParserNodeContext extends ProstoParserNodeBase {
1083
- constructor(_node, index, level, parserContext) {
1084
- super();
1085
- this._node = _node;
1086
- this.index = index;
1087
- this.level = level;
1088
- this.content = [];
1089
- this._customData = {};
1090
- this.hasNodes = [];
1091
- this.count = {};
1092
- this.mapContentRules = {
1093
- 'first': (content) => content[0],
1094
- 'shift': (content) => content.shift(),
1095
- 'pop': (content) => content.pop(),
1096
- 'last': (content) => content[content.length - 1],
1097
- 'join': (content) => content.join(''),
1098
- 'join-clear': (content) => content.splice(0).join(''),
1099
- 'copy': (content) => content,
1100
- };
1101
- this.options = _node.getOptions();
1102
- if (this.options.initCustomData) {
1103
- this._customData = this.options.initCustomData();
1104
- }
1105
- this._label = this.options.label || '';
1106
- this._icon = this.options.icon || '◦';
1107
- this.parserContext = parserContext || new ProstoParserContext(this);
1108
- if (parserContext) {
1109
- this.parent = parserContext.context || parserContext.root;
1110
- }
1111
- this.startPos = this.parserContext.getPosition();
1112
- this.endPos = this.parserContext.getPosition();
1113
- }
1114
- getOptions() {
1115
- return this.options;
1116
- }
1117
- extractCustomDataTree() {
1118
- let content = this.content;
1119
- if (this.contentCopiedTo) {
1120
- content = this.customData[this.contentCopiedTo];
1121
- }
1122
- if (Array.isArray(content)) {
1123
- return content.map(c => {
1124
- if (typeof c === 'string') {
1125
- return c;
1126
- }
1127
- else {
1128
- return extract(c);
1129
- }
1130
- });
1131
- }
1132
- else {
1133
- const c = content;
1134
- if (c instanceof ProstoParserNodeContext) {
1135
- return extract(c);
1136
- }
1137
- else {
1138
- return content;
1139
- }
1140
- }
1141
- function extract(c) {
1142
- const cd = { ...c.getCustomData() };
1143
- if (c.contentCopiedTo) {
1144
- cd[c.contentCopiedTo] = c.extractCustomDataTree();
1145
- }
1146
- return cd;
1147
- }
1148
- }
1149
- getPrevNode(n = 1) {
1150
- if (this.parent) {
1151
- const index = this.parent.content.findIndex(n => n === this) - n;
1152
- if (index >= 0)
1153
- return this.parent.content[index];
1154
- }
1155
- }
1156
- getPrevContext(n = 1) {
1157
- if (this.parent) {
1158
- const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
1159
- const index = contexts.findIndex(n => n === this) - n;
1160
- if (index >= 0)
1161
- return contexts[index];
1162
- }
1163
- }
1164
- set icon(value) {
1165
- this._icon = value;
1166
- }
1167
- get icon() {
1168
- return this._icon;
1169
- }
1170
- set label(value) {
1171
- this._label = value;
1172
- }
1173
- get label() {
1174
- return this._label;
1175
- }
1176
- getCustomData() {
1177
- return this._customData;
1178
- }
1179
- get customData() {
1180
- return this._customData;
1181
- }
1182
- get nodeId() {
1183
- return this._node.id;
1184
- }
1185
- get node() {
1186
- return this._node;
1187
- }
1188
- toTree(options) {
1189
- return parserTree.render(this, options);
1190
- }
1191
- getSearchTokens() {
1192
- var _a;
1193
- const rg = this.getEndTokenRg();
1194
- const tokens = rg ? [{
1195
- rg,
1196
- y: addFlag(rg, 'y'),
1197
- g: addFlag(rg, 'g'),
1198
- }] : [];
1199
- (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
1200
- const rg = node.getStartTokenRg();
1201
- if (rg) {
1202
- tokens.push({
1203
- rg,
1204
- y: addFlag(rg, 'y'),
1205
- g: addFlag(rg, 'g'),
1206
- node,
1207
- });
1208
- }
1209
- });
1210
- function addFlag(rg, f) {
1211
- return new RegExp(rg.source, rg.flags + f);
1212
- }
1213
- return tokens;
1214
- }
1215
- appendContent(input) {
1216
- let s = input;
1217
- this.endPos = this.parserContext.getPosition();
1218
- let { skip, bad } = this.getConstraintTokens();
1219
- skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
1220
- bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
1221
- if (skip) {
1222
- s = s.replace(skip, '');
1223
- }
1224
- if (bad) {
1225
- const m = bad.exec(s);
1226
- if (m) {
1227
- this.parserContext.jump(m.index);
1228
- this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
1229
- }
1230
- }
1231
- s = this.fireOnAppendContent(s);
1232
- if (s) {
1233
- this.content.push(s);
1234
- }
1235
- }
1236
- cleanup() {
1237
- this.options = null;
1238
- }
1239
- pushChild(child) {
1240
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1241
- if (!absorbRule) {
1242
- this.content.push(child);
1243
- }
1244
- }
1245
- fireAbsorb(child) {
1246
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1247
- if (absorbRule) {
1248
- switch (absorbRule) {
1249
- case 'append':
1250
- this.content.push(...child.content);
1251
- break;
1252
- case 'join':
1253
- this.appendContent(child.content.join(''));
1254
- break;
1255
- default:
1256
- const [action, target] = absorbRule.split('->');
1257
- const cd = this.getCustomData();
1258
- if (action === 'copy') {
1259
- cd[target] = child.content;
1260
- }
1261
- else if (action === 'join') {
1262
- cd[target] = child.content.join('');
1263
- }
1264
- else {
1265
- this.parserContext.panic(`Absorb action "${action}" is not supported.`);
1266
- }
1267
- }
1268
- }
1269
- }
1270
- has(node) {
1271
- return this.hasNodes.includes(node);
1272
- }
1273
- countOf(node) {
1274
- return this.count[node.id] || 0;
1275
- }
1276
- mapNamedGroups(matched) {
1277
- if (matched.groups) {
1278
- const cd = this.getCustomData();
1279
- for (const [key, value] of Object.entries(matched.groups)) {
1280
- if (key === 'content') {
1281
- this.appendContent(value);
1282
- }
1283
- else {
1284
- cd[key] = value;
1285
- }
1286
- }
1287
- }
1288
- }
1289
- fireOnPop() {
1290
- this.endPos = this.parserContext.getPosition();
1291
- this.processMappings();
1292
- const data = this.parserContext.getCallbackData();
1293
- this.node.beforeOnPop(data);
1294
- if (this.options.onPop) {
1295
- this.options.onPop(data);
1296
- }
1297
- }
1298
- fireOnMatch(matched) {
1299
- this.mapNamedGroups(matched);
1300
- const data = this.parserContext.getCallbackData(matched);
1301
- this.node.beforeOnMatch(data);
1302
- if (this.options.onMatch) {
1303
- return this.options.onMatch(data);
1304
- }
1305
- }
1306
- fireBeforeChildParse(child) {
1307
- const data = this.parserContext.getCallbackData();
1308
- this.node.beforeOnBeforeChildParse(child, data);
1309
- if (this.options.onBeforeChildParse) {
1310
- return this.options.onBeforeChildParse(child, data);
1311
- }
1312
- }
1313
- fireAfterChildParse(child) {
1314
- if (!this.hasNodes.includes(child.node)) {
1315
- this.hasNodes.push(child.node);
1316
- }
1317
- this.count[child.node.id] = this.count[child.node.id] || 0;
1318
- this.count[child.node.id]++;
1319
- const data = this.parserContext.getCallbackData();
1320
- this.node.beforeOnAfterChildParse(child, data);
1321
- if (this.options.onAfterChildParse) {
1322
- return this.options.onAfterChildParse(child, data);
1323
- }
1324
- }
1325
- fireOnAppendContent(s) {
1326
- let _s = s;
1327
- const data = this.parserContext.getCallbackData();
1328
- _s = this.node.beforeOnAppendContent(_s, data);
1329
- if (this.options.onAppendContent) {
1330
- _s = this.options.onAppendContent(_s, data);
1331
- }
1332
- return _s;
1333
- }
1334
- processMappings() {
1335
- this.parserContext.hoistManager.removeHoistOptions(this);
1336
- this.parserContext.hoistManager.processHoistOptions(this);
1337
- this.processMapContent();
1338
- }
1339
- processMapContent() {
1340
- const targetNodeOptions = this.options;
1341
- if (targetNodeOptions.mapContent) {
1342
- Object.keys(targetNodeOptions.mapContent).forEach((key) => {
1343
- const keyOfT = key;
1344
- if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
1345
- const mapRule = targetNodeOptions.mapContent[keyOfT];
1346
- if (typeof mapRule === 'function') {
1347
- this._customData[keyOfT] = mapRule(this.content);
1348
- }
1349
- else {
1350
- const ruleKey = mapRule;
1351
- if (ruleKey === 'copy')
1352
- this.contentCopiedTo = keyOfT;
1353
- this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
1354
- }
1355
- if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
1356
- this.contentCopiedTo = keyOfT;
1357
- }
1358
- }
1359
- });
1360
- }
1361
- }
1362
- }
1363
-
1364
- let idCounter = 0;
1365
- class ProstoParserNode extends ProstoParserNodeBase {
1366
- constructor(options) {
1367
- super();
1368
- this.options = options;
1369
- this.id = idCounter++;
1370
- }
1371
- getOptions() {
1372
- return {
1373
- label: this.options.label || '',
1374
- icon: this.options.icon || '',
1375
- startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
1376
- endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
1377
- popsAfterNode: [...(this.options.popsAfterNode || [])],
1378
- popsAtEOFSource: this.options.popsAtEOFSource || false,
1379
- badToken: this.options.badToken || '',
1380
- skipToken: this.options.skipToken || '',
1381
- recognizes: [...(this.options.recognizes || [])],
1382
- hoistChildren: [...(this.options.hoistChildren || [])],
1383
- mapContent: {
1384
- ...this.options.mapContent,
1385
- },
1386
- onPop: this.options.onPop,
1387
- onMatch: this.options.onMatch,
1388
- onAppendContent: this.options.onAppendContent,
1389
- onAfterChildParse: this.options.onAfterChildParse,
1390
- onBeforeChildParse: this.options.onBeforeChildParse,
1391
- initCustomData: this.options.initCustomData,
1392
- absorbs: this.options.absorbs,
1393
- };
1394
- }
1395
- createContext(index, level, rootContext) {
1396
- return new ProstoParserNodeContext(this, index, level, rootContext);
1397
- }
1398
- get name() {
1399
- return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
1400
- }
1401
- parse(source) {
1402
- return this.createContext(0, 0).parserContext.parse(source);
1403
- }
1404
- beforeOnPop(data) {
1405
- }
1406
- beforeOnMatch(data) {
1407
- }
1408
- beforeOnAppendContent(s, data) {
1409
- return s;
1410
- }
1411
- beforeOnAfterChildParse(child, data) {
1412
- }
1413
- beforeOnBeforeChildParse(child, data) {
1414
- }
1415
- }
1416
-
1417
- class BasicNode extends ProstoParserNode {
1418
- constructor(options) {
1419
- var _a, _b;
1420
- const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
1421
- const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
1422
- const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
1423
- const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
1424
- if (startsWith) {
1425
- startsWith.omit = startOption === 'omit';
1426
- startsWith.eject = startOption === 'eject';
1427
- startsWith.ignoreBackSlashed = startBSlash === 'ignore';
1428
- }
1429
- if (endsWith) {
1430
- endsWith.omit = endOption === 'omit';
1431
- endsWith.eject = endOption === 'eject';
1432
- endsWith.ignoreBackSlashed = endBSlash === 'ignore';
1433
- }
1434
- super({
1435
- icon: options.icon || '',
1436
- label: typeof options.label === 'string' ? options.label : '',
1437
- startsWith,
1438
- endsWith,
1439
- badToken: options.badToken,
1440
- skipToken: options.skipToken,
1441
- });
1442
- if (options.recursive) {
1443
- this.addAbsorbs(this, 'join');
1444
- }
1445
- }
1446
- }
1447
-
1448
- function parsePath(expr) {
1449
- return parser.parse(expr).extractCustomDataTree();
1450
- }
1451
- class ParametricNodeWithRegex extends BasicNode {
1452
- constructor(options, rgNode) {
1453
- super(options);
1454
- const hoistRegex = {
1455
- as: 'regex',
1456
- node: regexNode,
1457
- onConflict: 'overwrite',
1458
- removeChildFromContent: true,
1459
- deep: 1,
1460
- mapRule: ({ content }) => content.join('').replace(/^\(\^/, '(').replace(/\$\)$/, ')'),
1461
- };
1462
- this.mapContent('value', content => content.shift())
1463
- .popsAtEOFSource(true)
1464
- .addRecognizes(rgNode)
1465
- .addPopsAfterNode(rgNode)
1466
- .addHoistChildren(hoistRegex);
1467
- }
1468
- }
1469
- const regexNode = new BasicNode({
1470
- label: 'RegEx',
1471
- tokens: ['(', ')'],
1472
- backSlash: 'ignore-ignore',
1473
- recursive: true,
1474
- }).onMatch(({ parserContext, context }) => {
1475
- var _a;
1476
- if (((_a = parserContext.fromStack()) === null || _a === void 0 ? void 0 : _a.node) === context.node) {
1477
- if (!parserContext.here.startsWith('?:')) {
1478
- context.content[0] += '?:';
1479
- }
1480
- }
1481
- });
1482
- const paramNode = new ParametricNodeWithRegex({
1483
- label: 'Parameter',
1484
- tokens: [':', /[\/\-]/],
1485
- tokenOE: 'omit-eject',
1486
- backSlash: 'ignore-',
1487
- }, regexNode).initCustomData(() => ({ type: EPathSegmentType.VARIABLE, value: '', regex: '([^\\/]*)' }));
1488
- const wildcardNode = new ParametricNodeWithRegex({
1489
- label: 'Wildcard',
1490
- tokens: ['*', /[^*\()]/],
1491
- tokenOE: '-eject',
1492
- }, regexNode).initCustomData(() => ({ type: EPathSegmentType.WILDCARD, value: '*', regex: '(.*)' }));
1493
- const staticNode = new BasicNode({
1494
- label: 'Static',
1495
- tokens: [/[^:\*]/, /[:\*]/],
1496
- backSlash: '-ignore',
1497
- tokenOE: '-eject',
1498
- }).initCustomData(() => ({ type: EPathSegmentType.STATIC, value: '' }))
1499
- .mapContent('value', content => content.splice(0).join('').replace(/\\:/g, ':'))
1500
- .popsAtEOFSource(true);
1501
- const parser = new BasicNode({}).addRecognizes(staticNode, paramNode, wildcardNode);
1502
-
1503
- var EPathSegmentType;
1504
- (function (EPathSegmentType) {
1505
- EPathSegmentType[EPathSegmentType["STATIC"] = 0] = "STATIC";
1506
- EPathSegmentType[EPathSegmentType["VARIABLE"] = 1] = "VARIABLE";
1507
- EPathSegmentType[EPathSegmentType["REGEX"] = 2] = "REGEX";
1508
- EPathSegmentType[EPathSegmentType["WILDCARD"] = 3] = "WILDCARD";
1509
- })(EPathSegmentType || (EPathSegmentType = {}));
1510
-
1511
- function safeDecode(f, v) {
1512
- try {
1513
- return f(v);
1514
- }
1515
- catch (e) {
1516
- return v;
1517
- }
1518
- }
1519
- function safeDecodeURIComponent(uri) {
1520
- if (uri.indexOf('%') < 0)
1521
- return uri;
1522
- return safeDecode(decodeURIComponent, uri);
1523
- }
1524
- function safeDecodeURI(uri) {
1525
- if (uri.indexOf('%') < 0)
1526
- return uri;
1527
- return safeDecode(decodeURI, uri);
1528
- }
1529
-
1530
- function countOfSlashes(s) {
1531
- let last = 0;
1532
- let count = 0;
1533
- let index = s.indexOf('/');
1534
- last = index + 1;
1535
- while (index >= 0) {
1536
- count++;
1537
- index = s.indexOf('/', last);
1538
- last = index + 1;
1539
- }
1540
- return count;
1541
- }
1542
-
1543
- class CodeString {
1544
- constructor() {
1545
- this.code = '';
1546
- }
1547
- append(s, newLine = false) {
1548
- this.code += ['', s].flat().join(newLine ? '\n' : '');
1549
- }
1550
- prepend(s, newLine = false) {
1551
- this.code = [s, ''].flat().join(newLine ? '\n' : '') + this.code;
1552
- }
1553
- generateFunction(...args) {
1554
- return new Function(args.join(','), this.code);
1555
- }
1556
- toString() {
1557
- return this.code;
1558
- }
1559
- }
1560
-
1561
- function escapeRegex(s) {
1562
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1563
- }
1564
-
1565
- function generateFullMatchRegex(segments, nonCapturing = false) {
1566
- let regex = '';
1567
- segments.forEach(segment => {
1568
- switch (segment.type) {
1569
- case EPathSegmentType.STATIC:
1570
- regex += escapeRegex(segment.value);
1571
- break;
1572
- case EPathSegmentType.VARIABLE:
1573
- case EPathSegmentType.WILDCARD:
1574
- regex += nonCapturing ? segment.regex.replace(/^\(/, '(?:') : segment.regex;
1575
- }
1576
- });
1577
- return regex;
1578
- }
1579
- function generateFullMatchFunc(segments, ignoreCase = false) {
1580
- const str = new CodeString();
1581
- const regex = generateFullMatchRegex(segments);
1582
- let index = 0;
1583
- const obj = {};
1584
- segments.forEach(segment => {
1585
- switch (segment.type) {
1586
- case EPathSegmentType.VARIABLE:
1587
- case EPathSegmentType.WILDCARD:
1588
- index++;
1589
- obj[segment.value] = obj[segment.value] || [];
1590
- obj[segment.value].push(index);
1591
- }
1592
- });
1593
- Object.keys(obj).forEach(key => {
1594
- str.append(obj[key].length > 1
1595
- ? `\tparams['${key}'] = [${obj[key].map(i => `utils.safeDecodeURIComponent(a[${i}])`).join(', ')}]`
1596
- : `\tparams['${key}'] = utils.safeDecodeURIComponent(a[${obj[key][0]}])`, true);
1597
- });
1598
- str.prepend([`const a = path.match(/^${regex}$/${ignoreCase ? 'i' : ''})`, 'if (a) {'], true);
1599
- str.append(['}', 'return a'], true);
1600
- return str.generateFunction('path', 'params', 'utils');
1601
- }
1602
- function generatePathBuilder(segments) {
1603
- const str = new CodeString();
1604
- const obj = {};
1605
- const index = {};
1606
- segments.forEach(segment => {
1607
- switch (segment.type) {
1608
- case EPathSegmentType.VARIABLE:
1609
- case EPathSegmentType.WILDCARD:
1610
- obj[segment.value] = obj[segment.value] || 0;
1611
- obj[segment.value]++;
1612
- index[segment.value] = 0;
1613
- }
1614
- });
1615
- str.append('return `');
1616
- segments.forEach(segment => {
1617
- switch (segment.type) {
1618
- case EPathSegmentType.STATIC:
1619
- str.append(segment.value.replace(/`/g, '\\`'));
1620
- break;
1621
- case EPathSegmentType.VARIABLE:
1622
- case EPathSegmentType.WILDCARD:
1623
- if (obj[segment.value] > 1) {
1624
- str.append('${ params[\'' + segment.value + `\'][${index[segment.value]}] }`);
1625
- index[segment.value]++;
1626
- }
1627
- else {
1628
- str.append('${ params[\'' + segment.value + '\'] }');
1629
- }
1630
- }
1631
- });
1632
- str.append('`');
1633
- return str.generateFunction('params');
1634
- }
1635
-
1636
- const banner$2 = () => `[prostojs/router][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
1637
-
1638
- const methods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
1639
- const matcherFuncUtils = {
1640
- safeDecodeURIComponent,
1641
- };
1642
- class ProstoRouter {
1643
- constructor(_options) {
1644
- this.root = {};
1645
- this.routes = [];
1646
- this.routesRegistry = {};
1647
- this._options = {
1648
- ..._options,
1649
- };
1650
- if (!this._options.silent) {
1651
- consoleInfo('The Router Initialized');
1652
- }
1653
- const cacheOpts = {
1654
- limit: (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) || 0,
1655
- };
1656
- if (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) {
1657
- this.cache = {
1658
- GET: new ProstoCache(cacheOpts),
1659
- PUT: new ProstoCache(cacheOpts),
1660
- POST: new ProstoCache(cacheOpts),
1661
- PATCH: new ProstoCache(cacheOpts),
1662
- DELETE: new ProstoCache(cacheOpts),
1663
- HEAD: new ProstoCache(cacheOpts),
1664
- OPTIONS: new ProstoCache(cacheOpts),
1665
- };
1666
- }
1667
- }
1668
- refreshCache(method) {
1669
- if (this._options.cacheLimit && this.cache) {
1670
- if (method === '*') {
1671
- this.cache.GET.reset();
1672
- this.cache.PUT.reset();
1673
- this.cache.POST.reset();
1674
- this.cache.PATCH.reset();
1675
- this.cache.DELETE.reset();
1676
- this.cache.HEAD.reset();
1677
- this.cache.OPTIONS.reset();
1678
- }
1679
- else if (this.cache && this.cache[method]) {
1680
- this.cache[method].reset();
1681
- }
1682
- }
1683
- }
1684
- registerRoute(method, path, options, handler) {
1685
- this.refreshCache(method);
1686
- const opts = this.mergeOptions(options);
1687
- const normalPath = ('/' + path)
1688
- .replace(/^\/\//, '/')
1689
- .replace(/\/$/, '')
1690
- .replace(/%/g, '%25');
1691
- const { root } = this;
1692
- const segments = parsePath(normalPath);
1693
- if (!root[method]) {
1694
- root[method] = {
1695
- statics: {},
1696
- parametrics: {
1697
- byParts: [],
1698
- },
1699
- wildcards: [],
1700
- };
1701
- }
1702
- const rootMethod = root[method];
1703
- const generalized = method + ':' + segments.map(s => {
1704
- switch (s.type) {
1705
- case EPathSegmentType.STATIC: return s.value;
1706
- case EPathSegmentType.VARIABLE: return '<VAR' + (s.regex === '([^-\\/]*)' ? '' : s.regex) + '>';
1707
- case EPathSegmentType.WILDCARD: return s.value;
1708
- }
1709
- }).join('');
1710
- let route = this.routesRegistry[generalized];
1711
- if (route) {
1712
- if (this._options.disableDuplicatePath) {
1713
- const error = `Attempt to register duplicated path: "${path}". Duplicate paths are disabled.\nYou can enable duplicated paths removing 'disableDuplicatePath' option.`;
1714
- consoleError(error);
1715
- throw new Error(error);
1716
- }
1717
- if (route.handlers.includes(handler)) {
1718
- consoleError('Duplicate route with same handler ignored ' + generalized);
1719
- }
1720
- else {
1721
- consoleWarn('Duplicate route registered ' + generalized);
1722
- route.handlers.push(handler);
1723
- }
1724
- }
1725
- else {
1726
- const isStatic = segments.length === 1 && segments[0].type === EPathSegmentType.STATIC || segments.length === 0;
1727
- const isParametric = !!segments.find(p => p.type === EPathSegmentType.VARIABLE);
1728
- const isWildcard = !!segments.find(p => p.type === EPathSegmentType.WILDCARD);
1729
- const lengths = segments.map(s => s.type === EPathSegmentType.STATIC ? s.value.length : 0);
1730
- const normalPathCase = segments[0] ? (this._options.ignoreCase ? segments[0].value.toLowerCase() : segments[0].value) : '/';
1731
- this.routesRegistry[generalized] = route = {
1732
- method,
1733
- options: opts,
1734
- path: normalPath,
1735
- handlers: [handler],
1736
- isStatic,
1737
- isParametric,
1738
- isWildcard,
1739
- segments,
1740
- lengths,
1741
- minLength: lengths.reduce((a, b) => a + b, 0),
1742
- firstLength: lengths[0],
1743
- firstStatic: normalPathCase.slice(0, lengths[0]),
1744
- generalized,
1745
- fullMatch: generateFullMatchFunc(segments, this._options.ignoreCase),
1746
- pathBuilder: generatePathBuilder(segments),
1747
- };
1748
- this.routes.push(route);
1749
- if (route.isStatic) {
1750
- rootMethod.statics[normalPathCase] = route;
1751
- }
1752
- else {
1753
- if (route.isParametric && !route.isWildcard) {
1754
- const countOfParts = route.segments
1755
- .filter(s => s.type === EPathSegmentType.STATIC)
1756
- .map(s => countOfSlashes(s.value)).reduce((a, b) => a + b, 1);
1757
- const byParts = rootMethod.parametrics.byParts[countOfParts] = rootMethod.parametrics.byParts[countOfParts] || [];
1758
- byParts.push(route);
1759
- rootMethod.parametrics.byParts[countOfParts] = byParts.sort(routeSorter);
1760
- }
1761
- else if (route.isWildcard) {
1762
- rootMethod.wildcards.push(route);
1763
- rootMethod.wildcards = rootMethod.wildcards.sort(routeSorter);
1764
- }
1765
- }
1766
- }
1767
- return route.pathBuilder;
1768
- }
1769
- mergeOptions(options) {
1770
- return {
1771
- ...options,
1772
- };
1773
- }
1774
- sanitizePath(path) {
1775
- const end = path.indexOf('?');
1776
- let slicedPath = end >= 0 ? path.slice(0, end) : path;
1777
- if (this._options.ignoreTrailingSlash && slicedPath[slicedPath.length - 1] === '/') {
1778
- slicedPath = slicedPath.slice(0, slicedPath.length - 1);
1779
- }
1780
- const normalPath = safeDecodeURI(slicedPath
1781
- .replace(/%25/g, '%2525'));
1782
- return {
1783
- normalPath,
1784
- normalPathWithCase: this._options.ignoreCase ? normalPath.toLowerCase() : normalPath,
1785
- };
1786
- }
1787
- lookup(method, path) {
1788
- if (this._options.cacheLimit && this.cache && this.cache[method]) {
1789
- const cached = this.cache[method].get(path);
1790
- if (cached)
1791
- return cached;
1792
- }
1793
- const { normalPath, normalPathWithCase } = this.sanitizePath(path);
1794
- const rootMethod = this.root[method];
1795
- const lookupResult = {
1796
- route: null,
1797
- ctx: { params: {} },
1798
- };
1799
- const cache = (result) => {
1800
- if (this._options.cacheLimit && this.cache && this.cache[method]) {
1801
- this.cache[method].set(path, result);
1802
- }
1803
- return result;
1804
- };
1805
- if (rootMethod) {
1806
- lookupResult.route = rootMethod.statics[normalPathWithCase];
1807
- if (lookupResult.route)
1808
- return cache(lookupResult);
1809
- const pathSegmentsCount = countOfSlashes(normalPath) + 1;
1810
- const pathLength = normalPath.length;
1811
- const { parametrics } = rootMethod;
1812
- const bySegments = parametrics.byParts[pathSegmentsCount];
1813
- if (bySegments) {
1814
- for (let i = 0; i < bySegments.length; i++) {
1815
- lookupResult.route = bySegments[i];
1816
- if (pathLength >= lookupResult.route.minLength) {
1817
- if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
1818
- && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
1819
- return cache(lookupResult);
1820
- }
1821
- }
1822
- }
1823
- }
1824
- const { wildcards } = rootMethod;
1825
- for (let i = 0; i < wildcards.length; i++) {
1826
- lookupResult.route = wildcards[i];
1827
- if (pathLength >= lookupResult.route.minLength) {
1828
- if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
1829
- && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
1830
- return cache(lookupResult);
1831
- }
1832
- }
1833
- }
1834
- }
1835
- }
1836
- find(method, path) {
1837
- return this.lookup(method, path);
1838
- }
1839
- on(method, path, options, handler) {
1840
- const { opts, func } = extractOptionsAndHandler(options, handler);
1841
- if (method === '*') {
1842
- return methods.map(m => this.registerRoute(m, path, opts, func))[0];
1843
- }
1844
- return this.registerRoute(method, path, opts, func);
1845
- }
1846
- all(path, options, handler) {
1847
- const { opts, func } = extractOptionsAndHandler(options, handler);
1848
- return this.on('*', path, opts, func);
1849
- }
1850
- get(path, options, handler) {
1851
- const { opts, func } = extractOptionsAndHandler(options, handler);
1852
- return this.on('GET', path, opts, func);
1853
- }
1854
- put(path, options, handler) {
1855
- const { opts, func } = extractOptionsAndHandler(options, handler);
1856
- return this.on('PUT', path, opts, func);
1857
- }
1858
- post(path, options, handler) {
1859
- const { opts, func } = extractOptionsAndHandler(options, handler);
1860
- return this.on('POST', path, opts, func);
1861
- }
1862
- patch(path, options, handler) {
1863
- const { opts, func } = extractOptionsAndHandler(options, handler);
1864
- return this.on('PATCH', path, opts, func);
1865
- }
1866
- delete(path, options, handler) {
1867
- const { opts, func } = extractOptionsAndHandler(options, handler);
1868
- return this.on('DELETE', path, opts, func);
1869
- }
1870
- options(path, options, handler) {
1871
- const { opts, func } = extractOptionsAndHandler(options, handler);
1872
- return this.on('OPTIONS', path, opts, func);
1873
- }
1874
- head(path, options, handler) {
1875
- const { opts, func } = extractOptionsAndHandler(options, handler);
1876
- return this.on('HEAD', path, opts, func);
1877
- }
1878
- getRoutes() {
1879
- return this.routes;
1880
- }
1881
- toTree() {
1882
- const rootStyle = (v) => '' + v + '';
1883
- const paramStyle = (v) => '' + '' + ':' + v + '' + '';
1884
- const regexStyle = (v) => '' + '' + v + '' + '';
1885
- const handlerStyle = (v) => '' + '' + '→ ' + '' + '' + v;
1886
- const methodStyle = (v) => '' + '' + '• (' + v + ') ' + '';
1887
- const data = {
1888
- label: '⁕ Router',
1889
- stylist: rootStyle,
1890
- methods: [],
1891
- children: [],
1892
- };
1893
- function toChild(d, label, stylist) {
1894
- let found = d.children.find(c => c.label === label);
1895
- if (!found) {
1896
- found = {
1897
- label,
1898
- stylist,
1899
- methods: [],
1900
- children: [],
1901
- };
1902
- d.children.push(found);
1903
- }
1904
- return found;
1905
- }
1906
- this.routes.sort((a, b) => a.path > b.path ? 1 : -1).forEach(route => {
1907
- let cur = data;
1908
- let last = '';
1909
- route.segments.forEach(s => {
1910
- switch (s.type) {
1911
- case EPathSegmentType.STATIC:
1912
- const parts = s.value.split('/');
1913
- last += parts.shift();
1914
- for (let i = 0; i < parts.length; i++) {
1915
- if (last) {
1916
- cur = toChild(cur, last);
1917
- }
1918
- last = '/' + parts[i];
1919
- }
1920
- break;
1921
- case EPathSegmentType.VARIABLE:
1922
- case EPathSegmentType.WILDCARD:
1923
- last += `${paramStyle(s.value)}${regexStyle(s.regex)}`;
1924
- }
1925
- });
1926
- if (last) {
1927
- cur = toChild(cur, last, handlerStyle);
1928
- cur.methods.push(route.method);
1929
- }
1930
- });
1931
- new ProstoTree({
1932
- renderLabel: (node, behind) => {
1933
- const styledLabel = node.stylist ? node.stylist(node.label) : node.label;
1934
- if (node.methods.length) {
1935
- return styledLabel + '\n' + behind + node.methods.map(m => methodStyle(m)).join('\n' + behind);
1936
- }
1937
- return styledLabel;
1938
- },
1939
- }).print(data);
1940
- }
1941
- }
1942
- function extractOptionsAndHandler(options, handler) {
1943
- let opts = {};
1944
- let func = handler;
1945
- if (typeof options === 'function') {
1946
- func = options;
1947
- }
1948
- else {
1949
- opts = options;
1950
- }
1951
- return { opts, func };
1952
- }
1953
- function routeSorter(a, b) {
1954
- if (a.isWildcard !== b.isWildcard) {
1955
- return a.isWildcard ? 1 : -1;
1956
- }
1957
- const len = b.minLength - a.minLength;
1958
- if (len)
1959
- return len;
1960
- for (let i = 0; i < a.lengths.length; i++) {
1961
- const len = b.lengths[i] - a.lengths[i];
1962
- if (len)
1963
- return len;
1964
- }
1965
- return 0;
1966
- }
1967
- function consoleError(v) {
1968
- console.info('' + banner$2() + v + '');
1969
- }
1970
- function consoleWarn(v) {
1971
- console.info('' + banner$2() + v + '');
1972
- }
1973
- function consoleInfo(v) {
1974
- console.info('' + '' + banner$2() + v + '' + '');
1975
- }
1976
-
1977
- class Wooks {
1978
- constructor() {
1979
- this.router = new ProstoRouter({
1980
- silent: true,
1981
- });
1982
- }
1983
- getRouter() {
1984
- return this.router;
1985
- }
1986
- lookup(method, path) {
1987
- var _a, _b;
1988
- const found = this.getRouter().lookup(method, path || '');
1989
- useEventContext().store('routeParams').value = ((_a = found === null || found === void 0 ? void 0 : found.ctx) === null || _a === void 0 ? void 0 : _a.params) || {};
1990
- return ((_b = found === null || found === void 0 ? void 0 : found.route) === null || _b === void 0 ? void 0 : _b.handlers) || null;
1991
- }
1992
- on(method, path, handler) {
1993
- return this.router.on(method, path, handler);
1994
- }
1995
- }
1996
- let gWooks;
1997
- function getGlobalWooks() {
1998
- if (!gWooks) {
1999
- gWooks = new Wooks();
2000
- }
2001
- return gWooks;
2002
- }
2003
- class WooksAdapterBase {
2004
- constructor(wooks) {
2005
- if (wooks && wooks instanceof WooksAdapterBase) {
2006
- this.wooks = wooks.getWooks();
2007
- }
2008
- else if (wooks && wooks instanceof Wooks) {
2009
- this.wooks = wooks;
2010
- }
2011
- else {
2012
- this.wooks = getGlobalWooks();
2013
- }
2014
- }
2015
- getWooks() {
2016
- return this.wooks;
2017
- }
2018
- on(method, path, handler) {
2019
- return this.wooks.on(method, path, handler);
2020
- }
2021
- }
2022
-
2023
- var minimist = function (args, opts) {
2024
- if (!opts) opts = {};
2025
-
2026
- var flags = { bools : {}, strings : {}, unknownFn: null };
2027
-
2028
- if (typeof opts['unknown'] === 'function') {
2029
- flags.unknownFn = opts['unknown'];
2030
- }
2031
-
2032
- if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
2033
- flags.allBools = true;
2034
- } else {
2035
- [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
2036
- flags.bools[key] = true;
2037
- });
2038
- }
2039
-
2040
- var aliases = {};
2041
- Object.keys(opts.alias || {}).forEach(function (key) {
2042
- aliases[key] = [].concat(opts.alias[key]);
2043
- aliases[key].forEach(function (x) {
2044
- aliases[x] = [key].concat(aliases[key].filter(function (y) {
2045
- return x !== y;
2046
- }));
2047
- });
2048
- });
2049
-
2050
- [].concat(opts.string).filter(Boolean).forEach(function (key) {
2051
- flags.strings[key] = true;
2052
- if (aliases[key]) {
2053
- flags.strings[aliases[key]] = true;
2054
- }
2055
- });
2056
-
2057
- var defaults = opts['default'] || {};
2058
-
2059
- var argv = { _ : [] };
2060
- Object.keys(flags.bools).forEach(function (key) {
2061
- setArg(key, defaults[key] === undefined ? false : defaults[key]);
2062
- });
2063
-
2064
- var notFlags = [];
2065
-
2066
- if (args.indexOf('--') !== -1) {
2067
- notFlags = args.slice(args.indexOf('--')+1);
2068
- args = args.slice(0, args.indexOf('--'));
2069
- }
2070
-
2071
- function argDefined(key, arg) {
2072
- return (flags.allBools && /^--[^=]+$/.test(arg)) ||
2073
- flags.strings[key] || flags.bools[key] || aliases[key];
2074
- }
2075
-
2076
- function setArg (key, val, arg) {
2077
- if (arg && flags.unknownFn && !argDefined(key, arg)) {
2078
- if (flags.unknownFn(arg) === false) return;
2079
- }
2080
-
2081
- var value = !flags.strings[key] && isNumber(val)
2082
- ? Number(val) : val
2083
- ;
2084
- setKey(argv, key.split('.'), value);
2085
-
2086
- (aliases[key] || []).forEach(function (x) {
2087
- setKey(argv, x.split('.'), value);
2088
- });
2089
- }
2090
-
2091
- function setKey (obj, keys, value) {
2092
- var o = obj;
2093
- for (var i = 0; i < keys.length-1; i++) {
2094
- var key = keys[i];
2095
- if (isConstructorOrProto(o, key)) return;
2096
- if (o[key] === undefined) o[key] = {};
2097
- if (o[key] === Object.prototype || o[key] === Number.prototype
2098
- || o[key] === String.prototype) o[key] = {};
2099
- if (o[key] === Array.prototype) o[key] = [];
2100
- o = o[key];
2101
- }
2102
-
2103
- var key = keys[keys.length - 1];
2104
- if (isConstructorOrProto(o, key)) return;
2105
- if (o === Object.prototype || o === Number.prototype
2106
- || o === String.prototype) o = {};
2107
- if (o === Array.prototype) o = [];
2108
- if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
2109
- o[key] = value;
2110
- }
2111
- else if (Array.isArray(o[key])) {
2112
- o[key].push(value);
2113
- }
2114
- else {
2115
- o[key] = [ o[key], value ];
2116
- }
2117
- }
2118
-
2119
- function aliasIsBoolean(key) {
2120
- return aliases[key].some(function (x) {
2121
- return flags.bools[x];
2122
- });
2123
- }
2124
-
2125
- for (var i = 0; i < args.length; i++) {
2126
- var arg = args[i];
2127
-
2128
- if (/^--.+=/.test(arg)) {
2129
- // Using [\s\S] instead of . because js doesn't support the
2130
- // 'dotall' regex modifier. See:
2131
- // http://stackoverflow.com/a/1068308/13216
2132
- var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
2133
- var key = m[1];
2134
- var value = m[2];
2135
- if (flags.bools[key]) {
2136
- value = value !== 'false';
2137
- }
2138
- setArg(key, value, arg);
2139
- }
2140
- else if (/^--no-.+/.test(arg)) {
2141
- var key = arg.match(/^--no-(.+)/)[1];
2142
- setArg(key, false, arg);
2143
- }
2144
- else if (/^--.+/.test(arg)) {
2145
- var key = arg.match(/^--(.+)/)[1];
2146
- var next = args[i + 1];
2147
- if (next !== undefined && !/^-/.test(next)
2148
- && !flags.bools[key]
2149
- && !flags.allBools
2150
- && (aliases[key] ? !aliasIsBoolean(key) : true)) {
2151
- setArg(key, next, arg);
2152
- i++;
2153
- }
2154
- else if (/^(true|false)$/.test(next)) {
2155
- setArg(key, next === 'true', arg);
2156
- i++;
2157
- }
2158
- else {
2159
- setArg(key, flags.strings[key] ? '' : true, arg);
2160
- }
2161
- }
2162
- else if (/^-[^-]+/.test(arg)) {
2163
- var letters = arg.slice(1,-1).split('');
2164
-
2165
- var broken = false;
2166
- for (var j = 0; j < letters.length; j++) {
2167
- var next = arg.slice(j+2);
2168
-
2169
- if (next === '-') {
2170
- setArg(letters[j], next, arg);
2171
- continue;
2172
- }
2173
-
2174
- if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
2175
- setArg(letters[j], next.split('=')[1], arg);
2176
- broken = true;
2177
- break;
2178
- }
2179
-
2180
- if (/[A-Za-z]/.test(letters[j])
2181
- && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
2182
- setArg(letters[j], next, arg);
2183
- broken = true;
2184
- break;
2185
- }
2186
-
2187
- if (letters[j+1] && letters[j+1].match(/\W/)) {
2188
- setArg(letters[j], arg.slice(j+2), arg);
2189
- broken = true;
2190
- break;
2191
- }
2192
- else {
2193
- setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
2194
- }
2195
- }
2196
-
2197
- var key = arg.slice(-1)[0];
2198
- if (!broken && key !== '-') {
2199
- if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
2200
- && !flags.bools[key]
2201
- && (aliases[key] ? !aliasIsBoolean(key) : true)) {
2202
- setArg(key, args[i+1], arg);
2203
- i++;
2204
- }
2205
- else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
2206
- setArg(key, args[i+1] === 'true', arg);
2207
- i++;
2208
- }
2209
- else {
2210
- setArg(key, flags.strings[key] ? '' : true, arg);
2211
- }
2212
- }
2213
- }
2214
- else {
2215
- if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
2216
- argv._.push(
2217
- flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
2218
- );
2219
- }
2220
- if (opts.stopEarly) {
2221
- argv._.push.apply(argv._, args.slice(i + 1));
2222
- break;
2223
- }
2224
- }
2225
- }
2226
-
2227
- Object.keys(defaults).forEach(function (key) {
2228
- if (!hasKey(argv, key.split('.'))) {
2229
- setKey(argv, key.split('.'), defaults[key]);
2230
-
2231
- (aliases[key] || []).forEach(function (x) {
2232
- setKey(argv, x.split('.'), defaults[key]);
2233
- });
2234
- }
2235
- });
2236
-
2237
- if (opts['--']) {
2238
- argv['--'] = new Array();
2239
- notFlags.forEach(function(key) {
2240
- argv['--'].push(key);
2241
- });
2242
- }
2243
- else {
2244
- notFlags.forEach(function(key) {
2245
- argv._.push(key);
2246
- });
2247
- }
2248
-
2249
- return argv;
2250
- };
2251
-
2252
- function hasKey (obj, keys) {
2253
- var o = obj;
2254
- keys.slice(0,-1).forEach(function (key) {
2255
- o = (o[key] || {});
2256
- });
2257
-
2258
- var key = keys[keys.length - 1];
2259
- return key in o;
2260
- }
2261
-
2262
- function isNumber (x) {
2263
- if (typeof x === 'number') return true;
2264
- if (/^0x[0-9a-f]+$/i.test(x)) return true;
2265
- return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
2266
- }
2267
-
2268
-
2269
- function isConstructorOrProto (obj, key) {
2270
- return key === 'constructor' && typeof obj[key] === 'function' || key === '__proto__';
2271
- }
2272
-
2273
- function createCliContext(data) {
2274
- return createEventContext({
2275
- event: Object.assign(Object.assign({}, data), { type: 'CLI' }),
2276
- });
2277
- }
2278
- function useCliContext() {
2279
- return useEventContext('CLI');
2280
- }
3
+ import { Resolve, getMoostMate } from 'moost';
2281
4
 
2282
5
  /******************************************************************************
2283
6
  Copyright (c) Microsoft Corporation.
@@ -2304,67 +27,35 @@ function __awaiter(thisArg, _arguments, P, generator) {
2304
27
  });
2305
28
  }
2306
29
 
2307
- const banner$1 = () => `[${"@wooksjs/event-cli"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
30
+ const banner = () => `[${"@wooksjs/event-core"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
2308
31
 
2309
32
  /* istanbul ignore file */
2310
- function logError$1(error) {
2311
- console.error('' + '' + banner$1() + error + '');
33
+ function logError(error) {
34
+ console.error('' + '' + banner() + error + '');
2312
35
  }
2313
- class WooksCli extends WooksAdapterBase {
2314
- constructor(opts, wooks) {
2315
- super(wooks);
2316
- this.opts = opts;
2317
- }
2318
- cli(path, handler) {
2319
- return this.on('CLI', path, handler);
2320
- }
2321
- run(_argv) {
2322
- return __awaiter(this, void 0, void 0, function* () {
2323
- const argv = process.argv.slice(2) || _argv;
2324
- const firstFlagIndex = argv.findIndex(a => a.startsWith('-')) + 1;
2325
- const path = '/' + (firstFlagIndex ? argv.slice(0, firstFlagIndex - 1) : argv).map(v => encodeURIComponent(v)).join('/');
2326
- const { restoreCtx, clearCtx } = createCliContext({ argv });
2327
- const handlers = this.wooks.lookup('CLI', path);
2328
- if (handlers) {
2329
- try {
2330
- for (const handler of handlers) {
2331
- restoreCtx();
2332
- const response = yield handler();
2333
- if (typeof response === 'string') {
2334
- console.log(response);
2335
- }
2336
- else if (Array.isArray(response)) {
2337
- response.forEach(r => console.log(typeof r === 'string' ? r : JSON.stringify(r, null, ' ')));
2338
- }
2339
- else {
2340
- console.log(JSON.stringify(response, null, ' '));
2341
- }
2342
- }
2343
- }
2344
- catch (e) {
2345
- logError$1(e.message);
2346
- process.exit(1);
2347
- }
2348
- clearCtx();
2349
- }
2350
- else {
2351
- logError$1('Unknown command parameters');
2352
- process.exit(1);
2353
- }
2354
- });
36
+
37
+ function panic(error) {
38
+ logError(error);
39
+ return new Error(error);
40
+ }
41
+ /**
42
+ * Use existing event context
43
+ *
44
+ * !Must be called syncronously while context is reachable
45
+ *
46
+ * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
47
+ */
48
+ function useEventContext(expectedTypes) {
49
+ {
50
+ throw panic('Event context does not exist. Use event context synchronously within the runtime of the event.');
2355
51
  }
2356
52
  }
2357
- function createCliApp(opts, wooks) {
2358
- return new WooksCli(opts, wooks);
2359
- }
2360
53
 
2361
- function useFlags() {
2362
- const { store } = useCliContext();
2363
- const flags = store('flags');
2364
- if (!flags.value) {
2365
- flags.value = minimist(store('event').value.argv);
2366
- }
2367
- return flags.value;
54
+ function useEventId() {
55
+ const { store } = useEventContext();
56
+ const { init } = store('event');
57
+ const getId = () => init('id', () => randomUUID());
58
+ return { getId };
2368
59
  }
2369
60
 
2370
61
  class MoostCli {
@@ -2390,7 +81,7 @@ class MoostCli {
2390
81
  const path = typeof handler.path === 'string' ? handler.path : typeof opts.method === 'string' ? opts.method : '';
2391
82
  const targetPath = `${opts.prefix || ''}/${path}`.replace(/\/\/+/g, '/');
2392
83
  if (!fn) {
2393
- fn = () => __awaiter$1(this, void 0, void 0, function* () {
84
+ fn = () => __awaiter(this, void 0, void 0, function* () {
2394
85
  const { restoreCtx } = useCliContext();
2395
86
  const scopeId = useEventId().getId();
2396
87
  const unscope = opts.registerEventScope(scopeId);
@@ -2436,339 +127,6 @@ class MoostCli {
2436
127
  }
2437
128
  }
2438
129
 
2439
- var EHttpStatusCode;
2440
- (function (EHttpStatusCode) {
2441
- EHttpStatusCode[EHttpStatusCode["Continue"] = 100] = "Continue";
2442
- EHttpStatusCode[EHttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
2443
- EHttpStatusCode[EHttpStatusCode["Processing"] = 102] = "Processing";
2444
- EHttpStatusCode[EHttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
2445
- EHttpStatusCode[EHttpStatusCode["OK"] = 200] = "OK";
2446
- EHttpStatusCode[EHttpStatusCode["Created"] = 201] = "Created";
2447
- EHttpStatusCode[EHttpStatusCode["Accepted"] = 202] = "Accepted";
2448
- EHttpStatusCode[EHttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
2449
- EHttpStatusCode[EHttpStatusCode["NoContent"] = 204] = "NoContent";
2450
- EHttpStatusCode[EHttpStatusCode["ResetContent"] = 205] = "ResetContent";
2451
- EHttpStatusCode[EHttpStatusCode["PartialContent"] = 206] = "PartialContent";
2452
- EHttpStatusCode[EHttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
2453
- EHttpStatusCode[EHttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
2454
- EHttpStatusCode[EHttpStatusCode["IMUsed"] = 226] = "IMUsed";
2455
- EHttpStatusCode[EHttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
2456
- EHttpStatusCode[EHttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
2457
- EHttpStatusCode[EHttpStatusCode["Found"] = 302] = "Found";
2458
- EHttpStatusCode[EHttpStatusCode["SeeOther"] = 303] = "SeeOther";
2459
- EHttpStatusCode[EHttpStatusCode["NotModified"] = 304] = "NotModified";
2460
- EHttpStatusCode[EHttpStatusCode["UseProxy"] = 305] = "UseProxy";
2461
- EHttpStatusCode[EHttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy";
2462
- EHttpStatusCode[EHttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
2463
- EHttpStatusCode[EHttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
2464
- EHttpStatusCode[EHttpStatusCode["BadRequest"] = 400] = "BadRequest";
2465
- EHttpStatusCode[EHttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
2466
- EHttpStatusCode[EHttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
2467
- EHttpStatusCode[EHttpStatusCode["Forbidden"] = 403] = "Forbidden";
2468
- EHttpStatusCode[EHttpStatusCode["NotFound"] = 404] = "NotFound";
2469
- EHttpStatusCode[EHttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
2470
- EHttpStatusCode[EHttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
2471
- EHttpStatusCode[EHttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
2472
- EHttpStatusCode[EHttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
2473
- EHttpStatusCode[EHttpStatusCode["Conflict"] = 409] = "Conflict";
2474
- EHttpStatusCode[EHttpStatusCode["Gone"] = 410] = "Gone";
2475
- EHttpStatusCode[EHttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
2476
- EHttpStatusCode[EHttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
2477
- EHttpStatusCode[EHttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
2478
- EHttpStatusCode[EHttpStatusCode["URITooLong"] = 414] = "URITooLong";
2479
- EHttpStatusCode[EHttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
2480
- EHttpStatusCode[EHttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
2481
- EHttpStatusCode[EHttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
2482
- EHttpStatusCode[EHttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
2483
- EHttpStatusCode[EHttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
2484
- EHttpStatusCode[EHttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
2485
- EHttpStatusCode[EHttpStatusCode["Locked"] = 423] = "Locked";
2486
- EHttpStatusCode[EHttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
2487
- EHttpStatusCode[EHttpStatusCode["TooEarly"] = 425] = "TooEarly";
2488
- EHttpStatusCode[EHttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
2489
- EHttpStatusCode[EHttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
2490
- EHttpStatusCode[EHttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
2491
- EHttpStatusCode[EHttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
2492
- EHttpStatusCode[EHttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
2493
- EHttpStatusCode[EHttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
2494
- EHttpStatusCode[EHttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
2495
- EHttpStatusCode[EHttpStatusCode["BadGateway"] = 502] = "BadGateway";
2496
- EHttpStatusCode[EHttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
2497
- EHttpStatusCode[EHttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
2498
- EHttpStatusCode[EHttpStatusCode["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
2499
- EHttpStatusCode[EHttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
2500
- EHttpStatusCode[EHttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
2501
- EHttpStatusCode[EHttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
2502
- EHttpStatusCode[EHttpStatusCode["NotExtended"] = 510] = "NotExtended";
2503
- EHttpStatusCode[EHttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
2504
- })(EHttpStatusCode || (EHttpStatusCode = {}));
2505
-
2506
- ({
2507
- GET: EHttpStatusCode.OK,
2508
- POST: EHttpStatusCode.Created,
2509
- PUT: EHttpStatusCode.Created,
2510
- PATCH: EHttpStatusCode.Accepted,
2511
- DELETE: EHttpStatusCode.Accepted,
2512
- });
2513
-
2514
- function getConstructor(instance) {
2515
- return isConstructor(instance) ?
2516
- instance : instance.constructor ?
2517
- instance.constructor : Object.getPrototypeOf(instance).constructor;
2518
- }
2519
- function isConstructor(v) {
2520
- return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
2521
- }
2522
-
2523
- const banner = () => `[prostojs/mate][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
2524
-
2525
- function warn(text) {
2526
- console.log('' + banner() + text + '');
2527
- }
2528
- function logError(error) {
2529
- console.error('' + '' + banner() + error + '');
2530
- }
2531
-
2532
- const classMetadata = {};
2533
- const paramMetadata = {};
2534
- const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
2535
- function getMetaObject(target, prop) {
2536
- const isParam = typeof prop !== 'undefined';
2537
- const metadata = isParam ? paramMetadata : classMetadata;
2538
- const targetKey = Symbol.for(getConstructor(target));
2539
- let meta = metadata[targetKey] = metadata[targetKey] || {};
2540
- if (isParam)
2541
- meta = (meta[prop] = meta[prop] || {});
2542
- return meta;
2543
- }
2544
- const _reflect = {
2545
- getOwnMetadata(key, target, prop) {
2546
- return getMetaObject(target, prop)[key];
2547
- },
2548
- defineMetadata(key, data, target, prop) {
2549
- const meta = getMetaObject(target, prop);
2550
- meta[key] = data;
2551
- },
2552
- metadata(key, data) {
2553
- return ((target, propKey) => {
2554
- Reflect$1.defineMetadata(key, data, target, propKey);
2555
- });
2556
- },
2557
- };
2558
- if (!root.Reflect) {
2559
- root.Reflect = _reflect;
2560
- }
2561
- else {
2562
- const funcs = [
2563
- 'getOwnMetadata',
2564
- 'defineMetadata',
2565
- 'metadata',
2566
- ];
2567
- const target = root.Reflect;
2568
- let isOriginalReflectMetadata = true;
2569
- for (const func of funcs) {
2570
- if (typeof target[func] !== 'function') {
2571
- Object.defineProperty(target, func, { configurable: true, writable: true, value: _reflect[func] });
2572
- isOriginalReflectMetadata = false;
2573
- }
2574
- }
2575
- if (!isOriginalReflectMetadata) {
2576
- warn('A limited \'reflect-metadata\' implementation is used. In case of any issues include original \'reflect-metadata\' package and require it before any @prostojs/mate import.');
2577
- }
2578
- }
2579
- const Reflect$1 = _reflect;
2580
-
2581
- function panic(error) {
2582
- logError(error);
2583
- return new Error(error);
2584
- }
2585
-
2586
- const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
2587
- class Mate {
2588
- constructor(workspace, options = {}) {
2589
- this.workspace = workspace;
2590
- this.options = options;
2591
- }
2592
- set(args, key, value, isArray) {
2593
- var _a;
2594
- const newArgs = args.level === 'CLASS' ? { target: args.target }
2595
- : args.level === 'PROPERTY' ? { target: args.target, propKey: args.propKey }
2596
- : args;
2597
- let meta = Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {};
2598
- if (newArgs.propKey && this.options.readReturnType && !meta.returnType) {
2599
- meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
2600
- }
2601
- if (newArgs.propKey && this.options.readType && !meta.type) {
2602
- meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
2603
- }
2604
- const { index } = newArgs;
2605
- const cb = typeof key === 'function' ? key : undefined;
2606
- let data = meta;
2607
- if (!data.params) {
2608
- data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
2609
- }
2610
- if (typeof index === 'number') {
2611
- data.params = data.params || [];
2612
- data.params[index] = data.params[index] || {
2613
- type: undefined,
2614
- };
2615
- if (cb) {
2616
- data.params[index] = cb(data.params[index], args.propKey, typeof args.index === 'number' ? args.index : undefined);
2617
- }
2618
- else {
2619
- data = data.params[index];
2620
- }
2621
- }
2622
- if (typeof key !== 'function') {
2623
- if (isArray) {
2624
- const newArray = (data[key] || []);
2625
- if (!Array.isArray(newArray)) {
2626
- panic('Mate.add (isArray=true) called for non-array metadata');
2627
- }
2628
- newArray.unshift(value);
2629
- data[key] = newArray;
2630
- }
2631
- else {
2632
- data[key] = value;
2633
- }
2634
- }
2635
- else if (cb && typeof index !== 'number') {
2636
- meta = cb(data, args.propKey, typeof args.index === 'number' ? args.index : undefined);
2637
- }
2638
- Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
2639
- }
2640
- read(target, propKey, index) {
2641
- const isConstr = isConstructor(target);
2642
- const constructor = isConstr ? target : getConstructor(target);
2643
- const proto = constructor.prototype;
2644
- let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
2645
- if (this.options.inherit) {
2646
- const inheritFn = typeof this.options.inherit === 'function' ? this.options.inherit : undefined;
2647
- let shouldInherit = this.options.inherit;
2648
- if (inheritFn) {
2649
- if (typeof propKey === 'string') {
2650
- const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
2651
- shouldInherit = inheritFn(classMeta, propKey, ownMeta);
2652
- }
2653
- else {
2654
- shouldInherit = inheritFn(ownMeta);
2655
- }
2656
- }
2657
- if (shouldInherit) {
2658
- const parent = Object.getPrototypeOf(constructor);
2659
- if (typeof parent === 'function' && parent !== fnProto && parent !== constructor) {
2660
- const inheritedMeta = this.read(parent, propKey);
2661
- ownMeta = { ...inheritedMeta, ...ownMeta, params: ownMeta === null || ownMeta === void 0 ? void 0 : ownMeta.params };
2662
- }
2663
- }
2664
- }
2665
- return ownMeta;
2666
- }
2667
- apply(...decorators) {
2668
- return ((target, propKey, descriptor) => {
2669
- for (const d of decorators) {
2670
- d(target, propKey, descriptor);
2671
- }
2672
- });
2673
- }
2674
- decorate(key, value, isArray, level) {
2675
- return ((target, propKey, descriptor) => {
2676
- const args = {
2677
- target,
2678
- propKey,
2679
- descriptor: typeof descriptor === 'number' ? undefined : descriptor,
2680
- index: typeof descriptor === 'number' ? descriptor : undefined,
2681
- level,
2682
- };
2683
- this.set(args, key, value, isArray);
2684
- });
2685
- }
2686
- decorateClass(key, value, isArray) {
2687
- return this.decorate(key, value, isArray, 'CLASS');
2688
- }
2689
- }
2690
- const fnProto = Object.getPrototypeOf(Function);
2691
-
2692
- const METADATA_WORKSPACE = 'moost';
2693
- const moostMate = new Mate(METADATA_WORKSPACE, {
2694
- readType: true,
2695
- readReturnType: true,
2696
- });
2697
- function getMoostMate() {
2698
- return moostMate;
2699
- }
2700
-
2701
- var TPipePriority;
2702
- (function (TPipePriority) {
2703
- TPipePriority[TPipePriority["BEFORE_RESOLVE"] = 0] = "BEFORE_RESOLVE";
2704
- TPipePriority[TPipePriority["RESOLVE"] = 1] = "RESOLVE";
2705
- TPipePriority[TPipePriority["AFTER_RESOLVE"] = 2] = "AFTER_RESOLVE";
2706
- TPipePriority[TPipePriority["BEFORE_TRANSFORM"] = 3] = "BEFORE_TRANSFORM";
2707
- TPipePriority[TPipePriority["TRANSFORM"] = 4] = "TRANSFORM";
2708
- TPipePriority[TPipePriority["AFTER_TRANSFORM"] = 5] = "AFTER_TRANSFORM";
2709
- TPipePriority[TPipePriority["BEFORE_VALIDATE"] = 6] = "BEFORE_VALIDATE";
2710
- TPipePriority[TPipePriority["VALIDATE"] = 7] = "VALIDATE";
2711
- TPipePriority[TPipePriority["AFTER_VALIDATE"] = 8] = "AFTER_VALIDATE";
2712
- })(TPipePriority || (TPipePriority = {}));
2713
-
2714
- const resolvePipe = (_value, meta) => {
2715
- if (meta === null || meta === void 0 ? void 0 : meta.resolver) {
2716
- return meta.resolver();
2717
- }
2718
- return undefined;
2719
- };
2720
- resolvePipe.priority = TPipePriority.RESOLVE;
2721
-
2722
- [
2723
- {
2724
- handler: resolvePipe,
2725
- priority: TPipePriority.RESOLVE,
2726
- },
2727
- ];
2728
-
2729
- function Label(value) {
2730
- return getMoostMate().decorate('label', value);
2731
- }
2732
-
2733
- /**
2734
- * Hook to the Response Status
2735
- * @decorator
2736
- * @param resolver - resolver function
2737
- * @param label - field label
2738
- * @paramType unknown
2739
- */
2740
- function Resolve(resolver, label) {
2741
- return (target, key, index) => {
2742
- fillLabel(target, key, index, label);
2743
- getMoostMate().decorate('resolver', resolver)(target, key, index);
2744
- };
2745
- }
2746
- function fillLabel(target, key, index, name) {
2747
- if (name) {
2748
- const meta = getMoostMate().read(target, key);
2749
- 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)) {
2750
- Label(name)(target, key, index);
2751
- }
2752
- }
2753
- }
2754
-
2755
- getMoostMate().decorate((meta) => {
2756
- if (!meta.injectable)
2757
- meta.injectable = true;
2758
- return meta;
2759
- });
2760
-
2761
- var TInterceptorPriority;
2762
- (function (TInterceptorPriority) {
2763
- TInterceptorPriority[TInterceptorPriority["BEFORE_ALL"] = 0] = "BEFORE_ALL";
2764
- TInterceptorPriority[TInterceptorPriority["BEFORE_GUARD"] = 1] = "BEFORE_GUARD";
2765
- TInterceptorPriority[TInterceptorPriority["GUARD"] = 2] = "GUARD";
2766
- TInterceptorPriority[TInterceptorPriority["AFTER_GUARD"] = 3] = "AFTER_GUARD";
2767
- TInterceptorPriority[TInterceptorPriority["INTERCEPTOR"] = 4] = "INTERCEPTOR";
2768
- TInterceptorPriority[TInterceptorPriority["CATCH_ERROR"] = 5] = "CATCH_ERROR";
2769
- TInterceptorPriority[TInterceptorPriority["AFTER_ALL"] = 6] = "AFTER_ALL";
2770
- })(TInterceptorPriority || (TInterceptorPriority = {}));
2771
-
2772
130
  /**
2773
131
  * Get Cli Flag
2774
132
  * @decorator