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