orator 6.0.2 → 6.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/orator.js DELETED
@@ -1,4487 +0,0 @@
1
- "use strict";
2
-
3
- const _excluded = ["version", "host"];
4
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
5
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
6
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
7
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
8
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
10
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
11
- (function (f) {
12
- if (typeof exports === "object" && typeof module !== "undefined") {
13
- module.exports = f();
14
- } else if (typeof define === "function" && define.amd) {
15
- define([], f);
16
- } else {
17
- var g;
18
- if (typeof window !== "undefined") {
19
- g = window;
20
- } else if (typeof global !== "undefined") {
21
- g = global;
22
- } else if (typeof self !== "undefined") {
23
- g = self;
24
- } else {
25
- g = this;
26
- }
27
- g.Orator = f();
28
- }
29
- })(function () {
30
- var define, module, exports;
31
- return function () {
32
- function r(e, n, t) {
33
- function o(i, f) {
34
- if (!n[i]) {
35
- if (!e[i]) {
36
- var c = "function" == typeof require && require;
37
- if (!f && c) return c(i, !0);
38
- if (u) return u(i, !0);
39
- var a = new Error("Cannot find module '" + i + "'");
40
- throw a.code = "MODULE_NOT_FOUND", a;
41
- }
42
- var p = n[i] = {
43
- exports: {}
44
- };
45
- e[i][0].call(p.exports, function (r) {
46
- var n = e[i][1][r];
47
- return o(n || r);
48
- }, p, p.exports, r, e, n, t);
49
- }
50
- return n[i].exports;
51
- }
52
- for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]);
53
- return o;
54
- }
55
- return r;
56
- }()({
57
- 1: [function (require, module, exports) {
58
- (function (global) {
59
- (function () {
60
- 'use strict';
61
-
62
- var objectAssign = require('object-assign');
63
-
64
- // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
65
- // original notice:
66
-
67
- /*!
68
- * The buffer module from node.js, for the browser.
69
- *
70
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
71
- * @license MIT
72
- */
73
- function compare(a, b) {
74
- if (a === b) {
75
- return 0;
76
- }
77
- var x = a.length;
78
- var y = b.length;
79
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
80
- if (a[i] !== b[i]) {
81
- x = a[i];
82
- y = b[i];
83
- break;
84
- }
85
- }
86
- if (x < y) {
87
- return -1;
88
- }
89
- if (y < x) {
90
- return 1;
91
- }
92
- return 0;
93
- }
94
- function isBuffer(b) {
95
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
96
- return global.Buffer.isBuffer(b);
97
- }
98
- return !!(b != null && b._isBuffer);
99
- }
100
-
101
- // based on node assert, original notice:
102
- // NB: The URL to the CommonJS spec is kept just for tradition.
103
- // node-assert has evolved a lot since then, both in API and behavior.
104
-
105
- // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
106
- //
107
- // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
108
- //
109
- // Originally from narwhal.js (http://narwhaljs.org)
110
- // Copyright (c) 2009 Thomas Robinson <280north.com>
111
- //
112
- // Permission is hereby granted, free of charge, to any person obtaining a copy
113
- // of this software and associated documentation files (the 'Software'), to
114
- // deal in the Software without restriction, including without limitation the
115
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
116
- // sell copies of the Software, and to permit persons to whom the Software is
117
- // furnished to do so, subject to the following conditions:
118
- //
119
- // The above copyright notice and this permission notice shall be included in
120
- // all copies or substantial portions of the Software.
121
- //
122
- // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
123
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
124
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
125
- // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
126
- // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
127
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
128
-
129
- var util = require('util/');
130
- var hasOwn = Object.prototype.hasOwnProperty;
131
- var pSlice = Array.prototype.slice;
132
- var functionsHaveNames = function () {
133
- return function foo() {}.name === 'foo';
134
- }();
135
- function pToString(obj) {
136
- return Object.prototype.toString.call(obj);
137
- }
138
- function isView(arrbuf) {
139
- if (isBuffer(arrbuf)) {
140
- return false;
141
- }
142
- if (typeof global.ArrayBuffer !== 'function') {
143
- return false;
144
- }
145
- if (typeof ArrayBuffer.isView === 'function') {
146
- return ArrayBuffer.isView(arrbuf);
147
- }
148
- if (!arrbuf) {
149
- return false;
150
- }
151
- if (arrbuf instanceof DataView) {
152
- return true;
153
- }
154
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
155
- return true;
156
- }
157
- return false;
158
- }
159
- // 1. The assert module provides functions that throw
160
- // AssertionError's when particular conditions are not met. The
161
- // assert module must conform to the following interface.
162
-
163
- var assert = module.exports = ok;
164
-
165
- // 2. The AssertionError is defined in assert.
166
- // new assert.AssertionError({ message: message,
167
- // actual: actual,
168
- // expected: expected })
169
-
170
- var regex = /\s*function\s+([^\(\s]*)\s*/;
171
- // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
172
- function getName(func) {
173
- if (!util.isFunction(func)) {
174
- return;
175
- }
176
- if (functionsHaveNames) {
177
- return func.name;
178
- }
179
- var str = func.toString();
180
- var match = str.match(regex);
181
- return match && match[1];
182
- }
183
- assert.AssertionError = function AssertionError(options) {
184
- this.name = 'AssertionError';
185
- this.actual = options.actual;
186
- this.expected = options.expected;
187
- this.operator = options.operator;
188
- if (options.message) {
189
- this.message = options.message;
190
- this.generatedMessage = false;
191
- } else {
192
- this.message = getMessage(this);
193
- this.generatedMessage = true;
194
- }
195
- var stackStartFunction = options.stackStartFunction || fail;
196
- if (Error.captureStackTrace) {
197
- Error.captureStackTrace(this, stackStartFunction);
198
- } else {
199
- // non v8 browsers so we can have a stacktrace
200
- var err = new Error();
201
- if (err.stack) {
202
- var out = err.stack;
203
-
204
- // try to strip useless frames
205
- var fn_name = getName(stackStartFunction);
206
- var idx = out.indexOf('\n' + fn_name);
207
- if (idx >= 0) {
208
- // once we have located the function frame
209
- // we need to strip out everything before it (and its line)
210
- var next_line = out.indexOf('\n', idx + 1);
211
- out = out.substring(next_line + 1);
212
- }
213
- this.stack = out;
214
- }
215
- }
216
- };
217
-
218
- // assert.AssertionError instanceof Error
219
- util.inherits(assert.AssertionError, Error);
220
- function truncate(s, n) {
221
- if (typeof s === 'string') {
222
- return s.length < n ? s : s.slice(0, n);
223
- } else {
224
- return s;
225
- }
226
- }
227
- function inspect(something) {
228
- if (functionsHaveNames || !util.isFunction(something)) {
229
- return util.inspect(something);
230
- }
231
- var rawname = getName(something);
232
- var name = rawname ? ': ' + rawname : '';
233
- return '[Function' + name + ']';
234
- }
235
- function getMessage(self) {
236
- return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128);
237
- }
238
-
239
- // At present only the three keys mentioned above are used and
240
- // understood by the spec. Implementations or sub modules can pass
241
- // other keys to the AssertionError's constructor - they will be
242
- // ignored.
243
-
244
- // 3. All of the following functions must throw an AssertionError
245
- // when a corresponding condition is not met, with a message that
246
- // may be undefined if not provided. All assertion methods provide
247
- // both the actual and expected values to the assertion error for
248
- // display purposes.
249
-
250
- function fail(actual, expected, message, operator, stackStartFunction) {
251
- throw new assert.AssertionError({
252
- message: message,
253
- actual: actual,
254
- expected: expected,
255
- operator: operator,
256
- stackStartFunction: stackStartFunction
257
- });
258
- }
259
-
260
- // EXTENSION! allows for well behaved errors defined elsewhere.
261
- assert.fail = fail;
262
-
263
- // 4. Pure assertion tests whether a value is truthy, as determined
264
- // by !!guard.
265
- // assert.ok(guard, message_opt);
266
- // This statement is equivalent to assert.equal(true, !!guard,
267
- // message_opt);. To test strictly for the value true, use
268
- // assert.strictEqual(true, guard, message_opt);.
269
-
270
- function ok(value, message) {
271
- if (!value) fail(value, true, message, '==', assert.ok);
272
- }
273
- assert.ok = ok;
274
-
275
- // 5. The equality assertion tests shallow, coercive equality with
276
- // ==.
277
- // assert.equal(actual, expected, message_opt);
278
-
279
- assert.equal = function equal(actual, expected, message) {
280
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
281
- };
282
-
283
- // 6. The non-equality assertion tests for whether two objects are not equal
284
- // with != assert.notEqual(actual, expected, message_opt);
285
-
286
- assert.notEqual = function notEqual(actual, expected, message) {
287
- if (actual == expected) {
288
- fail(actual, expected, message, '!=', assert.notEqual);
289
- }
290
- };
291
-
292
- // 7. The equivalence assertion tests a deep equality relation.
293
- // assert.deepEqual(actual, expected, message_opt);
294
-
295
- assert.deepEqual = function deepEqual(actual, expected, message) {
296
- if (!_deepEqual(actual, expected, false)) {
297
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
298
- }
299
- };
300
- assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
301
- if (!_deepEqual(actual, expected, true)) {
302
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
303
- }
304
- };
305
- function _deepEqual(actual, expected, strict, memos) {
306
- // 7.1. All identical values are equivalent, as determined by ===.
307
- if (actual === expected) {
308
- return true;
309
- } else if (isBuffer(actual) && isBuffer(expected)) {
310
- return compare(actual, expected) === 0;
311
-
312
- // 7.2. If the expected value is a Date object, the actual value is
313
- // equivalent if it is also a Date object that refers to the same time.
314
- } else if (util.isDate(actual) && util.isDate(expected)) {
315
- return actual.getTime() === expected.getTime();
316
-
317
- // 7.3 If the expected value is a RegExp object, the actual value is
318
- // equivalent if it is also a RegExp object with the same source and
319
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
320
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
321
- return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase;
322
-
323
- // 7.4. Other pairs that do not both pass typeof value == 'object',
324
- // equivalence is determined by ==.
325
- } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) {
326
- return strict ? actual === expected : actual == expected;
327
-
328
- // If both values are instances of typed arrays, wrap their underlying
329
- // ArrayBuffers in a Buffer each to increase performance
330
- // This optimization requires the arrays to have the same type as checked by
331
- // Object.prototype.toString (aka pToString). Never perform binary
332
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
333
- // bit patterns are not identical.
334
- } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) {
335
- return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0;
336
-
337
- // 7.5 For all other Object pairs, including Array objects, equivalence is
338
- // determined by having the same number of owned properties (as verified
339
- // with Object.prototype.hasOwnProperty.call), the same set of keys
340
- // (although not necessarily the same order), equivalent values for every
341
- // corresponding key, and an identical 'prototype' property. Note: this
342
- // accounts for both named and indexed properties on Arrays.
343
- } else if (isBuffer(actual) !== isBuffer(expected)) {
344
- return false;
345
- } else {
346
- memos = memos || {
347
- actual: [],
348
- expected: []
349
- };
350
- var actualIndex = memos.actual.indexOf(actual);
351
- if (actualIndex !== -1) {
352
- if (actualIndex === memos.expected.indexOf(expected)) {
353
- return true;
354
- }
355
- }
356
- memos.actual.push(actual);
357
- memos.expected.push(expected);
358
- return objEquiv(actual, expected, strict, memos);
359
- }
360
- }
361
- function isArguments(object) {
362
- return Object.prototype.toString.call(object) == '[object Arguments]';
363
- }
364
- function objEquiv(a, b, strict, actualVisitedObjects) {
365
- if (a === null || a === undefined || b === null || b === undefined) return false;
366
- // if one is a primitive, the other must be same
367
- if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b;
368
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
369
- var aIsArgs = isArguments(a);
370
- var bIsArgs = isArguments(b);
371
- if (aIsArgs && !bIsArgs || !aIsArgs && bIsArgs) return false;
372
- if (aIsArgs) {
373
- a = pSlice.call(a);
374
- b = pSlice.call(b);
375
- return _deepEqual(a, b, strict);
376
- }
377
- var ka = objectKeys(a);
378
- var kb = objectKeys(b);
379
- var key, i;
380
- // having the same number of owned properties (keys incorporates
381
- // hasOwnProperty)
382
- if (ka.length !== kb.length) return false;
383
- //the same set of keys (although not necessarily the same order),
384
- ka.sort();
385
- kb.sort();
386
- //~~~cheap key test
387
- for (i = ka.length - 1; i >= 0; i--) {
388
- if (ka[i] !== kb[i]) return false;
389
- }
390
- //equivalent values for every corresponding key, and
391
- //~~~possibly expensive deep test
392
- for (i = ka.length - 1; i >= 0; i--) {
393
- key = ka[i];
394
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false;
395
- }
396
- return true;
397
- }
398
-
399
- // 8. The non-equivalence assertion tests for any deep inequality.
400
- // assert.notDeepEqual(actual, expected, message_opt);
401
-
402
- assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
403
- if (_deepEqual(actual, expected, false)) {
404
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
405
- }
406
- };
407
- assert.notDeepStrictEqual = notDeepStrictEqual;
408
- function notDeepStrictEqual(actual, expected, message) {
409
- if (_deepEqual(actual, expected, true)) {
410
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
411
- }
412
- }
413
-
414
- // 9. The strict equality assertion tests strict equality, as determined by ===.
415
- // assert.strictEqual(actual, expected, message_opt);
416
-
417
- assert.strictEqual = function strictEqual(actual, expected, message) {
418
- if (actual !== expected) {
419
- fail(actual, expected, message, '===', assert.strictEqual);
420
- }
421
- };
422
-
423
- // 10. The strict non-equality assertion tests for strict inequality, as
424
- // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
425
-
426
- assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
427
- if (actual === expected) {
428
- fail(actual, expected, message, '!==', assert.notStrictEqual);
429
- }
430
- };
431
- function expectedException(actual, expected) {
432
- if (!actual || !expected) {
433
- return false;
434
- }
435
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
436
- return expected.test(actual);
437
- }
438
- try {
439
- if (actual instanceof expected) {
440
- return true;
441
- }
442
- } catch (e) {
443
- // Ignore. The instanceof check doesn't work for arrow functions.
444
- }
445
- if (Error.isPrototypeOf(expected)) {
446
- return false;
447
- }
448
- return expected.call({}, actual) === true;
449
- }
450
- function _tryBlock(block) {
451
- var error;
452
- try {
453
- block();
454
- } catch (e) {
455
- error = e;
456
- }
457
- return error;
458
- }
459
- function _throws(shouldThrow, block, expected, message) {
460
- var actual;
461
- if (typeof block !== 'function') {
462
- throw new TypeError('"block" argument must be a function');
463
- }
464
- if (typeof expected === 'string') {
465
- message = expected;
466
- expected = null;
467
- }
468
- actual = _tryBlock(block);
469
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.');
470
- if (shouldThrow && !actual) {
471
- fail(actual, expected, 'Missing expected exception' + message);
472
- }
473
- var userProvidedMessage = typeof message === 'string';
474
- var isUnwantedException = !shouldThrow && util.isError(actual);
475
- var isUnexpectedException = !shouldThrow && actual && !expected;
476
- if (isUnwantedException && userProvidedMessage && expectedException(actual, expected) || isUnexpectedException) {
477
- fail(actual, expected, 'Got unwanted exception' + message);
478
- }
479
- if (shouldThrow && actual && expected && !expectedException(actual, expected) || !shouldThrow && actual) {
480
- throw actual;
481
- }
482
- }
483
-
484
- // 11. Expected to throw an error:
485
- // assert.throws(block, Error_opt, message_opt);
486
-
487
- assert.throws = function (block, /*optional*/error, /*optional*/message) {
488
- _throws(true, block, error, message);
489
- };
490
-
491
- // EXTENSION! This is annoying to write outside this module.
492
- assert.doesNotThrow = function (block, /*optional*/error, /*optional*/message) {
493
- _throws(false, block, error, message);
494
- };
495
- assert.ifError = function (err) {
496
- if (err) throw err;
497
- };
498
-
499
- // Expose a strict only variant of assert
500
- function strict(value, message) {
501
- if (!value) fail(value, true, message, '==', strict);
502
- }
503
- assert.strict = objectAssign(strict, assert, {
504
- equal: assert.strictEqual,
505
- deepEqual: assert.deepStrictEqual,
506
- notEqual: assert.notStrictEqual,
507
- notDeepEqual: assert.notDeepStrictEqual
508
- });
509
- assert.strict.strict = assert.strict;
510
- var objectKeys = Object.keys || function (obj) {
511
- var keys = [];
512
- for (var key in obj) {
513
- if (hasOwn.call(obj, key)) keys.push(key);
514
- }
515
- return keys;
516
- };
517
- }).call(this);
518
- }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
519
- }, {
520
- "object-assign": 23,
521
- "util/": 4
522
- }],
523
- 2: [function (require, module, exports) {
524
- if (typeof Object.create === 'function') {
525
- // implementation from standard node.js 'util' module
526
- module.exports = function inherits(ctor, superCtor) {
527
- ctor.super_ = superCtor;
528
- ctor.prototype = Object.create(superCtor.prototype, {
529
- constructor: {
530
- value: ctor,
531
- enumerable: false,
532
- writable: true,
533
- configurable: true
534
- }
535
- });
536
- };
537
- } else {
538
- // old school shim for old browsers
539
- module.exports = function inherits(ctor, superCtor) {
540
- ctor.super_ = superCtor;
541
- var TempCtor = function TempCtor() {};
542
- TempCtor.prototype = superCtor.prototype;
543
- ctor.prototype = new TempCtor();
544
- ctor.prototype.constructor = ctor;
545
- };
546
- }
547
- }, {}],
548
- 3: [function (require, module, exports) {
549
- module.exports = function isBuffer(arg) {
550
- return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function';
551
- };
552
- }, {}],
553
- 4: [function (require, module, exports) {
554
- (function (process, global) {
555
- (function () {
556
- // Copyright Joyent, Inc. and other Node contributors.
557
- //
558
- // Permission is hereby granted, free of charge, to any person obtaining a
559
- // copy of this software and associated documentation files (the
560
- // "Software"), to deal in the Software without restriction, including
561
- // without limitation the rights to use, copy, modify, merge, publish,
562
- // distribute, sublicense, and/or sell copies of the Software, and to permit
563
- // persons to whom the Software is furnished to do so, subject to the
564
- // following conditions:
565
- //
566
- // The above copyright notice and this permission notice shall be included
567
- // in all copies or substantial portions of the Software.
568
- //
569
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
570
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
571
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
572
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
573
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
574
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
575
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
576
-
577
- var formatRegExp = /%[sdj%]/g;
578
- exports.format = function (f) {
579
- if (!isString(f)) {
580
- var objects = [];
581
- for (var i = 0; i < arguments.length; i++) {
582
- objects.push(inspect(arguments[i]));
583
- }
584
- return objects.join(' ');
585
- }
586
- var i = 1;
587
- var args = arguments;
588
- var len = args.length;
589
- var str = String(f).replace(formatRegExp, function (x) {
590
- if (x === '%%') return '%';
591
- if (i >= len) return x;
592
- switch (x) {
593
- case '%s':
594
- return String(args[i++]);
595
- case '%d':
596
- return Number(args[i++]);
597
- case '%j':
598
- try {
599
- return JSON.stringify(args[i++]);
600
- } catch (_) {
601
- return '[Circular]';
602
- }
603
- default:
604
- return x;
605
- }
606
- });
607
- for (var x = args[i]; i < len; x = args[++i]) {
608
- if (isNull(x) || !isObject(x)) {
609
- str += ' ' + x;
610
- } else {
611
- str += ' ' + inspect(x);
612
- }
613
- }
614
- return str;
615
- };
616
-
617
- // Mark that a method should not be used.
618
- // Returns a modified function which warns once by default.
619
- // If --no-deprecation is set, then it is a no-op.
620
- exports.deprecate = function (fn, msg) {
621
- // Allow for deprecating things in the process of starting up.
622
- if (isUndefined(global.process)) {
623
- return function () {
624
- return exports.deprecate(fn, msg).apply(this, arguments);
625
- };
626
- }
627
- if (process.noDeprecation === true) {
628
- return fn;
629
- }
630
- var warned = false;
631
- function deprecated() {
632
- if (!warned) {
633
- if (process.throwDeprecation) {
634
- throw new Error(msg);
635
- } else if (process.traceDeprecation) {
636
- console.trace(msg);
637
- } else {
638
- console.error(msg);
639
- }
640
- warned = true;
641
- }
642
- return fn.apply(this, arguments);
643
- }
644
- return deprecated;
645
- };
646
- var debugs = {};
647
- var debugEnviron;
648
- exports.debuglog = function (set) {
649
- if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || '';
650
- set = set.toUpperCase();
651
- if (!debugs[set]) {
652
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
653
- var pid = process.pid;
654
- debugs[set] = function () {
655
- var msg = exports.format.apply(exports, arguments);
656
- console.error('%s %d: %s', set, pid, msg);
657
- };
658
- } else {
659
- debugs[set] = function () {};
660
- }
661
- }
662
- return debugs[set];
663
- };
664
-
665
- /**
666
- * Echos the value of a value. Trys to print the value out
667
- * in the best way possible given the different types.
668
- *
669
- * @param {Object} obj The object to print out.
670
- * @param {Object} opts Optional options object that alters the output.
671
- */
672
- /* legacy: obj, showHidden, depth, colors*/
673
- function inspect(obj, opts) {
674
- // default options
675
- var ctx = {
676
- seen: [],
677
- stylize: stylizeNoColor
678
- };
679
- // legacy...
680
- if (arguments.length >= 3) ctx.depth = arguments[2];
681
- if (arguments.length >= 4) ctx.colors = arguments[3];
682
- if (isBoolean(opts)) {
683
- // legacy...
684
- ctx.showHidden = opts;
685
- } else if (opts) {
686
- // got an "options" object
687
- exports._extend(ctx, opts);
688
- }
689
- // set default options
690
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
691
- if (isUndefined(ctx.depth)) ctx.depth = 2;
692
- if (isUndefined(ctx.colors)) ctx.colors = false;
693
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
694
- if (ctx.colors) ctx.stylize = stylizeWithColor;
695
- return formatValue(ctx, obj, ctx.depth);
696
- }
697
- exports.inspect = inspect;
698
-
699
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
700
- inspect.colors = {
701
- 'bold': [1, 22],
702
- 'italic': [3, 23],
703
- 'underline': [4, 24],
704
- 'inverse': [7, 27],
705
- 'white': [37, 39],
706
- 'grey': [90, 39],
707
- 'black': [30, 39],
708
- 'blue': [34, 39],
709
- 'cyan': [36, 39],
710
- 'green': [32, 39],
711
- 'magenta': [35, 39],
712
- 'red': [31, 39],
713
- 'yellow': [33, 39]
714
- };
715
-
716
- // Don't use 'blue' not visible on cmd.exe
717
- inspect.styles = {
718
- 'special': 'cyan',
719
- 'number': 'yellow',
720
- 'boolean': 'yellow',
721
- 'undefined': 'grey',
722
- 'null': 'bold',
723
- 'string': 'green',
724
- 'date': 'magenta',
725
- // "name": intentionally not styling
726
- 'regexp': 'red'
727
- };
728
- function stylizeWithColor(str, styleType) {
729
- var style = inspect.styles[styleType];
730
- if (style) {
731
- return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm';
732
- } else {
733
- return str;
734
- }
735
- }
736
- function stylizeNoColor(str, styleType) {
737
- return str;
738
- }
739
- function arrayToHash(array) {
740
- var hash = {};
741
- array.forEach(function (val, idx) {
742
- hash[val] = true;
743
- });
744
- return hash;
745
- }
746
- function formatValue(ctx, value, recurseTimes) {
747
- // Provide a hook for user-specified inspect functions.
748
- // Check that value is an object with an inspect function on it
749
- if (ctx.customInspect && value && isFunction(value.inspect) &&
750
- // Filter out the util module, it's inspect function is special
751
- value.inspect !== exports.inspect &&
752
- // Also filter out any prototype objects using the circular check.
753
- !(value.constructor && value.constructor.prototype === value)) {
754
- var ret = value.inspect(recurseTimes, ctx);
755
- if (!isString(ret)) {
756
- ret = formatValue(ctx, ret, recurseTimes);
757
- }
758
- return ret;
759
- }
760
-
761
- // Primitive types cannot have properties
762
- var primitive = formatPrimitive(ctx, value);
763
- if (primitive) {
764
- return primitive;
765
- }
766
-
767
- // Look up the keys of the object.
768
- var keys = Object.keys(value);
769
- var visibleKeys = arrayToHash(keys);
770
- if (ctx.showHidden) {
771
- keys = Object.getOwnPropertyNames(value);
772
- }
773
-
774
- // IE doesn't make error fields non-enumerable
775
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
776
- if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
777
- return formatError(value);
778
- }
779
-
780
- // Some type of object without properties can be shortcutted.
781
- if (keys.length === 0) {
782
- if (isFunction(value)) {
783
- var name = value.name ? ': ' + value.name : '';
784
- return ctx.stylize('[Function' + name + ']', 'special');
785
- }
786
- if (isRegExp(value)) {
787
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
788
- }
789
- if (isDate(value)) {
790
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
791
- }
792
- if (isError(value)) {
793
- return formatError(value);
794
- }
795
- }
796
- var base = '',
797
- array = false,
798
- braces = ['{', '}'];
799
-
800
- // Make Array say that they are Array
801
- if (isArray(value)) {
802
- array = true;
803
- braces = ['[', ']'];
804
- }
805
-
806
- // Make functions say that they are functions
807
- if (isFunction(value)) {
808
- var n = value.name ? ': ' + value.name : '';
809
- base = ' [Function' + n + ']';
810
- }
811
-
812
- // Make RegExps say that they are RegExps
813
- if (isRegExp(value)) {
814
- base = ' ' + RegExp.prototype.toString.call(value);
815
- }
816
-
817
- // Make dates with properties first say the date
818
- if (isDate(value)) {
819
- base = ' ' + Date.prototype.toUTCString.call(value);
820
- }
821
-
822
- // Make error with message first say the error
823
- if (isError(value)) {
824
- base = ' ' + formatError(value);
825
- }
826
- if (keys.length === 0 && (!array || value.length == 0)) {
827
- return braces[0] + base + braces[1];
828
- }
829
- if (recurseTimes < 0) {
830
- if (isRegExp(value)) {
831
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
832
- } else {
833
- return ctx.stylize('[Object]', 'special');
834
- }
835
- }
836
- ctx.seen.push(value);
837
- var output;
838
- if (array) {
839
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
840
- } else {
841
- output = keys.map(function (key) {
842
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
843
- });
844
- }
845
- ctx.seen.pop();
846
- return reduceToSingleString(output, base, braces);
847
- }
848
- function formatPrimitive(ctx, value) {
849
- if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
850
- if (isString(value)) {
851
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
852
- return ctx.stylize(simple, 'string');
853
- }
854
- if (isNumber(value)) return ctx.stylize('' + value, 'number');
855
- if (isBoolean(value)) return ctx.stylize('' + value, 'boolean');
856
- // For some reason typeof null is "object", so special case here.
857
- if (isNull(value)) return ctx.stylize('null', 'null');
858
- }
859
- function formatError(value) {
860
- return '[' + Error.prototype.toString.call(value) + ']';
861
- }
862
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
863
- var output = [];
864
- for (var i = 0, l = value.length; i < l; ++i) {
865
- if (hasOwnProperty(value, String(i))) {
866
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
867
- } else {
868
- output.push('');
869
- }
870
- }
871
- keys.forEach(function (key) {
872
- if (!key.match(/^\d+$/)) {
873
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
874
- }
875
- });
876
- return output;
877
- }
878
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
879
- var name, str, desc;
880
- desc = Object.getOwnPropertyDescriptor(value, key) || {
881
- value: value[key]
882
- };
883
- if (desc.get) {
884
- if (desc.set) {
885
- str = ctx.stylize('[Getter/Setter]', 'special');
886
- } else {
887
- str = ctx.stylize('[Getter]', 'special');
888
- }
889
- } else {
890
- if (desc.set) {
891
- str = ctx.stylize('[Setter]', 'special');
892
- }
893
- }
894
- if (!hasOwnProperty(visibleKeys, key)) {
895
- name = '[' + key + ']';
896
- }
897
- if (!str) {
898
- if (ctx.seen.indexOf(desc.value) < 0) {
899
- if (isNull(recurseTimes)) {
900
- str = formatValue(ctx, desc.value, null);
901
- } else {
902
- str = formatValue(ctx, desc.value, recurseTimes - 1);
903
- }
904
- if (str.indexOf('\n') > -1) {
905
- if (array) {
906
- str = str.split('\n').map(function (line) {
907
- return ' ' + line;
908
- }).join('\n').substr(2);
909
- } else {
910
- str = '\n' + str.split('\n').map(function (line) {
911
- return ' ' + line;
912
- }).join('\n');
913
- }
914
- }
915
- } else {
916
- str = ctx.stylize('[Circular]', 'special');
917
- }
918
- }
919
- if (isUndefined(name)) {
920
- if (array && key.match(/^\d+$/)) {
921
- return str;
922
- }
923
- name = JSON.stringify('' + key);
924
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
925
- name = name.substr(1, name.length - 2);
926
- name = ctx.stylize(name, 'name');
927
- } else {
928
- name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
929
- name = ctx.stylize(name, 'string');
930
- }
931
- }
932
- return name + ': ' + str;
933
- }
934
- function reduceToSingleString(output, base, braces) {
935
- var numLinesEst = 0;
936
- var length = output.reduce(function (prev, cur) {
937
- numLinesEst++;
938
- if (cur.indexOf('\n') >= 0) numLinesEst++;
939
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
940
- }, 0);
941
- if (length > 60) {
942
- return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
943
- }
944
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
945
- }
946
-
947
- // NOTE: These type checking functions intentionally don't use `instanceof`
948
- // because it is fragile and can be easily faked with `Object.create()`.
949
- function isArray(ar) {
950
- return Array.isArray(ar);
951
- }
952
- exports.isArray = isArray;
953
- function isBoolean(arg) {
954
- return typeof arg === 'boolean';
955
- }
956
- exports.isBoolean = isBoolean;
957
- function isNull(arg) {
958
- return arg === null;
959
- }
960
- exports.isNull = isNull;
961
- function isNullOrUndefined(arg) {
962
- return arg == null;
963
- }
964
- exports.isNullOrUndefined = isNullOrUndefined;
965
- function isNumber(arg) {
966
- return typeof arg === 'number';
967
- }
968
- exports.isNumber = isNumber;
969
- function isString(arg) {
970
- return typeof arg === 'string';
971
- }
972
- exports.isString = isString;
973
- function isSymbol(arg) {
974
- return typeof arg === 'symbol';
975
- }
976
- exports.isSymbol = isSymbol;
977
- function isUndefined(arg) {
978
- return arg === void 0;
979
- }
980
- exports.isUndefined = isUndefined;
981
- function isRegExp(re) {
982
- return isObject(re) && objectToString(re) === '[object RegExp]';
983
- }
984
- exports.isRegExp = isRegExp;
985
- function isObject(arg) {
986
- return typeof arg === 'object' && arg !== null;
987
- }
988
- exports.isObject = isObject;
989
- function isDate(d) {
990
- return isObject(d) && objectToString(d) === '[object Date]';
991
- }
992
- exports.isDate = isDate;
993
- function isError(e) {
994
- return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
995
- }
996
- exports.isError = isError;
997
- function isFunction(arg) {
998
- return typeof arg === 'function';
999
- }
1000
- exports.isFunction = isFunction;
1001
- function isPrimitive(arg) {
1002
- return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' ||
1003
- // ES6 symbol
1004
- typeof arg === 'undefined';
1005
- }
1006
- exports.isPrimitive = isPrimitive;
1007
- exports.isBuffer = require('./support/isBuffer');
1008
- function objectToString(o) {
1009
- return Object.prototype.toString.call(o);
1010
- }
1011
- function pad(n) {
1012
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
1013
- }
1014
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1015
-
1016
- // 26 Feb 16:19:34
1017
- function timestamp() {
1018
- var d = new Date();
1019
- var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
1020
- return [d.getDate(), months[d.getMonth()], time].join(' ');
1021
- }
1022
-
1023
- // log is just a thin wrapper to console.log that prepends a timestamp
1024
- exports.log = function () {
1025
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
1026
- };
1027
-
1028
- /**
1029
- * Inherit the prototype methods from one constructor into another.
1030
- *
1031
- * The Function.prototype.inherits from lang.js rewritten as a standalone
1032
- * function (not on Function.prototype). NOTE: If this file is to be loaded
1033
- * during bootstrapping this function needs to be rewritten using some native
1034
- * functions as prototype setup using normal JavaScript does not work as
1035
- * expected during bootstrapping (see mirror.js in r114903).
1036
- *
1037
- * @param {function} ctor Constructor function which needs to inherit the
1038
- * prototype.
1039
- * @param {function} superCtor Constructor function to inherit prototype from.
1040
- */
1041
- exports.inherits = require('inherits');
1042
- exports._extend = function (origin, add) {
1043
- // Don't do anything if add isn't an object
1044
- if (!add || !isObject(add)) return origin;
1045
- var keys = Object.keys(add);
1046
- var i = keys.length;
1047
- while (i--) {
1048
- origin[keys[i]] = add[keys[i]];
1049
- }
1050
- return origin;
1051
- };
1052
- function hasOwnProperty(obj, prop) {
1053
- return Object.prototype.hasOwnProperty.call(obj, prop);
1054
- }
1055
- }).call(this);
1056
- }).call(this, require('_process'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
1057
- }, {
1058
- "./support/isBuffer": 3,
1059
- "_process": 24,
1060
- "inherits": 2
1061
- }],
1062
- 5: [function (require, module, exports) {
1063
- /**
1064
- * Fable Core Pre-initialization Service Base
1065
- *
1066
- * For a couple services, we need to be able to instantiate them before the Fable object is fully initialized.
1067
- * This is a base class for those services.
1068
- *
1069
- * @author <steven@velozo.com>
1070
- */
1071
-
1072
- class FableCoreServiceProviderBase {
1073
- constructor(pOptions, pServiceHash) {
1074
- this.fable = false;
1075
- this.options = typeof pOptions === 'object' ? pOptions : {};
1076
- this.serviceType = 'Unknown';
1077
-
1078
- // The hash will be a non-standard UUID ... the UUID service uses this base class!
1079
- this.UUID = "CORESVC-".concat(Math.floor(Math.random() * (99999 - 10000) + 10000));
1080
- this.Hash = typeof pServiceHash === 'string' ? pServiceHash : "".concat(this.UUID);
1081
- }
1082
- // After fable is initialized, it would be expected to be wired in as a normal service.
1083
- connectFable(pFable) {
1084
- this.fable = pFable;
1085
- return true;
1086
- }
1087
- }
1088
- _defineProperty(FableCoreServiceProviderBase, "isFableService", true);
1089
- module.exports = FableCoreServiceProviderBase;
1090
- }, {}],
1091
- 6: [function (require, module, exports) {
1092
- /**
1093
- * Fable Service Base
1094
- * @author <steven@velozo.com>
1095
- */
1096
-
1097
- class FableServiceProviderBase {
1098
- constructor(pFable, pOptions, pServiceHash) {
1099
- this.fable = pFable;
1100
- this.options = typeof pOptions === 'object' ? pOptions : typeof pFable === 'object' && !pFable.isFable ? pFable : {};
1101
- this.serviceType = 'Unknown';
1102
- if (typeof pFable.getUUID == 'function') {
1103
- this.UUID = pFable.getUUID();
1104
- } else {
1105
- this.UUID = "NoFABLESVC-".concat(Math.floor(Math.random() * (99999 - 10000) + 10000));
1106
- }
1107
- this.Hash = typeof pServiceHash === 'string' ? pServiceHash : "".concat(this.UUID);
1108
-
1109
- // Pull back a few things
1110
- this.log = this.fable.log;
1111
- this.servicesMap = this.fable.servicesMap;
1112
- this.services = this.fable.services;
1113
- }
1114
- }
1115
- _defineProperty(FableServiceProviderBase, "isFableService", true);
1116
- module.exports = FableServiceProviderBase;
1117
- module.exports.CoreServiceProviderBase = require('./Fable-ServiceProviderBase-Preinit.js');
1118
- }, {
1119
- "./Fable-ServiceProviderBase-Preinit.js": 5
1120
- }],
1121
- 7: [function (require, module, exports) {
1122
- 'use strict';
1123
-
1124
- var UTF8_ACCEPT = 12;
1125
- var UTF8_REJECT = 0;
1126
- var UTF8_DATA = [
1127
- // The first part of the table maps bytes to character to a transition.
1128
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 7, 10, 9, 9, 9, 11, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
1129
- // The second part of the table maps a state to a new state when adding a
1130
- // transition.
1131
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 24, 36, 48, 60, 72, 84, 96, 0, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1132
- // The third part maps the current transition to a mask that needs to apply
1133
- // to the byte.
1134
- 0x7F, 0x3F, 0x3F, 0x3F, 0x00, 0x1F, 0x0F, 0x0F, 0x0F, 0x07, 0x07, 0x07];
1135
- function decodeURIComponent(uri) {
1136
- var percentPosition = uri.indexOf('%');
1137
- if (percentPosition === -1) return uri;
1138
- var length = uri.length;
1139
- var decoded = '';
1140
- var last = 0;
1141
- var codepoint = 0;
1142
- var startOfOctets = percentPosition;
1143
- var state = UTF8_ACCEPT;
1144
- while (percentPosition > -1 && percentPosition < length) {
1145
- var high = hexCodeToInt(uri[percentPosition + 1], 4);
1146
- var low = hexCodeToInt(uri[percentPosition + 2], 0);
1147
- var byte = high | low;
1148
- var type = UTF8_DATA[byte];
1149
- state = UTF8_DATA[256 + state + type];
1150
- codepoint = codepoint << 6 | byte & UTF8_DATA[364 + type];
1151
- if (state === UTF8_ACCEPT) {
1152
- decoded += uri.slice(last, startOfOctets);
1153
- decoded += codepoint <= 0xFFFF ? String.fromCharCode(codepoint) : String.fromCharCode(0xD7C0 + (codepoint >> 10), 0xDC00 + (codepoint & 0x3FF));
1154
- codepoint = 0;
1155
- last = percentPosition + 3;
1156
- percentPosition = startOfOctets = uri.indexOf('%', last);
1157
- } else if (state === UTF8_REJECT) {
1158
- return null;
1159
- } else {
1160
- percentPosition += 3;
1161
- if (percentPosition < length && uri.charCodeAt(percentPosition) === 37) continue;
1162
- return null;
1163
- }
1164
- }
1165
- return decoded + uri.slice(last);
1166
- }
1167
- var HEX = {
1168
- '0': 0,
1169
- '1': 1,
1170
- '2': 2,
1171
- '3': 3,
1172
- '4': 4,
1173
- '5': 5,
1174
- '6': 6,
1175
- '7': 7,
1176
- '8': 8,
1177
- '9': 9,
1178
- 'a': 10,
1179
- 'A': 10,
1180
- 'b': 11,
1181
- 'B': 11,
1182
- 'c': 12,
1183
- 'C': 12,
1184
- 'd': 13,
1185
- 'D': 13,
1186
- 'e': 14,
1187
- 'E': 14,
1188
- 'f': 15,
1189
- 'F': 15
1190
- };
1191
- function hexCodeToInt(c, shift) {
1192
- var i = HEX[c];
1193
- return i === undefined ? 255 : i << shift;
1194
- }
1195
- module.exports = decodeURIComponent;
1196
- }, {}],
1197
- 8: [function (require, module, exports) {
1198
- 'use strict';
1199
-
1200
- // do not edit .js files directly - edit src/index.jst
1201
- module.exports = function equal(a, b) {
1202
- if (a === b) return true;
1203
- if (a && b && typeof a == 'object' && typeof b == 'object') {
1204
- if (a.constructor !== b.constructor) return false;
1205
- var length, i, keys;
1206
- if (Array.isArray(a)) {
1207
- length = a.length;
1208
- if (length != b.length) return false;
1209
- for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
1210
- return true;
1211
- }
1212
- if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
1213
- if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
1214
- if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
1215
- keys = Object.keys(a);
1216
- length = keys.length;
1217
- if (length !== Object.keys(b).length) return false;
1218
- for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
1219
- for (i = length; i-- !== 0;) {
1220
- var key = keys[i];
1221
- if (!equal(a[key], b[key])) return false;
1222
- }
1223
- return true;
1224
- }
1225
-
1226
- // true if both NaN, false otherwise
1227
- return a !== a && b !== b;
1228
- };
1229
- }, {}],
1230
- 9: [function (require, module, exports) {
1231
- "use strict";
1232
-
1233
- const parse = require("./parse");
1234
- const stringify = require("./stringify");
1235
- const fastQuerystring = {
1236
- parse,
1237
- stringify
1238
- };
1239
-
1240
- /**
1241
- * Enable TS and JS support
1242
- *
1243
- * - `const qs = require('fast-querystring')`
1244
- * - `import qs from 'fast-querystring'`
1245
- */
1246
- module.exports = fastQuerystring;
1247
- module.exports.default = fastQuerystring;
1248
- module.exports.parse = parse;
1249
- module.exports.stringify = stringify;
1250
- }, {
1251
- "./parse": 11,
1252
- "./stringify": 12
1253
- }],
1254
- 10: [function (require, module, exports) {
1255
- // This file is taken from Node.js project.
1256
- // Full implementation can be found from https://github.com/nodejs/node/blob/main/lib/internal/querystring.js
1257
-
1258
- const hexTable = Array.from({
1259
- length: 256
1260
- }, (_, i) => "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
1261
-
1262
- // These characters do not need escaping when generating query strings:
1263
- // ! - . _ ~
1264
- // ' ( ) *
1265
- // digits
1266
- // alpha (uppercase)
1267
- // alpha (lowercase)
1268
- // rome-ignore format: the array should not be formatted
1269
- const noEscape = new Int8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1270
- // 0 - 15
1271
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1272
- // 16 - 31
1273
- 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,
1274
- // 32 - 47
1275
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
1276
- // 48 - 63
1277
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1278
- // 64 - 79
1279
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
1280
- // 80 - 95
1281
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1282
- // 96 - 111
1283
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 // 112 - 127
1284
- ]);
1285
-
1286
- /**
1287
- * @param {string} str
1288
- * @returns {string}
1289
- */
1290
- function encodeString(str) {
1291
- const len = str.length;
1292
- if (len === 0) return "";
1293
- let out = "";
1294
- let lastPos = 0;
1295
- let i = 0;
1296
- outer: for (; i < len; i++) {
1297
- let c = str.charCodeAt(i);
1298
-
1299
- // ASCII
1300
- while (c < 0x80) {
1301
- if (noEscape[c] !== 1) {
1302
- if (lastPos < i) out += str.slice(lastPos, i);
1303
- lastPos = i + 1;
1304
- out += hexTable[c];
1305
- }
1306
- if (++i === len) break outer;
1307
- c = str.charCodeAt(i);
1308
- }
1309
- if (lastPos < i) out += str.slice(lastPos, i);
1310
-
1311
- // Multi-byte characters ...
1312
- if (c < 0x800) {
1313
- lastPos = i + 1;
1314
- out += hexTable[0xc0 | c >> 6] + hexTable[0x80 | c & 0x3f];
1315
- continue;
1316
- }
1317
- if (c < 0xd800 || c >= 0xe000) {
1318
- lastPos = i + 1;
1319
- out += hexTable[0xe0 | c >> 12] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];
1320
- continue;
1321
- }
1322
- // Surrogate pair
1323
- ++i;
1324
-
1325
- // This branch should never happen because all URLSearchParams entries
1326
- // should already be converted to USVString. But, included for
1327
- // completion's sake anyway.
1328
- if (i >= len) {
1329
- throw new Error("URI malformed");
1330
- }
1331
- const c2 = str.charCodeAt(i) & 0x3ff;
1332
- lastPos = i + 1;
1333
- c = 0x10000 + ((c & 0x3ff) << 10 | c2);
1334
- out += hexTable[0xf0 | c >> 18] + hexTable[0x80 | c >> 12 & 0x3f] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];
1335
- }
1336
- if (lastPos === 0) return str;
1337
- if (lastPos < len) return out + str.slice(lastPos);
1338
- return out;
1339
- }
1340
- module.exports = {
1341
- encodeString
1342
- };
1343
- }, {}],
1344
- 11: [function (require, module, exports) {
1345
- "use strict";
1346
-
1347
- const fastDecode = require("fast-decode-uri-component");
1348
- const plusRegex = /\+/g;
1349
- const Empty = function Empty() {};
1350
- Empty.prototype = Object.create(null);
1351
-
1352
- /**
1353
- * @callback parse
1354
- * @param {string} input
1355
- */
1356
- function parse(input) {
1357
- // Optimization: Use new Empty() instead of Object.create(null) for performance
1358
- // v8 has a better optimization for initializing functions compared to Object
1359
- const result = new Empty();
1360
- if (typeof input !== "string") {
1361
- return result;
1362
- }
1363
- let inputLength = input.length;
1364
- let key = "";
1365
- let value = "";
1366
- let startingIndex = -1;
1367
- let equalityIndex = -1;
1368
- let shouldDecodeKey = false;
1369
- let shouldDecodeValue = false;
1370
- let keyHasPlus = false;
1371
- let valueHasPlus = false;
1372
- let hasBothKeyValuePair = false;
1373
- let c = 0;
1374
-
1375
- // Have a boundary of input.length + 1 to access last pair inside the loop.
1376
- for (let i = 0; i < inputLength + 1; i++) {
1377
- c = i !== inputLength ? input.charCodeAt(i) : 38;
1378
-
1379
- // Handle '&' and end of line to pass the current values to result
1380
- if (c === 38) {
1381
- hasBothKeyValuePair = equalityIndex > startingIndex;
1382
-
1383
- // Optimization: Reuse equality index to store the end of key
1384
- if (!hasBothKeyValuePair) {
1385
- equalityIndex = i;
1386
- }
1387
- key = input.slice(startingIndex + 1, equalityIndex);
1388
-
1389
- // Add key/value pair only if the range size is greater than 1; a.k.a. contains at least "="
1390
- if (hasBothKeyValuePair || key.length > 0) {
1391
- // Optimization: Replace '+' with space
1392
- if (keyHasPlus) {
1393
- key = key.replace(plusRegex, " ");
1394
- }
1395
-
1396
- // Optimization: Do not decode if it's not necessary.
1397
- if (shouldDecodeKey) {
1398
- key = fastDecode(key) || key;
1399
- }
1400
- if (hasBothKeyValuePair) {
1401
- value = input.slice(equalityIndex + 1, i);
1402
- if (valueHasPlus) {
1403
- value = value.replace(plusRegex, " ");
1404
- }
1405
- if (shouldDecodeValue) {
1406
- value = fastDecode(value) || value;
1407
- }
1408
- }
1409
- const currentValue = result[key];
1410
- if (currentValue === undefined) {
1411
- result[key] = value;
1412
- } else {
1413
- // Optimization: value.pop is faster than Array.isArray(value)
1414
- if (currentValue.pop) {
1415
- currentValue.push(value);
1416
- } else {
1417
- result[key] = [currentValue, value];
1418
- }
1419
- }
1420
- }
1421
-
1422
- // Reset reading key value pairs
1423
- value = "";
1424
- startingIndex = i;
1425
- equalityIndex = i;
1426
- shouldDecodeKey = false;
1427
- shouldDecodeValue = false;
1428
- keyHasPlus = false;
1429
- valueHasPlus = false;
1430
- }
1431
- // Check '='
1432
- else if (c === 61) {
1433
- if (equalityIndex <= startingIndex) {
1434
- equalityIndex = i;
1435
- }
1436
- // If '=' character occurs again, we should decode the input.
1437
- else {
1438
- shouldDecodeValue = true;
1439
- }
1440
- }
1441
- // Check '+', and remember to replace it with empty space.
1442
- else if (c === 43) {
1443
- if (equalityIndex > startingIndex) {
1444
- valueHasPlus = true;
1445
- } else {
1446
- keyHasPlus = true;
1447
- }
1448
- }
1449
- // Check '%' character for encoding
1450
- else if (c === 37) {
1451
- if (equalityIndex > startingIndex) {
1452
- shouldDecodeValue = true;
1453
- } else {
1454
- shouldDecodeKey = true;
1455
- }
1456
- }
1457
- }
1458
- return result;
1459
- }
1460
- module.exports = parse;
1461
- }, {
1462
- "fast-decode-uri-component": 7
1463
- }],
1464
- 12: [function (require, module, exports) {
1465
- "use strict";
1466
-
1467
- const {
1468
- encodeString
1469
- } = require("./internals/querystring");
1470
- function getAsPrimitive(value) {
1471
- const type = typeof value;
1472
- if (type === "string") {
1473
- // Length check is handled inside encodeString function
1474
- return encodeString(value);
1475
- } else if (type === "bigint") {
1476
- return value.toString();
1477
- } else if (type === "boolean") {
1478
- return value ? "true" : "false";
1479
- } else if (type === "number" && Number.isFinite(value)) {
1480
- return value < 1e21 ? "" + value : encodeString("" + value);
1481
- }
1482
- return "";
1483
- }
1484
-
1485
- /**
1486
- * @param {Record<string, string | number | boolean
1487
- * | ReadonlyArray<string | number | boolean> | null>} input
1488
- * @returns {string}
1489
- */
1490
- function stringify(input) {
1491
- let result = "";
1492
- if (input === null || typeof input !== "object") {
1493
- return result;
1494
- }
1495
- const separator = "&";
1496
- const keys = Object.keys(input);
1497
- const keyLength = keys.length;
1498
- let valueLength = 0;
1499
- for (let i = 0; i < keyLength; i++) {
1500
- const key = keys[i];
1501
- const value = input[key];
1502
- const encodedKey = encodeString(key) + "=";
1503
- if (i) {
1504
- result += separator;
1505
- }
1506
- if (Array.isArray(value)) {
1507
- valueLength = value.length;
1508
- for (let j = 0; j < valueLength; j++) {
1509
- if (j) {
1510
- result += separator;
1511
- }
1512
-
1513
- // Optimization: Dividing into multiple lines improves the performance.
1514
- // Since v8 does not need to care about the '+' character if it was one-liner.
1515
- result += encodedKey;
1516
- result += getAsPrimitive(value[j]);
1517
- }
1518
- } else {
1519
- result += encodedKey;
1520
- result += getAsPrimitive(value);
1521
- }
1522
- }
1523
- return result;
1524
- }
1525
- module.exports = stringify;
1526
- }, {
1527
- "./internals/querystring": 10
1528
- }],
1529
- 13: [function (require, module, exports) {
1530
- 'use strict';
1531
-
1532
- /*
1533
- Char codes:
1534
- '!': 33 - !
1535
- '#': 35 - %23
1536
- '$': 36 - %24
1537
- '%': 37 - %25
1538
- '&': 38 - %26
1539
- ''': 39 - '
1540
- '(': 40 - (
1541
- ')': 41 - )
1542
- '*': 42 - *
1543
- '+': 43 - %2B
1544
- ',': 44 - %2C
1545
- '-': 45 - -
1546
- '.': 46 - .
1547
- '/': 47 - %2F
1548
- ':': 58 - %3A
1549
- ';': 59 - %3B
1550
- '=': 61 - %3D
1551
- '?': 63 - %3F
1552
- '@': 64 - %40
1553
- '_': 95 - _
1554
- '~': 126 - ~
1555
- */
1556
- const assert = require('assert');
1557
- const querystring = require('fast-querystring');
1558
- const isRegexSafe = require('safe-regex2');
1559
- const deepEqual = require('fast-deep-equal');
1560
- const {
1561
- prettyPrintTree
1562
- } = require('./lib/pretty-print');
1563
- const {
1564
- StaticNode,
1565
- NODE_TYPES
1566
- } = require('./lib/node');
1567
- const Constrainer = require('./lib/constrainer');
1568
- const httpMethods = require('./lib/http-methods');
1569
- const httpMethodStrategy = require('./lib/strategies/http-method');
1570
- const {
1571
- safeDecodeURI,
1572
- safeDecodeURIComponent
1573
- } = require('./lib/url-sanitizer');
1574
- const FULL_PATH_REGEXP = /^https?:\/\/.*?\//;
1575
- const OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/;
1576
- if (!isRegexSafe(FULL_PATH_REGEXP)) {
1577
- throw new Error('the FULL_PATH_REGEXP is not safe, update this module');
1578
- }
1579
- if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) {
1580
- throw new Error('the OPTIONAL_PARAM_REGEXP is not safe, update this module');
1581
- }
1582
- function Router(opts) {
1583
- if (!(this instanceof Router)) {
1584
- return new Router(opts);
1585
- }
1586
- opts = opts || {};
1587
- this._opts = opts;
1588
- if (opts.defaultRoute) {
1589
- assert(typeof opts.defaultRoute === 'function', 'The default route must be a function');
1590
- this.defaultRoute = opts.defaultRoute;
1591
- } else {
1592
- this.defaultRoute = null;
1593
- }
1594
- if (opts.onBadUrl) {
1595
- assert(typeof opts.onBadUrl === 'function', 'The bad url handler must be a function');
1596
- this.onBadUrl = opts.onBadUrl;
1597
- } else {
1598
- this.onBadUrl = null;
1599
- }
1600
- if (opts.buildPrettyMeta) {
1601
- assert(typeof opts.buildPrettyMeta === 'function', 'buildPrettyMeta must be a function');
1602
- this.buildPrettyMeta = opts.buildPrettyMeta;
1603
- } else {
1604
- this.buildPrettyMeta = defaultBuildPrettyMeta;
1605
- }
1606
- if (opts.querystringParser) {
1607
- assert(typeof opts.querystringParser === 'function', 'querystringParser must be a function');
1608
- this.querystringParser = opts.querystringParser;
1609
- } else {
1610
- this.querystringParser = query => query === '' ? {} : querystring.parse(query);
1611
- }
1612
- this.caseSensitive = opts.caseSensitive === undefined ? true : opts.caseSensitive;
1613
- this.ignoreTrailingSlash = opts.ignoreTrailingSlash || false;
1614
- this.ignoreDuplicateSlashes = opts.ignoreDuplicateSlashes || false;
1615
- this.maxParamLength = opts.maxParamLength || 100;
1616
- this.allowUnsafeRegex = opts.allowUnsafeRegex || false;
1617
- this.constrainer = new Constrainer(opts.constraints);
1618
- this.routes = [];
1619
- this.trees = {};
1620
- }
1621
- Router.prototype.on = function on(method, path, opts, handler, store) {
1622
- if (typeof opts === 'function') {
1623
- if (handler !== undefined) {
1624
- store = handler;
1625
- }
1626
- handler = opts;
1627
- opts = {};
1628
- }
1629
- // path validation
1630
- assert(typeof path === 'string', 'Path should be a string');
1631
- assert(path.length > 0, 'The path could not be empty');
1632
- assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`');
1633
- // handler validation
1634
- assert(typeof handler === 'function', 'Handler should be a function');
1635
-
1636
- // path ends with optional parameter
1637
- const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP);
1638
- if (optionalParamMatch) {
1639
- assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path');
1640
- const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2');
1641
- const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2');
1642
- this.on(method, pathFull, opts, handler, store);
1643
- this.on(method, pathOptional, opts, handler, store);
1644
- return;
1645
- }
1646
- const route = path;
1647
- if (this.ignoreDuplicateSlashes) {
1648
- path = removeDuplicateSlashes(path);
1649
- }
1650
- if (this.ignoreTrailingSlash) {
1651
- path = trimLastSlash(path);
1652
- }
1653
- const methods = Array.isArray(method) ? method : [method];
1654
- for (const method of methods) {
1655
- assert(typeof method === 'string', 'Method should be a string');
1656
- assert(httpMethods.includes(method), "Method '".concat(method, "' is not an http method."));
1657
- this._on(method, path, opts, handler, store, route);
1658
- }
1659
- };
1660
- Router.prototype._on = function _on(method, path, opts, handler, store) {
1661
- let constraints = {};
1662
- if (opts.constraints !== undefined) {
1663
- assert(typeof opts.constraints === 'object' && opts.constraints !== null, 'Constraints should be an object');
1664
- if (Object.keys(opts.constraints).length !== 0) {
1665
- constraints = opts.constraints;
1666
- }
1667
- }
1668
- this.constrainer.validateConstraints(constraints);
1669
- // Let the constrainer know if any constraints are being used now
1670
- this.constrainer.noteUsage(constraints);
1671
-
1672
- // Boot the tree for this method if it doesn't exist yet
1673
- if (this.trees[method] === undefined) {
1674
- this.trees[method] = new StaticNode('/');
1675
- }
1676
- let pattern = path;
1677
- if (pattern === '*' && this.trees[method].prefix.length !== 0) {
1678
- const currentRoot = this.trees[method];
1679
- this.trees[method] = new StaticNode('');
1680
- this.trees[method].staticChildren['/'] = currentRoot;
1681
- }
1682
- let currentNode = this.trees[method];
1683
- let parentNodePathIndex = currentNode.prefix.length;
1684
- const params = [];
1685
- for (let i = 0; i <= pattern.length; i++) {
1686
- if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {
1687
- // It's a double colon
1688
- i++;
1689
- continue;
1690
- }
1691
- const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58;
1692
- const isWildcardNode = pattern.charCodeAt(i) === 42;
1693
- if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) {
1694
- let staticNodePath = pattern.slice(parentNodePathIndex, i);
1695
- if (!this.caseSensitive) {
1696
- staticNodePath = staticNodePath.toLowerCase();
1697
- }
1698
- staticNodePath = staticNodePath.split('::').join(':');
1699
- staticNodePath = staticNodePath.split('%').join('%25');
1700
- // add the static part of the route to the tree
1701
- currentNode = currentNode.createStaticChild(staticNodePath);
1702
- }
1703
- if (isParametricNode) {
1704
- let isRegexNode = false;
1705
- const regexps = [];
1706
- let lastParamStartIndex = i + 1;
1707
- for (let j = lastParamStartIndex;; j++) {
1708
- const charCode = pattern.charCodeAt(j);
1709
- const isRegexParam = charCode === 40;
1710
- const isStaticPart = charCode === 45 || charCode === 46;
1711
- const isEndOfNode = charCode === 47 || j === pattern.length;
1712
- if (isRegexParam || isStaticPart || isEndOfNode) {
1713
- const paramName = pattern.slice(lastParamStartIndex, j);
1714
- params.push(paramName);
1715
- isRegexNode = isRegexNode || isRegexParam || isStaticPart;
1716
- if (isRegexParam) {
1717
- const endOfRegexIndex = getClosingParenthensePosition(pattern, j);
1718
- const regexString = pattern.slice(j, endOfRegexIndex + 1);
1719
- if (!this.allowUnsafeRegex) {
1720
- assert(isRegexSafe(new RegExp(regexString)), "The regex '".concat(regexString, "' is not safe!"));
1721
- }
1722
- regexps.push(trimRegExpStartAndEnd(regexString));
1723
- j = endOfRegexIndex + 1;
1724
- } else {
1725
- regexps.push('(.*?)');
1726
- }
1727
- const staticPartStartIndex = j;
1728
- for (; j < pattern.length; j++) {
1729
- const charCode = pattern.charCodeAt(j);
1730
- if (charCode === 47) break;
1731
- if (charCode === 58) {
1732
- const nextCharCode = pattern.charCodeAt(j + 1);
1733
- if (nextCharCode === 58) j++;else break;
1734
- }
1735
- }
1736
- let staticPart = pattern.slice(staticPartStartIndex, j);
1737
- if (staticPart) {
1738
- staticPart = staticPart.split('::').join(':');
1739
- staticPart = staticPart.split('%').join('%25');
1740
- regexps.push(escapeRegExp(staticPart));
1741
- }
1742
- lastParamStartIndex = j + 1;
1743
- if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {
1744
- const nodePattern = isRegexNode ? '()' + staticPart : staticPart;
1745
- const nodePath = pattern.slice(i, j);
1746
- pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j);
1747
- i += nodePattern.length;
1748
- const regex = isRegexNode ? new RegExp('^' + regexps.join('') + '$') : null;
1749
- currentNode = currentNode.createParametricChild(regex, staticPart || null, nodePath);
1750
- parentNodePathIndex = i + 1;
1751
- break;
1752
- }
1753
- }
1754
- }
1755
- } else if (isWildcardNode) {
1756
- // add the wildcard parameter
1757
- params.push('*');
1758
- currentNode = currentNode.createWildcardChild();
1759
- parentNodePathIndex = i + 1;
1760
- if (i !== pattern.length - 1) {
1761
- throw new Error('Wildcard must be the last character in the route');
1762
- }
1763
- }
1764
- }
1765
- if (!this.caseSensitive) {
1766
- pattern = pattern.toLowerCase();
1767
- }
1768
- if (pattern === '*') {
1769
- pattern = '/*';
1770
- }
1771
- for (const existRoute of this.routes) {
1772
- const routeConstraints = existRoute.opts.constraints || {};
1773
- if (existRoute.method === method && existRoute.pattern === pattern && deepEqual(routeConstraints, constraints)) {
1774
- throw new Error("Method '".concat(method, "' already declared for route '").concat(pattern, "' with constraints '").concat(JSON.stringify(constraints), "'"));
1775
- }
1776
- }
1777
- const route = {
1778
- method,
1779
- path,
1780
- pattern,
1781
- params,
1782
- opts,
1783
- handler,
1784
- store
1785
- };
1786
- this.routes.push(route);
1787
- currentNode.addRoute(route, this.constrainer);
1788
- };
1789
- Router.prototype.hasConstraintStrategy = function (strategyName) {
1790
- return this.constrainer.hasConstraintStrategy(strategyName);
1791
- };
1792
- Router.prototype.addConstraintStrategy = function (constraints) {
1793
- this.constrainer.addConstraintStrategy(constraints);
1794
- this._rebuild(this.routes);
1795
- };
1796
- Router.prototype.reset = function reset() {
1797
- this.trees = {};
1798
- this.routes = [];
1799
- };
1800
- Router.prototype.off = function off(method, path, constraints) {
1801
- // path validation
1802
- assert(typeof path === 'string', 'Path should be a string');
1803
- assert(path.length > 0, 'The path could not be empty');
1804
- assert(path[0] === '/' || path[0] === '*', 'The first character of a path should be `/` or `*`');
1805
- // options validation
1806
- assert(typeof constraints === 'undefined' || typeof constraints === 'object' && !Array.isArray(constraints) && constraints !== null, 'Constraints should be an object or undefined.');
1807
-
1808
- // path ends with optional parameter
1809
- const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP);
1810
- if (optionalParamMatch) {
1811
- assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, 'Optional Parameter needs to be the last parameter of the path');
1812
- const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, '$1$2');
1813
- const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, '$2');
1814
- this.off(method, pathFull, constraints);
1815
- this.off(method, pathOptional, constraints);
1816
- return;
1817
- }
1818
- if (this.ignoreDuplicateSlashes) {
1819
- path = removeDuplicateSlashes(path);
1820
- }
1821
- if (this.ignoreTrailingSlash) {
1822
- path = trimLastSlash(path);
1823
- }
1824
- const methods = Array.isArray(method) ? method : [method];
1825
- for (const method of methods) {
1826
- this._off(method, path, constraints);
1827
- }
1828
- };
1829
- Router.prototype._off = function _off(method, path, constraints) {
1830
- // method validation
1831
- assert(typeof method === 'string', 'Method should be a string');
1832
- assert(httpMethods.includes(method), "Method '".concat(method, "' is not an http method."));
1833
- function matcherWithoutConstraints(route) {
1834
- return method !== route.method || path !== route.path;
1835
- }
1836
- function matcherWithConstraints(route) {
1837
- return matcherWithoutConstraints(route) || !deepEqual(constraints, route.opts.constraints || {});
1838
- }
1839
- const predicate = constraints ? matcherWithConstraints : matcherWithoutConstraints;
1840
-
1841
- // Rebuild tree without the specific route
1842
- const newRoutes = this.routes.filter(predicate);
1843
- this._rebuild(newRoutes);
1844
- };
1845
- Router.prototype.lookup = function lookup(req, res, ctx, done) {
1846
- if (typeof ctx === 'function') {
1847
- done = ctx;
1848
- ctx = undefined;
1849
- }
1850
- if (done === undefined) {
1851
- const constraints = this.constrainer.deriveConstraints(req, ctx);
1852
- const handle = this.find(req.method, req.url, constraints);
1853
- return this.callHandler(handle, req, res, ctx);
1854
- }
1855
- this.constrainer.deriveConstraints(req, ctx, (err, constraints) => {
1856
- if (err !== null) {
1857
- done(err);
1858
- return;
1859
- }
1860
- try {
1861
- const handle = this.find(req.method, req.url, constraints);
1862
- const result = this.callHandler(handle, req, res, ctx);
1863
- done(null, result);
1864
- } catch (err) {
1865
- done(err);
1866
- }
1867
- });
1868
- };
1869
- Router.prototype.callHandler = function callHandler(handle, req, res, ctx) {
1870
- if (handle === null) return this._defaultRoute(req, res, ctx);
1871
- return ctx === undefined ? handle.handler(req, res, handle.params, handle.store, handle.searchParams) : handle.handler.call(ctx, req, res, handle.params, handle.store, handle.searchParams);
1872
- };
1873
- Router.prototype.find = function find(method, path, derivedConstraints) {
1874
- let currentNode = this.trees[method];
1875
- if (currentNode === undefined) return null;
1876
- if (path.charCodeAt(0) !== 47) {
1877
- // 47 is '/'
1878
- path = path.replace(FULL_PATH_REGEXP, '/');
1879
- }
1880
-
1881
- // This must be run before sanitizeUrl as the resulting function
1882
- // .sliceParameter must be constructed with same URL string used
1883
- // throughout the rest of this function.
1884
- if (this.ignoreDuplicateSlashes) {
1885
- path = removeDuplicateSlashes(path);
1886
- }
1887
- let sanitizedUrl;
1888
- let querystring;
1889
- let shouldDecodeParam;
1890
- try {
1891
- sanitizedUrl = safeDecodeURI(path);
1892
- path = sanitizedUrl.path;
1893
- querystring = sanitizedUrl.querystring;
1894
- shouldDecodeParam = sanitizedUrl.shouldDecodeParam;
1895
- } catch (error) {
1896
- return this._onBadUrl(path);
1897
- }
1898
- if (this.ignoreTrailingSlash) {
1899
- path = trimLastSlash(path);
1900
- }
1901
- const originPath = path;
1902
- if (this.caseSensitive === false) {
1903
- path = path.toLowerCase();
1904
- }
1905
- const maxParamLength = this.maxParamLength;
1906
- let pathIndex = currentNode.prefix.length;
1907
- const params = [];
1908
- const pathLen = path.length;
1909
- const brothersNodesStack = [];
1910
- while (true) {
1911
- if (pathIndex === pathLen && currentNode.isLeafNode) {
1912
- const handle = currentNode.handlerStorage.getMatchingHandler(derivedConstraints);
1913
- if (handle !== null) {
1914
- return {
1915
- handler: handle.handler,
1916
- store: handle.store,
1917
- params: handle._createParamsObject(params),
1918
- searchParams: this.querystringParser(querystring)
1919
- };
1920
- }
1921
- }
1922
- let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length);
1923
- if (node === null) {
1924
- if (brothersNodesStack.length === 0) {
1925
- return null;
1926
- }
1927
- const brotherNodeState = brothersNodesStack.pop();
1928
- pathIndex = brotherNodeState.brotherPathIndex;
1929
- params.splice(brotherNodeState.paramsCount);
1930
- node = brotherNodeState.brotherNode;
1931
- }
1932
- currentNode = node;
1933
-
1934
- // static route
1935
- if (currentNode.kind === NODE_TYPES.STATIC) {
1936
- pathIndex += currentNode.prefix.length;
1937
- continue;
1938
- }
1939
- if (currentNode.kind === NODE_TYPES.WILDCARD) {
1940
- let param = originPath.slice(pathIndex);
1941
- if (shouldDecodeParam) {
1942
- param = safeDecodeURIComponent(param);
1943
- }
1944
- params.push(param);
1945
- pathIndex = pathLen;
1946
- continue;
1947
- }
1948
- if (currentNode.kind === NODE_TYPES.PARAMETRIC) {
1949
- let paramEndIndex = originPath.indexOf('/', pathIndex);
1950
- if (paramEndIndex === -1) {
1951
- paramEndIndex = pathLen;
1952
- }
1953
- let param = originPath.slice(pathIndex, paramEndIndex);
1954
- if (shouldDecodeParam) {
1955
- param = safeDecodeURIComponent(param);
1956
- }
1957
- if (currentNode.isRegex) {
1958
- const matchedParameters = currentNode.regex.exec(param);
1959
- if (matchedParameters === null) continue;
1960
- for (let i = 1; i < matchedParameters.length; i++) {
1961
- const matchedParam = matchedParameters[i];
1962
- if (matchedParam.length > maxParamLength) {
1963
- return null;
1964
- }
1965
- params.push(matchedParam);
1966
- }
1967
- } else {
1968
- if (param.length > maxParamLength) {
1969
- return null;
1970
- }
1971
- params.push(param);
1972
- }
1973
- pathIndex = paramEndIndex;
1974
- }
1975
- }
1976
- };
1977
- Router.prototype._rebuild = function (routes) {
1978
- this.reset();
1979
- for (const route of routes) {
1980
- const {
1981
- method,
1982
- path,
1983
- opts,
1984
- handler,
1985
- store
1986
- } = route;
1987
- this._on(method, path, opts, handler, store);
1988
- }
1989
- };
1990
- Router.prototype._defaultRoute = function (req, res, ctx) {
1991
- if (this.defaultRoute !== null) {
1992
- return ctx === undefined ? this.defaultRoute(req, res) : this.defaultRoute.call(ctx, req, res);
1993
- } else {
1994
- res.statusCode = 404;
1995
- res.end();
1996
- }
1997
- };
1998
- Router.prototype._onBadUrl = function (path) {
1999
- if (this.onBadUrl === null) {
2000
- return null;
2001
- }
2002
- const onBadUrl = this.onBadUrl;
2003
- return {
2004
- handler: (req, res, ctx) => onBadUrl(path, req, res),
2005
- params: {},
2006
- store: null
2007
- };
2008
- };
2009
- Router.prototype.prettyPrint = function () {
2010
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2011
- const method = options.method;
2012
- options.buildPrettyMeta = this.buildPrettyMeta.bind(this);
2013
- let tree = null;
2014
- if (method === undefined) {
2015
- const _this$constrainer$str = this.constrainer.strategies,
2016
- {
2017
- version,
2018
- host
2019
- } = _this$constrainer$str,
2020
- constraints = _objectWithoutProperties(_this$constrainer$str, _excluded);
2021
- constraints[httpMethodStrategy.name] = httpMethodStrategy;
2022
- const mergedRouter = new Router(_objectSpread(_objectSpread({}, this._opts), {}, {
2023
- constraints
2024
- }));
2025
- const mergedRoutes = this.routes.map(route => {
2026
- const constraints = _objectSpread(_objectSpread({}, route.opts.constraints), {}, {
2027
- [httpMethodStrategy.name]: route.method
2028
- });
2029
- return _objectSpread(_objectSpread({}, route), {}, {
2030
- method: 'MERGED',
2031
- opts: {
2032
- constraints
2033
- }
2034
- });
2035
- });
2036
- mergedRouter._rebuild(mergedRoutes);
2037
- tree = mergedRouter.trees.MERGED;
2038
- } else {
2039
- tree = this.trees[method];
2040
- }
2041
- if (tree == null) return '(empty tree)';
2042
- return prettyPrintTree(tree, options);
2043
- };
2044
- for (var i in httpMethods) {
2045
- /* eslint no-prototype-builtins: "off" */
2046
- if (!httpMethods.hasOwnProperty(i)) continue;
2047
- const m = httpMethods[i];
2048
- const methodName = m.toLowerCase();
2049
- if (Router.prototype[methodName]) throw new Error('Method already exists: ' + methodName);
2050
- Router.prototype[methodName] = function (path, handler, store) {
2051
- return this.on(m, path, handler, store);
2052
- };
2053
- }
2054
- Router.prototype.all = function (path, handler, store) {
2055
- this.on(httpMethods, path, handler, store);
2056
- };
2057
- module.exports = Router;
2058
- function escapeRegExp(string) {
2059
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2060
- }
2061
- function removeDuplicateSlashes(path) {
2062
- return path.replace(/\/\/+/g, '/');
2063
- }
2064
- function trimLastSlash(path) {
2065
- if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) {
2066
- return path.slice(0, -1);
2067
- }
2068
- return path;
2069
- }
2070
- function trimRegExpStartAndEnd(regexString) {
2071
- // removes chars that marks start "^" and end "$" of regexp
2072
- if (regexString.charCodeAt(1) === 94) {
2073
- regexString = regexString.slice(0, 1) + regexString.slice(2);
2074
- }
2075
- if (regexString.charCodeAt(regexString.length - 2) === 36) {
2076
- regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1);
2077
- }
2078
- return regexString;
2079
- }
2080
- function getClosingParenthensePosition(path, idx) {
2081
- // `path.indexOf()` will always return the first position of the closing parenthese,
2082
- // but it's inefficient for grouped or wrong regexp expressions.
2083
- // see issues #62 and #63 for more info
2084
-
2085
- var parentheses = 1;
2086
- while (idx < path.length) {
2087
- idx++;
2088
-
2089
- // ignore skipped chars
2090
- if (path[idx] === '\\') {
2091
- idx++;
2092
- continue;
2093
- }
2094
- if (path[idx] === ')') {
2095
- parentheses--;
2096
- } else if (path[idx] === '(') {
2097
- parentheses++;
2098
- }
2099
- if (!parentheses) return idx;
2100
- }
2101
- throw new TypeError('Invalid regexp expression in "' + path + '"');
2102
- }
2103
- function defaultBuildPrettyMeta(route) {
2104
- // buildPrettyMeta function must return an object, which will be parsed into key/value pairs for display
2105
- if (!route) return {};
2106
- if (!route.store) return {};
2107
- return Object.assign({}, route.store);
2108
- }
2109
- }, {
2110
- "./lib/constrainer": 14,
2111
- "./lib/http-methods": 16,
2112
- "./lib/node": 17,
2113
- "./lib/pretty-print": 18,
2114
- "./lib/strategies/http-method": 21,
2115
- "./lib/url-sanitizer": 22,
2116
- "assert": 1,
2117
- "fast-deep-equal": 8,
2118
- "fast-querystring": 9,
2119
- "safe-regex2": 25
2120
- }],
2121
- 14: [function (require, module, exports) {
2122
- 'use strict';
2123
-
2124
- const acceptVersionStrategy = require('./strategies/accept-version');
2125
- const acceptHostStrategy = require('./strategies/accept-host');
2126
- const assert = require('assert');
2127
- class Constrainer {
2128
- constructor(customStrategies) {
2129
- this.strategies = {
2130
- version: acceptVersionStrategy,
2131
- host: acceptHostStrategy
2132
- };
2133
- this.strategiesInUse = new Set();
2134
- this.asyncStrategiesInUse = new Set();
2135
-
2136
- // validate and optimize prototypes of given custom strategies
2137
- if (customStrategies) {
2138
- for (const strategy of Object.values(customStrategies)) {
2139
- this.addConstraintStrategy(strategy);
2140
- }
2141
- }
2142
- }
2143
- isStrategyUsed(strategyName) {
2144
- return this.strategiesInUse.has(strategyName) || this.asyncStrategiesInUse.has(strategyName);
2145
- }
2146
- hasConstraintStrategy(strategyName) {
2147
- const customConstraintStrategy = this.strategies[strategyName];
2148
- if (customConstraintStrategy !== undefined) {
2149
- return customConstraintStrategy.isCustom || this.isStrategyUsed(strategyName);
2150
- }
2151
- return false;
2152
- }
2153
- addConstraintStrategy(strategy) {
2154
- assert(typeof strategy.name === 'string' && strategy.name !== '', 'strategy.name is required.');
2155
- assert(strategy.storage && typeof strategy.storage === 'function', 'strategy.storage function is required.');
2156
- assert(strategy.deriveConstraint && typeof strategy.deriveConstraint === 'function', 'strategy.deriveConstraint function is required.');
2157
- if (this.strategies[strategy.name] && this.strategies[strategy.name].isCustom) {
2158
- throw new Error("There already exists a custom constraint with the name ".concat(strategy.name, "."));
2159
- }
2160
- if (this.isStrategyUsed(strategy.name)) {
2161
- throw new Error("There already exists a route with ".concat(strategy.name, " constraint."));
2162
- }
2163
- strategy.isCustom = true;
2164
- strategy.isAsync = strategy.deriveConstraint.length === 3;
2165
- this.strategies[strategy.name] = strategy;
2166
- if (strategy.mustMatchWhenDerived) {
2167
- this.noteUsage({
2168
- [strategy.name]: strategy
2169
- });
2170
- }
2171
- }
2172
- deriveConstraints(req, ctx, done) {
2173
- const constraints = this.deriveSyncConstraints(req, ctx);
2174
- if (done === undefined) {
2175
- return constraints;
2176
- }
2177
- this.deriveAsyncConstraints(constraints, req, ctx, done);
2178
- }
2179
- deriveSyncConstraints(req, ctx) {
2180
- return undefined;
2181
- }
2182
-
2183
- // When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used.
2184
- noteUsage(constraints) {
2185
- if (constraints) {
2186
- const beforeSize = this.strategiesInUse.size;
2187
- for (const key in constraints) {
2188
- const strategy = this.strategies[key];
2189
- if (strategy.isAsync) {
2190
- this.asyncStrategiesInUse.add(key);
2191
- } else {
2192
- this.strategiesInUse.add(key);
2193
- }
2194
- }
2195
- if (beforeSize !== this.strategiesInUse.size) {
2196
- this._buildDeriveConstraints();
2197
- }
2198
- }
2199
- }
2200
- newStoreForConstraint(constraint) {
2201
- if (!this.strategies[constraint]) {
2202
- throw new Error("No strategy registered for constraint key ".concat(constraint));
2203
- }
2204
- return this.strategies[constraint].storage();
2205
- }
2206
- validateConstraints(constraints) {
2207
- for (const key in constraints) {
2208
- const value = constraints[key];
2209
- if (typeof value === 'undefined') {
2210
- throw new Error('Can\'t pass an undefined constraint value, must pass null or no key at all');
2211
- }
2212
- const strategy = this.strategies[key];
2213
- if (!strategy) {
2214
- throw new Error("No strategy registered for constraint key ".concat(key));
2215
- }
2216
- if (strategy.validate) {
2217
- strategy.validate(value);
2218
- }
2219
- }
2220
- }
2221
- deriveAsyncConstraints(constraints, req, ctx, done) {
2222
- let asyncConstraintsCount = this.asyncStrategiesInUse.size;
2223
- if (asyncConstraintsCount === 0) {
2224
- done(null, constraints);
2225
- return;
2226
- }
2227
- constraints = constraints || {};
2228
- for (const key of this.asyncStrategiesInUse) {
2229
- const strategy = this.strategies[key];
2230
- strategy.deriveConstraint(req, ctx, (err, constraintValue) => {
2231
- if (err !== null) {
2232
- done(err);
2233
- return;
2234
- }
2235
- constraints[key] = constraintValue;
2236
- if (--asyncConstraintsCount === 0) {
2237
- done(null, constraints);
2238
- }
2239
- });
2240
- }
2241
- }
2242
-
2243
- // Optimization: build a fast function for deriving the constraints for all the strategies at once. We inline the definitions of the version constraint and the host constraint for performance.
2244
- // If no constraining strategies are in use (no routes constrain on host, or version, or any custom strategies) then we don't need to derive constraints for each route match, so don't do anything special, and just return undefined
2245
- // This allows us to not allocate an object to hold constraint values if no constraints are defined.
2246
- _buildDeriveConstraints() {
2247
- if (this.strategiesInUse.size === 0) return;
2248
- const lines = ['return {'];
2249
- for (const key of this.strategiesInUse) {
2250
- const strategy = this.strategies[key];
2251
- // Optimization: inline the derivation for the common built in constraints
2252
- if (!strategy.isCustom) {
2253
- if (key === 'version') {
2254
- lines.push(' version: req.headers[\'accept-version\'],');
2255
- } else if (key === 'host') {
2256
- lines.push(' host: req.headers.host || req.headers[\':authority\'],');
2257
- } else {
2258
- throw new Error('unknown non-custom strategy for compiling constraint derivation function');
2259
- }
2260
- } else {
2261
- lines.push(" ".concat(strategy.name, ": this.strategies.").concat(key, ".deriveConstraint(req, ctx),"));
2262
- }
2263
- }
2264
- lines.push('}');
2265
- this.deriveSyncConstraints = new Function('req', 'ctx', lines.join('\n')).bind(this); // eslint-disable-line
2266
- }
2267
- }
2268
-
2269
- module.exports = Constrainer;
2270
- }, {
2271
- "./strategies/accept-host": 19,
2272
- "./strategies/accept-version": 20,
2273
- "assert": 1
2274
- }],
2275
- 15: [function (require, module, exports) {
2276
- 'use strict';
2277
-
2278
- const httpMethodStrategy = require('./strategies/http-method');
2279
- class HandlerStorage {
2280
- constructor() {
2281
- this.unconstrainedHandler = null; // optimized reference to the handler that will match most of the time
2282
- this.constraints = [];
2283
- this.handlers = []; // unoptimized list of handler objects for which the fast matcher function will be compiled
2284
- this.constrainedHandlerStores = null;
2285
- }
2286
-
2287
- // This is the hot path for node handler finding -- change with care!
2288
- getMatchingHandler(derivedConstraints) {
2289
- if (derivedConstraints === undefined) {
2290
- return this.unconstrainedHandler;
2291
- }
2292
- return this._getHandlerMatchingConstraints(derivedConstraints);
2293
- }
2294
- addHandler(constrainer, route) {
2295
- const params = route.params;
2296
- const constraints = route.opts.constraints || {};
2297
- const handlerObject = {
2298
- params,
2299
- constraints,
2300
- handler: route.handler,
2301
- store: route.store || null,
2302
- _createParamsObject: this._compileCreateParamsObject(params)
2303
- };
2304
- const constraintsNames = Object.keys(constraints);
2305
- if (constraintsNames.length === 0) {
2306
- this.unconstrainedHandler = handlerObject;
2307
- }
2308
- for (const constraint of constraintsNames) {
2309
- if (!this.constraints.includes(constraint)) {
2310
- if (constraint === 'version') {
2311
- // always check the version constraint first as it is the most selective
2312
- this.constraints.unshift(constraint);
2313
- } else {
2314
- this.constraints.push(constraint);
2315
- }
2316
- }
2317
- }
2318
- const isMergedTree = constraintsNames.includes(httpMethodStrategy.name);
2319
- if (!isMergedTree && this.handlers.length >= 32) {
2320
- throw new Error('find-my-way supports a maximum of 32 route handlers per node when there are constraints, limit reached');
2321
- }
2322
- this.handlers.push(handlerObject);
2323
- // Sort the most constrained handlers to the front of the list of handlers so they are tested first.
2324
- this.handlers.sort((a, b) => Object.keys(a.constraints).length - Object.keys(b.constraints).length);
2325
- if (!isMergedTree) {
2326
- this._compileGetHandlerMatchingConstraints(constrainer, constraints);
2327
- }
2328
- }
2329
- _compileCreateParamsObject(params) {
2330
- const lines = [];
2331
- for (let i = 0; i < params.length; i++) {
2332
- lines.push("'".concat(params[i], "': paramsArray[").concat(i, "]"));
2333
- }
2334
- return new Function('paramsArray', "return {".concat(lines.join(','), "}")); // eslint-disable-line
2335
- }
2336
-
2337
- _getHandlerMatchingConstraints() {
2338
- return null;
2339
- }
2340
-
2341
- // Builds a store object that maps from constraint values to a bitmap of handler indexes which pass the constraint for a value
2342
- // So for a host constraint, this might look like { "fastify.io": 0b0010, "google.ca": 0b0101 }, meaning the 3rd handler is constrainted to fastify.io, and the 2nd and 4th handlers are constrained to google.ca.
2343
- // The store's implementation comes from the strategies provided to the Router.
2344
- _buildConstraintStore(store, constraint) {
2345
- for (let i = 0; i < this.handlers.length; i++) {
2346
- const handler = this.handlers[i];
2347
- const constraintValue = handler.constraints[constraint];
2348
- if (constraintValue !== undefined) {
2349
- let indexes = store.get(constraintValue) || 0;
2350
- indexes |= 1 << i; // set the i-th bit for the mask because this handler is constrained by this value https://stackoverflow.com/questions/1436438/how-do-you-set-clear-and-toggle-a-single-bit-in-javascrip
2351
- store.set(constraintValue, indexes);
2352
- }
2353
- }
2354
- }
2355
-
2356
- // Builds a bitmask for a given constraint that has a bit for each handler index that is 0 when that handler *is* constrained and 1 when the handler *isnt* constrainted. This is opposite to what might be obvious, but is just for convienience when doing the bitwise operations.
2357
- _constrainedIndexBitmask(constraint) {
2358
- let mask = 0;
2359
- for (let i = 0; i < this.handlers.length; i++) {
2360
- const handler = this.handlers[i];
2361
- const constraintValue = handler.constraints[constraint];
2362
- if (constraintValue !== undefined) {
2363
- mask |= 1 << i;
2364
- }
2365
- }
2366
- return ~mask;
2367
- }
2368
-
2369
- // Compile a fast function to match the handlers for this node
2370
- // The function implements a general case multi-constraint matching algorithm.
2371
- // The general idea is this: we have a bunch of handlers, each with a potentially different set of constraints, and sometimes none at all. We're given a list of constraint values and we have to use the constraint-value-comparison strategies to see which handlers match the constraint values passed in.
2372
- // We do this by asking each constraint store which handler indexes match the given constraint value for each store. Trickily, the handlers that a store says match are the handlers constrained by that store, but handlers that aren't constrained at all by that store could still match just fine. So, each constraint store can only describe matches for it, and it won't have any bearing on the handlers it doesn't care about. For this reason, we have to ask each stores which handlers match and track which have been matched (or not cared about) by all of them.
2373
- // We use bitmaps to represent these lists of matches so we can use bitwise operations to implement this efficiently. Bitmaps are cheap to allocate, let us implement this masking behaviour in one CPU instruction, and are quite compact in memory. We start with a bitmap set to all 1s representing every handler that is a match candidate, and then for each constraint, see which handlers match using the store, and then mask the result by the mask of handlers that that store applies to, and bitwise AND with the candidate list. Phew.
2374
- // We consider all this compiling function complexity to be worth it, because the naive implementation that just loops over the handlers asking which stores match is quite a bit slower.
2375
- _compileGetHandlerMatchingConstraints(constrainer) {
2376
- this.constrainedHandlerStores = {};
2377
- for (const constraint of this.constraints) {
2378
- const store = constrainer.newStoreForConstraint(constraint);
2379
- this.constrainedHandlerStores[constraint] = store;
2380
- this._buildConstraintStore(store, constraint);
2381
- }
2382
- const lines = [];
2383
- lines.push("\n let candidates = ".concat((1 << this.handlers.length) - 1, "\n let mask, matches\n "));
2384
- for (const constraint of this.constraints) {
2385
- // Setup the mask for indexes this constraint applies to. The mask bits are set to 1 for each position if the constraint applies.
2386
- lines.push("\n mask = ".concat(this._constrainedIndexBitmask(constraint), "\n value = derivedConstraints.").concat(constraint, "\n "));
2387
-
2388
- // If there's no constraint value, none of the handlers constrained by this constraint can match. Remove them from the candidates.
2389
- // If there is a constraint value, get the matching indexes bitmap from the store, and mask it down to only the indexes this constraint applies to, and then bitwise and with the candidates list to leave only matching candidates left.
2390
- const strategy = constrainer.strategies[constraint];
2391
- const matchMask = strategy.mustMatchWhenDerived ? 'matches' : '(matches | mask)';
2392
- lines.push("\n if (value === undefined) {\n candidates &= mask\n } else {\n matches = this.constrainedHandlerStores.".concat(constraint, ".get(value) || 0\n candidates &= ").concat(matchMask, "\n }\n if (candidates === 0) return null;\n "));
2393
- }
2394
-
2395
- // There are some constraints that can be derived and marked as "must match", where if they are derived, they only match routes that actually have a constraint on the value, like the SemVer version constraint.
2396
- // An example: a request comes in for version 1.x, and this node has a handler that matches the path, but there's no version constraint. For SemVer, the find-my-way semantics do not match this handler to that request.
2397
- // This function is used by Nodes with handlers to match when they don't have any constrained routes to exclude request that do have must match derived constraints present.
2398
- for (const constraint in constrainer.strategies) {
2399
- const strategy = constrainer.strategies[constraint];
2400
- if (strategy.mustMatchWhenDerived && !this.constraints.includes(constraint)) {
2401
- lines.push("if (derivedConstraints.".concat(constraint, " !== undefined) return null"));
2402
- }
2403
- }
2404
-
2405
- // Return the first handler who's bit is set in the candidates https://stackoverflow.com/questions/18134985/how-to-find-index-of-first-set-bit
2406
- lines.push('return this.handlers[Math.floor(Math.log2(candidates))]');
2407
- this._getHandlerMatchingConstraints = new Function('derivedConstraints', lines.join('\n')); // eslint-disable-line
2408
- }
2409
- }
2410
-
2411
- module.exports = HandlerStorage;
2412
- }, {
2413
- "./strategies/http-method": 21
2414
- }],
2415
- 16: [function (require, module, exports) {
2416
- 'use strict';
2417
-
2418
- // defined by Node.js http module, a snapshot from Node.js 18.12.0
2419
- const httpMethods = ['ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH', 'SOURCE', 'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE'];
2420
- module.exports = httpMethods;
2421
- }, {}],
2422
- 17: [function (require, module, exports) {
2423
- 'use strict';
2424
-
2425
- const HandlerStorage = require('./handler-storage');
2426
- const NODE_TYPES = {
2427
- STATIC: 0,
2428
- PARAMETRIC: 1,
2429
- WILDCARD: 2
2430
- };
2431
- class Node {
2432
- constructor() {
2433
- this.isLeafNode = false;
2434
- this.routes = null;
2435
- this.handlerStorage = null;
2436
- }
2437
- addRoute(route, constrainer) {
2438
- if (this.routes === null) {
2439
- this.routes = [];
2440
- }
2441
- if (this.handlerStorage === null) {
2442
- this.handlerStorage = new HandlerStorage();
2443
- }
2444
- this.isLeafNode = true;
2445
- this.routes.push(route);
2446
- this.handlerStorage.addHandler(constrainer, route);
2447
- }
2448
- }
2449
- class ParentNode extends Node {
2450
- constructor() {
2451
- super();
2452
- this.staticChildren = {};
2453
- }
2454
- findStaticMatchingChild(path, pathIndex) {
2455
- const staticChild = this.staticChildren[path.charAt(pathIndex)];
2456
- if (staticChild === undefined || !staticChild.matchPrefix(path, pathIndex)) {
2457
- return null;
2458
- }
2459
- return staticChild;
2460
- }
2461
- createStaticChild(path) {
2462
- if (path.length === 0) {
2463
- return this;
2464
- }
2465
- let staticChild = this.staticChildren[path.charAt(0)];
2466
- if (staticChild) {
2467
- let i = 1;
2468
- for (; i < staticChild.prefix.length; i++) {
2469
- if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {
2470
- staticChild = staticChild.split(this, i);
2471
- break;
2472
- }
2473
- }
2474
- return staticChild.createStaticChild(path.slice(i));
2475
- }
2476
- const label = path.charAt(0);
2477
- this.staticChildren[label] = new StaticNode(path);
2478
- return this.staticChildren[label];
2479
- }
2480
- }
2481
- class StaticNode extends ParentNode {
2482
- constructor(prefix) {
2483
- super();
2484
- this.prefix = prefix;
2485
- this.wildcardChild = null;
2486
- this.parametricChildren = [];
2487
- this.kind = NODE_TYPES.STATIC;
2488
- this._compilePrefixMatch();
2489
- }
2490
- createParametricChild(regex, staticSuffix, nodePath) {
2491
- const regexpSource = regex && regex.source;
2492
- let parametricChild = this.parametricChildren.find(child => {
2493
- const childRegexSource = child.regex && child.regex.source;
2494
- return childRegexSource === regexpSource;
2495
- });
2496
- if (parametricChild) {
2497
- parametricChild.nodePaths.add(nodePath);
2498
- return parametricChild;
2499
- }
2500
- parametricChild = new ParametricNode(regex, staticSuffix, nodePath);
2501
- this.parametricChildren.push(parametricChild);
2502
- this.parametricChildren.sort((child1, child2) => {
2503
- if (!child1.isRegex) return 1;
2504
- if (!child2.isRegex) return -1;
2505
- if (child1.staticSuffix === null) return 1;
2506
- if (child2.staticSuffix === null) return -1;
2507
- if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1;
2508
- if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1;
2509
- return 0;
2510
- });
2511
- return parametricChild;
2512
- }
2513
- createWildcardChild() {
2514
- if (this.wildcardChild) {
2515
- return this.wildcardChild;
2516
- }
2517
- this.wildcardChild = new WildcardNode();
2518
- return this.wildcardChild;
2519
- }
2520
- split(parentNode, length) {
2521
- const parentPrefix = this.prefix.slice(0, length);
2522
- const childPrefix = this.prefix.slice(length);
2523
- this.prefix = childPrefix;
2524
- this._compilePrefixMatch();
2525
- const staticNode = new StaticNode(parentPrefix);
2526
- staticNode.staticChildren[childPrefix.charAt(0)] = this;
2527
- parentNode.staticChildren[parentPrefix.charAt(0)] = staticNode;
2528
- return staticNode;
2529
- }
2530
- getNextNode(path, pathIndex, nodeStack, paramsCount) {
2531
- let node = this.findStaticMatchingChild(path, pathIndex);
2532
- let parametricBrotherNodeIndex = 0;
2533
- if (node === null) {
2534
- if (this.parametricChildren.length === 0) {
2535
- return this.wildcardChild;
2536
- }
2537
- node = this.parametricChildren[0];
2538
- parametricBrotherNodeIndex = 1;
2539
- }
2540
- if (this.wildcardChild !== null) {
2541
- nodeStack.push({
2542
- paramsCount,
2543
- brotherPathIndex: pathIndex,
2544
- brotherNode: this.wildcardChild
2545
- });
2546
- }
2547
- for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) {
2548
- nodeStack.push({
2549
- paramsCount,
2550
- brotherPathIndex: pathIndex,
2551
- brotherNode: this.parametricChildren[i]
2552
- });
2553
- }
2554
- return node;
2555
- }
2556
- _compilePrefixMatch() {
2557
- if (this.prefix.length === 1) {
2558
- this.matchPrefix = () => true;
2559
- return;
2560
- }
2561
- const lines = [];
2562
- for (let i = 1; i < this.prefix.length; i++) {
2563
- const charCode = this.prefix.charCodeAt(i);
2564
- lines.push("path.charCodeAt(i + ".concat(i, ") === ").concat(charCode));
2565
- }
2566
- this.matchPrefix = new Function('path', 'i', "return ".concat(lines.join(' && '))); // eslint-disable-line
2567
- }
2568
- }
2569
-
2570
- class ParametricNode extends ParentNode {
2571
- constructor(regex, staticSuffix, nodePath) {
2572
- super();
2573
- this.isRegex = !!regex;
2574
- this.regex = regex || null;
2575
- this.staticSuffix = staticSuffix || null;
2576
- this.kind = NODE_TYPES.PARAMETRIC;
2577
- this.nodePaths = new Set([nodePath]);
2578
- }
2579
- getNextNode(path, pathIndex) {
2580
- return this.findStaticMatchingChild(path, pathIndex);
2581
- }
2582
- }
2583
- class WildcardNode extends Node {
2584
- constructor() {
2585
- super();
2586
- this.kind = NODE_TYPES.WILDCARD;
2587
- }
2588
- getNextNode() {
2589
- return null;
2590
- }
2591
- }
2592
- module.exports = {
2593
- StaticNode,
2594
- ParametricNode,
2595
- WildcardNode,
2596
- NODE_TYPES
2597
- };
2598
- }, {
2599
- "./handler-storage": 15
2600
- }],
2601
- 18: [function (require, module, exports) {
2602
- 'use strict';
2603
-
2604
- const deepEqual = require('fast-deep-equal');
2605
- const httpMethodStrategy = require('./strategies/http-method');
2606
- const treeDataSymbol = Symbol('treeData');
2607
- function printObjectTree(obj) {
2608
- let parentPrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2609
- let tree = '';
2610
- const keys = Object.keys(obj);
2611
- for (let i = 0; i < keys.length; i++) {
2612
- const key = keys[i];
2613
- const value = obj[key];
2614
- const isLast = i === keys.length - 1;
2615
- const nodePrefix = isLast ? '└── ' : '├── ';
2616
- const childPrefix = isLast ? ' ' : '│ ';
2617
- const nodeData = value[treeDataSymbol] || '';
2618
- const prefixedNodeData = nodeData.split('\n').join('\n' + parentPrefix + childPrefix);
2619
- tree += parentPrefix + nodePrefix + key + prefixedNodeData + '\n';
2620
- tree += printObjectTree(value, parentPrefix + childPrefix);
2621
- }
2622
- return tree;
2623
- }
2624
- function parseFunctionName(fn) {
2625
- let fName = fn.name || '';
2626
- fName = fName.replace('bound', '').trim();
2627
- fName = (fName || 'anonymous') + '()';
2628
- return fName;
2629
- }
2630
- function parseMeta(meta) {
2631
- if (Array.isArray(meta)) return meta.map(m => parseMeta(m));
2632
- if (typeof meta === 'symbol') return meta.toString();
2633
- if (typeof meta === 'function') return parseFunctionName(meta);
2634
- return meta;
2635
- }
2636
- function getRouteMetaData(route, options) {
2637
- if (!options.includeMeta) return {};
2638
- const metaDataObject = options.buildPrettyMeta(route);
2639
- const filteredMetaData = {};
2640
- let includeMetaKeys = options.includeMeta;
2641
- if (!Array.isArray(includeMetaKeys)) {
2642
- includeMetaKeys = Reflect.ownKeys(metaDataObject);
2643
- }
2644
- for (const metaKey of includeMetaKeys) {
2645
- if (!Object.prototype.hasOwnProperty.call(metaDataObject, metaKey)) continue;
2646
- const serializedKey = metaKey.toString();
2647
- const metaValue = metaDataObject[metaKey];
2648
- if (metaValue !== undefined && metaValue !== null) {
2649
- const serializedValue = JSON.stringify(parseMeta(metaValue));
2650
- filteredMetaData[serializedKey] = serializedValue;
2651
- }
2652
- }
2653
- return filteredMetaData;
2654
- }
2655
- function serializeMetaData(metaData) {
2656
- let serializedMetaData = '';
2657
- for (const [key, value] of Object.entries(metaData)) {
2658
- serializedMetaData += "\n\u2022 (".concat(key, ") ").concat(value);
2659
- }
2660
- return serializedMetaData;
2661
- }
2662
-
2663
- // get original merged tree node route
2664
- function normalizeRoute(route) {
2665
- const constraints = _objectSpread({}, route.opts.constraints);
2666
- const method = constraints[httpMethodStrategy.name];
2667
- delete constraints[httpMethodStrategy.name];
2668
- return _objectSpread(_objectSpread({}, route), {}, {
2669
- method,
2670
- opts: {
2671
- constraints
2672
- }
2673
- });
2674
- }
2675
- function serializeRoute(route) {
2676
- let serializedRoute = " (".concat(route.method, ")");
2677
- const constraints = route.opts.constraints || {};
2678
- if (Object.keys(constraints).length !== 0) {
2679
- serializedRoute += ' ' + JSON.stringify(constraints);
2680
- }
2681
- serializedRoute += serializeMetaData(route.metaData);
2682
- return serializedRoute;
2683
- }
2684
- function mergeSimilarRoutes(routes) {
2685
- return routes.reduce((mergedRoutes, route) => {
2686
- for (const nodeRoute of mergedRoutes) {
2687
- if (deepEqual(route.opts.constraints, nodeRoute.opts.constraints) && deepEqual(route.metaData, nodeRoute.metaData)) {
2688
- nodeRoute.method += ', ' + route.method;
2689
- return mergedRoutes;
2690
- }
2691
- }
2692
- mergedRoutes.push(route);
2693
- return mergedRoutes;
2694
- }, []);
2695
- }
2696
- function serializeNode(node, prefix, options) {
2697
- let routes = node.routes;
2698
- if (options.method === undefined) {
2699
- routes = routes.map(normalizeRoute);
2700
- }
2701
- routes = routes.map(route => {
2702
- route.metaData = getRouteMetaData(route, options);
2703
- return route;
2704
- });
2705
- if (options.method === undefined) {
2706
- routes = mergeSimilarRoutes(routes);
2707
- }
2708
- return routes.map(serializeRoute).join("\n".concat(prefix));
2709
- }
2710
- function buildObjectTree(node, tree, prefix, options) {
2711
- if (node.isLeafNode || options.commonPrefix !== false) {
2712
- prefix = prefix || '(empty root node)';
2713
- tree = tree[prefix] = {};
2714
- if (node.isLeafNode) {
2715
- tree[treeDataSymbol] = serializeNode(node, prefix, options);
2716
- }
2717
- prefix = '';
2718
- }
2719
- if (node.staticChildren) {
2720
- for (const child of Object.values(node.staticChildren)) {
2721
- buildObjectTree(child, tree, prefix + child.prefix, options);
2722
- }
2723
- }
2724
- if (node.parametricChildren) {
2725
- for (const child of Object.values(node.parametricChildren)) {
2726
- const childPrefix = Array.from(child.nodePaths).join('|');
2727
- buildObjectTree(child, tree, prefix + childPrefix, options);
2728
- }
2729
- }
2730
- if (node.wildcardChild) {
2731
- buildObjectTree(node.wildcardChild, tree, '*', options);
2732
- }
2733
- }
2734
- function prettyPrintTree(root, options) {
2735
- const objectTree = {};
2736
- buildObjectTree(root, objectTree, root.prefix, options);
2737
- return printObjectTree(objectTree);
2738
- }
2739
- module.exports = {
2740
- prettyPrintTree
2741
- };
2742
- }, {
2743
- "./strategies/http-method": 21,
2744
- "fast-deep-equal": 8
2745
- }],
2746
- 19: [function (require, module, exports) {
2747
- 'use strict';
2748
-
2749
- const assert = require('assert');
2750
- function HostStorage() {
2751
- const hosts = {};
2752
- const regexHosts = [];
2753
- return {
2754
- get: host => {
2755
- const exact = hosts[host];
2756
- if (exact) {
2757
- return exact;
2758
- }
2759
- for (const regex of regexHosts) {
2760
- if (regex.host.test(host)) {
2761
- return regex.value;
2762
- }
2763
- }
2764
- },
2765
- set: (host, value) => {
2766
- if (host instanceof RegExp) {
2767
- regexHosts.push({
2768
- host,
2769
- value
2770
- });
2771
- } else {
2772
- hosts[host] = value;
2773
- }
2774
- }
2775
- };
2776
- }
2777
- module.exports = {
2778
- name: 'host',
2779
- mustMatchWhenDerived: false,
2780
- storage: HostStorage,
2781
- validate(value) {
2782
- assert(typeof value === 'string' || Object.prototype.toString.call(value) === '[object RegExp]', 'Host should be a string or a RegExp');
2783
- }
2784
- };
2785
- }, {
2786
- "assert": 1
2787
- }],
2788
- 20: [function (require, module, exports) {
2789
- 'use strict';
2790
-
2791
- const assert = require('assert');
2792
- function SemVerStore() {
2793
- if (!(this instanceof SemVerStore)) {
2794
- return new SemVerStore();
2795
- }
2796
- this.store = {};
2797
- this.maxMajor = 0;
2798
- this.maxMinors = {};
2799
- this.maxPatches = {};
2800
- }
2801
- SemVerStore.prototype.set = function (version, store) {
2802
- if (typeof version !== 'string') {
2803
- throw new TypeError('Version should be a string');
2804
- }
2805
- let [major, minor, patch] = version.split('.');
2806
- major = Number(major) || 0;
2807
- minor = Number(minor) || 0;
2808
- patch = Number(patch) || 0;
2809
- if (major >= this.maxMajor) {
2810
- this.maxMajor = major;
2811
- this.store.x = store;
2812
- this.store['*'] = store;
2813
- this.store['x.x'] = store;
2814
- this.store['x.x.x'] = store;
2815
- }
2816
- if (minor >= (this.maxMinors[major] || 0)) {
2817
- this.maxMinors[major] = minor;
2818
- this.store["".concat(major, ".x")] = store;
2819
- this.store["".concat(major, ".x.x")] = store;
2820
- }
2821
- if (patch >= (this.store["".concat(major, ".").concat(minor)] || 0)) {
2822
- this.maxPatches["".concat(major, ".").concat(minor)] = patch;
2823
- this.store["".concat(major, ".").concat(minor, ".x")] = store;
2824
- }
2825
- this.store["".concat(major, ".").concat(minor, ".").concat(patch)] = store;
2826
- return this;
2827
- };
2828
- SemVerStore.prototype.get = function (version) {
2829
- return this.store[version];
2830
- };
2831
- module.exports = {
2832
- name: 'version',
2833
- mustMatchWhenDerived: true,
2834
- storage: SemVerStore,
2835
- validate(value) {
2836
- assert(typeof value === 'string', 'Version should be a string');
2837
- }
2838
- };
2839
- }, {
2840
- "assert": 1
2841
- }],
2842
- 21: [function (require, module, exports) {
2843
- 'use strict';
2844
-
2845
- module.exports = {
2846
- name: '__fmw_internal_strategy_merged_tree_http_method__',
2847
- storage: function storage() {
2848
- const handlers = {};
2849
- return {
2850
- get: type => {
2851
- return handlers[type] || null;
2852
- },
2853
- set: (type, store) => {
2854
- handlers[type] = store;
2855
- }
2856
- };
2857
- },
2858
- deriveConstraint: req => {
2859
- /* istanbul ignore next */
2860
- return req.method;
2861
- },
2862
- mustMatchWhenDerived: true
2863
- };
2864
- }, {}],
2865
- 22: [function (require, module, exports) {
2866
- 'use strict';
2867
-
2868
- // It must spot all the chars where decodeURIComponent(x) !== decodeURI(x)
2869
- // The chars are: # $ & + , / : ; = ? @
2870
- function decodeComponentChar(highCharCode, lowCharCode) {
2871
- if (highCharCode === 50) {
2872
- if (lowCharCode === 53) return '%';
2873
- if (lowCharCode === 51) return '#';
2874
- if (lowCharCode === 52) return '$';
2875
- if (lowCharCode === 54) return '&';
2876
- if (lowCharCode === 66) return '+';
2877
- if (lowCharCode === 98) return '+';
2878
- if (lowCharCode === 67) return ',';
2879
- if (lowCharCode === 99) return ',';
2880
- if (lowCharCode === 70) return '/';
2881
- if (lowCharCode === 102) return '/';
2882
- return null;
2883
- }
2884
- if (highCharCode === 51) {
2885
- if (lowCharCode === 65) return ':';
2886
- if (lowCharCode === 97) return ':';
2887
- if (lowCharCode === 66) return ';';
2888
- if (lowCharCode === 98) return ';';
2889
- if (lowCharCode === 68) return '=';
2890
- if (lowCharCode === 100) return '=';
2891
- if (lowCharCode === 70) return '?';
2892
- if (lowCharCode === 102) return '?';
2893
- return null;
2894
- }
2895
- if (highCharCode === 52 && lowCharCode === 48) {
2896
- return '@';
2897
- }
2898
- return null;
2899
- }
2900
- function safeDecodeURI(path) {
2901
- let shouldDecode = false;
2902
- let shouldDecodeParam = false;
2903
- let querystring = '';
2904
- for (let i = 1; i < path.length; i++) {
2905
- const charCode = path.charCodeAt(i);
2906
- if (charCode === 37) {
2907
- const highCharCode = path.charCodeAt(i + 1);
2908
- const lowCharCode = path.charCodeAt(i + 2);
2909
- if (decodeComponentChar(highCharCode, lowCharCode) === null) {
2910
- shouldDecode = true;
2911
- } else {
2912
- shouldDecodeParam = true;
2913
- // %25 - encoded % char. We need to encode one more time to prevent double decoding
2914
- if (highCharCode === 50 && lowCharCode === 53) {
2915
- shouldDecode = true;
2916
- path = path.slice(0, i + 1) + '25' + path.slice(i + 1);
2917
- i += 2;
2918
- }
2919
- i += 2;
2920
- }
2921
- // Some systems do not follow RFC and separate the path and query
2922
- // string with a `;` character (code 59), e.g. `/foo;jsessionid=123456`.
2923
- // Thus, we need to split on `;` as well as `?` and `#`.
2924
- } else if (charCode === 63 || charCode === 59 || charCode === 35) {
2925
- querystring = path.slice(i + 1);
2926
- path = path.slice(0, i);
2927
- break;
2928
- }
2929
- }
2930
- const decodedPath = shouldDecode ? decodeURI(path) : path;
2931
- return {
2932
- path: decodedPath,
2933
- querystring,
2934
- shouldDecodeParam
2935
- };
2936
- }
2937
- function safeDecodeURIComponent(uriComponent) {
2938
- const startIndex = uriComponent.indexOf('%');
2939
- if (startIndex === -1) return uriComponent;
2940
- let decoded = '';
2941
- let lastIndex = startIndex;
2942
- for (let i = startIndex; i < uriComponent.length; i++) {
2943
- if (uriComponent.charCodeAt(i) === 37) {
2944
- const highCharCode = uriComponent.charCodeAt(i + 1);
2945
- const lowCharCode = uriComponent.charCodeAt(i + 2);
2946
- const decodedChar = decodeComponentChar(highCharCode, lowCharCode);
2947
- decoded += uriComponent.slice(lastIndex, i) + decodedChar;
2948
- lastIndex = i + 3;
2949
- }
2950
- }
2951
- return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex);
2952
- }
2953
- module.exports = {
2954
- safeDecodeURI,
2955
- safeDecodeURIComponent
2956
- };
2957
- }, {}],
2958
- 23: [function (require, module, exports) {
2959
- /*
2960
- object-assign
2961
- (c) Sindre Sorhus
2962
- @license MIT
2963
- */
2964
-
2965
- 'use strict';
2966
-
2967
- /* eslint-disable no-unused-vars */
2968
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
2969
- var hasOwnProperty = Object.prototype.hasOwnProperty;
2970
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
2971
- function toObject(val) {
2972
- if (val === null || val === undefined) {
2973
- throw new TypeError('Object.assign cannot be called with null or undefined');
2974
- }
2975
- return Object(val);
2976
- }
2977
- function shouldUseNative() {
2978
- try {
2979
- if (!Object.assign) {
2980
- return false;
2981
- }
2982
-
2983
- // Detect buggy property enumeration order in older V8 versions.
2984
-
2985
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
2986
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
2987
- test1[5] = 'de';
2988
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
2989
- return false;
2990
- }
2991
-
2992
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
2993
- var test2 = {};
2994
- for (var i = 0; i < 10; i++) {
2995
- test2['_' + String.fromCharCode(i)] = i;
2996
- }
2997
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
2998
- return test2[n];
2999
- });
3000
- if (order2.join('') !== '0123456789') {
3001
- return false;
3002
- }
3003
-
3004
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
3005
- var test3 = {};
3006
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
3007
- test3[letter] = letter;
3008
- });
3009
- if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
3010
- return false;
3011
- }
3012
- return true;
3013
- } catch (err) {
3014
- // We don't expect any of the above to throw, but better to be safe.
3015
- return false;
3016
- }
3017
- }
3018
- module.exports = shouldUseNative() ? Object.assign : function (target, source) {
3019
- var from;
3020
- var to = toObject(target);
3021
- var symbols;
3022
- for (var s = 1; s < arguments.length; s++) {
3023
- from = Object(arguments[s]);
3024
- for (var key in from) {
3025
- if (hasOwnProperty.call(from, key)) {
3026
- to[key] = from[key];
3027
- }
3028
- }
3029
- if (getOwnPropertySymbols) {
3030
- symbols = getOwnPropertySymbols(from);
3031
- for (var i = 0; i < symbols.length; i++) {
3032
- if (propIsEnumerable.call(from, symbols[i])) {
3033
- to[symbols[i]] = from[symbols[i]];
3034
- }
3035
- }
3036
- }
3037
- }
3038
- return to;
3039
- };
3040
- }, {}],
3041
- 24: [function (require, module, exports) {
3042
- // shim for using process in browser
3043
- var process = module.exports = {};
3044
-
3045
- // cached from whatever global is present so that test runners that stub it
3046
- // don't break things. But we need to wrap it in a try catch in case it is
3047
- // wrapped in strict mode code which doesn't define any globals. It's inside a
3048
- // function because try/catches deoptimize in certain engines.
3049
-
3050
- var cachedSetTimeout;
3051
- var cachedClearTimeout;
3052
- function defaultSetTimout() {
3053
- throw new Error('setTimeout has not been defined');
3054
- }
3055
- function defaultClearTimeout() {
3056
- throw new Error('clearTimeout has not been defined');
3057
- }
3058
- (function () {
3059
- try {
3060
- if (typeof setTimeout === 'function') {
3061
- cachedSetTimeout = setTimeout;
3062
- } else {
3063
- cachedSetTimeout = defaultSetTimout;
3064
- }
3065
- } catch (e) {
3066
- cachedSetTimeout = defaultSetTimout;
3067
- }
3068
- try {
3069
- if (typeof clearTimeout === 'function') {
3070
- cachedClearTimeout = clearTimeout;
3071
- } else {
3072
- cachedClearTimeout = defaultClearTimeout;
3073
- }
3074
- } catch (e) {
3075
- cachedClearTimeout = defaultClearTimeout;
3076
- }
3077
- })();
3078
- function runTimeout(fun) {
3079
- if (cachedSetTimeout === setTimeout) {
3080
- //normal enviroments in sane situations
3081
- return setTimeout(fun, 0);
3082
- }
3083
- // if setTimeout wasn't available but was latter defined
3084
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3085
- cachedSetTimeout = setTimeout;
3086
- return setTimeout(fun, 0);
3087
- }
3088
- try {
3089
- // when when somebody has screwed with setTimeout but no I.E. maddness
3090
- return cachedSetTimeout(fun, 0);
3091
- } catch (e) {
3092
- try {
3093
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3094
- return cachedSetTimeout.call(null, fun, 0);
3095
- } catch (e) {
3096
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
3097
- return cachedSetTimeout.call(this, fun, 0);
3098
- }
3099
- }
3100
- }
3101
- function runClearTimeout(marker) {
3102
- if (cachedClearTimeout === clearTimeout) {
3103
- //normal enviroments in sane situations
3104
- return clearTimeout(marker);
3105
- }
3106
- // if clearTimeout wasn't available but was latter defined
3107
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3108
- cachedClearTimeout = clearTimeout;
3109
- return clearTimeout(marker);
3110
- }
3111
- try {
3112
- // when when somebody has screwed with setTimeout but no I.E. maddness
3113
- return cachedClearTimeout(marker);
3114
- } catch (e) {
3115
- try {
3116
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3117
- return cachedClearTimeout.call(null, marker);
3118
- } catch (e) {
3119
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
3120
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3121
- return cachedClearTimeout.call(this, marker);
3122
- }
3123
- }
3124
- }
3125
- var queue = [];
3126
- var draining = false;
3127
- var currentQueue;
3128
- var queueIndex = -1;
3129
- function cleanUpNextTick() {
3130
- if (!draining || !currentQueue) {
3131
- return;
3132
- }
3133
- draining = false;
3134
- if (currentQueue.length) {
3135
- queue = currentQueue.concat(queue);
3136
- } else {
3137
- queueIndex = -1;
3138
- }
3139
- if (queue.length) {
3140
- drainQueue();
3141
- }
3142
- }
3143
- function drainQueue() {
3144
- if (draining) {
3145
- return;
3146
- }
3147
- var timeout = runTimeout(cleanUpNextTick);
3148
- draining = true;
3149
- var len = queue.length;
3150
- while (len) {
3151
- currentQueue = queue;
3152
- queue = [];
3153
- while (++queueIndex < len) {
3154
- if (currentQueue) {
3155
- currentQueue[queueIndex].run();
3156
- }
3157
- }
3158
- queueIndex = -1;
3159
- len = queue.length;
3160
- }
3161
- currentQueue = null;
3162
- draining = false;
3163
- runClearTimeout(timeout);
3164
- }
3165
- process.nextTick = function (fun) {
3166
- var args = new Array(arguments.length - 1);
3167
- if (arguments.length > 1) {
3168
- for (var i = 1; i < arguments.length; i++) {
3169
- args[i - 1] = arguments[i];
3170
- }
3171
- }
3172
- queue.push(new Item(fun, args));
3173
- if (queue.length === 1 && !draining) {
3174
- runTimeout(drainQueue);
3175
- }
3176
- };
3177
-
3178
- // v8 likes predictible objects
3179
- function Item(fun, array) {
3180
- this.fun = fun;
3181
- this.array = array;
3182
- }
3183
- Item.prototype.run = function () {
3184
- this.fun.apply(null, this.array);
3185
- };
3186
- process.title = 'browser';
3187
- process.browser = true;
3188
- process.env = {};
3189
- process.argv = [];
3190
- process.version = ''; // empty string to avoid regexp issues
3191
- process.versions = {};
3192
- function noop() {}
3193
- process.on = noop;
3194
- process.addListener = noop;
3195
- process.once = noop;
3196
- process.off = noop;
3197
- process.removeListener = noop;
3198
- process.removeAllListeners = noop;
3199
- process.emit = noop;
3200
- process.prependListener = noop;
3201
- process.prependOnceListener = noop;
3202
- process.listeners = function (name) {
3203
- return [];
3204
- };
3205
- process.binding = function (name) {
3206
- throw new Error('process.binding is not supported');
3207
- };
3208
- process.cwd = function () {
3209
- return '/';
3210
- };
3211
- process.chdir = function (dir) {
3212
- throw new Error('process.chdir is not supported');
3213
- };
3214
- process.umask = function () {
3215
- return 0;
3216
- };
3217
- }, {}],
3218
- 25: [function (require, module, exports) {
3219
- 'use strict';
3220
-
3221
- var parse = require('ret');
3222
- var types = parse.types;
3223
- module.exports = function (re, opts) {
3224
- if (!opts) opts = {};
3225
- var replimit = opts.limit === undefined ? 25 : opts.limit;
3226
- if (isRegExp(re)) re = re.source;else if (typeof re !== 'string') re = String(re);
3227
- try {
3228
- re = parse(re);
3229
- } catch (err) {
3230
- return false;
3231
- }
3232
- var reps = 0;
3233
- return function walk(node, starHeight) {
3234
- var i;
3235
- var ok;
3236
- var len;
3237
- if (node.type === types.REPETITION) {
3238
- starHeight++;
3239
- reps++;
3240
- if (starHeight > 1) return false;
3241
- if (reps > replimit) return false;
3242
- }
3243
- if (node.options) {
3244
- for (i = 0, len = node.options.length; i < len; i++) {
3245
- ok = walk({
3246
- stack: node.options[i]
3247
- }, starHeight);
3248
- if (!ok) return false;
3249
- }
3250
- }
3251
- var stack = node.stack || node.value && node.value.stack;
3252
- if (!stack) return true;
3253
- for (i = 0; i < stack.length; i++) {
3254
- ok = walk(stack[i], starHeight);
3255
- if (!ok) return false;
3256
- }
3257
- return true;
3258
- }(re, 0);
3259
- };
3260
- function isRegExp(x) {
3261
- return {}.toString.call(x) === '[object RegExp]';
3262
- }
3263
- }, {
3264
- "ret": 26
3265
- }],
3266
- 26: [function (require, module, exports) {
3267
- const util = require('./util');
3268
- const types = require('./types');
3269
- const sets = require('./sets');
3270
- const positions = require('./positions');
3271
- module.exports = regexpStr => {
3272
- var i = 0,
3273
- l,
3274
- c,
3275
- start = {
3276
- type: types.ROOT,
3277
- stack: []
3278
- },
3279
- // Keep track of last clause/group and stack.
3280
- lastGroup = start,
3281
- last = start.stack,
3282
- groupStack = [];
3283
- var repeatErr = i => {
3284
- util.error(regexpStr, "Nothing to repeat at column ".concat(i - 1));
3285
- };
3286
-
3287
- // Decode a few escaped characters.
3288
- var str = util.strToChars(regexpStr);
3289
- l = str.length;
3290
-
3291
- // Iterate through each character in string.
3292
- while (i < l) {
3293
- c = str[i++];
3294
- switch (c) {
3295
- // Handle escaped characters, inclues a few sets.
3296
- case '\\':
3297
- c = str[i++];
3298
- switch (c) {
3299
- case 'b':
3300
- last.push(positions.wordBoundary());
3301
- break;
3302
- case 'B':
3303
- last.push(positions.nonWordBoundary());
3304
- break;
3305
- case 'w':
3306
- last.push(sets.words());
3307
- break;
3308
- case 'W':
3309
- last.push(sets.notWords());
3310
- break;
3311
- case 'd':
3312
- last.push(sets.ints());
3313
- break;
3314
- case 'D':
3315
- last.push(sets.notInts());
3316
- break;
3317
- case 's':
3318
- last.push(sets.whitespace());
3319
- break;
3320
- case 'S':
3321
- last.push(sets.notWhitespace());
3322
- break;
3323
- default:
3324
- // Check if c is integer.
3325
- // In which case it's a reference.
3326
- if (/\d/.test(c)) {
3327
- last.push({
3328
- type: types.REFERENCE,
3329
- value: parseInt(c, 10)
3330
- });
3331
-
3332
- // Escaped character.
3333
- } else {
3334
- last.push({
3335
- type: types.CHAR,
3336
- value: c.charCodeAt(0)
3337
- });
3338
- }
3339
- }
3340
- break;
3341
-
3342
- // Positionals.
3343
- case '^':
3344
- last.push(positions.begin());
3345
- break;
3346
- case '$':
3347
- last.push(positions.end());
3348
- break;
3349
-
3350
- // Handle custom sets.
3351
- case '[':
3352
- // Check if this class is 'anti' i.e. [^abc].
3353
- var not;
3354
- if (str[i] === '^') {
3355
- not = true;
3356
- i++;
3357
- } else {
3358
- not = false;
3359
- }
3360
-
3361
- // Get all the characters in class.
3362
- var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
3363
-
3364
- // Increase index by length of class.
3365
- i += classTokens[1];
3366
- last.push({
3367
- type: types.SET,
3368
- set: classTokens[0],
3369
- not
3370
- });
3371
- break;
3372
-
3373
- // Class of any character except \n.
3374
- case '.':
3375
- last.push(sets.anyChar());
3376
- break;
3377
-
3378
- // Push group onto stack.
3379
- case '(':
3380
- // Create group.
3381
- var group = {
3382
- type: types.GROUP,
3383
- stack: [],
3384
- remember: true
3385
- };
3386
- c = str[i];
3387
-
3388
- // If if this is a special kind of group.
3389
- if (c === '?') {
3390
- c = str[i + 1];
3391
- i += 2;
3392
-
3393
- // Match if followed by.
3394
- if (c === '=') {
3395
- group.followedBy = true;
3396
-
3397
- // Match if not followed by.
3398
- } else if (c === '!') {
3399
- group.notFollowedBy = true;
3400
- } else if (c !== ':') {
3401
- util.error(regexpStr, "Invalid group, character '".concat(c, "'") + " after '?' at column ".concat(i - 1));
3402
- }
3403
- group.remember = false;
3404
- }
3405
-
3406
- // Insert subgroup into current group stack.
3407
- last.push(group);
3408
-
3409
- // Remember the current group for when the group closes.
3410
- groupStack.push(lastGroup);
3411
-
3412
- // Make this new group the current group.
3413
- lastGroup = group;
3414
- last = group.stack;
3415
- break;
3416
-
3417
- // Pop group out of stack.
3418
- case ')':
3419
- if (groupStack.length === 0) {
3420
- util.error(regexpStr, "Unmatched ) at column ".concat(i - 1));
3421
- }
3422
- lastGroup = groupStack.pop();
3423
-
3424
- // Check if this group has a PIPE.
3425
- // To get back the correct last stack.
3426
- last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
3427
- break;
3428
-
3429
- // Use pipe character to give more choices.
3430
- case '|':
3431
- // Create array where options are if this is the first PIPE
3432
- // in this clause.
3433
- if (!lastGroup.options) {
3434
- lastGroup.options = [lastGroup.stack];
3435
- delete lastGroup.stack;
3436
- }
3437
-
3438
- // Create a new stack and add to options for rest of clause.
3439
- var stack = [];
3440
- lastGroup.options.push(stack);
3441
- last = stack;
3442
- break;
3443
-
3444
- // Repetition.
3445
- // For every repetition, remove last element from last stack
3446
- // then insert back a RANGE object.
3447
- // This design is chosen because there could be more than
3448
- // one repetition symbols in a regex i.e. `a?+{2,3}`.
3449
- case '{':
3450
- var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)),
3451
- min,
3452
- max;
3453
- if (rs !== null) {
3454
- if (last.length === 0) {
3455
- repeatErr(i);
3456
- }
3457
- min = parseInt(rs[1], 10);
3458
- max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
3459
- i += rs[0].length;
3460
- last.push({
3461
- type: types.REPETITION,
3462
- min,
3463
- max,
3464
- value: last.pop()
3465
- });
3466
- } else {
3467
- last.push({
3468
- type: types.CHAR,
3469
- value: 123
3470
- });
3471
- }
3472
- break;
3473
- case '?':
3474
- if (last.length === 0) {
3475
- repeatErr(i);
3476
- }
3477
- last.push({
3478
- type: types.REPETITION,
3479
- min: 0,
3480
- max: 1,
3481
- value: last.pop()
3482
- });
3483
- break;
3484
- case '+':
3485
- if (last.length === 0) {
3486
- repeatErr(i);
3487
- }
3488
- last.push({
3489
- type: types.REPETITION,
3490
- min: 1,
3491
- max: Infinity,
3492
- value: last.pop()
3493
- });
3494
- break;
3495
- case '*':
3496
- if (last.length === 0) {
3497
- repeatErr(i);
3498
- }
3499
- last.push({
3500
- type: types.REPETITION,
3501
- min: 0,
3502
- max: Infinity,
3503
- value: last.pop()
3504
- });
3505
- break;
3506
-
3507
- // Default is a character that is not `\[](){}?+*^$`.
3508
- default:
3509
- last.push({
3510
- type: types.CHAR,
3511
- value: c.charCodeAt(0)
3512
- });
3513
- }
3514
- }
3515
-
3516
- // Check if any groups have not been closed.
3517
- if (groupStack.length !== 0) {
3518
- util.error(regexpStr, 'Unterminated group');
3519
- }
3520
- return start;
3521
- };
3522
- module.exports.types = types;
3523
- }, {
3524
- "./positions": 27,
3525
- "./sets": 28,
3526
- "./types": 29,
3527
- "./util": 30
3528
- }],
3529
- 27: [function (require, module, exports) {
3530
- const types = require('./types');
3531
- exports.wordBoundary = () => ({
3532
- type: types.POSITION,
3533
- value: 'b'
3534
- });
3535
- exports.nonWordBoundary = () => ({
3536
- type: types.POSITION,
3537
- value: 'B'
3538
- });
3539
- exports.begin = () => ({
3540
- type: types.POSITION,
3541
- value: '^'
3542
- });
3543
- exports.end = () => ({
3544
- type: types.POSITION,
3545
- value: '$'
3546
- });
3547
- }, {
3548
- "./types": 29
3549
- }],
3550
- 28: [function (require, module, exports) {
3551
- const types = require('./types');
3552
- const INTS = () => [{
3553
- type: types.RANGE,
3554
- from: 48,
3555
- to: 57
3556
- }];
3557
- const WORDS = () => {
3558
- return [{
3559
- type: types.CHAR,
3560
- value: 95
3561
- }, {
3562
- type: types.RANGE,
3563
- from: 97,
3564
- to: 122
3565
- }, {
3566
- type: types.RANGE,
3567
- from: 65,
3568
- to: 90
3569
- }].concat(INTS());
3570
- };
3571
- const WHITESPACE = () => {
3572
- return [{
3573
- type: types.CHAR,
3574
- value: 9
3575
- }, {
3576
- type: types.CHAR,
3577
- value: 10
3578
- }, {
3579
- type: types.CHAR,
3580
- value: 11
3581
- }, {
3582
- type: types.CHAR,
3583
- value: 12
3584
- }, {
3585
- type: types.CHAR,
3586
- value: 13
3587
- }, {
3588
- type: types.CHAR,
3589
- value: 32
3590
- }, {
3591
- type: types.CHAR,
3592
- value: 160
3593
- }, {
3594
- type: types.CHAR,
3595
- value: 5760
3596
- }, {
3597
- type: types.RANGE,
3598
- from: 8192,
3599
- to: 8202
3600
- }, {
3601
- type: types.CHAR,
3602
- value: 8232
3603
- }, {
3604
- type: types.CHAR,
3605
- value: 8233
3606
- }, {
3607
- type: types.CHAR,
3608
- value: 8239
3609
- }, {
3610
- type: types.CHAR,
3611
- value: 8287
3612
- }, {
3613
- type: types.CHAR,
3614
- value: 12288
3615
- }, {
3616
- type: types.CHAR,
3617
- value: 65279
3618
- }];
3619
- };
3620
- const NOTANYCHAR = () => {
3621
- return [{
3622
- type: types.CHAR,
3623
- value: 10
3624
- }, {
3625
- type: types.CHAR,
3626
- value: 13
3627
- }, {
3628
- type: types.CHAR,
3629
- value: 8232
3630
- }, {
3631
- type: types.CHAR,
3632
- value: 8233
3633
- }];
3634
- };
3635
-
3636
- // Predefined class objects.
3637
- exports.words = () => ({
3638
- type: types.SET,
3639
- set: WORDS(),
3640
- not: false
3641
- });
3642
- exports.notWords = () => ({
3643
- type: types.SET,
3644
- set: WORDS(),
3645
- not: true
3646
- });
3647
- exports.ints = () => ({
3648
- type: types.SET,
3649
- set: INTS(),
3650
- not: false
3651
- });
3652
- exports.notInts = () => ({
3653
- type: types.SET,
3654
- set: INTS(),
3655
- not: true
3656
- });
3657
- exports.whitespace = () => ({
3658
- type: types.SET,
3659
- set: WHITESPACE(),
3660
- not: false
3661
- });
3662
- exports.notWhitespace = () => ({
3663
- type: types.SET,
3664
- set: WHITESPACE(),
3665
- not: true
3666
- });
3667
- exports.anyChar = () => ({
3668
- type: types.SET,
3669
- set: NOTANYCHAR(),
3670
- not: true
3671
- });
3672
- }, {
3673
- "./types": 29
3674
- }],
3675
- 29: [function (require, module, exports) {
3676
- module.exports = {
3677
- ROOT: 0,
3678
- GROUP: 1,
3679
- POSITION: 2,
3680
- SET: 3,
3681
- RANGE: 4,
3682
- REPETITION: 5,
3683
- REFERENCE: 6,
3684
- CHAR: 7
3685
- };
3686
- }, {}],
3687
- 30: [function (require, module, exports) {
3688
- const types = require('./types');
3689
- const sets = require('./sets');
3690
- const CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
3691
- const SLSH = {
3692
- '0': 0,
3693
- 't': 9,
3694
- 'n': 10,
3695
- 'v': 11,
3696
- 'f': 12,
3697
- 'r': 13
3698
- };
3699
-
3700
- /**
3701
- * Finds character representations in str and convert all to
3702
- * their respective characters
3703
- *
3704
- * @param {String} str
3705
- * @return {String}
3706
- */
3707
- exports.strToChars = function (str) {
3708
- /* jshint maxlen: false */
3709
- var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;
3710
- str = str.replace(chars_regex, function (s, b, lbs, a16, b16, c8, dctrl, eslsh) {
3711
- if (lbs) {
3712
- return s;
3713
- }
3714
- var code = b ? 8 : a16 ? parseInt(a16, 16) : b16 ? parseInt(b16, 16) : c8 ? parseInt(c8, 8) : dctrl ? CTRL.indexOf(dctrl) : SLSH[eslsh];
3715
- var c = String.fromCharCode(code);
3716
-
3717
- // Escape special regex characters.
3718
- if (/[[\]{}^$.|?*+()]/.test(c)) {
3719
- c = '\\' + c;
3720
- }
3721
- return c;
3722
- });
3723
- return str;
3724
- };
3725
-
3726
- /**
3727
- * turns class into tokens
3728
- * reads str until it encounters a ] not preceeded by a \
3729
- *
3730
- * @param {String} str
3731
- * @param {String} regexpStr
3732
- * @return {Array.<Array.<Object>, Number>}
3733
- */
3734
- exports.tokenizeClass = (str, regexpStr) => {
3735
- /* jshint maxlen: false */
3736
- var tokens = [];
3737
- var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?([^])/g;
3738
- var rs, c;
3739
- while ((rs = regexp.exec(str)) != null) {
3740
- if (rs[1]) {
3741
- tokens.push(sets.words());
3742
- } else if (rs[2]) {
3743
- tokens.push(sets.ints());
3744
- } else if (rs[3]) {
3745
- tokens.push(sets.whitespace());
3746
- } else if (rs[4]) {
3747
- tokens.push(sets.notWords());
3748
- } else if (rs[5]) {
3749
- tokens.push(sets.notInts());
3750
- } else if (rs[6]) {
3751
- tokens.push(sets.notWhitespace());
3752
- } else if (rs[7]) {
3753
- tokens.push({
3754
- type: types.RANGE,
3755
- from: (rs[8] || rs[9]).charCodeAt(0),
3756
- to: rs[10].charCodeAt(0)
3757
- });
3758
- } else if (c = rs[12]) {
3759
- tokens.push({
3760
- type: types.CHAR,
3761
- value: c.charCodeAt(0)
3762
- });
3763
- } else {
3764
- return [tokens, regexp.lastIndex];
3765
- }
3766
- }
3767
- exports.error(regexpStr, 'Unterminated character class');
3768
- };
3769
-
3770
- /**
3771
- * Shortcut to throw errors.
3772
- *
3773
- * @param {String} regexp
3774
- * @param {String} msg
3775
- */
3776
- exports.error = (regexp, msg) => {
3777
- throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
3778
- };
3779
- }, {
3780
- "./sets": 28,
3781
- "./types": 29
3782
- }],
3783
- 31: [function (require, module, exports) {
3784
- // Simple default configuration for application, when none is provided
3785
-
3786
- module.exports = {
3787
- "Product": "Unnamed_Service",
3788
- "ProductVersion": "0.0.1",
3789
- "ServicePort": 8080
3790
- };
3791
- }, {}],
3792
- 32: [function (require, module, exports) {
3793
- /**
3794
- * Default Service Server
3795
- */
3796
- module.exports = require('./Orator-ServiceServer-IPC.js');
3797
- }, {
3798
- "./Orator-ServiceServer-IPC.js": 35
3799
- }],
3800
- 33: [function (require, module, exports) {
3801
- const libFableServiceProviderBase = require('fable-serviceproviderbase');
3802
- class OratorServiceServerBase extends libFableServiceProviderBase {
3803
- constructor(pFable, pOptions, pServiceHash) {
3804
- super(pFable, pOptions, pServiceHash);
3805
- this.serviceType = 'OratorServiceServer';
3806
- this.ServiceServerType = 'Base';
3807
- this.Name = this.fable.settings.Product;
3808
- this.URL = 'BASE_SERVICE_SERVER';
3809
- this.Port = this.options.ServicePort;
3810
- this.Active = false;
3811
- }
3812
-
3813
- /*
3814
- * Service Lifecycle Functions
3815
- *************************************************************************/
3816
- listen(pPort, fCallback) {
3817
- // Sometimes, listen does not listen on network calls.
3818
- this.Active = true;
3819
- return fCallback();
3820
- }
3821
- close(fCallback) {
3822
- this.Active = false;
3823
- return fCallback();
3824
- }
3825
- /*************************************************************************
3826
- * End of Service Lifecycle Functions
3827
- */
3828
-
3829
- /*
3830
- * Content parsing functions
3831
- *************************************************************************/
3832
- bodyParser(pOptions) {
3833
- return (pRequest, pResponse, fNext) => {
3834
- fNext();
3835
- };
3836
- }
3837
- /*************************************************************************
3838
- * End of Service Lifecycle Functions
3839
- */
3840
-
3841
- /*
3842
- * Service Route Creation Functions
3843
- *
3844
- * These base functions provide basic validation for the routes, but don't actually
3845
- * do anything with them. The design intent here is to allow derived classes to call
3846
- * these functions to validate that they conform to expected standards.
3847
- *
3848
- * Something like:
3849
- get (pRoute, ...fRouteProcessingFunctions)
3850
- {
3851
- if (!super.get(pRoute, ...fRouteProcessingFunctions))
3852
- {
3853
- this.log.error(`Restify provider failed to map route [${pRoute}]!`);
3854
- return false;
3855
- }
3856
- //...now we can do our actual get mapping function!....
3857
- }
3858
- * This pattern and calling super is totally optional, obviously.
3859
- *************************************************************************/
3860
- use(fHandlerFunction) {
3861
- if (typeof fHandlerFunction != 'function') {
3862
- this.log.error("Orator USE global handler mapping failed -- parameter was expected to be a function with prototype function(Request, Response, Next) but type was ".concat(typeof fHandlerFunction, " instead of a string."));
3863
- return false;
3864
- }
3865
- return true;
3866
- }
3867
- doGet(pRoute) {
3868
- return true;
3869
- }
3870
- get(pRoute) {
3871
- if (typeof pRoute != 'string') {
3872
- this.log.error("Orator GET Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3873
- return false;
3874
- }
3875
- for (var _len = arguments.length, fRouteProcessingFunctions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3876
- fRouteProcessingFunctions[_key - 1] = arguments[_key];
3877
- }
3878
- return this.doGet(pRoute, ...fRouteProcessingFunctions);
3879
- }
3880
- getWithBodyParser(pRoute) {
3881
- for (var _len2 = arguments.length, fRouteProcessingFunctions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3882
- fRouteProcessingFunctions[_key2 - 1] = arguments[_key2];
3883
- }
3884
- return this.get(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3885
- }
3886
- doPut(pRoute) {
3887
- return true;
3888
- }
3889
- put(pRoute) {
3890
- if (typeof pRoute != 'string') {
3891
- this.log.error("Orator PUT Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3892
- return false;
3893
- }
3894
- for (var _len3 = arguments.length, fRouteProcessingFunctions = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
3895
- fRouteProcessingFunctions[_key3 - 1] = arguments[_key3];
3896
- }
3897
- return this.doPut(pRoute, ...fRouteProcessingFunctions);
3898
- }
3899
- putWithBodyParser(pRoute) {
3900
- for (var _len4 = arguments.length, fRouteProcessingFunctions = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
3901
- fRouteProcessingFunctions[_key4 - 1] = arguments[_key4];
3902
- }
3903
- return this.put(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3904
- }
3905
- doPost(pRoute) {
3906
- return true;
3907
- }
3908
- post(pRoute) {
3909
- if (typeof pRoute != 'string') {
3910
- this.log.error("Orator POST Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3911
- return false;
3912
- }
3913
- for (var _len5 = arguments.length, fRouteProcessingFunctions = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
3914
- fRouteProcessingFunctions[_key5 - 1] = arguments[_key5];
3915
- }
3916
- return this.doPost(pRoute, ...fRouteProcessingFunctions);
3917
- }
3918
- postWithBodyParser(pRoute) {
3919
- for (var _len6 = arguments.length, fRouteProcessingFunctions = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
3920
- fRouteProcessingFunctions[_key6 - 1] = arguments[_key6];
3921
- }
3922
- return this.post(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3923
- }
3924
- doDel(pRoute) {
3925
- return true;
3926
- }
3927
- del(pRoute) {
3928
- if (typeof pRoute != 'string') {
3929
- this.log.error("Orator DEL Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3930
- return false;
3931
- }
3932
- for (var _len7 = arguments.length, fRouteProcessingFunctions = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
3933
- fRouteProcessingFunctions[_key7 - 1] = arguments[_key7];
3934
- }
3935
- return this.doDel(pRoute, ...fRouteProcessingFunctions);
3936
- }
3937
- delWithBodyParser(pRoute) {
3938
- for (var _len8 = arguments.length, fRouteProcessingFunctions = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) {
3939
- fRouteProcessingFunctions[_key8 - 1] = arguments[_key8];
3940
- }
3941
- return this.del(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3942
- }
3943
- doPatch(pRoute) {
3944
- return true;
3945
- }
3946
- patch(pRoute) {
3947
- if (typeof pRoute != 'string') {
3948
- this.log.error("Orator PATCH Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3949
- return false;
3950
- }
3951
- for (var _len9 = arguments.length, fRouteProcessingFunctions = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
3952
- fRouteProcessingFunctions[_key9 - 1] = arguments[_key9];
3953
- }
3954
- return this.doPatch(pRoute, ...fRouteProcessingFunctions);
3955
- }
3956
- patchWithBodyParser(pRoute) {
3957
- for (var _len10 = arguments.length, fRouteProcessingFunctions = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {
3958
- fRouteProcessingFunctions[_key10 - 1] = arguments[_key10];
3959
- }
3960
- return this.patch(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3961
- }
3962
- doOpts(pRoute) {
3963
- return true;
3964
- }
3965
- opts(pRoute) {
3966
- if (typeof pRoute != 'string') {
3967
- this.log.error("Orator OPTS Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3968
- return false;
3969
- }
3970
- for (var _len11 = arguments.length, fRouteProcessingFunctions = new Array(_len11 > 1 ? _len11 - 1 : 0), _key11 = 1; _key11 < _len11; _key11++) {
3971
- fRouteProcessingFunctions[_key11 - 1] = arguments[_key11];
3972
- }
3973
- return this.doOpts(pRoute, ...fRouteProcessingFunctions);
3974
- }
3975
- optsWithBodyParser(pRoute) {
3976
- for (var _len12 = arguments.length, fRouteProcessingFunctions = new Array(_len12 > 1 ? _len12 - 1 : 0), _key12 = 1; _key12 < _len12; _key12++) {
3977
- fRouteProcessingFunctions[_key12 - 1] = arguments[_key12];
3978
- }
3979
- return this.opts(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3980
- }
3981
- doHead(pRoute) {
3982
- return true;
3983
- }
3984
- head(pRoute) {
3985
- if (typeof pRoute != 'string') {
3986
- this.log.error("Orator HEAD Route mapping failed -- route parameter was ".concat(typeof pRoute, " instead of a string."));
3987
- return false;
3988
- }
3989
- return true;
3990
- }
3991
- headWithBodyParser(pRoute) {
3992
- for (var _len13 = arguments.length, fRouteProcessingFunctions = new Array(_len13 > 1 ? _len13 - 1 : 0), _key13 = 1; _key13 < _len13; _key13++) {
3993
- fRouteProcessingFunctions[_key13 - 1] = arguments[_key13];
3994
- }
3995
- return this.head(pRoute, this.bodyParser(), ...fRouteProcessingFunctions);
3996
- }
3997
- /*************************************************************************
3998
- * End of Service Route Creation Functions
3999
- */
4000
-
4001
- // Programmatically invoke a route
4002
- invoke(pMethod, pRoute, pData, fCallback) {
4003
- // The base class version of this does nothing
4004
- this.log.debug("Orator invoke called for route [".concat(pRoute, "] and landed on the base class; the service provider likely does not implement programmatic invoke capabilities."), pData);
4005
- return false;
4006
- }
4007
- }
4008
- module.exports = OratorServiceServerBase;
4009
- }, {
4010
- "fable-serviceproviderbase": 6
4011
- }],
4012
- 34: [function (require, module, exports) {
4013
- class OratorServiceServerIPCSynthesizedResponse {
4014
- constructor(pHandler, pLog, pRequestGUID) {
4015
- this.log = pLog;
4016
- if (pHandler.hasOwnProperty('params')) {
4017
- this.params = pHandler.params;
4018
- } else {
4019
- this.params = {};
4020
- }
4021
- if (pHandler.hasOwnProperty('searchParams')) {
4022
- this.searchParams = pHandler.searchParams;
4023
- } else {
4024
- this.searchParams = {};
4025
- }
4026
- this.requestGUID = pRequestGUID;
4027
- this.responseData = null;
4028
- this.responseStatus = -1;
4029
- }
4030
- send(pData) {
4031
- if (typeof pData == 'string') {
4032
- // This is a string! Append it to the responsedata.
4033
- if (this.responseData === null) {
4034
- this.responseData = pData;
4035
- return true;
4036
- } else if (typeof this.responseData == 'string') {
4037
- this.responseData = this.responseData + pData;
4038
- return true;
4039
- } else {
4040
- this.log("Request ".concat(this.requestGUID, " has tried to send() a string value after send()ing data type ").concat(typeof this.responseData, "."), pData);
4041
- return false;
4042
- }
4043
- } else if (typeof pData == 'object') {
4044
- if (this.responseData === null) {
4045
- this.responseData = JSON.stringify(pData);
4046
- return true;
4047
- } else if (typeof this.responseData == 'string') {
4048
- // TODO: Discuss best way to handle this / if to handle this
4049
- this.responseData += this.responseData + JSON.stringify(pData);
4050
- return true;
4051
- } else {
4052
- this.log("Request ".concat(this.requestGUID, " has tried to send() an object value to be auto stringified after send()ing data type ").concat(typeof this.responseData, "."), pData);
4053
- return false;
4054
- }
4055
- }
4056
- }
4057
- }
4058
- module.exports = OratorServiceServerIPCSynthesizedResponse;
4059
- }, {}],
4060
- 35: [function (require, module, exports) {
4061
- const libOratorServiceServerBase = require('./Orator-ServiceServer-Base.js');
4062
-
4063
- // A synthesized response object, for simple IPC.
4064
- const libOratorServiceServerIPCSynthesizedResponse = require('./Orator-ServiceServer-IPC-SynthesizedResponse.js');
4065
- // A simple constrainer for the find-my-way router since we aren't using any kind of headers to pass version or host
4066
- //const libOratorServiceServerIPCCustomConstrainer = require('./Orator-ServiceServer-IPC-RouterConstrainer.js');
4067
-
4068
- // This library is the default router for our services
4069
- const libFindMyWay = require('find-my-way');
4070
- class OratorServiceServerIPC extends libOratorServiceServerBase {
4071
- constructor(pFable, pOptions, pServiceHash) {
4072
- super(pFable, pOptions, pServiceHash);
4073
- this.router = libFindMyWay(this.options);
4074
- //this.router.addConstraintStrategy(libOratorServiceServerIPCCustomConstrainer);
4075
-
4076
- this.ServiceServerType = 'IPC';
4077
- this.URL = 'IPC';
4078
- this.Port = 0;
4079
- this.preBehaviorFunctions = [];
4080
- this.behaviorMap = {};
4081
- this.postBehaviorFunctions = [];
4082
- }
4083
- use(fHandlerFunction) {
4084
- return this.addPreBehaviorFunction(fHandlerFunction);
4085
- }
4086
- addPreBehaviorFunction(fHandlerFunction) {
4087
- if (!super.use(fHandlerFunction)) {
4088
- this.log.error("IPC provider failed to map USE handler function!");
4089
- return false;
4090
- }
4091
- this.preBehaviorFunctions.push(fHandlerFunction);
4092
- return true;
4093
- }
4094
- executePreBehaviorFunctions(pRequest, pResponse, fNext) {
4095
- let tmpAnticipate = this.fable.serviceManager.instantiateServiceProviderWithoutRegistration('Anticipate');
4096
- for (let i = 0; i < this.preBehaviorFunctions.length; i++) {
4097
- let tmpPreBehaviorFunction = this.preBehaviorFunctions[i];
4098
- tmpAnticipate.anticipate(fStageComplete => {
4099
- return tmpPreBehaviorFunction(pRequest, pResponse, fStageComplete);
4100
- });
4101
- }
4102
- tmpAnticipate.wait(pError => {
4103
- if (pError) {
4104
- this.log.error("IPC Provider preBehaviorFunction ".concat(pFunctionIndex, " failed with error: ").concat(pError), pError);
4105
- }
4106
- return fNext(pError);
4107
- });
4108
- }
4109
- addPostBehaviorFunction(fHandlerFunction) {
4110
- if (!super.use(fHandlerFunction)) {
4111
- this.log.error("IPC provider failed to map USE handler function!");
4112
- return false;
4113
- }
4114
- this.postBehaviorFunctions.push(fHandlerFunction);
4115
- return true;
4116
- }
4117
- executePostBehaviorFunctions(pRequest, pResponse, fNext) {
4118
- let tmpAnticipate = this.fable.serviceManager.instantiateServiceProviderWithoutRegistration('Anticipate');
4119
- for (let i = 0; i < this.postBehaviorFunctions.length; i++) {
4120
- let tmpPostBehaviorFunction = this.postBehaviorFunctions[i];
4121
- tmpAnticipate.anticipate(fStageComplete => {
4122
- return tmpPostBehaviorFunction(pRequest, pResponse, fStageComplete);
4123
- });
4124
- }
4125
- tmpAnticipate.wait(pError => {
4126
- if (pError) {
4127
- this.log.error("IPC Provider postBehaviorFunction ".concat(pFunctionIndex, " failed with error: ").concat(pError), pError);
4128
- }
4129
- return fNext(pError);
4130
- });
4131
- }
4132
-
4133
- /*
4134
- * Service Route Creation Functions
4135
- *
4136
- * These base functions provide basic validation for the routes, but don't actually
4137
- * do anything with them. The design intent here is to allow derived classes to call
4138
- * these functions to validate that they conform to expected standards.
4139
- *
4140
- * Something like:
4141
- get (pRoute, ...fRouteProcessingFunctions)
4142
- {
4143
- //...now we can do our actual get mapping function!....
4144
- }
4145
- * This pattern and calling super is totally optional, obviously.
4146
- *************************************************************************/
4147
- addRouteProcessor(pMethod, pRoute, pRouteFunctionArray) {
4148
- // We have a constrainer on IPC so we can control channels eventually, if we like.
4149
- // For now it just makes sure it was added with an IPC service server.
4150
- this.router.on(pMethod, pRoute, this.buildFindMyWayHandler(pRouteFunctionArray));
4151
- return true;
4152
- }
4153
- buildFindMyWayHandler(pRouteFunctionArray) {
4154
- let tmpRouteFunctionArray = pRouteFunctionArray;
4155
- return (pRequest, pResponse, pData) => {
4156
- let tmpAnticipate = this.fable.serviceManager.instantiateServiceProviderWithoutRegistration('Anticipate');
4157
- tmpAnticipate.anticipate(fNext => {
4158
- return this.executePreBehaviorFunctions(pRequest, pResponse, fNext);
4159
- });
4160
- for (let i = 0; i < tmpRouteFunctionArray.length; i++) {
4161
- let tmpRouteFunction = tmpRouteFunctionArray[i];
4162
- tmpAnticipate.anticipate(fNext => {
4163
- return tmpRouteFunction(pRequest, pResponse, fNext);
4164
- });
4165
- }
4166
- tmpAnticipate.anticipate(fStageComplete => {
4167
- return this.executePostBehaviorFunctions(pRequest, pResponse, fStageComplete);
4168
- });
4169
- return new Promise((fResolve, fReject) => {
4170
- tmpAnticipate.wait(pBehaviorFunctionError => {
4171
- if (pBehaviorFunctionError) {
4172
- this.log.error("IPC Provider behavior function ".concat(pFunctionIndex, " failed with error: ").concat(pBehaviorFunctionError), pBehaviorFunctionError);
4173
- return fReject(pBehaviorFunctionError);
4174
- }
4175
- return fResolve();
4176
- });
4177
- });
4178
- };
4179
- }
4180
-
4181
- // This is the virtualized "body parser"
4182
- bodyParser() {
4183
- return (pRequest, pResponse, fNext) => {
4184
- return fNext();
4185
- };
4186
- }
4187
- doGet(pRoute) {
4188
- for (var _len14 = arguments.length, fRouteProcessingFunctions = new Array(_len14 > 1 ? _len14 - 1 : 0), _key14 = 1; _key14 < _len14; _key14++) {
4189
- fRouteProcessingFunctions[_key14 - 1] = arguments[_key14];
4190
- }
4191
- return this.addRouteProcessor('GET', pRoute, Array.from(fRouteProcessingFunctions));
4192
- }
4193
- doPut(pRoute) {
4194
- for (var _len15 = arguments.length, fRouteProcessingFunctions = new Array(_len15 > 1 ? _len15 - 1 : 0), _key15 = 1; _key15 < _len15; _key15++) {
4195
- fRouteProcessingFunctions[_key15 - 1] = arguments[_key15];
4196
- }
4197
- return this.addRouteProcessor('PUT', pRoute, Array.from(fRouteProcessingFunctions));
4198
- }
4199
- doPost(pRoute) {
4200
- for (var _len16 = arguments.length, fRouteProcessingFunctions = new Array(_len16 > 1 ? _len16 - 1 : 0), _key16 = 1; _key16 < _len16; _key16++) {
4201
- fRouteProcessingFunctions[_key16 - 1] = arguments[_key16];
4202
- }
4203
- return this.addRouteProcessor('POST', pRoute, Array.from(fRouteProcessingFunctions));
4204
- }
4205
- doDel(pRoute) {
4206
- for (var _len17 = arguments.length, fRouteProcessingFunctions = new Array(_len17 > 1 ? _len17 - 1 : 0), _key17 = 1; _key17 < _len17; _key17++) {
4207
- fRouteProcessingFunctions[_key17 - 1] = arguments[_key17];
4208
- }
4209
- return this.addRouteProcessor('DELETE', pRoute, Array.from(fRouteProcessingFunctions));
4210
- }
4211
- doPatch(pRoute) {
4212
- for (var _len18 = arguments.length, fRouteProcessingFunctions = new Array(_len18 > 1 ? _len18 - 1 : 0), _key18 = 1; _key18 < _len18; _key18++) {
4213
- fRouteProcessingFunctions[_key18 - 1] = arguments[_key18];
4214
- }
4215
- return this.addRouteProcessor('PATCH', pRoute, Array.from(fRouteProcessingFunctions));
4216
- }
4217
- doOpts(pRoute) {
4218
- for (var _len19 = arguments.length, fRouteProcessingFunctions = new Array(_len19 > 1 ? _len19 - 1 : 0), _key19 = 1; _key19 < _len19; _key19++) {
4219
- fRouteProcessingFunctions[_key19 - 1] = arguments[_key19];
4220
- }
4221
- return this.addRouteProcessor('OPTIONS', pRoute, Array.from(fRouteProcessingFunctions));
4222
- }
4223
- doHead(pRoute) {
4224
- for (var _len20 = arguments.length, fRouteProcessingFunctions = new Array(_len20 > 1 ? _len20 - 1 : 0), _key20 = 1; _key20 < _len20; _key20++) {
4225
- fRouteProcessingFunctions[_key20 - 1] = arguments[_key20];
4226
- }
4227
- return this.addRouteProcessor('HEAD', pRoute, Array.from(fRouteProcessingFunctions));
4228
- }
4229
- /*************************************************************************
4230
- * End of Service Route Creation Functions
4231
- */
4232
-
4233
- // Programmatically invoke a route
4234
- invoke(pMethod, pRoute, pData, fCallback) {
4235
- // If the data is skipped and a callback is parameter 3, do the right thing
4236
- let tmpCallback = typeof fCallback == 'function' ? fCallback : typeof pData == 'function' ? pData : false;
4237
- if (!tmpCallback) {
4238
- throw new Error("IPC Provider invoke() called without a callback function.");
4239
- }
4240
-
4241
- // Create a bare minimum request object for IPC to pass to our router
4242
- let tmpRequest = {
4243
- method: pMethod,
4244
- url: pRoute,
4245
- guid: this.fable.getUUID()
4246
- };
4247
-
4248
- // For now, dealing with no handler constraints.
4249
- let tmpHandler = this.router.find(tmpRequest.method, tmpRequest.url);
4250
-
4251
- // Create a container for the IPC response data to be aggregated to from send() methodds
4252
- let tmpSynthesizedResponseData = new libOratorServiceServerIPCSynthesizedResponse(tmpHandler, this.log, tmpRequest.guid);
4253
-
4254
- // Map parsed params back to the request object
4255
- tmpRequest.params = tmpSynthesizedResponseData.params;
4256
- tmpRequest.searchParams = tmpSynthesizedResponseData.searchParams;
4257
-
4258
- //params: handle._createParamsObject(params)//,
4259
- //searchParams: this.querystringParser(querystring)
4260
-
4261
- tmpHandler.handler(tmpRequest, tmpSynthesizedResponseData, pData).then(pResults => {
4262
- return tmpCallback(null, tmpSynthesizedResponseData.responseData, tmpSynthesizedResponseData, pResults);
4263
- }, pError => {
4264
- this.log.trace('IPC Response Received', {
4265
- Error: pError
4266
- });
4267
- if (pError) {
4268
- this.log.error("IPC Request Error Request GUID [".concat(tmpRequest.guid, "] handling route [").concat(pRoute, "]: ").concat(pError), {
4269
- Error: pError,
4270
- Route: pRoute,
4271
- Data: pData
4272
- });
4273
- }
4274
- return tmpCallback(pError, tmpSynthesizedResponseData.responseData, tmpSynthesizedResponseData);
4275
- });
4276
- }
4277
- }
4278
- module.exports = OratorServiceServerIPC;
4279
- }, {
4280
- "./Orator-ServiceServer-Base.js": 33,
4281
- "./Orator-ServiceServer-IPC-SynthesizedResponse.js": 34,
4282
- "find-my-way": 13
4283
- }],
4284
- 36: [function (require, module, exports) {
4285
- /**
4286
- * Orator Service Abstraction
4287
- *
4288
- * @license MIT
4289
- *
4290
- * @author Steven Velozo <steven@velozo.com>
4291
- * @module Orator Service
4292
- */
4293
-
4294
- const libFableServiceProviderBase = require('fable-serviceproviderbase');
4295
- const libDefaultOratorServiceServer = require('./Orator-Default-ServiceServer.js');
4296
- const defaultOratorConfiguration = require('./Orator-Default-Configuration.js');
4297
- class Orator extends libFableServiceProviderBase {
4298
- constructor(pFable, pOptions, pServiceHash) {
4299
- super(pFable, pOptions, pServiceHash);
4300
- this.serviceType = 'Orator';
4301
-
4302
- // Create the empty, important logic containers
4303
- this.serviceServer = false;
4304
- this.serviceServerProvider = false;
4305
- if (typeof pServiceProvider !== 'undefined') {
4306
- this.serviceServerProvider = pServiceProvider;
4307
- }
4308
-
4309
- // Now check to see that the ServicePort is set (this used to be APIServerPort)
4310
- if (!this.options.hasOwnProperty('ServicePort')) {
4311
- if (this.fable.settings.hasOwnProperty('APIServerPort')) {
4312
- // Automatically migrate the legacy APIServerPort to ServicePort
4313
- this.options.ServicePort = this.fable.settings.APIServerPort;
4314
- } else {
4315
- // Default to whatever the ... default is!
4316
- this.options.ServicePort = defaultOratorConfiguration.ServicePort;
4317
- }
4318
- }
4319
-
4320
- // Now check to see that the Product name is set
4321
- if (!this.options.hasOwnProperty('Product')) {
4322
- this.options.Product = defaultOratorConfiguration.Product;
4323
- }
4324
- }
4325
- onBeforeInitialize() {
4326
- if (this.fable.settings.LogNoisiness > 3) {
4327
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " onBeforeInitialize:"));
4328
- }
4329
- }
4330
- onBeforeInitializeAsync(fNext) {
4331
- this.onBeforeInitialize();
4332
- // Check to see if there is a service server active; if not instantiate one (and use IPC if none is registered with Fable as the default provider)
4333
- if (!this.serviceServer) {
4334
- // If the developer hasn't set this to a service provider class of their own choosing,
4335
- // TODO: Give the developer a chance to set a service provider instantiation address of their own choosing.
4336
- // use the built-in network-less one.
4337
- if (!this.fable.OratorServiceServer) {
4338
- // If there isn't a default Service Server setup, create one.
4339
- let tmpServiceServerOptions = typeof this.options.ServiceServerOptions == 'undefined' ? {} : this.options.ServiceServerOptions;
4340
- if (!this.fable.serviceManager.servicesMap.hasOwnProperty('OratorServiceServer')) {
4341
- // Only register IPC if there isn't one yet.
4342
- this.fable.serviceManager.addServiceType('OratorServiceServer', libDefaultOratorServiceServer);
4343
- }
4344
- this.fable.serviceManager.instantiateServiceProvider('OratorServiceServer', tmpServiceServerOptions, 'OratorServiceServer-AutoInit');
4345
- }
4346
- this.serviceServer = this.fable.OratorServiceServer;
4347
- // For legacy reasons, we also will provide this under the "webServer" variable.
4348
- this.webServer = this.serviceServer;
4349
- } else {
4350
- this.log.warn("Orator attempting to initialize a service server after initialization has already completed.");
4351
- }
4352
- fNext();
4353
- }
4354
- onInitialize() {
4355
- if (this.fable.settings.LogNoisiness > 3) {
4356
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " onInitialize:"));
4357
- }
4358
- }
4359
- onInitializeAsync(fNext) {
4360
- this.onInitialize();
4361
- return fNext();
4362
- }
4363
- onAfterInitialize() {
4364
- if (this.fable.settings.LogNoisiness > 3) {
4365
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " onAfterInitialize:"));
4366
- }
4367
- }
4368
- onAfterInitializeAsync(fNext) {
4369
- this.onAfterInitialize();
4370
- return fNext();
4371
- }
4372
- initialize(fCallback) {
4373
- // I hate this -- is there a reason to not require a callback?
4374
- let tmpCallback = typeof fCallback === 'function' ? fCallback : () => {};
4375
- if (!this.initializeTimestamp) {
4376
- let tmpAnticipate = this.fable.serviceManager.instantiateServiceProviderWithoutRegistration('Anticipate');
4377
- if (this.fable.LogNoisiness > 3) {
4378
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " beginning initialization steps..."));
4379
- }
4380
- tmpAnticipate.anticipate(this.onBeforeInitializeAsync.bind(this));
4381
- tmpAnticipate.anticipate(this.onInitializeAsync.bind(this));
4382
- tmpAnticipate.anticipate(this.onAfterInitializeAsync.bind(this));
4383
- tmpAnticipate.wait(pError => {
4384
- this.initializeTimestamp = this.fable.log.getTimeStamp();
4385
- if (this.fable.LogNoisiness > 2) {
4386
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " initialization steps complete."));
4387
- }
4388
- return tmpCallback(pError);
4389
- });
4390
- } else {
4391
- this.log.warn("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " async initialize called but initialization is already completed. Aborting."));
4392
- // TODO: Should this be returning an error?
4393
- return tmpCallback();
4394
- }
4395
- }
4396
- onBeforeStartService(fNext) {
4397
- return fNext();
4398
- }
4399
- onStartService(fNext) {
4400
- this.onAfterInitialize();
4401
- return this.serviceServer.listen(this.options.ServicePort, pError => {
4402
- this.log.info("".concat(this.serviceServer.Name, " listening at ").concat(this.serviceServer.URL, " port ").concat(this.serviceServer.Port));
4403
- return fNext(pError);
4404
- });
4405
- }
4406
- onAfterStartService(fNext) {
4407
- return fNext();
4408
- }
4409
- startService(fNext) {
4410
- var tmpNext = typeof fNext === 'function' ? fNext : () => {};
4411
- let tmpAnticipate = this.fable.serviceManager.instantiateServiceProviderWithoutRegistration('Anticipate');
4412
- if (this.fable.LogNoisiness > 3) {
4413
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " beginning startService steps..."));
4414
- }
4415
-
4416
- // Auto initialize if there is no serviceServer
4417
- if (!this.serviceServer) {
4418
- tmpAnticipate.anticipate(this.initialize.bind(this));
4419
- }
4420
- tmpAnticipate.anticipate(this.onBeforeStartService.bind(this));
4421
- tmpAnticipate.anticipate(this.onStartService.bind(this));
4422
- tmpAnticipate.anticipate(this.onAfterStartService.bind(this));
4423
- tmpAnticipate.wait(pError => {
4424
- this.startServiceTimestamp = this.fable.log.getTimeStamp();
4425
- if (this.fable.LogNoisiness > 2) {
4426
- this.log.trace("Orator [".concat(this.UUID, "]::[").concat(this.Hash, "] ").concat(this.options.Product, " startService steps complete."));
4427
- }
4428
- return tmpNext(pError);
4429
- });
4430
- }
4431
- stopService(fCallback) {
4432
- var tmpCallback = typeof fCallback === 'function' ? fCallback : () => {};
4433
- if (!this.serviceServer) {
4434
- let tmpMessage = "Orator attempting to stop a service server but the service server has not been intialized yet.";
4435
- this.log.warn(tmpMessage);
4436
- return tmpCallback(tmpMessage);
4437
- }
4438
- if (!this.serviceServer.Active) {
4439
- let tmpMessage = "Orator attempting to stop a service server but the service server is not actively running.";
4440
- this.log.warn(tmpMessage);
4441
- return tmpCallback(tmpMessage);
4442
- }
4443
- return this.serviceServer.close(tmpCallback);
4444
- }
4445
- invoke(pMethod, pRoute, pData, fCallback) {
4446
- //this.log.trace(`Orator [${this.UUID}]::[${this.Hash}] ${this.options.Product} invoking ${pMethod} ${pRoute}`);
4447
- return this.serviceServer.invoke(pMethod, pRoute, pData, fCallback);
4448
- }
4449
-
4450
- /*
4451
- * Legacy Orator Functions
4452
- *************************************************************************/
4453
- startWebServer(fNext) {
4454
- return this.startService(fNext);
4455
- }
4456
-
4457
- // For legacy purposes
4458
- stopWebServer(fNext) {
4459
- return this.stopService(fNext);
4460
- }
4461
-
4462
- // For legacy purposes
4463
- getWebServer() {
4464
- // The old behavior was to lazily construct the service the first time
4465
- // this accessor function is called.
4466
- if (!this.serviceServer) {
4467
- this.initializeServiceServer();
4468
- }
4469
- return this.serviceServer;
4470
- }
4471
- /*************************************************************************
4472
- * End of Legacy Orator Functions
4473
- */
4474
- }
4475
-
4476
- module.exports = Orator;
4477
- module.exports.ServiceServerBase = require('./Orator-ServiceServer-Base.js');
4478
- module.exports.ServiceServerIPC = require('./Orator-ServiceServer-IPC.js');
4479
- }, {
4480
- "./Orator-Default-Configuration.js": 31,
4481
- "./Orator-Default-ServiceServer.js": 32,
4482
- "./Orator-ServiceServer-Base.js": 33,
4483
- "./Orator-ServiceServer-IPC.js": 35,
4484
- "fable-serviceproviderbase": 6
4485
- }]
4486
- }, {}, [36])(36);
4487
- });