@moostjs/otel 0.4.22 → 0.4.23

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 +1967 -18
  2. package/dist/index.mjs +1967 -18
  3. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -345,8 +345,8 @@ function isConstructor(v) {
345
345
  return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
346
346
  }
347
347
 
348
- const classMetadata = new WeakMap();
349
- const paramMetadata = new WeakMap();
348
+ let classMetadata = new WeakMap();
349
+ let paramMetadata = new WeakMap();
350
350
  const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
351
351
  function getMetaObject(target, prop) {
352
352
  const isParam = typeof prop !== 'undefined';
@@ -376,6 +376,10 @@ const _reflect = {
376
376
  Reflect$1.defineMetadata(key, data, target, propKey);
377
377
  });
378
378
  },
379
+ _cleanup: (() => {
380
+ classMetadata = new WeakMap();
381
+ paramMetadata = new WeakMap();
382
+ }),
379
383
  };
380
384
  if (!root.Reflect) {
381
385
  root.Reflect = _reflect;
@@ -395,31 +399,42 @@ else {
395
399
  }
396
400
  const Reflect$1 = _reflect;
397
401
 
398
- const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
402
+ const Reflect$2 = ((global === null || global === void 0 ? void 0 : global.Reflect) ||
403
+ (self === null || self === void 0 ? void 0 : self.Reflect) ||
404
+ Reflect$1);
399
405
  class Mate {
400
406
  constructor(workspace, options = {}) {
401
407
  this.workspace = workspace;
402
408
  this.options = options;
403
409
  this.logger = options.logger || console;
404
410
  }
411
+ _cleanup() {
412
+ var _a;
413
+ (_a = Reflect$2._cleanup) === null || _a === void 0 ? void 0 : _a.call(Reflect$2);
414
+ }
405
415
  set(args, key, value, isArray) {
406
416
  var _a;
407
417
  let level = 'CLASS';
408
- const newArgs = args.level === 'CLASS' ? { target: args.target }
409
- : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
418
+ const newArgs = args.level === 'CLASS'
419
+ ? { target: args.target }
420
+ : args.level === 'PROP'
421
+ ? { target: args.target, propKey: args.propKey }
410
422
  : args;
411
- let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
412
- if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
413
- meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
423
+ let meta = (Reflect$2.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
424
+ if (newArgs.propKey &&
425
+ this.options.readReturnType &&
426
+ !meta.returnType &&
427
+ args.descriptor) {
428
+ meta.returnType = Reflect$2.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
414
429
  }
415
430
  if (newArgs.propKey && this.options.readType && !meta.type) {
416
- meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
431
+ meta.type = Reflect$2.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
417
432
  }
418
433
  const { index } = newArgs;
419
434
  const cb = typeof key === 'function' ? key : undefined;
420
435
  let data = meta;
421
436
  if (!data.params) {
422
- data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
437
+ data.params = (_a = Reflect$2.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
423
438
  }
424
439
  if (typeof index === 'number') {
425
440
  level = 'PARAM';
@@ -434,7 +449,11 @@ class Mate {
434
449
  data = data.params[index];
435
450
  }
436
451
  }
437
- else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
452
+ else if (!index &&
453
+ !args.descriptor &&
454
+ args.propKey &&
455
+ this.options.collectPropKeys &&
456
+ args.level !== 'CLASS') {
438
457
  this.set({ ...args, level: 'CLASS' }, (meta) => {
439
458
  if (!meta.properties) {
440
459
  meta.properties = [args.propKey];
@@ -445,7 +464,14 @@ class Mate {
445
464
  return meta;
446
465
  });
447
466
  }
448
- level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
467
+ level =
468
+ typeof index === 'number'
469
+ ? 'PARAM'
470
+ : newArgs.propKey && newArgs.descriptor
471
+ ? 'METHOD'
472
+ : newArgs.propKey
473
+ ? 'PROP'
474
+ : 'CLASS';
449
475
  if (typeof key !== 'function') {
450
476
  if (isArray) {
451
477
  const newArray = (data[key] || []);
@@ -462,14 +488,14 @@ class Mate {
462
488
  else if (cb && typeof index !== 'number') {
463
489
  meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
464
490
  }
465
- Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
491
+ Reflect$2.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
466
492
  }
467
493
  read(target, propKey) {
468
494
  var _a;
469
495
  const isConstr = isConstructor(target);
470
496
  const constructor = isConstr ? target : getConstructor$1(target);
471
497
  const proto = constructor.prototype;
472
- let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
498
+ let ownMeta = Reflect$2.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
473
499
  if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
474
500
  const parent = Object.getPrototypeOf(constructor);
475
501
  if (typeof parent === 'function' &&
@@ -485,7 +511,7 @@ class Mate {
485
511
  let shouldInherit = this.options.inherit;
486
512
  if (inheritFn) {
487
513
  if (typeof propKey === 'string') {
488
- const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
514
+ const classMeta = Reflect$2.getOwnMetadata(this.workspace, constructor);
489
515
  shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
490
516
  }
491
517
  else {
@@ -505,8 +531,7 @@ class Mate {
505
531
  ownParams &&
506
532
  (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
507
533
  for (let i = 0; i < ownParams.length; i++) {
508
- if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
509
- 'undefined') {
534
+ if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !== 'undefined') {
510
535
  const ownParam = ownParams[i];
511
536
  if (ownMeta.params &&
512
537
  inheritFn &&
@@ -548,7 +573,13 @@ class Mate {
548
573
  decorateConditional(ccb) {
549
574
  return ((target, propKey, descriptor) => {
550
575
  const hasIndex = typeof descriptor === 'number';
551
- const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
576
+ const decoratorLevel = hasIndex
577
+ ? 'PARAM'
578
+ : propKey && descriptor
579
+ ? 'METHOD'
580
+ : propKey
581
+ ? 'PROP'
582
+ : 'CLASS';
552
583
  const d = ccb(decoratorLevel);
553
584
  if (d) {
554
585
  d(target, propKey, descriptor);
@@ -716,6 +747,11 @@ class Infact {
716
747
  this._silent = false;
717
748
  this.logger = options.logger || console;
718
749
  }
750
+ _cleanup() {
751
+ this.registry = {};
752
+ this.instanceRegistries = new WeakMap();
753
+ this.scopes = {};
754
+ }
719
755
  setLogger(logger) {
720
756
  this.logger = logger;
721
757
  }
@@ -1162,6 +1198,1919 @@ const resolvePipe = definePipeFn((_value, metas, level) => {
1162
1198
  },
1163
1199
  ];
1164
1200
 
1201
+ function getAugmentedNamespace(n) {
1202
+ if (n.__esModule) return n;
1203
+ var f = n.default;
1204
+ if (typeof f == "function") {
1205
+ var a = function a () {
1206
+ if (this instanceof a) {
1207
+ return Reflect.construct(f, arguments, this.constructor);
1208
+ }
1209
+ return f.apply(this, arguments);
1210
+ };
1211
+ a.prototype = f.prototype;
1212
+ } else a = {};
1213
+ Object.defineProperty(a, '__esModule', {value: true});
1214
+ Object.keys(n).forEach(function (k) {
1215
+ var d = Object.getOwnPropertyDescriptor(n, k);
1216
+ Object.defineProperty(a, k, d.get ? d : {
1217
+ enumerable: true,
1218
+ get: function () {
1219
+ return n[k];
1220
+ }
1221
+ });
1222
+ });
1223
+ return a;
1224
+ }
1225
+
1226
+ var router_cjs_prod = {};
1227
+
1228
+ class ProstoCache {
1229
+ constructor(options) {
1230
+ this.data = {};
1231
+ this.limits = [];
1232
+ this.expireOrder = [];
1233
+ this.expireSeries = {};
1234
+ this.options = {
1235
+ limit: 1000,
1236
+ ...options,
1237
+ };
1238
+ }
1239
+ set(key, value) {
1240
+ var _a, _b, _c;
1241
+ if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.limit) === 0)
1242
+ return;
1243
+ 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;
1244
+ if (expires) {
1245
+ this.del(key);
1246
+ }
1247
+ this.data[key] = {
1248
+ value: value,
1249
+ expires,
1250
+ };
1251
+ if (expires) {
1252
+ this.pushExpires(key, expires);
1253
+ }
1254
+ this.pushLimit(key);
1255
+ }
1256
+ get(key) {
1257
+ var _a;
1258
+ return (_a = this.data[key]) === null || _a === void 0 ? void 0 : _a.value;
1259
+ }
1260
+ del(key) {
1261
+ const entry = this.data[key];
1262
+ if (entry) {
1263
+ delete this.data[key];
1264
+ if (entry.expires) {
1265
+ let es = this.expireSeries[entry.expires];
1266
+ if (es) {
1267
+ es = this.expireSeries[entry.expires] = es.filter(k => k !== key);
1268
+ }
1269
+ if (!es || !es.length) {
1270
+ delete this.expireSeries[entry.expires];
1271
+ const { found, index } = this.searchExpireOrder(entry.expires);
1272
+ if (found) {
1273
+ this.expireOrder.splice(index, 1);
1274
+ if (index === 0) {
1275
+ console.log('calling prepareTimeout');
1276
+ this.prepareTimeout();
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ reset() {
1284
+ this.data = {};
1285
+ if (this.nextTimeout) {
1286
+ clearTimeout(this.nextTimeout);
1287
+ }
1288
+ this.expireOrder = [];
1289
+ this.expireSeries = {};
1290
+ this.limits = [];
1291
+ }
1292
+ searchExpireOrder(time) {
1293
+ return binarySearch(this.expireOrder, time);
1294
+ }
1295
+ pushLimit(key) {
1296
+ var _a;
1297
+ const limit = (_a = this.options) === null || _a === void 0 ? void 0 : _a.limit;
1298
+ if (limit) {
1299
+ const newObj = [key, ...(this.limits.filter(item => item !== key && this.data[item]))];
1300
+ const tail = newObj.slice(limit);
1301
+ this.limits = newObj.slice(0, limit);
1302
+ if (tail.length) {
1303
+ tail.forEach(tailItem => {
1304
+ this.del(tailItem);
1305
+ });
1306
+ }
1307
+ }
1308
+ }
1309
+ prepareTimeout() {
1310
+ if (this.nextTimeout) {
1311
+ clearTimeout(this.nextTimeout);
1312
+ }
1313
+ const time = this.expireOrder[0];
1314
+ const del = (time) => {
1315
+ for (const key of (this.expireSeries[time] || [])) {
1316
+ delete this.data[key];
1317
+ }
1318
+ delete this.expireSeries[time];
1319
+ this.expireOrder = this.expireOrder.slice(1);
1320
+ this.prepareTimeout();
1321
+ };
1322
+ if (time) {
1323
+ const delta = time - Math.round(new Date().getTime() / 1);
1324
+ if (delta > 0) {
1325
+ this.nextTimeout = setTimeout(() => {
1326
+ del(time);
1327
+ }, delta);
1328
+ }
1329
+ else {
1330
+ del(time);
1331
+ }
1332
+ }
1333
+ }
1334
+ pushExpires(key, time) {
1335
+ const { found, index } = this.searchExpireOrder(time);
1336
+ if (!found) {
1337
+ this.expireOrder.splice(index, 0, time);
1338
+ }
1339
+ const e = this.expireSeries[time] = this.expireSeries[time] || [];
1340
+ e.push(key);
1341
+ if (!found && index === 0) {
1342
+ this.prepareTimeout();
1343
+ }
1344
+ }
1345
+ }
1346
+ function binarySearch(a, n) {
1347
+ let start = 0;
1348
+ let end = a.length - 1;
1349
+ let mid = 0;
1350
+ while (start <= end) {
1351
+ mid = Math.floor((start + end) / 2);
1352
+ if (a[mid] === n) {
1353
+ return {
1354
+ found: true,
1355
+ index: mid,
1356
+ };
1357
+ }
1358
+ if (n < a[mid]) {
1359
+ end = mid - 1;
1360
+ mid--;
1361
+ }
1362
+ else {
1363
+ start = mid + 1;
1364
+ mid++;
1365
+ }
1366
+ }
1367
+ return {
1368
+ found: false,
1369
+ index: mid,
1370
+ };
1371
+ }
1372
+
1373
+ var cache_esmBundler = /*#__PURE__*/Object.freeze({
1374
+ __proto__: null,
1375
+ ProstoCache: ProstoCache
1376
+ });
1377
+
1378
+ var require$$0 = /*@__PURE__*/getAugmentedNamespace(cache_esmBundler);
1379
+
1380
+ const dim = '';
1381
+ const reset = '';
1382
+ class ProstoTree {
1383
+ constructor(options) {
1384
+ var _a, _b, _c, _d;
1385
+ const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
1386
+ const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
1387
+ const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
1388
+ const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
1389
+ const branches = {
1390
+ end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
1391
+ middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
1392
+ vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
1393
+ hLine,
1394
+ };
1395
+ this.options = {
1396
+ label: label,
1397
+ children: children,
1398
+ renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
1399
+ branches,
1400
+ branchWidth,
1401
+ };
1402
+ }
1403
+ _render(root, opts) {
1404
+ const { children, renderLabel } = this.options;
1405
+ let s = `${renderLabel(root, '')}\n`;
1406
+ const { end, middle, vLine, hLine } = this.options.branches;
1407
+ const endBranch = end + hLine + reset + ' ';
1408
+ const middleBranch = middle + hLine + reset + ' ';
1409
+ const { branchWidth } = this.options;
1410
+ if (root) {
1411
+ treeNode(root);
1412
+ }
1413
+ function treeNode(node, behind = '', level = 1) {
1414
+ const items = (node && node[children]);
1415
+ const count = items && items.length || 0;
1416
+ if (items) {
1417
+ if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
1418
+ s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
1419
+ }
1420
+ else {
1421
+ let itemsToRender = items;
1422
+ const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
1423
+ if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
1424
+ itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
1425
+ }
1426
+ if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
1427
+ s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
1428
+ itemsToRender.forEach((childNode, i) => {
1429
+ const last = i + 1 === count;
1430
+ const branch = last ? endBranch : middleBranch;
1431
+ const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
1432
+ s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
1433
+ if (typeof childNode === 'object') {
1434
+ treeNode(childNode, nextBehind, level + 1);
1435
+ }
1436
+ });
1437
+ if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
1438
+ s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
1439
+ }
1440
+ }
1441
+ }
1442
+ return s;
1443
+ }
1444
+ render(root, opts) {
1445
+ return this._render(root, opts);
1446
+ }
1447
+ print(root, opts) {
1448
+ const s = this.render(root, opts);
1449
+ console.log(s);
1450
+ return s;
1451
+ }
1452
+ }
1453
+ function renderCollapsedChildren(count) {
1454
+ return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
1455
+ }
1456
+
1457
+ var tree_esmBundler = /*#__PURE__*/Object.freeze({
1458
+ __proto__: null,
1459
+ ProstoTree: ProstoTree
1460
+ });
1461
+
1462
+ function renderCodeFragment(lines, options) {
1463
+ const row = (options.row || 1) - 1;
1464
+ const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
1465
+ const limit = Math.min(options.limit || 6, lines.length);
1466
+ const offset = Math.min(options.offset || 3, lines.length);
1467
+ const error = options.error;
1468
+ const errorEnd = options.errorEnd;
1469
+ let output = '';
1470
+ const delta = rowEnd - row;
1471
+ const maxIndex = lines.length;
1472
+ if (delta > limit) {
1473
+ let longestLine = 0;
1474
+ const newLimit = Math.floor(limit / 2);
1475
+ for (let i = 0; i < newLimit + offset; i++) {
1476
+ const index = row + i - offset;
1477
+ const line = lines[index] || '';
1478
+ longestLine = Math.max(line.length, longestLine);
1479
+ output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
1480
+ }
1481
+ let output2 = '';
1482
+ for (let i = newLimit + offset; i > 0; i--) {
1483
+ const index = rowEnd - i + offset;
1484
+ const line = lines[index] || '';
1485
+ longestLine = Math.max(line.length, longestLine);
1486
+ output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
1487
+ }
1488
+ output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
1489
+ }
1490
+ else {
1491
+ for (let i = 0; i < limit + offset; i++) {
1492
+ const index = row + i - offset;
1493
+ if (index <= lines.length + 1) {
1494
+ const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
1495
+ output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
1496
+ }
1497
+ }
1498
+ }
1499
+ return output;
1500
+ }
1501
+ function lineStyles(s) {
1502
+ return '' + (s || '')
1503
+ .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
1504
+ .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
1505
+ }
1506
+ function lineStylesError(s) {
1507
+ return '' + (s || '') + '';
1508
+ }
1509
+ function renderLine(line, index, error, style = '') {
1510
+ const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
1511
+ if (typeof error === 'number') {
1512
+ const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
1513
+ return renderLineNumber(index, true) +
1514
+ st +
1515
+ lineStyles(line.slice(0, error)) +
1516
+ lineStylesError(line.slice(error, error + errorLength)) +
1517
+ lineStyles(line.slice(error + errorLength)) +
1518
+ renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
1519
+ }
1520
+ return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
1521
+ }
1522
+ function renderLineNumber(i, isError = false, bold = false) {
1523
+ let s = ' ';
1524
+ const sep = i === '———';
1525
+ if (i && i > 0 || typeof i === 'string') {
1526
+ s = ' ' + String(i);
1527
+ }
1528
+ s = s.slice(s.length - 5);
1529
+ return '\n' + '' + (sep ? '' : '') +
1530
+ (isError ? '' + '' : (bold ? '' : '')) +
1531
+ s + (sep ? i : ' | ') + '';
1532
+ }
1533
+
1534
+ function escapeRegex(s) {
1535
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1536
+ }
1537
+
1538
+ class ProstoParserNodeBase {
1539
+ addRecognizes(...args) {
1540
+ for (const node of args) {
1541
+ if (!this.options.recognizes)
1542
+ this.options.recognizes = [];
1543
+ if (!this.options.recognizes.includes(node)) {
1544
+ this.options.recognizes.push(node);
1545
+ }
1546
+ }
1547
+ return this;
1548
+ }
1549
+ addAbsorbs(node, rule = 'append') {
1550
+ this.options.absorbs = this.options.absorbs || {};
1551
+ if (Array.isArray(node)) {
1552
+ node.forEach(n => {
1553
+ this.options.absorbs[n.id] = rule;
1554
+ this.addRecognizes(n);
1555
+ });
1556
+ }
1557
+ else {
1558
+ this.options.absorbs[node.id] = rule;
1559
+ this.addRecognizes(node);
1560
+ }
1561
+ return this;
1562
+ }
1563
+ addPopsAfterNode(...args) {
1564
+ for (const node of args) {
1565
+ if (!this.options.popsAfterNode)
1566
+ this.options.popsAfterNode = [];
1567
+ if (!this.options.popsAfterNode.includes(node)) {
1568
+ this.options.popsAfterNode.push(node);
1569
+ }
1570
+ }
1571
+ this.addRecognizes(...args);
1572
+ return this;
1573
+ }
1574
+ addHoistChildren(...args) {
1575
+ if (!this.options.hoistChildren)
1576
+ this.options.hoistChildren = [];
1577
+ this.options.hoistChildren.push(...args);
1578
+ return this;
1579
+ }
1580
+ set icon(value) {
1581
+ this.options.icon = value;
1582
+ }
1583
+ set label(value) {
1584
+ this.options.label = value;
1585
+ }
1586
+ get startsWith() {
1587
+ return this.options.startsWith;
1588
+ }
1589
+ set startsWith(value) {
1590
+ this.options.startsWith = value;
1591
+ }
1592
+ get endsWith() {
1593
+ return this.options.endsWith;
1594
+ }
1595
+ set endsWith(value) {
1596
+ this.options.endsWith = value;
1597
+ }
1598
+ getPopsAtEOFSource() {
1599
+ return this.options.popsAtEOFSource;
1600
+ }
1601
+ popsAtEOFSource(value) {
1602
+ this.options.popsAtEOFSource = value;
1603
+ return this;
1604
+ }
1605
+ get absorbs() {
1606
+ return this.options.absorbs;
1607
+ }
1608
+ get badToken() {
1609
+ return this.options.badToken;
1610
+ }
1611
+ set badToken(value) {
1612
+ this.options.badToken = value;
1613
+ }
1614
+ get skipToken() {
1615
+ return this.options.skipToken;
1616
+ }
1617
+ set skipToken(value) {
1618
+ this.options.skipToken = value;
1619
+ }
1620
+ get recognizes() {
1621
+ return this.options.recognizes || [];
1622
+ }
1623
+ set recognizes(value) {
1624
+ this.options.recognizes = value;
1625
+ }
1626
+ get hoistChildren() {
1627
+ return this.options.hoistChildren || [];
1628
+ }
1629
+ set hoistChildren(value) {
1630
+ this.options.hoistChildren = value;
1631
+ }
1632
+ getMapContent() {
1633
+ return this.options.mapContent;
1634
+ }
1635
+ mapContent(key, value = 'copy') {
1636
+ this.options.mapContent = this.options.mapContent || {};
1637
+ this.options.mapContent[key] = value;
1638
+ return this;
1639
+ }
1640
+ onMatch(value) {
1641
+ this.options.onMatch = value;
1642
+ return this;
1643
+ }
1644
+ onAppendContent(value) {
1645
+ this.options.onAppendContent = value;
1646
+ return this;
1647
+ }
1648
+ onAfterChildParse(value) {
1649
+ this.options.onAfterChildParse = value;
1650
+ return this;
1651
+ }
1652
+ onBeforeChildParse(value) {
1653
+ this.options.onBeforeChildParse = value;
1654
+ return this;
1655
+ }
1656
+ onMatchStartToken(value) {
1657
+ if (this.options.startsWith) {
1658
+ this.options.startsWith.onMatchToken = value;
1659
+ }
1660
+ return this;
1661
+ }
1662
+ onMatchEndToken(value) {
1663
+ if (this.options.endsWith) {
1664
+ this.options.endsWith.onMatchToken = value;
1665
+ }
1666
+ return this;
1667
+ }
1668
+ initCustomData(value) {
1669
+ this.options.initCustomData = value;
1670
+ return this;
1671
+ }
1672
+ onPop(value) {
1673
+ this.options.onPop = value;
1674
+ return this;
1675
+ }
1676
+ get popsAfterNode() {
1677
+ return this.options.popsAfterNode || [];
1678
+ }
1679
+ set popsAfterNode(nodes) {
1680
+ this.options.popsAfterNode = nodes;
1681
+ }
1682
+ clearStartsWith() {
1683
+ delete this.options.startsWith;
1684
+ return this;
1685
+ }
1686
+ clearEndsWith() {
1687
+ delete this.options.endsWith;
1688
+ return this;
1689
+ }
1690
+ clearPopsAtEOFSource() {
1691
+ delete this.options.popsAtEOFSource;
1692
+ return this;
1693
+ }
1694
+ clearBadToken() {
1695
+ delete this.options.badToken;
1696
+ return this;
1697
+ }
1698
+ clearSkipToken() {
1699
+ delete this.options.skipToken;
1700
+ return this;
1701
+ }
1702
+ clearAbsorbs(node) {
1703
+ if (this.options.absorbs) {
1704
+ if (node && Array.isArray(node)) {
1705
+ for (const n of node) {
1706
+ delete this.options.absorbs[n.id];
1707
+ }
1708
+ }
1709
+ else if (node) {
1710
+ delete this.options.absorbs[node.id];
1711
+ }
1712
+ else {
1713
+ this.options.absorbs = {};
1714
+ }
1715
+ }
1716
+ return this;
1717
+ }
1718
+ clearRecognizes(...args) {
1719
+ var _a;
1720
+ if (args.length) {
1721
+ this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
1722
+ }
1723
+ else {
1724
+ this.options.recognizes = [];
1725
+ }
1726
+ return this;
1727
+ }
1728
+ clearHoistChildren() {
1729
+ delete this.options.hoistChildren;
1730
+ return this;
1731
+ }
1732
+ clearMapContent() {
1733
+ delete this.options.mapContent;
1734
+ return this;
1735
+ }
1736
+ removeOnPop() {
1737
+ delete this.options.onPop;
1738
+ return this;
1739
+ }
1740
+ removeOnMatch() {
1741
+ delete this.options.onMatch;
1742
+ return this;
1743
+ }
1744
+ removeOnAppendContent() {
1745
+ delete this.options.onAppendContent;
1746
+ return this;
1747
+ }
1748
+ removeOnBeforeChildParse() {
1749
+ delete this.options.onBeforeChildParse;
1750
+ return this;
1751
+ }
1752
+ removeOnAfterChildParse() {
1753
+ delete this.options.onAfterChildParse;
1754
+ return this;
1755
+ }
1756
+ fireNodeMatched(matched, cbData) {
1757
+ return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
1758
+ }
1759
+ fireNodeEndMatched(matched, cbData) {
1760
+ return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
1761
+ }
1762
+ fireMatched(descr, matched, cbData) {
1763
+ const { omit, eject, onMatchToken } = descr;
1764
+ let cbResult = true;
1765
+ if (onMatchToken) {
1766
+ cbResult = onMatchToken({
1767
+ ...cbData,
1768
+ matched,
1769
+ });
1770
+ }
1771
+ const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
1772
+ const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
1773
+ return {
1774
+ omit: cbOmit !== undefined ? cbOmit : omit,
1775
+ eject: cbEject !== undefined ? cbEject : eject,
1776
+ confirmed: cbResult !== false,
1777
+ };
1778
+ }
1779
+ getStartTokenRg() {
1780
+ return this.getRgOutOfTokenDescriptor(this.options.startsWith);
1781
+ }
1782
+ getEndTokenRg() {
1783
+ return this.getRgOutOfTokenDescriptor(this.options.endsWith);
1784
+ }
1785
+ getConstraintTokens() {
1786
+ return {
1787
+ skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
1788
+ bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
1789
+ };
1790
+ }
1791
+ getRgOutOfTokenDescriptor(descr) {
1792
+ if (descr) {
1793
+ const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
1794
+ let token;
1795
+ if (typeof descr.token === 'function') {
1796
+ token = descr.token(this);
1797
+ }
1798
+ else {
1799
+ token = descr.token;
1800
+ }
1801
+ if (token instanceof RegExp) {
1802
+ return new RegExp(prefix + token.source, token.flags);
1803
+ }
1804
+ else {
1805
+ return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex(t)).join('|')})`);
1806
+ }
1807
+ }
1808
+ }
1809
+ }
1810
+
1811
+ class ProstoHoistManager {
1812
+ constructor() {
1813
+ this.data = {};
1814
+ }
1815
+ addHoistOptions(ctx) {
1816
+ if (ctx.hoistChildren) {
1817
+ ctx.hoistChildren.forEach(options => {
1818
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1819
+ const hoist = this.data[nodeId] = (this.data[nodeId] || {});
1820
+ if (hoist) {
1821
+ hoist[ctx.index] = {
1822
+ options,
1823
+ context: ctx,
1824
+ };
1825
+ }
1826
+ });
1827
+ }
1828
+ }
1829
+ removeHoistOptions(ctx) {
1830
+ if (ctx.hoistChildren) {
1831
+ ctx.hoistChildren.forEach(options => {
1832
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1833
+ const hoist = this.data[nodeId];
1834
+ if (hoist) {
1835
+ delete hoist[ctx.index];
1836
+ }
1837
+ });
1838
+ }
1839
+ }
1840
+ processHoistOptions(ctx) {
1841
+ const id = ctx.node.id;
1842
+ const hoist = this.data[id];
1843
+ if (hoist) {
1844
+ Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
1845
+ const customData = context.getCustomData();
1846
+ if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
1847
+ if (options.asArray) {
1848
+ const hoisted = customData[options.as] = (customData[options.as] || []);
1849
+ if (!Array.isArray(hoisted)) {
1850
+ if (!options.onConflict || options.onConflict === 'error') {
1851
+ 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.`);
1852
+ }
1853
+ else if (options.onConflict === 'overwrite') {
1854
+ customData[options.as] = [doTheMapRule(options, ctx)];
1855
+ }
1856
+ else if (options.onConflict !== 'ignore') {
1857
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1858
+ }
1859
+ }
1860
+ else {
1861
+ hoisted.push(doTheMapRule(options, ctx));
1862
+ }
1863
+ }
1864
+ else {
1865
+ if (customData[options.as]) {
1866
+ if (!options.onConflict || options.onConflict === 'error') {
1867
+ throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
1868
+ }
1869
+ else if (options.onConflict === 'overwrite') {
1870
+ customData[options.as] = doTheMapRule(options, ctx);
1871
+ }
1872
+ else if (options.onConflict !== 'ignore') {
1873
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1874
+ }
1875
+ }
1876
+ else {
1877
+ customData[options.as] = doTheMapRule(options, ctx);
1878
+ }
1879
+ }
1880
+ if (options.removeChildFromContent) {
1881
+ context.content = context.content.filter(c => c !== ctx);
1882
+ }
1883
+ }
1884
+ });
1885
+ }
1886
+ function doTheMapRule(options, ctx) {
1887
+ var _a;
1888
+ if (typeof options.mapRule === 'function') {
1889
+ return options.mapRule(ctx);
1890
+ }
1891
+ if (options.mapRule === 'content.join') {
1892
+ return ctx.content.join('');
1893
+ }
1894
+ if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
1895
+ const key = options.mapRule.slice(11);
1896
+ if (key) {
1897
+ return ctx.getCustomData()[key];
1898
+ }
1899
+ else {
1900
+ return ctx.getCustomData();
1901
+ }
1902
+ }
1903
+ return ctx;
1904
+ }
1905
+ }
1906
+ }
1907
+
1908
+ const banner = '' + '[parser]' + '';
1909
+ class ProstoParserContext {
1910
+ constructor(root) {
1911
+ this.root = root;
1912
+ this.nodes = {};
1913
+ this.pos = 0;
1914
+ this.index = 0;
1915
+ this.behind = '';
1916
+ this.here = '';
1917
+ this.src = '';
1918
+ this.stack = [];
1919
+ this.l = 0;
1920
+ this.hoistManager = new ProstoHoistManager();
1921
+ this.context = root;
1922
+ }
1923
+ parse(src) {
1924
+ this.src = src,
1925
+ this.here = src,
1926
+ this.l = src.length;
1927
+ const cache = {};
1928
+ while (this.pos < this.l) {
1929
+ const searchTokens = this.context.getSearchTokens();
1930
+ let closestIndex = Number.MAX_SAFE_INTEGER;
1931
+ let closestToken;
1932
+ let matched;
1933
+ for (const t of searchTokens) {
1934
+ const key = t.g.source;
1935
+ t.g.lastIndex = this.pos;
1936
+ let cached = cache[key];
1937
+ if (cached === null)
1938
+ continue;
1939
+ if (cached && cached.index < this.pos) {
1940
+ cached = null;
1941
+ delete cache[key];
1942
+ }
1943
+ if (!cached) {
1944
+ cached = t.g.exec(this.src);
1945
+ if (cached || (this.pos === 0 && !cached)) {
1946
+ cache[key] = cached;
1947
+ }
1948
+ }
1949
+ if (cached && cached.index < closestIndex) {
1950
+ closestIndex = cached.index;
1951
+ matched = cached;
1952
+ closestToken = t;
1953
+ if (closestIndex === this.pos)
1954
+ break;
1955
+ }
1956
+ }
1957
+ if (closestToken && matched) {
1958
+ const toAppend = this.src.slice(this.pos, closestIndex);
1959
+ if (toAppend) {
1960
+ this.context.appendContent(toAppend);
1961
+ this.jump(toAppend.length);
1962
+ }
1963
+ const matchedToken = matched[0];
1964
+ if (closestToken.node) {
1965
+ const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
1966
+ if (!confirmed)
1967
+ continue;
1968
+ let toAppend = '';
1969
+ if (eject) {
1970
+ this.context.appendContent(matchedToken);
1971
+ }
1972
+ else if (!omit) {
1973
+ toAppend = matchedToken;
1974
+ }
1975
+ this.jump(matchedToken.length);
1976
+ this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
1977
+ this.context.fireOnMatch(matched);
1978
+ continue;
1979
+ }
1980
+ else {
1981
+ const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
1982
+ if (!confirmed)
1983
+ continue;
1984
+ if (!eject && !omit) {
1985
+ this.context.appendContent(matchedToken);
1986
+ }
1987
+ if (!eject) {
1988
+ this.jump(matchedToken.length);
1989
+ }
1990
+ this.context.mapNamedGroups(matched);
1991
+ this.pop();
1992
+ continue;
1993
+ }
1994
+ }
1995
+ else {
1996
+ this.context.appendContent(this.here);
1997
+ this.jump(this.here.length);
1998
+ }
1999
+ }
2000
+ if (this.context !== this.root) {
2001
+ while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
2002
+ this.pop();
2003
+ }
2004
+ if (this.context !== this.root) {
2005
+ this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
2006
+ }
2007
+ return this.root;
2008
+ }
2009
+ pop() {
2010
+ const parentContext = this.stack.pop();
2011
+ this.context.fireOnPop();
2012
+ if (parentContext) {
2013
+ parentContext.fireAfterChildParse(this.context);
2014
+ parentContext.fireAbsorb(this.context);
2015
+ this.context.cleanup();
2016
+ const node = this.context.node;
2017
+ this.context = parentContext;
2018
+ if (parentContext.popsAfterNode.includes(node)) {
2019
+ this.pop();
2020
+ }
2021
+ }
2022
+ else {
2023
+ this.context.cleanup();
2024
+ }
2025
+ }
2026
+ pushNewContext(newNode, content) {
2027
+ this.index++;
2028
+ const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
2029
+ ctx.content = content;
2030
+ this.context.fireBeforeChildParse(ctx);
2031
+ this.context.pushChild(ctx);
2032
+ this.stack.push(this.context);
2033
+ this.hoistManager.addHoistOptions(this.context);
2034
+ this.context = ctx;
2035
+ return ctx;
2036
+ }
2037
+ fromStack(depth = 0) {
2038
+ return this.stack[this.stack.length - depth - 1];
2039
+ }
2040
+ jump(n = 1) {
2041
+ this.pos += n;
2042
+ this.behind = this.src.slice(0, this.pos);
2043
+ this.here = this.src.slice(this.pos, this.l);
2044
+ return this.pos;
2045
+ }
2046
+ getCallbackData(matched) {
2047
+ return {
2048
+ parserContext: this,
2049
+ context: this.context,
2050
+ matched,
2051
+ customData: this.context.getCustomData(),
2052
+ };
2053
+ }
2054
+ getPosition(offset = 0) {
2055
+ var _a;
2056
+ const past = this.src.slice(0, this.pos + offset).split('\n');
2057
+ const row = past.length;
2058
+ const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
2059
+ return {
2060
+ row, col, pos: this.pos,
2061
+ };
2062
+ }
2063
+ panic(message, errorBackOffset = 0) {
2064
+ if (this.pos > 0) {
2065
+ const { row, col } = this.getPosition(-errorBackOffset);
2066
+ console.error(banner + '', message, '');
2067
+ console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
2068
+ console.error(renderCodeFragment(this.src.split('\n'), {
2069
+ row: row,
2070
+ error: col,
2071
+ }));
2072
+ }
2073
+ throw new Error(message);
2074
+ }
2075
+ panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
2076
+ if (this.pos > 0) {
2077
+ const { row, col } = this.getPosition(-bottomBackOffset);
2078
+ console.error(banner + '', message, '');
2079
+ console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
2080
+ console.error(renderCodeFragment(this.src.split('\n'), {
2081
+ row: this.context.startPos.row,
2082
+ error: this.context.startPos.col - topBackOffset,
2083
+ rowEnd: row,
2084
+ errorEnd: col,
2085
+ }));
2086
+ }
2087
+ throw new Error(message);
2088
+ }
2089
+ }
2090
+
2091
+ const styles = {
2092
+ banner: (s) => '' + s + '',
2093
+ text: (s) => '' + s + '',
2094
+ valuesDim: (s) => '' + '' + s + '' + '',
2095
+ boolean: (s) => '' + s + '',
2096
+ booleanDim: (s) => '' + '' + s + '' + '',
2097
+ underscore: (s) => '' + s + '',
2098
+ values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
2099
+ nodeDim: (s) => '' + '' + s + '' + '',
2100
+ node: (s) => '' + s + '',
2101
+ };
2102
+ const stringOutputLimit = 70;
2103
+ const parserTree = new ProstoTree({
2104
+ children: 'content',
2105
+ renderLabel: (context) => {
2106
+ if (typeof context === 'string') {
2107
+ return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
2108
+ }
2109
+ else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
2110
+ let keys = '';
2111
+ const data = context.getCustomData();
2112
+ Object.keys(data).forEach(key => {
2113
+ const val = data[key];
2114
+ if (typeof val === 'string' || typeof val === 'number') {
2115
+ keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
2116
+ }
2117
+ else if (Array.isArray(val)) {
2118
+ keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
2119
+ }
2120
+ else if (typeof val === 'object') {
2121
+ keys += ' ' + styles.valuesDim(`{ ${key} }`);
2122
+ }
2123
+ else if (typeof val === 'boolean' && val) {
2124
+ const st = key ? styles.boolean : styles.booleanDim;
2125
+ keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
2126
+ }
2127
+ });
2128
+ return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
2129
+ }
2130
+ return '';
2131
+ },
2132
+ });
2133
+ function cut(s, n) {
2134
+ const c = s.replace(/\n/g, '\\n');
2135
+ if (c.length <= n)
2136
+ return c;
2137
+ return c.slice(0, n) + '' + '…';
2138
+ }
2139
+
2140
+ class ProstoParserNodeContext extends ProstoParserNodeBase {
2141
+ constructor(_node, index, level, parserContext) {
2142
+ super();
2143
+ this._node = _node;
2144
+ this.index = index;
2145
+ this.level = level;
2146
+ this.content = [];
2147
+ this._customData = {};
2148
+ this.hasNodes = [];
2149
+ this.count = {};
2150
+ this.mapContentRules = {
2151
+ 'first': (content) => content[0],
2152
+ 'shift': (content) => content.shift(),
2153
+ 'pop': (content) => content.pop(),
2154
+ 'last': (content) => content[content.length - 1],
2155
+ 'join': (content) => content.join(''),
2156
+ 'join-clear': (content) => content.splice(0).join(''),
2157
+ 'copy': (content) => content,
2158
+ };
2159
+ this.options = _node.getOptions();
2160
+ if (this.options.initCustomData) {
2161
+ this._customData = this.options.initCustomData();
2162
+ }
2163
+ this._label = this.options.label || '';
2164
+ this._icon = this.options.icon || '◦';
2165
+ this.parserContext = parserContext || new ProstoParserContext(this);
2166
+ if (parserContext) {
2167
+ this.parent = parserContext.context || parserContext.root;
2168
+ }
2169
+ this.startPos = this.parserContext.getPosition();
2170
+ this.endPos = this.parserContext.getPosition();
2171
+ }
2172
+ getOptions() {
2173
+ return this.options;
2174
+ }
2175
+ extractCustomDataTree() {
2176
+ let content = this.content;
2177
+ if (this.contentCopiedTo) {
2178
+ content = this.customData[this.contentCopiedTo];
2179
+ }
2180
+ if (Array.isArray(content)) {
2181
+ return content.map(c => {
2182
+ if (typeof c === 'string') {
2183
+ return c;
2184
+ }
2185
+ else {
2186
+ return extract(c);
2187
+ }
2188
+ });
2189
+ }
2190
+ else {
2191
+ const c = content;
2192
+ if (c instanceof ProstoParserNodeContext) {
2193
+ return extract(c);
2194
+ }
2195
+ else {
2196
+ return content;
2197
+ }
2198
+ }
2199
+ function extract(c) {
2200
+ const cd = { ...c.getCustomData() };
2201
+ if (c.contentCopiedTo) {
2202
+ cd[c.contentCopiedTo] = c.extractCustomDataTree();
2203
+ }
2204
+ return cd;
2205
+ }
2206
+ }
2207
+ getPrevNode(n = 1) {
2208
+ if (this.parent) {
2209
+ const index = this.parent.content.findIndex(n => n === this) - n;
2210
+ if (index >= 0)
2211
+ return this.parent.content[index];
2212
+ }
2213
+ }
2214
+ getPrevContext(n = 1) {
2215
+ if (this.parent) {
2216
+ const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
2217
+ const index = contexts.findIndex(n => n === this) - n;
2218
+ if (index >= 0)
2219
+ return contexts[index];
2220
+ }
2221
+ }
2222
+ set icon(value) {
2223
+ this._icon = value;
2224
+ }
2225
+ get icon() {
2226
+ return this._icon;
2227
+ }
2228
+ set label(value) {
2229
+ this._label = value;
2230
+ }
2231
+ get label() {
2232
+ return this._label;
2233
+ }
2234
+ getCustomData() {
2235
+ return this._customData;
2236
+ }
2237
+ get customData() {
2238
+ return this._customData;
2239
+ }
2240
+ get nodeId() {
2241
+ return this._node.id;
2242
+ }
2243
+ get node() {
2244
+ return this._node;
2245
+ }
2246
+ toTree(options) {
2247
+ return parserTree.render(this, options);
2248
+ }
2249
+ getSearchTokens() {
2250
+ var _a;
2251
+ const rg = this.getEndTokenRg();
2252
+ const tokens = rg ? [{
2253
+ rg,
2254
+ y: addFlag(rg, 'y'),
2255
+ g: addFlag(rg, 'g'),
2256
+ }] : [];
2257
+ (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
2258
+ const rg = node.getStartTokenRg();
2259
+ if (rg) {
2260
+ tokens.push({
2261
+ rg,
2262
+ y: addFlag(rg, 'y'),
2263
+ g: addFlag(rg, 'g'),
2264
+ node,
2265
+ });
2266
+ }
2267
+ });
2268
+ function addFlag(rg, f) {
2269
+ return new RegExp(rg.source, rg.flags + f);
2270
+ }
2271
+ return tokens;
2272
+ }
2273
+ appendContent(input) {
2274
+ let s = input;
2275
+ this.endPos = this.parserContext.getPosition();
2276
+ let { skip, bad } = this.getConstraintTokens();
2277
+ skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
2278
+ bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
2279
+ if (skip) {
2280
+ s = s.replace(skip, '');
2281
+ }
2282
+ if (bad) {
2283
+ const m = bad.exec(s);
2284
+ if (m) {
2285
+ this.parserContext.jump(m.index);
2286
+ this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
2287
+ }
2288
+ }
2289
+ s = this.fireOnAppendContent(s);
2290
+ if (s) {
2291
+ this.content.push(s);
2292
+ }
2293
+ }
2294
+ cleanup() {
2295
+ this.options = null;
2296
+ }
2297
+ pushChild(child) {
2298
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
2299
+ if (!absorbRule) {
2300
+ this.content.push(child);
2301
+ }
2302
+ }
2303
+ fireAbsorb(child) {
2304
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
2305
+ if (absorbRule) {
2306
+ switch (absorbRule) {
2307
+ case 'append':
2308
+ this.content.push(...child.content);
2309
+ break;
2310
+ case 'join':
2311
+ this.appendContent(child.content.join(''));
2312
+ break;
2313
+ default:
2314
+ const [action, target] = absorbRule.split('->');
2315
+ const cd = this.getCustomData();
2316
+ if (action === 'copy') {
2317
+ cd[target] = child.content;
2318
+ }
2319
+ else if (action === 'join') {
2320
+ cd[target] = child.content.join('');
2321
+ }
2322
+ else {
2323
+ this.parserContext.panic(`Absorb action "${action}" is not supported.`);
2324
+ }
2325
+ }
2326
+ }
2327
+ }
2328
+ has(node) {
2329
+ return this.hasNodes.includes(node);
2330
+ }
2331
+ countOf(node) {
2332
+ return this.count[node.id] || 0;
2333
+ }
2334
+ mapNamedGroups(matched) {
2335
+ if (matched.groups) {
2336
+ const cd = this.getCustomData();
2337
+ for (const [key, value] of Object.entries(matched.groups)) {
2338
+ if (key === 'content') {
2339
+ this.appendContent(value);
2340
+ }
2341
+ else {
2342
+ cd[key] = value;
2343
+ }
2344
+ }
2345
+ }
2346
+ }
2347
+ fireOnPop() {
2348
+ this.endPos = this.parserContext.getPosition();
2349
+ this.processMappings();
2350
+ const data = this.parserContext.getCallbackData();
2351
+ this.node.beforeOnPop(data);
2352
+ if (this.options.onPop) {
2353
+ this.options.onPop(data);
2354
+ }
2355
+ }
2356
+ fireOnMatch(matched) {
2357
+ this.mapNamedGroups(matched);
2358
+ const data = this.parserContext.getCallbackData(matched);
2359
+ this.node.beforeOnMatch(data);
2360
+ if (this.options.onMatch) {
2361
+ return this.options.onMatch(data);
2362
+ }
2363
+ }
2364
+ fireBeforeChildParse(child) {
2365
+ const data = this.parserContext.getCallbackData();
2366
+ this.node.beforeOnBeforeChildParse(child, data);
2367
+ if (this.options.onBeforeChildParse) {
2368
+ return this.options.onBeforeChildParse(child, data);
2369
+ }
2370
+ }
2371
+ fireAfterChildParse(child) {
2372
+ if (!this.hasNodes.includes(child.node)) {
2373
+ this.hasNodes.push(child.node);
2374
+ }
2375
+ this.count[child.node.id] = this.count[child.node.id] || 0;
2376
+ this.count[child.node.id]++;
2377
+ const data = this.parserContext.getCallbackData();
2378
+ this.node.beforeOnAfterChildParse(child, data);
2379
+ if (this.options.onAfterChildParse) {
2380
+ return this.options.onAfterChildParse(child, data);
2381
+ }
2382
+ }
2383
+ fireOnAppendContent(s) {
2384
+ let _s = s;
2385
+ const data = this.parserContext.getCallbackData();
2386
+ _s = this.node.beforeOnAppendContent(_s, data);
2387
+ if (this.options.onAppendContent) {
2388
+ _s = this.options.onAppendContent(_s, data);
2389
+ }
2390
+ return _s;
2391
+ }
2392
+ processMappings() {
2393
+ this.parserContext.hoistManager.removeHoistOptions(this);
2394
+ this.parserContext.hoistManager.processHoistOptions(this);
2395
+ this.processMapContent();
2396
+ }
2397
+ processMapContent() {
2398
+ const targetNodeOptions = this.options;
2399
+ if (targetNodeOptions.mapContent) {
2400
+ Object.keys(targetNodeOptions.mapContent).forEach((key) => {
2401
+ const keyOfT = key;
2402
+ if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
2403
+ const mapRule = targetNodeOptions.mapContent[keyOfT];
2404
+ if (typeof mapRule === 'function') {
2405
+ this._customData[keyOfT] = mapRule(this.content);
2406
+ }
2407
+ else {
2408
+ const ruleKey = mapRule;
2409
+ if (ruleKey === 'copy')
2410
+ this.contentCopiedTo = keyOfT;
2411
+ this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
2412
+ }
2413
+ if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
2414
+ this.contentCopiedTo = keyOfT;
2415
+ }
2416
+ }
2417
+ });
2418
+ }
2419
+ }
2420
+ }
2421
+
2422
+ let idCounter = 0;
2423
+ class ProstoParserNode extends ProstoParserNodeBase {
2424
+ constructor(options) {
2425
+ super();
2426
+ this.options = options;
2427
+ this.id = idCounter++;
2428
+ }
2429
+ getOptions() {
2430
+ return {
2431
+ label: this.options.label || '',
2432
+ icon: this.options.icon || '',
2433
+ startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
2434
+ endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
2435
+ popsAfterNode: [...(this.options.popsAfterNode || [])],
2436
+ popsAtEOFSource: this.options.popsAtEOFSource || false,
2437
+ badToken: this.options.badToken || '',
2438
+ skipToken: this.options.skipToken || '',
2439
+ recognizes: [...(this.options.recognizes || [])],
2440
+ hoistChildren: [...(this.options.hoistChildren || [])],
2441
+ mapContent: {
2442
+ ...this.options.mapContent,
2443
+ },
2444
+ onPop: this.options.onPop,
2445
+ onMatch: this.options.onMatch,
2446
+ onAppendContent: this.options.onAppendContent,
2447
+ onAfterChildParse: this.options.onAfterChildParse,
2448
+ onBeforeChildParse: this.options.onBeforeChildParse,
2449
+ initCustomData: this.options.initCustomData,
2450
+ absorbs: this.options.absorbs,
2451
+ };
2452
+ }
2453
+ createContext(index, level, rootContext) {
2454
+ return new ProstoParserNodeContext(this, index, level, rootContext);
2455
+ }
2456
+ get name() {
2457
+ return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
2458
+ }
2459
+ parse(source) {
2460
+ return this.createContext(0, 0).parserContext.parse(source);
2461
+ }
2462
+ beforeOnPop(data) {
2463
+ }
2464
+ beforeOnMatch(data) {
2465
+ }
2466
+ beforeOnAppendContent(s, data) {
2467
+ return s;
2468
+ }
2469
+ beforeOnAfterChildParse(child, data) {
2470
+ }
2471
+ beforeOnBeforeChildParse(child, data) {
2472
+ }
2473
+ }
2474
+
2475
+ class BasicNode extends ProstoParserNode {
2476
+ constructor(options) {
2477
+ var _a, _b;
2478
+ const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
2479
+ const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
2480
+ const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
2481
+ const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
2482
+ if (startsWith) {
2483
+ startsWith.omit = startOption === 'omit';
2484
+ startsWith.eject = startOption === 'eject';
2485
+ startsWith.ignoreBackSlashed = startBSlash === 'ignore';
2486
+ }
2487
+ if (endsWith) {
2488
+ endsWith.omit = endOption === 'omit';
2489
+ endsWith.eject = endOption === 'eject';
2490
+ endsWith.ignoreBackSlashed = endBSlash === 'ignore';
2491
+ }
2492
+ super({
2493
+ icon: options.icon || '',
2494
+ label: typeof options.label === 'string' ? options.label : '',
2495
+ startsWith,
2496
+ endsWith,
2497
+ badToken: options.badToken,
2498
+ skipToken: options.skipToken,
2499
+ });
2500
+ if (options.recursive) {
2501
+ this.addAbsorbs(this, 'join');
2502
+ }
2503
+ }
2504
+ }
2505
+
2506
+ var parser_esmBundler = /*#__PURE__*/Object.freeze({
2507
+ __proto__: null,
2508
+ BasicNode: BasicNode,
2509
+ ProstoParserContext: ProstoParserContext,
2510
+ ProstoParserNode: ProstoParserNode,
2511
+ ProstoParserNodeContext: ProstoParserNodeContext,
2512
+ renderCodeFragment: renderCodeFragment
2513
+ });
2514
+
2515
+ var require$$1 = /*@__PURE__*/getAugmentedNamespace(parser_esmBundler);
2516
+
2517
+ var require$$2 = /*@__PURE__*/getAugmentedNamespace(tree_esmBundler);
2518
+
2519
+ (function (exports) {
2520
+
2521
+ Object.defineProperty(exports, '__esModule', { value: true });
2522
+
2523
+ var cache = require$$0;
2524
+ var parser$1 = require$$1;
2525
+ var tree = require$$2;
2526
+
2527
+ function parsePath(expr) {
2528
+ return parser.parse(expr).extractCustomDataTree();
2529
+ }
2530
+ class ParametricNodeWithRegex extends parser$1.BasicNode {
2531
+ constructor(options, rgNode) {
2532
+ super(options);
2533
+ const hoistRegex = {
2534
+ as: 'regex',
2535
+ node: regexNode,
2536
+ onConflict: 'overwrite',
2537
+ removeChildFromContent: true,
2538
+ deep: 1,
2539
+ mapRule: ({ content }) => content.join('').replace(/^\(\^/, '(').replace(/\$\)$/, ')'),
2540
+ };
2541
+ this.mapContent('name', 'join')
2542
+ .mapContent('value', content => content.shift())
2543
+ .popsAtEOFSource(true)
2544
+ .addRecognizes(rgNode)
2545
+ .addPopsAfterNode(rgNode)
2546
+ .addHoistChildren(hoistRegex);
2547
+ }
2548
+ beforeOnPop(data) {
2549
+ if (data.customData.name.endsWith('?')) {
2550
+ data.customData.name = data.customData.name.slice(0, -1);
2551
+ data.customData.value = data.customData.name;
2552
+ data.customData.optional = true;
2553
+ }
2554
+ else if (data.parserContext.here[0] === '?') {
2555
+ data.customData.optional = true;
2556
+ data.parserContext.jump();
2557
+ }
2558
+ }
2559
+ }
2560
+ const regexNode = new parser$1.BasicNode({
2561
+ label: 'RegEx',
2562
+ tokens: ['(', ')'],
2563
+ backSlash: 'ignore-ignore',
2564
+ recursive: true,
2565
+ }).onMatch(({ parserContext, context }) => {
2566
+ var _a;
2567
+ if (((_a = parserContext.fromStack()) === null || _a === void 0 ? void 0 : _a.node) === context.node) {
2568
+ if (!parserContext.here.startsWith('?:')) {
2569
+ context.content[0] += '?:';
2570
+ }
2571
+ }
2572
+ });
2573
+ const paramNode = new ParametricNodeWithRegex({
2574
+ label: 'Parameter',
2575
+ tokens: [':', /[\/\-]/],
2576
+ tokenOE: 'omit-eject',
2577
+ backSlash: 'ignore-',
2578
+ }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.VARIABLE, value: '', regex: '([^\\/]*)', name: '' }));
2579
+ const wildcardNode = new ParametricNodeWithRegex({
2580
+ label: 'Wildcard',
2581
+ tokens: ['*', /[^*\()]/],
2582
+ tokenOE: '-eject',
2583
+ }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.WILDCARD, value: '*', regex: '(.*)', name: '' }));
2584
+ const staticNode = new parser$1.BasicNode({
2585
+ label: 'Static',
2586
+ tokens: [/[^:\*]/, /[:\*]/],
2587
+ backSlash: '-ignore',
2588
+ tokenOE: '-eject',
2589
+ }).initCustomData(() => ({ type: exports.EPathSegmentType.STATIC, value: '' }))
2590
+ .mapContent('value', content => content.splice(0).join('').replace(/\\:/g, ':'))
2591
+ .popsAtEOFSource(true);
2592
+ const parser = new parser$1.BasicNode({}).addRecognizes(staticNode, paramNode, wildcardNode);
2593
+
2594
+ exports.EPathSegmentType = void 0;
2595
+ (function (EPathSegmentType) {
2596
+ EPathSegmentType[EPathSegmentType["STATIC"] = 0] = "STATIC";
2597
+ EPathSegmentType[EPathSegmentType["VARIABLE"] = 1] = "VARIABLE";
2598
+ EPathSegmentType[EPathSegmentType["REGEX"] = 2] = "REGEX";
2599
+ EPathSegmentType[EPathSegmentType["WILDCARD"] = 3] = "WILDCARD";
2600
+ })(exports.EPathSegmentType || (exports.EPathSegmentType = {}));
2601
+
2602
+ function safeDecode(f, v) {
2603
+ try {
2604
+ return f(v);
2605
+ }
2606
+ catch (e) {
2607
+ return v;
2608
+ }
2609
+ }
2610
+ function safeDecodeURIComponent(uri) {
2611
+ if (!uri || uri.indexOf('%') < 0)
2612
+ return uri;
2613
+ return safeDecode(decodeURIComponent, uri);
2614
+ }
2615
+ function safeDecodeURI(uri) {
2616
+ if (!uri || uri.indexOf('%') < 0)
2617
+ return uri;
2618
+ return safeDecode(decodeURI, uri);
2619
+ }
2620
+
2621
+ function countOfSlashes(s) {
2622
+ let last = 0;
2623
+ let count = 0;
2624
+ let index = s.indexOf('/');
2625
+ last = index + 1;
2626
+ while (index >= 0) {
2627
+ count++;
2628
+ index = s.indexOf('/', last);
2629
+ last = index + 1;
2630
+ }
2631
+ return count;
2632
+ }
2633
+
2634
+ class CodeString {
2635
+ constructor() {
2636
+ this.code = '';
2637
+ }
2638
+ append(s, newLine = false) {
2639
+ this.code += ['', s].flat().join(newLine ? '\n' : '');
2640
+ }
2641
+ prepend(s, newLine = false) {
2642
+ this.code = [s, ''].flat().join(newLine ? '\n' : '') + this.code;
2643
+ }
2644
+ generateFunction(...args) {
2645
+ return new Function(args.join(','), this.code);
2646
+ }
2647
+ toString() {
2648
+ return this.code;
2649
+ }
2650
+ }
2651
+
2652
+ function escapeRegex(s) {
2653
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
2654
+ }
2655
+
2656
+ function generateFullMatchRegex(segments, nonCapturing = false) {
2657
+ let regex = '';
2658
+ let optional = false;
2659
+ segments.forEach(segment => {
2660
+ switch (segment.type) {
2661
+ case exports.EPathSegmentType.STATIC:
2662
+ if (optional) {
2663
+ if (['-', '/'].includes(segment.value)) {
2664
+ regex += escapeRegex(segment.value) + '?';
2665
+ }
2666
+ else {
2667
+ throw new Error(`Static route segment "${segment.value}" is not allowed after optional parameters.`);
2668
+ }
2669
+ }
2670
+ else {
2671
+ regex += escapeRegex(segment.value);
2672
+ }
2673
+ break;
2674
+ case exports.EPathSegmentType.VARIABLE:
2675
+ case exports.EPathSegmentType.WILDCARD:
2676
+ if (optional && !segment.optional)
2677
+ throw new Error('Obligatory route parameters are not allowed after optional parameters. Use "?" to mark it as an optional route parameter.');
2678
+ if (segment.optional && !optional) {
2679
+ if (regex.endsWith('/')) {
2680
+ regex += '?';
2681
+ }
2682
+ }
2683
+ regex += nonCapturing ? segment.regex.replace(/^\(/, '(?:') : segment.regex;
2684
+ if (segment.optional) {
2685
+ optional = true;
2686
+ regex += '?';
2687
+ }
2688
+ }
2689
+ });
2690
+ return regex;
2691
+ }
2692
+ function generateFullMatchFunc(segments, ignoreCase = false) {
2693
+ const str = new CodeString();
2694
+ const regex = generateFullMatchRegex(segments);
2695
+ let index = 0;
2696
+ const obj = {};
2697
+ segments.forEach(segment => {
2698
+ switch (segment.type) {
2699
+ case exports.EPathSegmentType.VARIABLE:
2700
+ case exports.EPathSegmentType.WILDCARD:
2701
+ index++;
2702
+ obj[segment.value] = obj[segment.value] || [];
2703
+ obj[segment.value].push(index);
2704
+ }
2705
+ });
2706
+ Object.keys(obj).forEach(key => {
2707
+ str.append(obj[key].length > 1
2708
+ ? `\tparams['${key}'] = [${obj[key].map(i => `utils.safeDecodeURIComponent(a[${i}])`).join(', ')}]`
2709
+ : `\tparams['${key}'] = utils.safeDecodeURIComponent(a[${obj[key][0]}])`, true);
2710
+ });
2711
+ str.prepend([`const a = path.match(/^${regex}$/${ignoreCase ? 'i' : ''})`, 'if (a) {'], true);
2712
+ str.append(['}', 'return a'], true);
2713
+ return str.generateFunction('path', 'params', 'utils');
2714
+ }
2715
+ function generatePathBuilder(segments) {
2716
+ const str = new CodeString();
2717
+ const obj = {};
2718
+ const index = {};
2719
+ segments.forEach(segment => {
2720
+ switch (segment.type) {
2721
+ case exports.EPathSegmentType.VARIABLE:
2722
+ case exports.EPathSegmentType.WILDCARD:
2723
+ obj[segment.value] = obj[segment.value] || 0;
2724
+ obj[segment.value]++;
2725
+ index[segment.value] = 0;
2726
+ }
2727
+ });
2728
+ str.append('return `');
2729
+ segments.forEach(segment => {
2730
+ switch (segment.type) {
2731
+ case exports.EPathSegmentType.STATIC:
2732
+ str.append(segment.value.replace(/`/g, '\\`'));
2733
+ break;
2734
+ case exports.EPathSegmentType.VARIABLE:
2735
+ case exports.EPathSegmentType.WILDCARD:
2736
+ if (obj[segment.value] > 1) {
2737
+ str.append('${ params[\'' + segment.value + `\'][${index[segment.value]}] }`);
2738
+ index[segment.value]++;
2739
+ }
2740
+ else {
2741
+ str.append('${ params[\'' + segment.value + '\'] }');
2742
+ }
2743
+ }
2744
+ });
2745
+ str.append('`');
2746
+ return str.generateFunction('params');
2747
+ }
2748
+
2749
+ const banner = () => `[prostojs/router][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
2750
+
2751
+ const methods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
2752
+ const matcherFuncUtils = {
2753
+ safeDecodeURIComponent,
2754
+ };
2755
+ class ProstoRouter {
2756
+ constructor(_options) {
2757
+ this.root = {};
2758
+ this.routes = [];
2759
+ this.routesRegistry = {};
2760
+ this._options = {
2761
+ ..._options,
2762
+ };
2763
+ if (!this._options.silent) {
2764
+ consoleInfo('The Router Initialized');
2765
+ }
2766
+ const cacheOpts = {
2767
+ limit: (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) || 0,
2768
+ };
2769
+ if (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) {
2770
+ this.cache = {
2771
+ GET: new cache.ProstoCache(cacheOpts),
2772
+ PUT: new cache.ProstoCache(cacheOpts),
2773
+ POST: new cache.ProstoCache(cacheOpts),
2774
+ PATCH: new cache.ProstoCache(cacheOpts),
2775
+ DELETE: new cache.ProstoCache(cacheOpts),
2776
+ HEAD: new cache.ProstoCache(cacheOpts),
2777
+ OPTIONS: new cache.ProstoCache(cacheOpts),
2778
+ };
2779
+ }
2780
+ }
2781
+ refreshCache(method) {
2782
+ if (this._options.cacheLimit && this.cache) {
2783
+ if (method === '*') {
2784
+ this.cache.GET.reset();
2785
+ this.cache.PUT.reset();
2786
+ this.cache.POST.reset();
2787
+ this.cache.PATCH.reset();
2788
+ this.cache.DELETE.reset();
2789
+ this.cache.HEAD.reset();
2790
+ this.cache.OPTIONS.reset();
2791
+ }
2792
+ else if (this.cache && this.cache[method]) {
2793
+ this.cache[method].reset();
2794
+ }
2795
+ }
2796
+ }
2797
+ registerRoute(method, path, options, handler) {
2798
+ this.refreshCache(method);
2799
+ const opts = this.mergeOptions(options);
2800
+ const normalPath = ('/' + path)
2801
+ .replace(/^\/\//, '/')
2802
+ .replace(/\/$/, '')
2803
+ .replace(/%/g, '%25');
2804
+ const { root } = this;
2805
+ const segments = parsePath(normalPath);
2806
+ if (!root[method]) {
2807
+ root[method] = {
2808
+ statics: {},
2809
+ parametrics: {
2810
+ byParts: [],
2811
+ },
2812
+ wildcards: [],
2813
+ };
2814
+ }
2815
+ const rootMethod = root[method];
2816
+ const generalized = method + ':' + segments.map(s => {
2817
+ switch (s.type) {
2818
+ case exports.EPathSegmentType.STATIC: return s.value;
2819
+ case exports.EPathSegmentType.VARIABLE: return '<VAR' + (s.regex === '([^-\\/]*)' ? '' : s.regex) + '>';
2820
+ case exports.EPathSegmentType.WILDCARD: return s.value;
2821
+ }
2822
+ }).join('');
2823
+ let route = this.routesRegistry[generalized];
2824
+ if (route) {
2825
+ if (this._options.disableDuplicatePath) {
2826
+ const error = `Attempt to register duplicated path: "${path}". Duplicate paths are disabled.\nYou can enable duplicated paths removing 'disableDuplicatePath' option.`;
2827
+ consoleError(error);
2828
+ throw new Error(error);
2829
+ }
2830
+ if (route.handlers.includes(handler)) {
2831
+ consoleError('Duplicate route with same handler ignored ' + generalized);
2832
+ }
2833
+ else {
2834
+ consoleWarn('Duplicate route registered ' + generalized);
2835
+ route.handlers.push(handler);
2836
+ }
2837
+ }
2838
+ else {
2839
+ const isStatic = segments.length === 1 && segments[0].type === exports.EPathSegmentType.STATIC || segments.length === 0;
2840
+ const isParametric = !!segments.find(p => p.type === exports.EPathSegmentType.VARIABLE);
2841
+ const firstOptional = segments.findIndex(p => p.optional);
2842
+ const isOptional = firstOptional >= 0;
2843
+ const isWildcard = !!segments.find(p => p.type === exports.EPathSegmentType.WILDCARD);
2844
+ const lengths = segments.slice(0, firstOptional >= 0 ? firstOptional : undefined).map(s => s.type === exports.EPathSegmentType.STATIC ? s.value.length : 0);
2845
+ const normalPathCase = segments[0] ? (this._options.ignoreCase ? segments[0].value.toLowerCase() : segments[0].value) : '/';
2846
+ this.routesRegistry[generalized] = route = {
2847
+ method,
2848
+ options: opts,
2849
+ path: normalPath,
2850
+ handlers: [handler],
2851
+ isStatic,
2852
+ isParametric,
2853
+ isOptional,
2854
+ isWildcard,
2855
+ segments,
2856
+ lengths,
2857
+ minLength: lengths.reduce((a, b) => a + b, 0),
2858
+ firstLength: lengths[0],
2859
+ firstStatic: normalPathCase.slice(0, lengths[0]),
2860
+ generalized,
2861
+ fullMatch: generateFullMatchFunc(segments, this._options.ignoreCase),
2862
+ pathBuilder: generatePathBuilder(segments),
2863
+ };
2864
+ this.routes.push(route);
2865
+ if (route.isStatic) {
2866
+ rootMethod.statics[normalPathCase] = route;
2867
+ }
2868
+ else {
2869
+ if (route.isParametric && !route.isWildcard && !route.isOptional) {
2870
+ const countOfParts = route.segments
2871
+ .filter(s => s.type === exports.EPathSegmentType.STATIC)
2872
+ .map(s => countOfSlashes(s.value)).reduce((a, b) => a + b, 1);
2873
+ const byParts = rootMethod.parametrics.byParts[countOfParts] = rootMethod.parametrics.byParts[countOfParts] || [];
2874
+ byParts.push(route);
2875
+ rootMethod.parametrics.byParts[countOfParts] = byParts.sort(routeSorter);
2876
+ }
2877
+ else if (route.isWildcard || route.isOptional) {
2878
+ if (route.isOptional && route.firstStatic.endsWith('/')) {
2879
+ route.firstStatic = route.firstStatic.slice(0, -1);
2880
+ route.firstLength--;
2881
+ route.minLength = Math.min(route.minLength, route.firstLength);
2882
+ }
2883
+ rootMethod.wildcards.push(route);
2884
+ rootMethod.wildcards = rootMethod.wildcards.sort(routeSorter);
2885
+ }
2886
+ }
2887
+ }
2888
+ return {
2889
+ getPath: route.pathBuilder,
2890
+ getArgs: () => route.segments.filter(p => p.type === exports.EPathSegmentType.VARIABLE || p.type === exports.EPathSegmentType.WILDCARD).map(s => s.name),
2891
+ getStaticPart: () => route.firstStatic,
2892
+ test: route.fullMatch,
2893
+ isStatic: route.isStatic,
2894
+ isParametric: route.isParametric,
2895
+ isWildcard: route.isWildcard,
2896
+ generalized,
2897
+ };
2898
+ }
2899
+ mergeOptions(options) {
2900
+ return {
2901
+ ...options,
2902
+ };
2903
+ }
2904
+ sanitizePath(path, ignoreTrailingSlash) {
2905
+ const end = path.indexOf('?');
2906
+ let slicedPath = end >= 0 ? path.slice(0, end) : path;
2907
+ if ((ignoreTrailingSlash || this._options.ignoreTrailingSlash) && slicedPath[slicedPath.length - 1] === '/') {
2908
+ slicedPath = slicedPath.slice(0, slicedPath.length - 1);
2909
+ }
2910
+ const normalPath = safeDecodeURI(slicedPath
2911
+ .replace(/%25/g, '%2525'));
2912
+ return {
2913
+ normalPath,
2914
+ normalPathWithCase: this._options.ignoreCase ? normalPath.toLowerCase() : normalPath,
2915
+ };
2916
+ }
2917
+ lookup(method, path, ignoreTrailingSlash) {
2918
+ if (this._options.cacheLimit && this.cache && this.cache[method]) {
2919
+ const cached = this.cache[method].get(path);
2920
+ if (cached)
2921
+ return cached;
2922
+ }
2923
+ const { normalPath, normalPathWithCase } = this.sanitizePath(path, ignoreTrailingSlash);
2924
+ const rootMethod = this.root[method];
2925
+ const lookupResult = {
2926
+ route: null,
2927
+ ctx: { params: {} },
2928
+ };
2929
+ const cache = (result) => {
2930
+ if (this._options.cacheLimit && this.cache && this.cache[method]) {
2931
+ this.cache[method].set(path, result);
2932
+ }
2933
+ return result;
2934
+ };
2935
+ if (rootMethod) {
2936
+ lookupResult.route = rootMethod.statics[normalPathWithCase];
2937
+ if (lookupResult.route)
2938
+ return cache(lookupResult);
2939
+ const pathSegmentsCount = countOfSlashes(normalPath) + 1;
2940
+ const pathLength = normalPath.length;
2941
+ const { parametrics } = rootMethod;
2942
+ const bySegments = parametrics.byParts[pathSegmentsCount];
2943
+ if (bySegments) {
2944
+ for (let i = 0; i < bySegments.length; i++) {
2945
+ lookupResult.route = bySegments[i];
2946
+ if (pathLength >= lookupResult.route.minLength) {
2947
+ if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2948
+ && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2949
+ return cache(lookupResult);
2950
+ }
2951
+ }
2952
+ }
2953
+ }
2954
+ const { wildcards } = rootMethod;
2955
+ for (let i = 0; i < wildcards.length; i++) {
2956
+ lookupResult.route = wildcards[i];
2957
+ if (pathLength >= lookupResult.route.minLength) {
2958
+ if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2959
+ && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2960
+ return cache(lookupResult);
2961
+ }
2962
+ }
2963
+ }
2964
+ }
2965
+ }
2966
+ find(method, path) {
2967
+ return this.lookup(method, path);
2968
+ }
2969
+ on(method, path, options, handler) {
2970
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2971
+ if (method === '*') {
2972
+ return methods.map(m => this.registerRoute(m, path, opts, func))[0];
2973
+ }
2974
+ return this.registerRoute(method, path, opts, func);
2975
+ }
2976
+ all(path, options, handler) {
2977
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2978
+ return this.on('*', path, opts, func);
2979
+ }
2980
+ get(path, options, handler) {
2981
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2982
+ return this.on('GET', path, opts, func);
2983
+ }
2984
+ put(path, options, handler) {
2985
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2986
+ return this.on('PUT', path, opts, func);
2987
+ }
2988
+ post(path, options, handler) {
2989
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2990
+ return this.on('POST', path, opts, func);
2991
+ }
2992
+ patch(path, options, handler) {
2993
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2994
+ return this.on('PATCH', path, opts, func);
2995
+ }
2996
+ delete(path, options, handler) {
2997
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2998
+ return this.on('DELETE', path, opts, func);
2999
+ }
3000
+ options(path, options, handler) {
3001
+ const { opts, func } = extractOptionsAndHandler(options, handler);
3002
+ return this.on('OPTIONS', path, opts, func);
3003
+ }
3004
+ head(path, options, handler) {
3005
+ const { opts, func } = extractOptionsAndHandler(options, handler);
3006
+ return this.on('HEAD', path, opts, func);
3007
+ }
3008
+ getRoutes() {
3009
+ return this.routes;
3010
+ }
3011
+ toTree() {
3012
+ const rootStyle = (v) => '' + v + '';
3013
+ const paramStyle = (v) => '' + '' + ':' + v + '' + '';
3014
+ const regexStyle = (v) => '' + '' + v + '' + '';
3015
+ const handlerStyle = (v) => '' + '' + '→ ' + '' + '' + v;
3016
+ const methodStyle = (v) => '' + '' + '• (' + v + ') ' + '';
3017
+ const data = {
3018
+ label: '⁕ Router',
3019
+ stylist: rootStyle,
3020
+ methods: [],
3021
+ children: [],
3022
+ };
3023
+ function toChild(d, label, stylist) {
3024
+ let found = d.children.find(c => c.label === label);
3025
+ if (!found) {
3026
+ found = {
3027
+ label,
3028
+ stylist,
3029
+ methods: [],
3030
+ children: [],
3031
+ };
3032
+ d.children.push(found);
3033
+ }
3034
+ return found;
3035
+ }
3036
+ this.routes.sort((a, b) => a.path > b.path ? 1 : -1).forEach(route => {
3037
+ let cur = data;
3038
+ let last = '';
3039
+ route.segments.forEach(s => {
3040
+ let parts;
3041
+ switch (s.type) {
3042
+ case exports.EPathSegmentType.STATIC:
3043
+ parts = s.value.split('/');
3044
+ last += parts.shift();
3045
+ for (let i = 0; i < parts.length; i++) {
3046
+ if (last) {
3047
+ cur = toChild(cur, last);
3048
+ }
3049
+ last = '/' + parts[i];
3050
+ }
3051
+ break;
3052
+ case exports.EPathSegmentType.VARIABLE:
3053
+ case exports.EPathSegmentType.WILDCARD:
3054
+ last += `${paramStyle(s.value)}${regexStyle(s.regex)}`;
3055
+ }
3056
+ });
3057
+ if (last) {
3058
+ cur = toChild(cur, last, handlerStyle);
3059
+ cur.methods.push(route.method);
3060
+ }
3061
+ });
3062
+ new tree.ProstoTree({
3063
+ renderLabel: (node, behind) => {
3064
+ const styledLabel = node.stylist ? node.stylist(node.label) : node.label;
3065
+ if (node.methods.length) {
3066
+ return styledLabel + '\n' + behind + node.methods.map(m => methodStyle(m)).join('\n' + behind);
3067
+ }
3068
+ return styledLabel;
3069
+ },
3070
+ }).print(data);
3071
+ }
3072
+ }
3073
+ function extractOptionsAndHandler(options, handler) {
3074
+ let opts = {};
3075
+ let func = handler;
3076
+ if (typeof options === 'function') {
3077
+ func = options;
3078
+ }
3079
+ else {
3080
+ opts = options;
3081
+ }
3082
+ return { opts, func };
3083
+ }
3084
+ function routeSorter(a, b) {
3085
+ if (a.isWildcard !== b.isWildcard) {
3086
+ return a.isWildcard ? 1 : -1;
3087
+ }
3088
+ const len = b.minLength - a.minLength;
3089
+ if (len)
3090
+ return len;
3091
+ for (let i = 0; i < a.lengths.length; i++) {
3092
+ const len = b.lengths[i] - a.lengths[i];
3093
+ if (len)
3094
+ return len;
3095
+ }
3096
+ return 0;
3097
+ }
3098
+ function consoleError(v) {
3099
+ console.info('' + banner() + v + '');
3100
+ }
3101
+ function consoleWarn(v) {
3102
+ console.info('' + banner() + v + '');
3103
+ }
3104
+ function consoleInfo(v) {
3105
+ console.info('' + '' + banner() + v + '' + '');
3106
+ }
3107
+
3108
+ exports.ProstoRouter = ProstoRouter;
3109
+ exports.escapeRegex = escapeRegex;
3110
+ exports.safeDecodeURI = safeDecodeURI;
3111
+ exports.safeDecodeURIComponent = safeDecodeURIComponent;
3112
+ } (router_cjs_prod));
3113
+
1165
3114
  function getOtelMate() {
1166
3115
  return getMoostMate();
1167
3116
  }