orator 3.0.3 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/orator.js
CHANGED
|
@@ -105,7 +105,7 @@ assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual
|
|
|
105
105
|
// assert.throws(block, Error_opt, message_opt);
|
|
106
106
|
assert.throws=function(block,/*optional*/error,/*optional*/message){_throws(true,block,error,message);};// EXTENSION! This is annoying to write outside this module.
|
|
107
107
|
assert.doesNotThrow=function(block,/*optional*/error,/*optional*/message){_throws(false,block,error,message);};assert.ifError=function(err){if(err)throw err;};// Expose a strict only variant of assert
|
|
108
|
-
function strict(value,message){if(!value)fail(value,true,message,'==',strict);}assert.strict=objectAssign(strict,assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual});assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key);}return keys;};}).call(this);}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"object-assign":
|
|
108
|
+
function strict(value,message){if(!value)fail(value,true,message,'==',strict);}assert.strict=objectAssign(strict,assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual});assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key);}return keys;};}).call(this);}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"object-assign":51,"util/":4}],2:[function(require,module,exports){if(typeof Object.create==='function'){// implementation from standard node.js 'util' module
|
|
109
109
|
module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}});};}else{// old school shim for old browsers
|
|
110
110
|
module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;};}},{}],3:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==='object'&&typeof arg.copy==='function'&&typeof arg.fill==='function'&&typeof arg.readUInt8==='function';};},{}],4:[function(require,module,exports){(function(process,global){(function(){// Copyright Joyent, Inc. and other Node contributors.
|
|
111
111
|
//
|
|
@@ -178,7 +178,7 @@ exports.log=function(){console.log('%s - %s',timestamp(),exports.format.apply(ex
|
|
|
178
178
|
* prototype.
|
|
179
179
|
* @param {function} superCtor Constructor function to inherit prototype from.
|
|
180
180
|
*/exports.inherits=require('inherits');exports._extend=function(origin,add){// Don't do anything if add isn't an object
|
|
181
|
-
if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]];}return origin;};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}}).call(this);}).call(this,require('_process'),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":3,"_process":
|
|
181
|
+
if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]];}return origin;};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}}).call(this);}).call(this,require('_process'),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":3,"_process":56,"inherits":2}],5:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.default=asyncify;var _initialParams=require('./internal/initialParams.js');var _initialParams2=_interopRequireDefault(_initialParams);var _setImmediate=require('./internal/setImmediate.js');var _setImmediate2=_interopRequireDefault(_setImmediate);var _wrapAsync=require('./internal/wrapAsync.js');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
182
182
|
* Take a sync function and make it async, passing its return value to a
|
|
183
183
|
* callback. This is useful for plugging sync functions into a waterfall,
|
|
184
184
|
* series, or other async functions. Any arguments passed to the generated
|
|
@@ -234,7 +234,27 @@ if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.lengt
|
|
|
234
234
|
*
|
|
235
235
|
* q.push(files);
|
|
236
236
|
*/function asyncify(func){if((0,_wrapAsync.isAsync)(func)){return function(...args/*, callback*/){const callback=args.pop();const promise=func.apply(this,args);return handlePromise(promise,callback);};}return(0,_initialParams2.default)(function(args,callback){var result;try{result=func.apply(this,args);}catch(e){return callback(e);}// if result is Promise object
|
|
237
|
-
if(result&&typeof result.then==='function'){return handlePromise(result,callback);}else{callback(null,result);}});}function handlePromise(promise,callback){return promise.then(value=>{invokeCallback(callback,null,value);},err=>{invokeCallback(callback,err&&err.message?err:new Error(err));});}function invokeCallback(callback,error,value){try{callback(error,value);}catch(err){(0,_setImmediate2.default)(e=>{throw e;},err);}}module.exports=exports['default'];},{"./internal/initialParams.js":
|
|
237
|
+
if(result&&typeof result.then==='function'){return handlePromise(result,callback);}else{callback(null,result);}});}function handlePromise(promise,callback){return promise.then(value=>{invokeCallback(callback,null,value);},err=>{invokeCallback(callback,err&&err.message?err:new Error(err));});}function invokeCallback(callback,error,value){try{callback(error,value);}catch(err){(0,_setImmediate2.default)(e=>{throw e;},err);}}module.exports=exports['default'];},{"./internal/initialParams.js":14,"./internal/setImmediate.js":19,"./internal/wrapAsync.js":21}],6:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _eachOfLimit=require('./internal/eachOfLimit.js');var _eachOfLimit2=_interopRequireDefault(_eachOfLimit);var _withoutIndex=require('./internal/withoutIndex.js');var _withoutIndex2=_interopRequireDefault(_withoutIndex);var _wrapAsync=require('./internal/wrapAsync.js');var _wrapAsync2=_interopRequireDefault(_wrapAsync);var _awaitify=require('./internal/awaitify.js');var _awaitify2=_interopRequireDefault(_awaitify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
238
|
+
* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
|
|
239
|
+
*
|
|
240
|
+
* @name eachLimit
|
|
241
|
+
* @static
|
|
242
|
+
* @memberOf module:Collections
|
|
243
|
+
* @method
|
|
244
|
+
* @see [async.each]{@link module:Collections.each}
|
|
245
|
+
* @alias forEachLimit
|
|
246
|
+
* @category Collection
|
|
247
|
+
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
|
|
248
|
+
* @param {number} limit - The maximum number of async operations at a time.
|
|
249
|
+
* @param {AsyncFunction} iteratee - An async function to apply to each item in
|
|
250
|
+
* `coll`.
|
|
251
|
+
* The array index is not passed to the iteratee.
|
|
252
|
+
* If you need the index, use `eachOfLimit`.
|
|
253
|
+
* Invoked with (item, callback).
|
|
254
|
+
* @param {Function} [callback] - A callback which is called when all
|
|
255
|
+
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
|
|
256
|
+
* @returns {Promise} a promise, if a callback is omitted
|
|
257
|
+
*/function eachLimit(coll,limit,iteratee,callback){return(0,_eachOfLimit2.default)(limit)(coll,(0,_withoutIndex2.default)((0,_wrapAsync2.default)(iteratee)),callback);}exports.default=(0,_awaitify2.default)(eachLimit,4);module.exports=exports['default'];},{"./internal/awaitify.js":10,"./internal/eachOfLimit.js":12,"./internal/withoutIndex.js":20,"./internal/wrapAsync.js":21}],7:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _eachOfLimit2=require('./internal/eachOfLimit.js');var _eachOfLimit3=_interopRequireDefault(_eachOfLimit2);var _wrapAsync=require('./internal/wrapAsync.js');var _wrapAsync2=_interopRequireDefault(_wrapAsync);var _awaitify=require('./internal/awaitify.js');var _awaitify2=_interopRequireDefault(_awaitify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
238
258
|
* The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
|
|
239
259
|
* time.
|
|
240
260
|
*
|
|
@@ -254,7 +274,7 @@ if(result&&typeof result.then==='function'){return handlePromise(result,callback
|
|
|
254
274
|
* @param {Function} [callback] - A callback which is called when all
|
|
255
275
|
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
|
|
256
276
|
* @returns {Promise} a promise, if a callback is omitted
|
|
257
|
-
*/function eachOfLimit(coll,limit,iteratee,callback){return(0,_eachOfLimit3.default)(limit)(coll,(0,_wrapAsync2.default)(iteratee),callback);}exports.default=(0,_awaitify2.default)(eachOfLimit,4);module.exports=exports['default'];},{"./internal/awaitify.js":
|
|
277
|
+
*/function eachOfLimit(coll,limit,iteratee,callback){return(0,_eachOfLimit3.default)(limit)(coll,(0,_wrapAsync2.default)(iteratee),callback);}exports.default=(0,_awaitify2.default)(eachOfLimit,4);module.exports=exports['default'];},{"./internal/awaitify.js":10,"./internal/eachOfLimit.js":12,"./internal/wrapAsync.js":21}],8:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _eachOfLimit=require('./eachOfLimit.js');var _eachOfLimit2=_interopRequireDefault(_eachOfLimit);var _awaitify=require('./internal/awaitify.js');var _awaitify2=_interopRequireDefault(_awaitify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
258
278
|
* The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
|
|
259
279
|
*
|
|
260
280
|
* @name eachOfSeries
|
|
@@ -271,18 +291,18 @@ if(result&&typeof result.then==='function'){return handlePromise(result,callback
|
|
|
271
291
|
* @param {Function} [callback] - A callback which is called when all `iteratee`
|
|
272
292
|
* functions have finished, or an error occurs. Invoked with (err).
|
|
273
293
|
* @returns {Promise} a promise, if a callback is omitted
|
|
274
|
-
*/function eachOfSeries(coll,iteratee,callback){return(0,_eachOfLimit2.default)(coll,1,iteratee,callback);}exports.default=(0,_awaitify2.default)(eachOfSeries,3);module.exports=exports['default'];},{"./eachOfLimit.js":
|
|
294
|
+
*/function eachOfSeries(coll,iteratee,callback){return(0,_eachOfLimit2.default)(coll,1,iteratee,callback);}exports.default=(0,_awaitify2.default)(eachOfSeries,3);module.exports=exports['default'];},{"./eachOfLimit.js":7,"./internal/awaitify.js":10}],9:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.default=asyncEachOfLimit;var _breakLoop=require('./breakLoop.js');var _breakLoop2=_interopRequireDefault(_breakLoop);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}// for async generators
|
|
275
295
|
function asyncEachOfLimit(generator,limit,iteratee,callback){let done=false;let canceled=false;let awaiting=false;let running=0;let idx=0;function replenish(){//console.log('replenish')
|
|
276
296
|
if(running>=limit||awaiting||done)return;//console.log('replenish awaiting')
|
|
277
297
|
awaiting=true;generator.next().then(({value,done:iterDone})=>{//console.log('got value', value)
|
|
278
298
|
if(canceled||done)return;awaiting=false;if(iterDone){done=true;if(running<=0){//console.log('done nextCb')
|
|
279
299
|
callback(null);}return;}running++;iteratee(value,idx,iterateeCallback);idx++;replenish();}).catch(handleError);}function iterateeCallback(err,result){//console.log('iterateeCallback')
|
|
280
300
|
running-=1;if(canceled)return;if(err)return handleError(err);if(err===false){done=true;canceled=true;return;}if(result===_breakLoop2.default||done&&running<=0){done=true;//console.log('done iterCb')
|
|
281
|
-
return callback(null);}replenish();}function handleError(err){if(canceled)return;awaiting=false;done=true;callback(err);}replenish();}module.exports=exports['default'];},{"./breakLoop.js":
|
|
301
|
+
return callback(null);}replenish();}function handleError(err){if(canceled)return;awaiting=false;done=true;callback(err);}replenish();}module.exports=exports['default'];},{"./breakLoop.js":11}],10:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.default=awaitify;// conditionally promisify a function.
|
|
282
302
|
// only return a promise if a callback is omitted
|
|
283
|
-
function awaitify(asyncFn,arity=asyncFn.length){if(!arity)throw new Error('arity is undefined');function awaitable(...args){if(typeof args[arity-1]==='function'){return asyncFn.apply(this,args);}return new Promise((resolve,reject)=>{args[arity-1]=(err,...cbArgs)=>{if(err)return reject(err);resolve(cbArgs.length>1?cbArgs:cbArgs[0]);};asyncFn.apply(this,args);});}return awaitable;}module.exports=exports['default'];},{}],
|
|
303
|
+
function awaitify(asyncFn,arity=asyncFn.length){if(!arity)throw new Error('arity is undefined');function awaitable(...args){if(typeof args[arity-1]==='function'){return asyncFn.apply(this,args);}return new Promise((resolve,reject)=>{args[arity-1]=(err,...cbArgs)=>{if(err)return reject(err);resolve(cbArgs.length>1?cbArgs:cbArgs[0]);};asyncFn.apply(this,args);});}return awaitable;}module.exports=exports['default'];},{}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});// A temporary value used to identify if the loop should be broken.
|
|
284
304
|
// See #1064, #1293
|
|
285
|
-
const breakLoop={};exports.default=breakLoop;module.exports=exports["default"];},{}],
|
|
305
|
+
const breakLoop={};exports.default=breakLoop;module.exports=exports["default"];},{}],12:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _once=require('./once.js');var _once2=_interopRequireDefault(_once);var _iterator=require('./iterator.js');var _iterator2=_interopRequireDefault(_iterator);var _onlyOnce=require('./onlyOnce.js');var _onlyOnce2=_interopRequireDefault(_onlyOnce);var _wrapAsync=require('./wrapAsync.js');var _asyncEachOfLimit=require('./asyncEachOfLimit.js');var _asyncEachOfLimit2=_interopRequireDefault(_asyncEachOfLimit);var _breakLoop=require('./breakLoop.js');var _breakLoop2=_interopRequireDefault(_breakLoop);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}exports.default=limit=>{return(obj,iteratee,callback)=>{callback=(0,_once2.default)(callback);if(limit<=0){throw new RangeError('concurrency limit cannot be less than 1');}if(!obj){return callback(null);}if((0,_wrapAsync.isAsyncGenerator)(obj)){return(0,_asyncEachOfLimit2.default)(obj,limit,iteratee,callback);}if((0,_wrapAsync.isAsyncIterable)(obj)){return(0,_asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](),limit,iteratee,callback);}var nextElem=(0,_iterator2.default)(obj);var done=false;var canceled=false;var running=0;var looping=false;function iterateeCallback(err,value){if(canceled)return;running-=1;if(err){done=true;callback(err);}else if(err===false){done=true;canceled=true;}else if(value===_breakLoop2.default||done&&running<=0){done=true;return callback(null);}else if(!looping){replenish();}}function replenish(){looping=true;while(running<limit&&!done){var elem=nextElem();if(elem===null){done=true;if(running<=0){callback(null);}return;}running+=1;iteratee(elem.value,elem.key,(0,_onlyOnce2.default)(iterateeCallback));}looping=false;}replenish();};};module.exports=exports['default'];},{"./asyncEachOfLimit.js":9,"./breakLoop.js":11,"./iterator.js":16,"./once.js":17,"./onlyOnce.js":18,"./wrapAsync.js":21}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=function(coll){return coll[Symbol.iterator]&&coll[Symbol.iterator]();};module.exports=exports["default"];},{}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=function(fn){return function(...args/*, callback*/){var callback=args.pop();return fn.call(this,args,callback);};};module.exports=exports["default"];},{}],15:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.default=isArrayLike;function isArrayLike(value){return value&&typeof value.length==='number'&&value.length>=0&&value.length%1===0;}module.exports=exports['default'];},{}],16:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.default=createIterator;var _isArrayLike=require('./isArrayLike.js');var _isArrayLike2=_interopRequireDefault(_isArrayLike);var _getIterator=require('./getIterator.js');var _getIterator2=_interopRequireDefault(_getIterator);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function createArrayIterator(coll){var i=-1;var len=coll.length;return function next(){return++i<len?{value:coll[i],key:i}:null;};}function createES2015Iterator(iterator){var i=-1;return function next(){var item=iterator.next();if(item.done)return null;i++;return{value:item.value,key:i};};}function createObjectIterator(obj){var okeys=obj?Object.keys(obj):[];var i=-1;var len=okeys.length;return function next(){var key=okeys[++i];if(key==='__proto__'){return next();}return i<len?{value:obj[key],key}:null;};}function createIterator(coll){if((0,_isArrayLike2.default)(coll)){return createArrayIterator(coll);}var iterator=(0,_getIterator2.default)(coll);return iterator?createES2015Iterator(iterator):createObjectIterator(coll);}module.exports=exports['default'];},{"./getIterator.js":13,"./isArrayLike.js":15}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=once;function once(fn){function wrapper(...args){if(fn===null)return;var callFn=fn;fn=null;callFn.apply(this,args);}Object.assign(wrapper,fn);return wrapper;}module.exports=exports["default"];},{}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=onlyOnce;function onlyOnce(fn){return function(...args){if(fn===null)throw new Error("Callback was already called.");var callFn=fn;fn=null;callFn.apply(this,args);};}module.exports=exports["default"];},{}],19:[function(require,module,exports){(function(process,setImmediate){(function(){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.fallback=fallback;exports.wrap=wrap;/* istanbul ignore file */var hasQueueMicrotask=exports.hasQueueMicrotask=typeof queueMicrotask==='function'&&queueMicrotask;var hasSetImmediate=exports.hasSetImmediate=typeof setImmediate==='function'&&setImmediate;var hasNextTick=exports.hasNextTick=typeof process==='object'&&typeof process.nextTick==='function';function fallback(fn){setTimeout(fn,0);}function wrap(defer){return(fn,...args)=>defer(()=>fn(...args));}var _defer;if(hasQueueMicrotask){_defer=queueMicrotask;}else if(hasSetImmediate){_defer=setImmediate;}else if(hasNextTick){_defer=process.nextTick;}else{_defer=fallback;}exports.default=wrap(_defer);}).call(this);}).call(this,require('_process'),require("timers").setImmediate);},{"_process":56,"timers":63}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_withoutIndex;function _withoutIndex(iteratee){return(value,index,callback)=>iteratee(value,callback);}module.exports=exports["default"];},{}],21:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports.isAsyncIterable=exports.isAsyncGenerator=exports.isAsync=undefined;var _asyncify=require('../asyncify.js');var _asyncify2=_interopRequireDefault(_asyncify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function isAsync(fn){return fn[Symbol.toStringTag]==='AsyncFunction';}function isAsyncGenerator(fn){return fn[Symbol.toStringTag]==='AsyncGenerator';}function isAsyncIterable(obj){return typeof obj[Symbol.asyncIterator]==='function';}function wrapAsync(asyncFn){if(typeof asyncFn!=='function')throw new Error('expected a function');return isAsync(asyncFn)?(0,_asyncify2.default)(asyncFn):asyncFn;}exports.default=wrapAsync;exports.isAsync=isAsync;exports.isAsyncGenerator=isAsyncGenerator;exports.isAsyncIterable=isAsyncIterable;},{"../asyncify.js":5}],22:[function(require,module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _once=require('./internal/once.js');var _once2=_interopRequireDefault(_once);var _onlyOnce=require('./internal/onlyOnce.js');var _onlyOnce2=_interopRequireDefault(_onlyOnce);var _wrapAsync=require('./internal/wrapAsync.js');var _wrapAsync2=_interopRequireDefault(_wrapAsync);var _awaitify=require('./internal/awaitify.js');var _awaitify2=_interopRequireDefault(_awaitify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
286
306
|
* Runs the `tasks` array of functions in series, each passing their results to
|
|
287
307
|
* the next in the array. However, if any of the `tasks` pass an error to their
|
|
288
308
|
* own callback, the next function is not executed, and the main `callback` is
|
|
@@ -338,7 +358,7 @@ const breakLoop={};exports.default=breakLoop;module.exports=exports["default"];}
|
|
|
338
358
|
* // arg1 now equals 'three'
|
|
339
359
|
* callback(null, 'done');
|
|
340
360
|
* }
|
|
341
|
-
*/function waterfall(tasks,callback){callback=(0,_once2.default)(callback);if(!Array.isArray(tasks))return callback(new Error('First argument to waterfall must be an array of functions'));if(!tasks.length)return callback();var taskIndex=0;function nextTask(args){var task=(0,_wrapAsync2.default)(tasks[taskIndex++]);task(...args,(0,_onlyOnce2.default)(next));}function next(err,...args){if(err===false)return;if(err||taskIndex===tasks.length){return callback(err,...args);}nextTask(args);}nextTask([]);}exports.default=(0,_awaitify2.default)(waterfall);module.exports=exports['default'];},{"./internal/awaitify.js":
|
|
361
|
+
*/function waterfall(tasks,callback){callback=(0,_once2.default)(callback);if(!Array.isArray(tasks))return callback(new Error('First argument to waterfall must be an array of functions'));if(!tasks.length)return callback();var taskIndex=0;function nextTask(args){var task=(0,_wrapAsync2.default)(tasks[taskIndex++]);task(...args,(0,_onlyOnce2.default)(next));}function next(err,...args){if(err===false)return;if(err||taskIndex===tasks.length){return callback(err,...args);}nextTask(args);}nextTask([]);}exports.default=(0,_awaitify2.default)(waterfall);module.exports=exports['default'];},{"./internal/awaitify.js":10,"./internal/once.js":17,"./internal/onlyOnce.js":18,"./internal/wrapAsync.js":21}],23:[function(require,module,exports){/**
|
|
342
362
|
* Base Logger Class
|
|
343
363
|
*
|
|
344
364
|
* @license MIT
|
|
@@ -355,19 +375,19 @@ generateInsecureUUID(){let tmpDate=new Date().getTime();let tmpUUID='LOGSTREAM-x
|
|
|
355
375
|
// ..but good enough for unique log stream identifiers
|
|
356
376
|
let tmpRandomData=(tmpDate+Math.random()*16)%16|0;tmpDate=Math.floor(tmpDate/16);return(pCharacter=='x'?tmpRandomData:tmpRandomData&0x3|0x8).toString(16);});return tmpUUID;}initialize(){// No operation.
|
|
357
377
|
}trace(pLogText,pLogObject){this.write("trace",pLogText,pLogObject);}debug(pLogText,pLogObject){this.write("debug",pLogText,pLogObject);}info(pLogText,pLogObject){this.write("info",pLogText,pLogObject);}warn(pLogText,pLogObject){this.write("warn",pLogText,pLogObject);}error(pLogText,pLogObject){this.write("error",pLogText,pLogObject);}fatal(pLogText,pLogObject){this.write("fatal",pLogText,pLogObject);}write(pLogLevel,pLogText,pLogObject){// The base logger does nothing.
|
|
358
|
-
return true;}}module.exports=BaseLogger;},{}],
|
|
378
|
+
return true;}}module.exports=BaseLogger;},{}],24:[function(require,module,exports){/**
|
|
359
379
|
* Default Logger Provider Function
|
|
360
380
|
*
|
|
361
381
|
* @license MIT
|
|
362
382
|
*
|
|
363
383
|
* @author Steven Velozo <steven@velozo.com>
|
|
364
384
|
*/ // Return the providers that are available without extensions loaded
|
|
365
|
-
getDefaultProviders=()=>{let tmpDefaultProviders={};tmpDefaultProviders.console=require('./Fable-Log-Logger-Console.js');tmpDefaultProviders.default=tmpDefaultProviders.console;return tmpDefaultProviders;};module.exports=getDefaultProviders();},{"./Fable-Log-Logger-Console.js":
|
|
385
|
+
getDefaultProviders=()=>{let tmpDefaultProviders={};tmpDefaultProviders.console=require('./Fable-Log-Logger-Console.js');tmpDefaultProviders.default=tmpDefaultProviders.console;return tmpDefaultProviders;};module.exports=getDefaultProviders();},{"./Fable-Log-Logger-Console.js":26}],25:[function(require,module,exports){module.exports=[{"loggertype":"console","streamtype":"console","level":"trace"}];},{}],26:[function(require,module,exports){let libBaseLogger=require('./Fable-Log-BaseLogger.js');class ConsoleLogger extends libBaseLogger{constructor(pLogStreamSettings,pFableLog){super(pLogStreamSettings);this._ShowTimeStamps=pLogStreamSettings.hasOwnProperty('showtimestamps')?pLogStreamSettings.showtimestamps==true:false;this._FormattedTimeStamps=pLogStreamSettings.hasOwnProperty('formattedtimestamps')?pLogStreamSettings.formattedtimestamps==true:false;this._ContextMessage=pLogStreamSettings.hasOwnProperty('Context')?`(${pLogStreamSettings.Context})`:pFableLog._Settings.hasOwnProperty('Product')?`(${pFableLog._Settings.Product})`:'Unnamed_Log_Context';// Allow the user to decide what gets output to the console
|
|
366
386
|
this._OutputLogLinesToConsole=pLogStreamSettings.hasOwnProperty('outputloglinestoconsole')?pLogStreamSettings.outputloglinestoconsole:true;this._OutputObjectsToConsole=pLogStreamSettings.hasOwnProperty('outputobjectstoconsole')?pLogStreamSettings.outputobjectstoconsole:true;// Precompute the prefix for each level
|
|
367
387
|
this.prefixCache={};for(let i=0;i<=this.levels.length;i++){this.prefixCache[this.levels[i]]=`[${this.levels[i]}] ${this._ContextMessage}: `;if(this._ShowTimeStamps){// If there is a timestamp we need a to prepend space before the prefixcache string, since the timestamp comes first
|
|
368
388
|
this.prefixCache[this.levels[i]]=' '+this.prefixCache[this.levels[i]];}}}write(pLevel,pLogText,pObject){let tmpTimeStamp='';if(this._ShowTimeStamps&&this._FormattedTimeStamps){tmpTimeStamp=new Date().toISOString();}else if(this._ShowTimeStamps){tmpTimeStamp=+new Date();}let tmpLogLine=`${tmpTimeStamp}${this.prefixCache[pLevel]}${pLogText}`;if(this._OutputLogLinesToConsole){console.log(tmpLogLine);}// Write out the object on a separate line if it is passed in
|
|
369
389
|
if(this._OutputObjectsToConsole&&typeof pObject!=='undefined'){console.log(JSON.stringify(pObject,null,2));}// Provide an easy way to be overridden and be consistent
|
|
370
|
-
return tmpLogLine;}}module.exports=ConsoleLogger;},{"./Fable-Log-BaseLogger.js":
|
|
390
|
+
return tmpLogLine;}}module.exports=ConsoleLogger;},{"./Fable-Log-BaseLogger.js":23}],27:[function(require,module,exports){/**
|
|
371
391
|
* Fable Logging Add-on
|
|
372
392
|
*
|
|
373
393
|
* @license MIT
|
|
@@ -390,7 +410,7 @@ for(let i=0;i<this._StreamDefinitions.length;i++){let tmpStreamDefinition=Object
|
|
|
390
410
|
for(let i=0;i<this.logStreams.length;i++){this.logStreams[i].initialize();}}logTime(pMessage,pDatum){let tmpMessage=typeof pMessage!=='undefined'?pMessage:'Time';let tmpTime=new Date();this.info(`${tmpMessage} ${tmpTime} (epoch ${+tmpTime})`,pDatum);}// Get a timestamp
|
|
391
411
|
getTimeStamp(){return+new Date();}getTimeDelta(pTimeStamp){let tmpEndTime=+new Date();return tmpEndTime-pTimeStamp;}// Log the delta between a timestamp, and now with a message
|
|
392
412
|
logTimeDelta(pTimeDelta,pMessage,pDatum){let tmpMessage=typeof pMessage!=='undefined'?pMessage:'Time Measurement';let tmpDatum=typeof pDatum==='object'?pDatum:{};let tmpEndTime=+new Date();this.info(`${tmpMessage} logged at (epoch ${+tmpEndTime}) took (${pTimeDelta}ms)`,pDatum);}logTimeDeltaHuman(pTimeDelta,pMessage,pDatum){let tmpMessage=typeof pMessage!=='undefined'?pMessage:'Time Measurement';let tmpEndTime=+new Date();let tmpMs=parseInt(pTimeDelta%1000);let tmpSeconds=parseInt(pTimeDelta/1000%60);let tmpMinutes=parseInt(pTimeDelta/(1000*60)%60);let tmpHours=parseInt(pTimeDelta/(1000*60*60));tmpMs=tmpMs<10?"00"+tmpMs:tmpMs<100?"0"+tmpMs:tmpMs;tmpSeconds=tmpSeconds<10?"0"+tmpSeconds:tmpSeconds;tmpMinutes=tmpMinutes<10?"0"+tmpMinutes:tmpMinutes;tmpHours=tmpHours<10?"0"+tmpHours:tmpHours;this.info(`${tmpMessage} logged at (epoch ${+tmpEndTime}) took (${pTimeDelta}ms) or (${tmpHours}:${tmpMinutes}:${tmpSeconds}.${tmpMs})`,pDatum);}logTimeDeltaRelative(pStartTime,pMessage,pDatum){this.logTimeDelta(this.getTimeDelta(pStartTime),pMessage,pDatum);}logTimeDeltaRelativeHuman(pStartTime,pMessage,pDatum){this.logTimeDeltaHuman(this.getTimeDelta(pStartTime),pMessage,pDatum);}}// This is for backwards compatibility
|
|
393
|
-
function autoConstruct(pSettings){return new FableLog(pSettings);}module.exports={new:autoConstruct,FableLog:FableLog};},{"./Fable-Log-DefaultProviders-Node.js":
|
|
413
|
+
function autoConstruct(pSettings){return new FableLog(pSettings);}module.exports={new:autoConstruct,FableLog:FableLog};},{"./Fable-Log-DefaultProviders-Node.js":24,"./Fable-Log-DefaultStreams.json":25}],28:[function(require,module,exports){module.exports={"Product":"ApplicationNameHere","ProductVersion":"0.0.0","ConfigFile":false,"LogStreams":[{"level":"trace"}]};},{}],29:[function(require,module,exports){(function(process){(function(){/**
|
|
394
414
|
* Fable Settings Template Processor
|
|
395
415
|
*
|
|
396
416
|
* This class allows environment variables to come in via templated expressions, and defaults to be set.
|
|
@@ -402,7 +422,7 @@ function autoConstruct(pSettings){return new FableLog(pSettings);}module.exports
|
|
|
402
422
|
*/class FableSettingsTemplateProcessor{constructor(pDependencies){// Use a no-dependencies templating engine to parse out environment variables
|
|
403
423
|
this.templateProcessor=new pDependencies.precedent();// TODO: Make the environment variable wrap expression demarcation characters configurable?
|
|
404
424
|
this.templateProcessor.addPattern('${','}',pTemplateValue=>{let tmpTemplateValue=pTemplateValue.trim();let tmpSeparatorIndex=tmpTemplateValue.indexOf('|');// If there is no pipe, the default value will end up being whatever the variable name is.
|
|
405
|
-
let tmpDefaultValue=tmpTemplateValue.substring(tmpSeparatorIndex+1);let tmpEnvironmentVariableName=tmpSeparatorIndex>-1?tmpTemplateValue.substring(0,tmpSeparatorIndex):tmpTemplateValue;if(process.env.hasOwnProperty(tmpEnvironmentVariableName)){return process.env[tmpEnvironmentVariableName];}else{return tmpDefaultValue;}});}parseSetting(pString){return this.templateProcessor.parseString(pString);}}module.exports=FableSettingsTemplateProcessor;}).call(this);}).call(this,require('_process'));},{"_process":
|
|
425
|
+
let tmpDefaultValue=tmpTemplateValue.substring(tmpSeparatorIndex+1);let tmpEnvironmentVariableName=tmpSeparatorIndex>-1?tmpTemplateValue.substring(0,tmpSeparatorIndex):tmpTemplateValue;if(process.env.hasOwnProperty(tmpEnvironmentVariableName)){return process.env[tmpEnvironmentVariableName];}else{return tmpDefaultValue;}});}parseSetting(pString){return this.templateProcessor.parseString(pString);}}module.exports=FableSettingsTemplateProcessor;}).call(this);}).call(this,require('_process'));},{"_process":56}],30:[function(require,module,exports){/**
|
|
406
426
|
* Fable Settings Add-on
|
|
407
427
|
*
|
|
408
428
|
* @license MIT
|
|
@@ -438,7 +458,7 @@ this._configureEnvTemplating(tmpSettingsTo);return tmpSettingsTo;}// Fill in set
|
|
|
438
458
|
fill(pSettingsFrom){// If an invalid settings from object is passed in (e.g. object constructor without passing in anything) this should still work
|
|
439
459
|
let tmpSettingsFrom=typeof pSettingsFrom==='object'?pSettingsFrom:{};// do not mutate the From object property values
|
|
440
460
|
let tmpSettingsFromCopy=JSON.parse(JSON.stringify(tmpSettingsFrom));this.settings=this._deepMergeObjects(tmpSettingsFromCopy,this.settings);return this.settings;}};// This is for backwards compatibility
|
|
441
|
-
function autoConstruct(pSettings){return new FableSettings(pSettings);}module.exports={new:autoConstruct,FableSettings:FableSettings};},{"./Fable-Settings-Default":
|
|
461
|
+
function autoConstruct(pSettings){return new FableSettings(pSettings);}module.exports={new:autoConstruct,FableSettings:FableSettings};},{"./Fable-Settings-Default":28,"./Fable-Settings-TemplateProcessor.js":29,"precedent":53}],31:[function(require,module,exports){/**
|
|
442
462
|
* Random Byte Generator - Browser version
|
|
443
463
|
*
|
|
444
464
|
* @license MIT
|
|
@@ -457,7 +477,7 @@ this.getRandomValues(tmpBuffer);return tmpBuffer;}// Math.random()-based (RNG)
|
|
|
457
477
|
generateRandomBytes(){// If all else fails, use Math.random(). It's fast, but is of unspecified
|
|
458
478
|
// quality.
|
|
459
479
|
let tmpBuffer=new Uint8Array(16);// eslint-disable-line no-undef
|
|
460
|
-
for(let i=0,tmpValue;i<16;i++){if((i&0x03)===0){tmpValue=Math.random()*0x100000000;}tmpBuffer[i]=tmpValue>>>((i&0x03)<<3)&0xff;}return tmpBuffer;}generate(){if(this.getRandomValues){return this.generateWhatWGBytes();}else{return this.generateRandomBytes();}}}module.exports=RandomBytes;},{}],
|
|
480
|
+
for(let i=0,tmpValue;i<16;i++){if((i&0x03)===0){tmpValue=Math.random()*0x100000000;}tmpBuffer[i]=tmpValue>>>((i&0x03)<<3)&0xff;}return tmpBuffer;}generate(){if(this.getRandomValues){return this.generateWhatWGBytes();}else{return this.generateRandomBytes();}}}module.exports=RandomBytes;},{}],32:[function(require,module,exports){/**
|
|
461
481
|
* Fable UUID Generator
|
|
462
482
|
*
|
|
463
483
|
* @license MIT
|
|
@@ -482,29 +502,58 @@ generateUUIDv4(){let tmpBuffer=new Array(16);var tmpRandomBytes=this.randomByteG
|
|
|
482
502
|
tmpRandomBytes[6]=tmpRandomBytes[6]&0x0f|0x40;tmpRandomBytes[8]=tmpRandomBytes[8]&0x3f|0x80;return this.bytesToUUID(tmpRandomBytes);}// Simple random UUID generation
|
|
483
503
|
generateRandom(){let tmpUUID='';for(let i=0;i<this._UUIDLength;i++){tmpUUID+=this._UUIDRandomDictionary.charAt(Math.floor(Math.random()*(this._UUIDRandomDictionary.length-1)));}return tmpUUID;}// Adapted from node-uuid (https://github.com/kelektiv/node-uuid)
|
|
484
504
|
getUUID(){if(this._UUIDModeRandom){return this.generateRandom();}else{return this.generateUUIDv4();}}}// This is for backwards compatibility
|
|
485
|
-
function autoConstruct(pSettings){return new FableUUID(pSettings);}module.exports={new:autoConstruct,FableUUID:FableUUID};},{"./Fable-UUID-Random.js":
|
|
486
|
-
|
|
505
|
+
function autoConstruct(pSettings){return new FableUUID(pSettings);}module.exports={new:autoConstruct,FableUUID:FableUUID};},{"./Fable-UUID-Random.js":31}],33:[function(require,module,exports){class FableUtility{// Underscore and lodash have a behavior, _.template, which compiles a
|
|
506
|
+
// string-based template with code snippets into simple executable pieces,
|
|
507
|
+
// with the added twist of returning a precompiled function ready to go.
|
|
508
|
+
//
|
|
509
|
+
// NOTE: This does not implement underscore escape expressions
|
|
510
|
+
// NOTE: This does not implement underscore magic browser variable assignment
|
|
511
|
+
//
|
|
512
|
+
// This is an implementation of that.
|
|
513
|
+
// TODO: Make this use precedent, add configuration, add debugging.
|
|
514
|
+
constructor(pFable,pTemplateText){this.fable=pFable;// These are the exact regex's used in lodash/underscore
|
|
515
|
+
// TODO: Switch this to precedent
|
|
516
|
+
this.Matchers={Evaluate:/<%([\s\S]+?)%>/g,Interpolate:/<%=([\s\S]+?)%>/g,Escaper:/\\|'|\r|\n|\t|\u2028|\u2029/g,Unescaper:/\\(\\|'|r|n|t|u2028|u2029)/g,// This is how underscore does it, so we are keeping it for now.
|
|
517
|
+
GuaranteedNonMatch:/.^/};// This is a helper for the escaper and unescaper functions.
|
|
518
|
+
// Right now we are going to keep what underscore is doing, but, not forever.
|
|
519
|
+
this.templateEscapes={'\\':'\\',"'":"'",'r':'\r','\r':'r','n':'\n','\n':'n','t':'\t','\t':'t','u2028':'\u2028','\u2028':'u2028','u2029':'\u2029','\u2029':'u2029'};// This is defined as such to underscore that it is a dynamic programming
|
|
520
|
+
// function on this class.
|
|
521
|
+
this.renderFunction=()=>{return``;};}// Underscore and lodash have a behavior, _.extend, which merges objects.
|
|
522
|
+
// Now that es6 gives us this, use the native thingy.
|
|
523
|
+
extend(pDestinationObject,...pSourceObjects){return Object.assign(pDestinationObject,...pSourceObjects);}renderTemplate(pData){return this.renderFunction(pData);}templateFunction(pData){let fRenderTemplateBound=this.renderTemplate.bind(this);return fRenderTemplateBound;}buildTemplateFunction(pTemplateText,pData){// For now this is being kept in a weird form ... this is to mimic the old
|
|
524
|
+
// underscore code until this is rewritten using precedent.
|
|
525
|
+
this.TemplateSource="__p+='"+pTemplateText.replace(this.Matchers.Escaper,pMatch=>{return`\\${this.templateEscapes[pMatch]}`;}).replace(this.Matchers.Interpolate||this.Matchers.GuaranteedNonMatch,(pMatch,pCode)=>{return`'+\n(${decodeURIComponent(pCode)})+\n'`;}).replace(this.Matchers.Evaluate||this.Matchers.GuaranteedNonMatch,(pMatch,pCode)=>{return`';\n${decodeURIComponent(pCode)}\n;__p+='`;})+`';\n`;this.TemplateSource=`with(pTemplateDataObject||{}){\n${this.TemplateSource}}\n`;this.TemplateSource=`var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n${this.TemplateSource}return __p;\n`;this.renderFunction=new Function('pTemplateDataObject',this.TemplateSource);if(typeof pData!='undefined'){return this.renderFunction(pData);}// Provide the compiled function source as a convenience for build time
|
|
526
|
+
// precompilation.
|
|
527
|
+
this.TemplateSourceCompiled='function(obj){\n'+this.TemplateSource+'}';return this.templateFunction();}}module.exports=FableUtility;},{}],34:[function(require,module,exports){const libFableUtilityTemplate=require('./Fable-Utility-Template.js');const libAsyncWaterfall=require('async/waterfall');const libAsyncEachLimit=require('async/eachLimit');class FableUtility{constructor(pFable){this.fable=pFable;// These two functions are used extensively throughout
|
|
528
|
+
this.waterfall=libAsyncWaterfall;this.eachLimit=libAsyncEachLimit;}// Underscore and lodash have a behavior, _.extend, which merges objects.
|
|
529
|
+
// Now that es6 gives us this, use the native thingy.
|
|
530
|
+
extend(pDestinationObject,...pSourceObjects){return Object.assign(pDestinationObject,...pSourceObjects);}// Underscore and lodash have a behavior, _.template, which compiles a
|
|
531
|
+
// string-based template with code snippets into simple executable pieces,
|
|
532
|
+
// with the added twist of returning a precompiled function ready to go.
|
|
533
|
+
template(pTemplateText,pData){let tmpTemplate=new libFableUtilityTemplate(this.fable,pTemplateText);return tmpTemplate.buildTemplateFunction(pTemplateText,pData);}// This is a safe, modern version of chunk from underscore
|
|
534
|
+
// Algorithm pulled from a mix of these two polyfills:
|
|
535
|
+
// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_chunk
|
|
536
|
+
// https://youmightnotneed.com/lodash
|
|
537
|
+
// This implementation was most tolerant in browsers. Uglify can fix the rest.
|
|
538
|
+
chunk(pInput,pChunkSize,pChunkCache){let tmpInputArray=[...pInput];// Note lodash defaults to 1, underscore defaults to 0
|
|
539
|
+
let tmpChunkSize=typeof pChunkSize=='number'?pChunkSize:0;let tmpChunkCache=typeof pChunkCache!='undefined'?pChunkCache:[];if(tmpChunkSize<=0){return tmpChunkCache;}while(tmpInputArray.length){tmpChunkCache.push(tmpInputArray.splice(0,tmpChunkSize));}return tmpChunkCache;}}module.exports=FableUtility;},{"./Fable-Utility-Template.js":33,"async/eachLimit":6,"async/waterfall":22}],35:[function(require,module,exports){/**
|
|
540
|
+
* Fable Application Services Support Library
|
|
487
541
|
* @license MIT
|
|
488
542
|
* @author <steven@velozo.com>
|
|
489
|
-
*/const libFableSettings=require('fable-settings').FableSettings;const libFableUUID=require('fable-uuid').FableUUID;const libFableLog=require('fable-log').FableLog
|
|
490
|
-
|
|
491
|
-
*
|
|
492
|
-
* @class Fable
|
|
493
|
-
*/class Fable{constructor(pSettings){let tmpSettings=new libFableSettings(pSettings);this.settingsManager=tmpSettings;// Instantiate the UUID generator
|
|
494
|
-
this.libUUID=new libFableUUID(this.settingsManager.settings);this.log=new libFableLog(this.settingsManager.settings);this.log.initialize();}get settings(){return this.settingsManager.settings;}get fable(){return this;}getUUID(){return this.libUUID.getUUID();}}// This is for backwards compatibility
|
|
495
|
-
function autoConstruct(pSettings){return new Fable(pSettings);}module.exports=Fable;},{"fable-log":25,"fable-settings":28,"fable-uuid":30}],32:[function(require,module,exports){'use strict';var UTF8_ACCEPT=12;var UTF8_REJECT=0;var UTF8_DATA=[// The first part of the table maps bytes to character to a transition.
|
|
543
|
+
*/const libFableSettings=require('fable-settings').FableSettings;const libFableUUID=require('fable-uuid').FableUUID;const libFableLog=require('fable-log').FableLog;const libFableUtility=require('./Fable-Utility.js');class Fable{constructor(pSettings){let tmpSettings=new libFableSettings(pSettings);this.settingsManager=tmpSettings;// Instantiate the UUID generator
|
|
544
|
+
this.libUUID=new libFableUUID(this.settingsManager.settings);this.log=new libFableLog(this.settingsManager.settings);this.log.initialize();this.Utility=new libFableUtility(this);}get settings(){return this.settingsManager.settings;}get fable(){return this;}getUUID(){return this.libUUID.getUUID();}}module.exports=Fable;},{"./Fable-Utility.js":34,"fable-log":27,"fable-settings":30,"fable-uuid":32}],36:[function(require,module,exports){'use strict';var UTF8_ACCEPT=12;var UTF8_REJECT=0;var UTF8_DATA=[// The first part of the table maps bytes to character to a transition.
|
|
496
545
|
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,// The second part of the table maps a state to a new state when adding a
|
|
497
546
|
// transition.
|
|
498
547
|
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,// The third part maps the current transition to a mask that needs to apply
|
|
499
548
|
// to the byte.
|
|
500
|
-
0x7F,0x3F,0x3F,0x3F,0x00,0x1F,0x0F,0x0F,0x0F,0x07,0x07,0x07];function decodeURIComponent(uri){var percentPosition=uri.indexOf('%');if(percentPosition===-1)return uri;var length=uri.length;var decoded='';var last=0;var codepoint=0;var startOfOctets=percentPosition;var state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4);var low=hexCodeToInt(uri[percentPosition+2],0);var byte=high|low;var type=UTF8_DATA[byte];state=UTF8_DATA[256+state+type];codepoint=codepoint<<6|byte&UTF8_DATA[364+type];if(state===UTF8_ACCEPT){decoded+=uri.slice(last,startOfOctets);decoded+=codepoint<=0xFFFF?String.fromCharCode(codepoint):String.fromCharCode(0xD7C0+(codepoint>>10),0xDC00+(codepoint&0x3FF));codepoint=0;last=percentPosition+3;percentPosition=startOfOctets=uri.indexOf('%',last);}else if(state===UTF8_REJECT){return null;}else{percentPosition+=3;if(percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null;}}return decoded+uri.slice(last);}var HEX={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'A':10,'b':11,'B':11,'c':12,'C':12,'d':13,'D':13,'e':14,'E':14,'f':15,'F':15};function hexCodeToInt(c,shift){var i=HEX[c];return i===undefined?255:i<<shift;}module.exports=decodeURIComponent;},{}],
|
|
549
|
+
0x7F,0x3F,0x3F,0x3F,0x00,0x1F,0x0F,0x0F,0x0F,0x07,0x07,0x07];function decodeURIComponent(uri){var percentPosition=uri.indexOf('%');if(percentPosition===-1)return uri;var length=uri.length;var decoded='';var last=0;var codepoint=0;var startOfOctets=percentPosition;var state=UTF8_ACCEPT;while(percentPosition>-1&&percentPosition<length){var high=hexCodeToInt(uri[percentPosition+1],4);var low=hexCodeToInt(uri[percentPosition+2],0);var byte=high|low;var type=UTF8_DATA[byte];state=UTF8_DATA[256+state+type];codepoint=codepoint<<6|byte&UTF8_DATA[364+type];if(state===UTF8_ACCEPT){decoded+=uri.slice(last,startOfOctets);decoded+=codepoint<=0xFFFF?String.fromCharCode(codepoint):String.fromCharCode(0xD7C0+(codepoint>>10),0xDC00+(codepoint&0x3FF));codepoint=0;last=percentPosition+3;percentPosition=startOfOctets=uri.indexOf('%',last);}else if(state===UTF8_REJECT){return null;}else{percentPosition+=3;if(percentPosition<length&&uri.charCodeAt(percentPosition)===37)continue;return null;}}return decoded+uri.slice(last);}var HEX={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'A':10,'b':11,'B':11,'c':12,'C':12,'d':13,'D':13,'e':14,'E':14,'f':15,'F':15};function hexCodeToInt(c,shift){var i=HEX[c];return i===undefined?255:i<<shift;}module.exports=decodeURIComponent;},{}],37:[function(require,module,exports){'use strict';// do not edit .js files directly - edit src/index.jst
|
|
501
550
|
module.exports=function equal(a,b){if(a===b)return true;if(a&&b&&typeof a=='object'&&typeof b=='object'){if(a.constructor!==b.constructor)return false;var length,i,keys;if(Array.isArray(a)){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(!equal(a[i],b[i]))return false;return true;}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();keys=Object.keys(a);length=keys.length;if(length!==Object.keys(b).length)return false;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i]))return false;for(i=length;i--!==0;){var key=keys[i];if(!equal(a[key],b[key]))return false;}return true;}// true if both NaN, false otherwise
|
|
502
|
-
return a!==a&&b!==b;};},{}],
|
|
551
|
+
return a!==a&&b!==b;};},{}],38:[function(require,module,exports){"use strict";const parse=require("./parse");const stringify=require("./stringify");const fastQuerystring={parse,stringify};/**
|
|
503
552
|
* Enable TS and JS support
|
|
504
553
|
*
|
|
505
554
|
* - `const qs = require('fast-querystring')`
|
|
506
555
|
* - `import qs from 'fast-querystring'`
|
|
507
|
-
*/module.exports=fastQuerystring;module.exports.default=fastQuerystring;module.exports.parse=parse;module.exports.stringify=stringify;},{"./parse":
|
|
556
|
+
*/module.exports=fastQuerystring;module.exports.default=fastQuerystring;module.exports.parse=parse;module.exports.stringify=stringify;},{"./parse":40,"./stringify":41}],39:[function(require,module,exports){// This file is taken from Node.js project.
|
|
508
557
|
// Full implementation can be found from https://github.com/nodejs/node/blob/main/lib/internal/querystring.js
|
|
509
558
|
const hexTable=Array.from({length:256},(_,i)=>"%"+((i<16?"0":"")+i.toString(16)).toUpperCase());// These characters do not need escaping when generating query strings:
|
|
510
559
|
// ! - . _ ~
|
|
@@ -530,7 +579,7 @@ if(c<0x800){lastPos=i+1;out+=hexTable[0xc0|c>>6]+hexTable[0x80|c&0x3f];continue;
|
|
|
530
579
|
++i;// This branch should never happen because all URLSearchParams entries
|
|
531
580
|
// should already be converted to USVString. But, included for
|
|
532
581
|
// completion's sake anyway.
|
|
533
|
-
if(i>=len){throw new Error("URI malformed");}const c2=str.charCodeAt(i)&0x3ff;lastPos=i+1;c=0x10000+((c&0x3ff)<<10|c2);out+=hexTable[0xf0|c>>18]+hexTable[0x80|c>>12&0x3f]+hexTable[0x80|c>>6&0x3f]+hexTable[0x80|c&0x3f];}if(lastPos===0)return str;if(lastPos<len)return out+str.slice(lastPos);return out;}module.exports={encodeString};},{}],
|
|
582
|
+
if(i>=len){throw new Error("URI malformed");}const c2=str.charCodeAt(i)&0x3ff;lastPos=i+1;c=0x10000+((c&0x3ff)<<10|c2);out+=hexTable[0xf0|c>>18]+hexTable[0x80|c>>12&0x3f]+hexTable[0x80|c>>6&0x3f]+hexTable[0x80|c&0x3f];}if(lastPos===0)return str;if(lastPos<len)return out+str.slice(lastPos);return out;}module.exports={encodeString};},{}],40:[function(require,module,exports){"use strict";const fastDecode=require("fast-decode-uri-component");const plusRegex=/\+/g;const Empty=function(){};Empty.prototype=Object.create(null);/**
|
|
534
583
|
* @callback parse
|
|
535
584
|
* @param {string} input
|
|
536
585
|
*/function parse(input){// Optimization: Use new Empty() instead of Object.create(null) for performance
|
|
@@ -547,15 +596,15 @@ value="";startingIndex=i;equalityIndex=i;shouldDecodeKey=false;shouldDecodeValue
|
|
|
547
596
|
else if(c===61){if(equalityIndex<=startingIndex){equalityIndex=i;}// If '=' character occurs again, we should decode the input.
|
|
548
597
|
else{shouldDecodeValue=true;}}// Check '+', and remember to replace it with empty space.
|
|
549
598
|
else if(c===43){if(equalityIndex>startingIndex){valueHasPlus=true;}else{keyHasPlus=true;}}// Check '%' character for encoding
|
|
550
|
-
else if(c===37){if(equalityIndex>startingIndex){shouldDecodeValue=true;}else{shouldDecodeKey=true;}}}return result;}module.exports=parse;},{"fast-decode-uri-component":
|
|
599
|
+
else if(c===37){if(equalityIndex>startingIndex){shouldDecodeValue=true;}else{shouldDecodeKey=true;}}}return result;}module.exports=parse;},{"fast-decode-uri-component":36}],41:[function(require,module,exports){"use strict";const{encodeString}=require("./internals/querystring");function getAsPrimitive(value){const type=typeof value;if(type==="string"){// Length check is handled inside encodeString function
|
|
551
600
|
return encodeString(value);}else if(type==="bigint"){return value.toString();}else if(type==="boolean"){return value?"true":"false";}else if(type==="number"&&Number.isFinite(value)){return value<1e21?""+value:encodeString(""+value);}return"";}/**
|
|
552
601
|
* @param {Record<string, string | number | boolean
|
|
553
602
|
* | ReadonlyArray<string | number | boolean> | null>} input
|
|
554
603
|
* @returns {string}
|
|
555
604
|
*/function stringify(input){let result="";if(input===null||typeof input!=="object"){return result;}const separator="&";const keys=Object.keys(input);const keyLength=keys.length;let valueLength=0;for(let i=0;i<keyLength;i++){const key=keys[i];const value=input[key];const encodedKey=encodeString(key)+"=";if(i){result+=separator;}if(Array.isArray(value)){valueLength=value.length;for(let j=0;j<valueLength;j++){if(j){result+=separator;}// Optimization: Dividing into multiple lines improves the performance.
|
|
556
605
|
// Since v8 does not need to care about the '+' character if it was one-liner.
|
|
557
|
-
result+=encodedKey;result+=getAsPrimitive(value[j]);}}else{result+=encodedKey;result+=getAsPrimitive(value);}}return result;}module.exports=stringify;},{"./internals/querystring":
|
|
558
|
-
}}class ParametricNode extends ParentNode{constructor(regex,staticSuffix){super();this.isRegex=!!regex;this.regex=regex||null;this.staticSuffix=staticSuffix||null;this.kind=NODE_TYPES.PARAMETRIC;}getNextNode(path,pathIndex){return this.findStaticMatchingChild(path,pathIndex);}}class WildcardNode extends Node{constructor(){super();this.kind=NODE_TYPES.WILDCARD;}getNextNode(){return null;}}module.exports={StaticNode,ParametricNode,WildcardNode,NODE_TYPES};},{"./handler_storage":
|
|
606
|
+
result+=encodedKey;result+=getAsPrimitive(value[j]);}}else{result+=encodedKey;result+=getAsPrimitive(value);}}return result;}module.exports=stringify;},{"./internals/querystring":39}],42:[function(require,module,exports){'use strict';const HandlerStorage=require('./handler_storage');const NODE_TYPES={STATIC:0,PARAMETRIC:1,WILDCARD:2};class Node{constructor(){this.handlerStorage=new HandlerStorage();}}class ParentNode extends Node{constructor(){super();this.staticChildren={};}findStaticMatchingChild(path,pathIndex){const staticChild=this.staticChildren[path.charAt(pathIndex)];if(staticChild===undefined||!staticChild.matchPrefix(path,pathIndex)){return null;}return staticChild;}createStaticChild(path){if(path.length===0){return this;}let staticChild=this.staticChildren[path.charAt(0)];if(staticChild){let i=1;for(;i<staticChild.prefix.length;i++){if(path.charCodeAt(i)!==staticChild.prefix.charCodeAt(i)){staticChild=staticChild.split(this,i);break;}}return staticChild.createStaticChild(path.slice(i));}const label=path.charAt(0);this.staticChildren[label]=new StaticNode(path);return this.staticChildren[label];}}class StaticNode extends ParentNode{constructor(prefix){super();this.prefix=prefix;this.wildcardChild=null;this.parametricChildren=[];this.kind=NODE_TYPES.STATIC;this._compilePrefixMatch();}createParametricChild(regex,staticSuffix){const regexpSource=regex&®ex.source;let parametricChild=this.parametricChildren.find(child=>{const childRegexSource=child.regex&&child.regex.source;return childRegexSource===regexpSource;});if(parametricChild){return parametricChild;}parametricChild=new ParametricNode(regex,staticSuffix);this.parametricChildren.push(parametricChild);this.parametricChildren.sort((child1,child2)=>{if(!child1.isRegex)return 1;if(!child2.isRegex)return-1;if(child1.staticSuffix===null)return 1;if(child2.staticSuffix===null)return-1;if(child2.staticSuffix.endsWith(child1.staticSuffix))return 1;if(child1.staticSuffix.endsWith(child2.staticSuffix))return-1;return 0;});return parametricChild;}createWildcardChild(){if(this.wildcardChild){return this.wildcardChild;}this.wildcardChild=new WildcardNode();return this.wildcardChild;}split(parentNode,length){const parentPrefix=this.prefix.slice(0,length);const childPrefix=this.prefix.slice(length);this.prefix=childPrefix;this._compilePrefixMatch();const staticNode=new StaticNode(parentPrefix);staticNode.staticChildren[childPrefix.charAt(0)]=this;parentNode.staticChildren[parentPrefix.charAt(0)]=staticNode;return staticNode;}getNextNode(path,pathIndex,nodeStack,paramsCount){let node=this.findStaticMatchingChild(path,pathIndex);let parametricBrotherNodeIndex=0;if(node===null){if(this.parametricChildren.length===0){return this.wildcardChild;}node=this.parametricChildren[0];parametricBrotherNodeIndex=1;}if(this.wildcardChild!==null){nodeStack.push({paramsCount,brotherPathIndex:pathIndex,brotherNode:this.wildcardChild});}for(let i=this.parametricChildren.length-1;i>=parametricBrotherNodeIndex;i--){nodeStack.push({paramsCount,brotherPathIndex:pathIndex,brotherNode:this.parametricChildren[i]});}return node;}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>true;return;}const lines=[];for(let i=1;i<this.prefix.length;i++){const charCode=this.prefix.charCodeAt(i);lines.push(`path.charCodeAt(i + ${i}) === ${charCode}`);}this.matchPrefix=new Function('path','i',`return ${lines.join(' && ')}`);// eslint-disable-line
|
|
607
|
+
}}class ParametricNode extends ParentNode{constructor(regex,staticSuffix){super();this.isRegex=!!regex;this.regex=regex||null;this.staticSuffix=staticSuffix||null;this.kind=NODE_TYPES.PARAMETRIC;}getNextNode(path,pathIndex){return this.findStaticMatchingChild(path,pathIndex);}}class WildcardNode extends Node{constructor(){super();this.kind=NODE_TYPES.WILDCARD;}getNextNode(){return null;}}module.exports={StaticNode,ParametricNode,WildcardNode,NODE_TYPES};},{"./handler_storage":43}],43:[function(require,module,exports){'use strict';class HandlerStorage{constructor(){this.unconstrainedHandler=null;// optimized reference to the handler that will match most of the time
|
|
559
608
|
this.constraints=[];this.handlers=[];// unoptimized list of handler objects for which the fast matcher function will be compiled
|
|
560
609
|
this.constrainedHandlerStores=null;}// This is the hot path for node handler finding -- change with care!
|
|
561
610
|
getMatchingHandler(derivedConstraints){if(derivedConstraints===undefined){return this.unconstrainedHandler;}return this._getHandlerMatchingConstraints(derivedConstraints);}addHandler(handler,params,store,constrainer,constraints){const handlerObject={handler,params,constraints,store:store||null,_createParamsObject:this._compileCreateParamsObject(params)};if(Object.keys(constraints).length===0){this.unconstrainedHandler=handlerObject;}for(const constraint of Object.keys(constraints)){if(!this.constraints.includes(constraint)){if(constraint==='version'){// always check the version constraint first as it is the most selective
|
|
@@ -594,7 +643,7 @@ const strategy=constrainer.strategies[constraint];const matchMask=strategy.mustM
|
|
|
594
643
|
// 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.
|
|
595
644
|
for(const constraint in constrainer.strategies){const strategy=constrainer.strategies[constraint];if(strategy.mustMatchWhenDerived&&!this.constraints.includes(constraint)){lines.push(`if (derivedConstraints.${constraint} !== undefined) return null`);}}// 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
|
|
596
645
|
lines.push('return this.handlers[Math.floor(Math.log2(candidates))]');this._getHandlerMatchingConstraints=new Function('derivedConstraints',lines.join('\n'));// eslint-disable-line
|
|
597
|
-
}}module.exports=HandlerStorage;},{}],
|
|
646
|
+
}}module.exports=HandlerStorage;},{}],44:[function(require,module,exports){'use strict';/*
|
|
598
647
|
Char codes:
|
|
599
648
|
'!': 33 - !
|
|
600
649
|
'#': 35 - %23
|
|
@@ -642,15 +691,15 @@ if(regexString.charCodeAt(1)===94){regexString=regexString.slice(0,1)+regexStrin
|
|
|
642
691
|
// see issues #62 and #63 for more info
|
|
643
692
|
var parentheses=1;while(idx<path.length){idx++;// ignore skipped chars
|
|
644
693
|
if(path[idx]==='\\'){idx++;continue;}if(path[idx]===')'){parentheses--;}else if(path[idx]==='('){parentheses++;}if(!parentheses)return idx;}throw new TypeError('Invalid regexp expression in "'+path+'"');}function defaultBuildPrettyMeta(route){// buildPrettyMeta function must return an object, which will be parsed into key/value pairs for display
|
|
645
|
-
if(!route)return{};if(!route.store)return{};return Object.assign({},route.store);}},{"./custom_node":
|
|
694
|
+
if(!route)return{};if(!route.store)return{};return Object.assign({},route.store);}},{"./custom_node":42,"./lib/constrainer":45,"./lib/http-methods":46,"./lib/pretty-print":47,"./lib/url-sanitizer":50,"assert":1,"fast-deep-equal":37,"fast-querystring":38,"safe-regex2":57}],45:[function(require,module,exports){'use strict';const acceptVersionStrategy=require('./strategies/accept-version');const acceptHostStrategy=require('./strategies/accept-host');const assert=require('assert');class Constrainer{constructor(customStrategies){this.strategies={version:acceptVersionStrategy,host:acceptHostStrategy};this.strategiesInUse=new Set();this.asyncStrategiesInUse=new Set();// validate and optimize prototypes of given custom strategies
|
|
646
695
|
if(customStrategies){for(const strategy of Object.values(customStrategies)){this.addConstraintStrategy(strategy);}}}isStrategyUsed(strategyName){return this.strategiesInUse.has(strategyName)||this.asyncStrategiesInUse.has(strategyName);}hasConstraintStrategy(strategyName){const customConstraintStrategy=this.strategies[strategyName];if(customConstraintStrategy!==undefined){return customConstraintStrategy.isCustom||this.isStrategyUsed(strategyName);}return false;}addConstraintStrategy(strategy){assert(typeof strategy.name==='string'&&strategy.name!=='','strategy.name is required.');assert(strategy.storage&&typeof strategy.storage==='function','strategy.storage function is required.');assert(strategy.deriveConstraint&&typeof strategy.deriveConstraint==='function','strategy.deriveConstraint function is required.');if(this.strategies[strategy.name]&&this.strategies[strategy.name].isCustom){throw new Error(`There already exists a custom constraint with the name ${strategy.name}.`);}if(this.isStrategyUsed(strategy.name)){throw new Error(`There already exists a route with ${strategy.name} constraint.`);}strategy.isCustom=true;strategy.isAsync=strategy.deriveConstraint.length===3;this.strategies[strategy.name]=strategy;if(strategy.mustMatchWhenDerived){this.noteUsage({[strategy.name]:strategy});}}deriveConstraints(req,ctx,done){const constraints=this.deriveSyncConstraints(req,ctx);if(done===undefined){return constraints;}this.deriveAsyncConstraints(constraints,req,ctx,done);}deriveSyncConstraints(req,ctx){return undefined;}// When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used.
|
|
647
696
|
noteUsage(constraints){if(constraints){const beforeSize=this.strategiesInUse.size;for(const key in constraints){const strategy=this.strategies[key];if(strategy.isAsync){this.asyncStrategiesInUse.add(key);}else{this.strategiesInUse.add(key);}}if(beforeSize!==this.strategiesInUse.size){this._buildDeriveConstraints();}}}newStoreForConstraint(constraint){if(!this.strategies[constraint]){throw new Error(`No strategy registered for constraint key ${constraint}`);}return this.strategies[constraint].storage();}validateConstraints(constraints){for(const key in constraints){const value=constraints[key];if(typeof value==='undefined'){throw new Error('Can\'t pass an undefined constraint value, must pass null or no key at all');}const strategy=this.strategies[key];if(!strategy){throw new Error(`No strategy registered for constraint key ${key}`);}if(strategy.validate){strategy.validate(value);}}}deriveAsyncConstraints(constraints,req,ctx,done){let asyncConstraintsCount=this.asyncStrategiesInUse.size;if(asyncConstraintsCount===0){done(null,constraints);return;}constraints=constraints||{};for(const key of this.asyncStrategiesInUse){const strategy=this.strategies[key];strategy.deriveConstraint(req,ctx,(err,constraintValue)=>{if(err!==null){done(err);return;}constraints[key]=constraintValue;if(--asyncConstraintsCount===0){done(null,constraints);}});}}// 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.
|
|
648
697
|
// 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
|
|
649
698
|
// This allows us to not allocate an object to hold constraint values if no constraints are defined.
|
|
650
699
|
_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;const lines=['return {'];for(const key of this.strategiesInUse){const strategy=this.strategies[key];// Optimization: inline the derivation for the common built in constraints
|
|
651
700
|
if(!strategy.isCustom){if(key==='version'){lines.push(' version: req.headers[\'accept-version\'],');}else if(key==='host'){lines.push(' host: req.headers.host || req.headers[\':authority\'],');}else{throw new Error('unknown non-custom strategy for compiling constraint derivation function');}}else{lines.push(` ${strategy.name}: this.strategies.${key}.deriveConstraint(req, ctx),`);}}lines.push('}');this.deriveSyncConstraints=new Function('req','ctx',lines.join('\n')).bind(this);// eslint-disable-line
|
|
652
|
-
}}module.exports=Constrainer;},{"./strategies/accept-host":
|
|
653
|
-
const httpMethods=['ACL','BIND','CHECKOUT','CONNECT','COPY','DELETE','GET','HEAD','LINK','LOCK','M-SEARCH','MERGE','MKACTIVITY','MKCALENDAR','MKCOL','MOVE','NOTIFY','OPTIONS','PATCH','POST','PROPFIND','PROPPATCH','PURGE','PUT','REBIND','REPORT','SEARCH','SOURCE','SUBSCRIBE','TRACE','UNBIND','UNLINK','UNLOCK','UNSUBSCRIBE'];module.exports=httpMethods;},{}],
|
|
701
|
+
}}module.exports=Constrainer;},{"./strategies/accept-host":48,"./strategies/accept-version":49,"assert":1}],46:[function(require,module,exports){'use strict';// defined by Node.js http module, a snapshot from Node.js 18.12.0
|
|
702
|
+
const httpMethods=['ACL','BIND','CHECKOUT','CONNECT','COPY','DELETE','GET','HEAD','LINK','LOCK','M-SEARCH','MERGE','MKACTIVITY','MKCALENDAR','MKCOL','MOVE','NOTIFY','OPTIONS','PATCH','POST','PROPFIND','PROPPATCH','PURGE','PUT','REBIND','REPORT','SEARCH','SOURCE','SUBSCRIBE','TRACE','UNBIND','UNLINK','UNLOCK','UNSUBSCRIBE'];module.exports=httpMethods;},{}],47:[function(require,module,exports){'use strict';/* eslint-disable no-multi-spaces */const indent=' ';const branchIndent='│ ';const midBranchIndent='├── ';const endBranchIndent='└── ';const wildcardDelimiter='*';const pathDelimiter='/';const pathRegExp=/(?=\/)/;/* eslint-enable */function parseFunctionName(fn){let fName=fn.name||'';fName=fName.replace('bound','').trim();fName=(fName||'anonymous')+'()';return fName;}function parseMeta(meta){if(Array.isArray(meta))return meta.map(m=>parseMeta(m));if(typeof meta==='symbol')return meta.toString();if(typeof meta==='function')return parseFunctionName(meta);return meta;}function buildMetaObject(route,metaArray){const out={};const cleanMeta=this.buildPrettyMeta(route);if(!Array.isArray(metaArray))metaArray=cleanMeta?Reflect.ownKeys(cleanMeta):[];metaArray.forEach(m=>{const metaKey=typeof m==='symbol'?m.toString():m;if(cleanMeta&&cleanMeta[m]){out[metaKey]=parseMeta(cleanMeta[m]);}});return out;}function prettyPrintRoutesArray(routeArray,opts={}){if(!this.buildPrettyMeta)throw new Error('buildPrettyMeta not defined');opts.includeMeta=opts.includeMeta||null;// array of meta objects to display
|
|
654
703
|
const mergedRouteArray=[];let tree='';routeArray.sort((a,b)=>{if(!a.path||!b.path)return 0;return a.path.localeCompare(b.path);});// merge alike paths
|
|
655
704
|
for(let i=0;i<routeArray.length;i++){const route=routeArray[i];const pathExists=mergedRouteArray.find(r=>route.path===r.path);if(pathExists){// path already declared, add new method and break out of loop
|
|
656
705
|
pathExists.handlers.push({method:route.method,opts:route.opts.constraints||undefined,meta:opts.includeMeta?buildMetaObject.call(this,route,opts.includeMeta):null});continue;}const routeHandler={method:route.method,opts:route.opts.constraints||undefined,meta:opts.includeMeta?buildMetaObject.call(this,route,opts.includeMeta):null};mergedRouteArray.push({path:route.path,methods:[route.method],opts:[route.opts],handlers:[routeHandler]});}// insert root level path if none defined
|
|
@@ -668,13 +717,13 @@ const paramIndices=flattenedNode.prefix.split('').map((ch,idx)=>ch===':'?idx:nul
|
|
|
668
717
|
name+=flattenedNode.prefix.slice(prevLoc,loc+1);// insert parameters
|
|
669
718
|
name+=handler.params[handler.params.length-paramIndices.length+idx];if(idx===paramIndices.length-1)name+=flattenedNode.prefix.slice(loc+1);prevLoc=loc+1;});}else{// there are no parameters, return full object
|
|
670
719
|
name=flattenedNode.prefix;}if(index===0){paramName+=`${name} ${suffix}`;}else{paramName+=`\n${prefix}${tail?indent:branchIndent}${name} ${suffix}`;}if(opts.includeMeta){const meta=buildMetaObject.call(this,handler,opts.includeMeta);Object.keys(meta).forEach((m,hidx)=>{paramName+=`\n${prefix||''}${tail?indent:branchIndent}`;paramName+=`• (${m}) ${JSON.stringify(meta[m])}`;});}});}else{paramName=flattenedNode.prefix;}let tree=`${prefix}${tail?endBranchIndent:midBranchIndent}${paramName}\n`;prefix=`${prefix}${tail?indent:branchIndent}`;const labels=Object.keys(flattenedNode.children);for(let i=0;i<labels.length;i++){const child=flattenedNode.children[labels[i]];tree+=prettyPrintFlattenedNode.call(this,child,prefix,i===labels.length-1,opts);}return tree;}function flattenNode(flattened,node,method){if(node.handlerStorage.handlers.length!==0){flattened.nodes.push({method,node});}if(node.parametricChildren&&node.parametricChildren[0]){if(!flattened.children[':']){flattened.children[':']={prefix:':',nodes:[],children:{}};}flattenNode(flattened.children[':'],node.parametricChildren[0],method);}if(node.wildcardChild){if(!flattened.children['*']){flattened.children['*']={prefix:'*',nodes:[],children:{}};}flattenNode(flattened.children['*'],node.wildcardChild,method);}if(node.staticChildren){for(const child of Object.values(node.staticChildren)){// split on the slash separator but use a regex to lookahead and not actually match it, preserving it in the returned string segments
|
|
671
|
-
const childPrefixSegments=child.prefix.split(pathRegExp);let cursor=flattened;let parent;for(const segment of childPrefixSegments){parent=cursor;cursor=cursor.children[segment];if(!cursor){cursor={prefix:segment,nodes:[],children:{}};parent.children[segment]=cursor;}}flattenNode(cursor,child,method);}}}function compressFlattenedNode(flattenedNode){const childKeys=Object.keys(flattenedNode.children);if(flattenedNode.nodes.length===0&&childKeys.length===1){const child=flattenedNode.children[childKeys[0]];if(child.nodes.length<=1){compressFlattenedNode(child);flattenedNode.nodes=child.nodes;flattenedNode.prefix+=child.prefix;flattenedNode.children=child.children;return flattenedNode;}}for(const key of Object.keys(flattenedNode.children)){compressFlattenedNode(flattenedNode.children[key]);}return flattenedNode;}module.exports={flattenNode,compressFlattenedNode,prettyPrintFlattenedNode,prettyPrintRoutesArray};},{}],
|
|
720
|
+
const childPrefixSegments=child.prefix.split(pathRegExp);let cursor=flattened;let parent;for(const segment of childPrefixSegments){parent=cursor;cursor=cursor.children[segment];if(!cursor){cursor={prefix:segment,nodes:[],children:{}};parent.children[segment]=cursor;}}flattenNode(cursor,child,method);}}}function compressFlattenedNode(flattenedNode){const childKeys=Object.keys(flattenedNode.children);if(flattenedNode.nodes.length===0&&childKeys.length===1){const child=flattenedNode.children[childKeys[0]];if(child.nodes.length<=1){compressFlattenedNode(child);flattenedNode.nodes=child.nodes;flattenedNode.prefix+=child.prefix;flattenedNode.children=child.children;return flattenedNode;}}for(const key of Object.keys(flattenedNode.children)){compressFlattenedNode(flattenedNode.children[key]);}return flattenedNode;}module.exports={flattenNode,compressFlattenedNode,prettyPrintFlattenedNode,prettyPrintRoutesArray};},{}],48:[function(require,module,exports){'use strict';const assert=require('assert');function HostStorage(){const hosts={};const regexHosts=[];return{get:host=>{const exact=hosts[host];if(exact){return exact;}for(const regex of regexHosts){if(regex.host.test(host)){return regex.value;}}},set:(host,value)=>{if(host instanceof RegExp){regexHosts.push({host,value});}else{hosts[host]=value;}}};}module.exports={name:'host',mustMatchWhenDerived:false,storage:HostStorage,validate(value){assert(typeof value==='string'||Object.prototype.toString.call(value)==='[object RegExp]','Host should be a string or a RegExp');}};},{"assert":1}],49:[function(require,module,exports){'use strict';const assert=require('assert');function SemVerStore(){if(!(this instanceof SemVerStore)){return new SemVerStore();}this.store={};this.maxMajor=0;this.maxMinors={};this.maxPatches={};}SemVerStore.prototype.set=function(version,store){if(typeof version!=='string'){throw new TypeError('Version should be a string');}let[major,minor,patch]=version.split('.');major=Number(major)||0;minor=Number(minor)||0;patch=Number(patch)||0;if(major>=this.maxMajor){this.maxMajor=major;this.store.x=store;this.store['*']=store;this.store['x.x']=store;this.store['x.x.x']=store;}if(minor>=(this.maxMinors[major]||0)){this.maxMinors[major]=minor;this.store[`${major}.x`]=store;this.store[`${major}.x.x`]=store;}if(patch>=(this.store[`${major}.${minor}`]||0)){this.maxPatches[`${major}.${minor}`]=patch;this.store[`${major}.${minor}.x`]=store;}this.store[`${major}.${minor}.${patch}`]=store;return this;};SemVerStore.prototype.get=function(version){return this.store[version];};module.exports={name:'version',mustMatchWhenDerived:true,storage:SemVerStore,validate(value){assert(typeof value==='string','Version should be a string');}};},{"assert":1}],50:[function(require,module,exports){'use strict';// It must spot all the chars where decodeURIComponent(x) !== decodeURI(x)
|
|
672
721
|
// The chars are: # $ & + , / : ; = ? @
|
|
673
722
|
function decodeComponentChar(highCharCode,lowCharCode){if(highCharCode===50){if(lowCharCode===53)return'%';if(lowCharCode===51)return'#';if(lowCharCode===52)return'$';if(lowCharCode===54)return'&';if(lowCharCode===66)return'+';if(lowCharCode===98)return'+';if(lowCharCode===67)return',';if(lowCharCode===99)return',';if(lowCharCode===70)return'/';if(lowCharCode===102)return'/';return null;}if(highCharCode===51){if(lowCharCode===65)return':';if(lowCharCode===97)return':';if(lowCharCode===66)return';';if(lowCharCode===98)return';';if(lowCharCode===68)return'=';if(lowCharCode===100)return'=';if(lowCharCode===70)return'?';if(lowCharCode===102)return'?';return null;}if(highCharCode===52&&lowCharCode===48){return'@';}return null;}function safeDecodeURI(path){let shouldDecode=false;let shouldDecodeParam=false;let querystring='';for(let i=1;i<path.length;i++){const charCode=path.charCodeAt(i);if(charCode===37){const highCharCode=path.charCodeAt(i+1);const lowCharCode=path.charCodeAt(i+2);if(decodeComponentChar(highCharCode,lowCharCode)===null){shouldDecode=true;}else{shouldDecodeParam=true;// %25 - encoded % char. We need to encode one more time to prevent double decoding
|
|
674
723
|
if(highCharCode===50&&lowCharCode===53){shouldDecode=true;path=path.slice(0,i+1)+'25'+path.slice(i+1);i+=2;}i+=2;}// Some systems do not follow RFC and separate the path and query
|
|
675
724
|
// string with a `;` character (code 59), e.g. `/foo;jsessionid=123456`.
|
|
676
725
|
// Thus, we need to split on `;` as well as `?` and `#`.
|
|
677
|
-
}else if(charCode===63||charCode===59||charCode===35){querystring=path.slice(i+1);path=path.slice(0,i);break;}}const decodedPath=shouldDecode?decodeURI(path):path;return{path:decodedPath,querystring,shouldDecodeParam};}function safeDecodeURIComponent(uriComponent){const startIndex=uriComponent.indexOf('%');if(startIndex===-1)return uriComponent;let decoded='';let lastIndex=startIndex;for(let i=startIndex;i<uriComponent.length;i++){if(uriComponent.charCodeAt(i)===37){const highCharCode=uriComponent.charCodeAt(i+1);const lowCharCode=uriComponent.charCodeAt(i+2);const decodedChar=decodeComponentChar(highCharCode,lowCharCode);decoded+=uriComponent.slice(lastIndex,i)+decodedChar;lastIndex=i+3;}}return uriComponent.slice(0,startIndex)+decoded+uriComponent.slice(lastIndex);}module.exports={safeDecodeURI,safeDecodeURIComponent};},{}],
|
|
726
|
+
}else if(charCode===63||charCode===59||charCode===35){querystring=path.slice(i+1);path=path.slice(0,i);break;}}const decodedPath=shouldDecode?decodeURI(path):path;return{path:decodedPath,querystring,shouldDecodeParam};}function safeDecodeURIComponent(uriComponent){const startIndex=uriComponent.indexOf('%');if(startIndex===-1)return uriComponent;let decoded='';let lastIndex=startIndex;for(let i=startIndex;i<uriComponent.length;i++){if(uriComponent.charCodeAt(i)===37){const highCharCode=uriComponent.charCodeAt(i+1);const lowCharCode=uriComponent.charCodeAt(i+2);const decodedChar=decodeComponentChar(highCharCode,lowCharCode);decoded+=uriComponent.slice(lastIndex,i)+decodedChar;lastIndex=i+3;}}return uriComponent.slice(0,startIndex)+decoded+uriComponent.slice(lastIndex);}module.exports={safeDecodeURI,safeDecodeURIComponent};},{}],51:[function(require,module,exports){/*
|
|
678
727
|
object-assign
|
|
679
728
|
(c) Sindre Sorhus
|
|
680
729
|
@license MIT
|
|
@@ -684,12 +733,12 @@ var test1=new String('abc');// eslint-disable-line no-new-wrappers
|
|
|
684
733
|
test1[5]='de';if(Object.getOwnPropertyNames(test1)[0]==='5'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
|
|
685
734
|
var test2={};for(var i=0;i<10;i++){test2['_'+String.fromCharCode(i)]=i;}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n];});if(order2.join('')!=='0123456789'){return false;}// https://bugs.chromium.org/p/v8/issues/detail?id=3056
|
|
686
735
|
var test3={};'abcdefghijklmnopqrst'.split('').forEach(function(letter){test3[letter]=letter;});if(Object.keys(Object.assign({},test3)).join('')!=='abcdefghijklmnopqrst'){return false;}return true;}catch(err){// We don't expect any of the above to throw, but better to be safe.
|
|
687
|
-
return false;}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key];}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]];}}}}return to;};},{}],
|
|
736
|
+
return false;}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key];}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]];}}}}return to;};},{}],52:[function(require,module,exports){class OratorServiceServerBase{constructor(pOrator){this.orator=pOrator;this.log=pOrator.log;this.Name=this.orator.settings.Product;this.URL='BASE_SERVICE_SERVER';this.Port=this.orator.settings.ServicePort;this.Active=false;}/*
|
|
688
737
|
* Service Lifecycle Functions
|
|
689
738
|
*************************************************************************/listen(pPort,fCallback){// Sometimes, listen does not listen on network calls.
|
|
690
739
|
this.Active=true;return fCallback();}close(fCallback){this.Active=false;return fCallback();}/*************************************************************************
|
|
691
740
|
* End of Service Lifecycle Functions
|
|
692
|
-
*/ /*
|
|
741
|
+
*/use(fHandlerFunction){if(typeof fHandlerFunction!='function'){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 ${typeof fHandlerFunction} instead of a string.`);return false;}return true;}/*
|
|
693
742
|
* Service Route Creation Functions
|
|
694
743
|
*
|
|
695
744
|
* These base functions provide basic validation for the routes, but don't actually
|
|
@@ -714,7 +763,7 @@ this.Active=true;return fCallback();}close(fCallback){this.Active=false;return f
|
|
|
714
763
|
* End of Service Route Creation Functions
|
|
715
764
|
*/ // Programmatically invoke a route
|
|
716
765
|
invoke(pMethod,pRoute,pData,fCallback){// The base class version of this does nothing
|
|
717
|
-
this.log.debug(`Orator invoke called for route [${pRoute}] and landed on the base class; the service provider likely does not implement programmatic invoke capabilities.`,pData);return false;}}module.exports=OratorServiceServerBase;},{}],
|
|
766
|
+
this.log.debug(`Orator invoke called for route [${pRoute}] and landed on the base class; the service provider likely does not implement programmatic invoke capabilities.`,pData);return false;}}module.exports=OratorServiceServerBase;},{}],53:[function(require,module,exports){/**
|
|
718
767
|
* Precedent Meta-Templating
|
|
719
768
|
*
|
|
720
769
|
* @license MIT
|
|
@@ -736,7 +785,7 @@ this.log.debug(`Orator invoke called for route [${pRoute}] and landed on the bas
|
|
|
736
785
|
* @method parseString
|
|
737
786
|
* @param {string} pString - The string to parse
|
|
738
787
|
* @return {string} The result from the parser
|
|
739
|
-
*/parseString(pString){return this.StringParser.parseString(pString,this.ParseTree);}}module.exports=Precedent;},{"./StringParser.js":
|
|
788
|
+
*/parseString(pString){return this.StringParser.parseString(pString,this.ParseTree);}}module.exports=Precedent;},{"./StringParser.js":54,"./WordTree.js":55}],54:[function(require,module,exports){/**
|
|
740
789
|
* String Parser
|
|
741
790
|
*
|
|
742
791
|
* @license MIT
|
|
@@ -801,7 +850,7 @@ else{pParserState.Output+=pCharacter;}}/**
|
|
|
801
850
|
* @param {string} pString - The string to parse.
|
|
802
851
|
* @param {Object} pParseTree - The parse tree to begin parsing from (usually root)
|
|
803
852
|
*/parseString(pString,pParseTree){let tmpParserState=this.newParserState(pParseTree);for(var i=0;i<pString.length;i++){// TODO: This is not fast.
|
|
804
|
-
this.parseCharacter(pString[i],tmpParserState);}this.flushOutputBuffer(tmpParserState);return tmpParserState.Output;}}module.exports=StringParser;},{}],
|
|
853
|
+
this.parseCharacter(pString[i],tmpParserState);}this.flushOutputBuffer(tmpParserState);return tmpParserState.Output;}}module.exports=StringParser;},{}],55:[function(require,module,exports){/**
|
|
805
854
|
* Word Tree
|
|
806
855
|
*
|
|
807
856
|
* @license MIT
|
|
@@ -826,7 +875,7 @@ this.parseCharacter(pString[i],tmpParserState);}this.flushOutputBuffer(tmpParser
|
|
|
826
875
|
* @param {number} pParser - The function to parse if this is the matched pattern, once the Pattern End is met. If this is a string, a simple replacement occurs.
|
|
827
876
|
* @return {bool} True if adding the pattern was successful
|
|
828
877
|
*/addPattern(pPatternStart,pPatternEnd,pParser){if(pPatternStart.length<1)return false;if(typeof pPatternEnd==='string'&&pPatternEnd.length<1)return false;let tmpLeaf=this.ParseTree;// Add the tree of leaves iteratively
|
|
829
|
-
for(var i=0;i<pPatternStart.length;i++)tmpLeaf=this.addChild(tmpLeaf,pPatternStart,i);tmpLeaf.PatternStart=pPatternStart;tmpLeaf.PatternEnd=typeof pPatternEnd==='string'&&pPatternEnd.length>0?pPatternEnd:pPatternStart;tmpLeaf.Parse=typeof pParser==='function'?pParser:typeof pParser==='string'?()=>{return pParser;}:pData=>{return pData;};return true;}}module.exports=WordTree;},{}],
|
|
878
|
+
for(var i=0;i<pPatternStart.length;i++)tmpLeaf=this.addChild(tmpLeaf,pPatternStart,i);tmpLeaf.PatternStart=pPatternStart;tmpLeaf.PatternEnd=typeof pPatternEnd==='string'&&pPatternEnd.length>0?pPatternEnd:pPatternStart;tmpLeaf.Parse=typeof pParser==='function'?pParser:typeof pParser==='string'?()=>{return pParser;}:pData=>{return pData;};return true;}}module.exports=WordTree;},{}],56:[function(require,module,exports){// shim for using process in browser
|
|
830
879
|
var process=module.exports={};// cached from whatever global is present so that test runners that stub it
|
|
831
880
|
// don't break things. But we need to wrap it in a try catch in case it is
|
|
832
881
|
// wrapped in strict mode code which doesn't define any globals. It's inside a
|
|
@@ -844,7 +893,7 @@ return cachedClearTimeout.call(null,marker);}catch(e){// same as above but when
|
|
|
844
893
|
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
|
|
845
894
|
return cachedClearTimeout.call(this,marker);}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}if(queue.length){drainQueue();}}function drainQueue(){if(draining){return;}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run();}}queueIndex=-1;len=queue.length;}currentQueue=null;draining=false;runClearTimeout(timeout);}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue);}};// v8 likes predictible objects
|
|
846
895
|
function Item(fun,array){this.fun=fun;this.array=array;}Item.prototype.run=function(){this.fun.apply(null,this.array);};process.title='browser';process.browser=true;process.env={};process.argv=[];process.version='';// empty string to avoid regexp issues
|
|
847
|
-
process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[];};process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/';};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],
|
|
896
|
+
process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[];};process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/';};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],57:[function(require,module,exports){'use strict';var parse=require('ret');var types=parse.types;module.exports=function(re,opts){if(!opts)opts={};var replimit=opts.limit===undefined?25:opts.limit;if(isRegExp(re))re=re.source;else if(typeof re!=='string')re=String(re);try{re=parse(re);}catch(err){return false;}var reps=0;return function walk(node,starHeight){var i;var ok;var len;if(node.type===types.REPETITION){starHeight++;reps++;if(starHeight>1)return false;if(reps>replimit)return false;}if(node.options){for(i=0,len=node.options.length;i<len;i++){ok=walk({stack:node.options[i]},starHeight);if(!ok)return false;}}var stack=node.stack||node.value&&node.value.stack;if(!stack)return true;for(i=0;i<stack.length;i++){ok=walk(stack[i],starHeight);if(!ok)return false;}return true;}(re,0);};function isRegExp(x){return{}.toString.call(x)==='[object RegExp]';}},{"ret":58}],58:[function(require,module,exports){const util=require('./util');const types=require('./types');const sets=require('./sets');const positions=require('./positions');module.exports=regexpStr=>{var i=0,l,c,start={type:types.ROOT,stack:[]},// Keep track of last clause/group and stack.
|
|
848
897
|
lastGroup=start,last=start.stack,groupStack=[];var repeatErr=i=>{util.error(regexpStr,`Nothing to repeat at column ${i-1}`);};// Decode a few escaped characters.
|
|
849
898
|
var str=util.strToChars(regexpStr);l=str.length;// Iterate through each character in string.
|
|
850
899
|
while(i<l){c=str[i++];switch(c){// Handle escaped characters, inclues a few sets.
|
|
@@ -879,8 +928,8 @@ var stack=[];lastGroup.options.push(stack);last=stack;break;// Repetition.
|
|
|
879
928
|
// one repetition symbols in a regex i.e. `a?+{2,3}`.
|
|
880
929
|
case'{':var rs=/^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)),min,max;if(rs!==null){if(last.length===0){repeatErr(i);}min=parseInt(rs[1],10);max=rs[2]?rs[3]?parseInt(rs[3],10):Infinity:min;i+=rs[0].length;last.push({type:types.REPETITION,min,max,value:last.pop()});}else{last.push({type:types.CHAR,value:123});}break;case'?':if(last.length===0){repeatErr(i);}last.push({type:types.REPETITION,min:0,max:1,value:last.pop()});break;case'+':if(last.length===0){repeatErr(i);}last.push({type:types.REPETITION,min:1,max:Infinity,value:last.pop()});break;case'*':if(last.length===0){repeatErr(i);}last.push({type:types.REPETITION,min:0,max:Infinity,value:last.pop()});break;// Default is a character that is not `\[](){}?+*^$`.
|
|
881
930
|
default:last.push({type:types.CHAR,value:c.charCodeAt(0)});}}// Check if any groups have not been closed.
|
|
882
|
-
if(groupStack.length!==0){util.error(regexpStr,'Unterminated group');}return start;};module.exports.types=types;},{"./positions":
|
|
883
|
-
exports.words=()=>({type:types.SET,set:WORDS(),not:false});exports.notWords=()=>({type:types.SET,set:WORDS(),not:true});exports.ints=()=>({type:types.SET,set:INTS(),not:false});exports.notInts=()=>({type:types.SET,set:INTS(),not:true});exports.whitespace=()=>({type:types.SET,set:WHITESPACE(),not:false});exports.notWhitespace=()=>({type:types.SET,set:WHITESPACE(),not:true});exports.anyChar=()=>({type:types.SET,set:NOTANYCHAR(),not:true});},{"./types":
|
|
931
|
+
if(groupStack.length!==0){util.error(regexpStr,'Unterminated group');}return start;};module.exports.types=types;},{"./positions":59,"./sets":60,"./types":61,"./util":62}],59:[function(require,module,exports){const types=require('./types');exports.wordBoundary=()=>({type:types.POSITION,value:'b'});exports.nonWordBoundary=()=>({type:types.POSITION,value:'B'});exports.begin=()=>({type:types.POSITION,value:'^'});exports.end=()=>({type:types.POSITION,value:'$'});},{"./types":61}],60:[function(require,module,exports){const types=require('./types');const INTS=()=>[{type:types.RANGE,from:48,to:57}];const WORDS=()=>{return[{type:types.CHAR,value:95},{type:types.RANGE,from:97,to:122},{type:types.RANGE,from:65,to:90}].concat(INTS());};const WHITESPACE=()=>{return[{type:types.CHAR,value:9},{type:types.CHAR,value:10},{type:types.CHAR,value:11},{type:types.CHAR,value:12},{type:types.CHAR,value:13},{type:types.CHAR,value:32},{type:types.CHAR,value:160},{type:types.CHAR,value:5760},{type:types.RANGE,from:8192,to:8202},{type:types.CHAR,value:8232},{type:types.CHAR,value:8233},{type:types.CHAR,value:8239},{type:types.CHAR,value:8287},{type:types.CHAR,value:12288},{type:types.CHAR,value:65279}];};const NOTANYCHAR=()=>{return[{type:types.CHAR,value:10},{type:types.CHAR,value:13},{type:types.CHAR,value:8232},{type:types.CHAR,value:8233}];};// Predefined class objects.
|
|
932
|
+
exports.words=()=>({type:types.SET,set:WORDS(),not:false});exports.notWords=()=>({type:types.SET,set:WORDS(),not:true});exports.ints=()=>({type:types.SET,set:INTS(),not:false});exports.notInts=()=>({type:types.SET,set:INTS(),not:true});exports.whitespace=()=>({type:types.SET,set:WHITESPACE(),not:false});exports.notWhitespace=()=>({type:types.SET,set:WHITESPACE(),not:true});exports.anyChar=()=>({type:types.SET,set:NOTANYCHAR(),not:true});},{"./types":61}],61:[function(require,module,exports){module.exports={ROOT:0,GROUP:1,POSITION:2,SET:3,RANGE:4,REPETITION:5,REFERENCE:6,CHAR:7};},{}],62:[function(require,module,exports){const types=require('./types');const sets=require('./sets');const CTRL='@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';const SLSH={'0':0,'t':9,'n':10,'v':11,'f':12,'r':13};/**
|
|
884
933
|
* Finds character representations in str and convert all to
|
|
885
934
|
* their respective characters
|
|
886
935
|
*
|
|
@@ -899,39 +948,39 @@ if(/[[\]{}^$.|?*+()]/.test(c)){c='\\'+c;}return c;});return str;};/**
|
|
|
899
948
|
*
|
|
900
949
|
* @param {String} regexp
|
|
901
950
|
* @param {String} msg
|
|
902
|
-
*/exports.error=(regexp,msg)=>{throw new SyntaxError('Invalid regular expression: /'+regexp+'/: '+msg);};},{"./sets":
|
|
951
|
+
*/exports.error=(regexp,msg)=>{throw new SyntaxError('Invalid regular expression: /'+regexp+'/: '+msg);};},{"./sets":60,"./types":61}],63:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require('process/browser.js').nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;// DOM APIs, for completeness
|
|
903
952
|
exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout);};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval);};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close();};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn;}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id);};// Does not start the time, just sets up the members needed.
|
|
904
953
|
exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs;};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1;};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout();},msecs);}};// That's not how node.js implements it but the exposed api is the same.
|
|
905
954
|
exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){// fn.call() is faster so we optimize for the common use-case
|
|
906
955
|
// @see http://jsperf.com/call-apply-segu
|
|
907
956
|
if(args){fn.apply(null,args);}else{fn.call(null);}// Prevent ids from leaking
|
|
908
|
-
exports.clearImmediate(id);}});return id;};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id];};}).call(this);}).call(this,require("timers").setImmediate,require("timers").clearImmediate);},{"process/browser.js":
|
|
957
|
+
exports.clearImmediate(id);}});return id;};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id];};}).call(this);}).call(this,require("timers").setImmediate,require("timers").clearImmediate);},{"process/browser.js":56,"timers":63}],64:[function(require,module,exports){/**
|
|
909
958
|
* Simple browser shim loader - assign the npm module to a window global automatically
|
|
910
959
|
*
|
|
911
960
|
* @license MIT
|
|
912
961
|
* @author <steven@velozo.com>
|
|
913
|
-
*/var libNPMModuleWrapper=require('./Orator.js');if(typeof window==='object'&&!window.hasOwnProperty('Orator')){window.Orator=libNPMModuleWrapper;}module.exports=libNPMModuleWrapper;},{"./Orator.js":
|
|
914
|
-
module.exports={"Product":"Unnamed_Service","ProductVersion":"0.0.1","ServicePort":8080};},{}],
|
|
962
|
+
*/var libNPMModuleWrapper=require('./Orator.js');if(typeof window==='object'&&!window.hasOwnProperty('Orator')){window.Orator=libNPMModuleWrapper;}module.exports=libNPMModuleWrapper;},{"./Orator.js":70}],65:[function(require,module,exports){// Simple default configuration for application, when none is provided
|
|
963
|
+
module.exports={"Product":"Unnamed_Service","ProductVersion":"0.0.1","ServicePort":8080};},{}],66:[function(require,module,exports){/**
|
|
915
964
|
* Default Service Server Function
|
|
916
965
|
*
|
|
917
966
|
* @license MIT
|
|
918
967
|
*
|
|
919
968
|
* @author Steven Velozo <steven@velozo.com>
|
|
920
969
|
*/ // Return the servers that are available without extensions loaded
|
|
921
|
-
getDefaultServiceServers=()=>{let tmpDefaultServiceServers={};tmpDefaultServiceServers.ipc=require('./Orator-ServiceServer-IPC.js');tmpDefaultServiceServers.default=tmpDefaultServiceServers.ipc;return tmpDefaultServiceServers;};module.exports=getDefaultServiceServers();},{"./Orator-ServiceServer-IPC.js":
|
|
970
|
+
getDefaultServiceServers=()=>{let tmpDefaultServiceServers={};tmpDefaultServiceServers.ipc=require('./Orator-ServiceServer-IPC.js');tmpDefaultServiceServers.default=tmpDefaultServiceServers.ipc;return tmpDefaultServiceServers;};module.exports=getDefaultServiceServers();},{"./Orator-ServiceServer-IPC.js":69}],67:[function(require,module,exports){'use strict';// This is taken directly from the find-my-way documentation for custom constraints and only mildly edited
|
|
922
971
|
const ipcResponseTypeStrategy={// strategy name for referencing in the route handler `constraints` options
|
|
923
972
|
name:'ipc',isAsync:true,// storage factory for storing routes in the find-my-way route tree
|
|
924
973
|
storage:()=>{let handlers={};return{get:type=>{return handlers[type]||null;},set:(type,store)=>{handlers[type]=store;}};},// function to get the value of the constraint from each incoming request
|
|
925
974
|
deriveConstraint:(pRequest,pContext,fDone)=>{// If we wanted to deny the IPC request based on a constraint, we would do:
|
|
926
975
|
// fDone(new Error(`The request was denied because ____ in the Request object wasn't right...`));
|
|
927
976
|
return fDone(null,'IPC');},// optional flag marking if handlers without constraints can match requests that have a value for this constraint
|
|
928
|
-
mustMatchWhenDerived:true};module.exports=ipcResponseTypeStrategy;},{}],
|
|
977
|
+
mustMatchWhenDerived:true};module.exports=ipcResponseTypeStrategy;},{}],68:[function(require,module,exports){class OratorServiceServerIPCSynthesizedResponse{constructor(pLog,pRequestGUID){this.log=pLog;this.requestGUID=pRequestGUID;this.responseData=null;this.responseStatus=-1;}send(pData){if(typeof pData=='string'){// This is a string! Append it to the responsedata.
|
|
929
978
|
if(this.responseData===null){this.responseData=pData;return true;}else if(typeof this.responseData=='string'){this.responseData=this.responseData+pData;return true;}else{this.log(`Request ${this.requestGUID} has tried to send() a string value after send()ing data type ${typeof this.responseData}.`,pData);return false;}}else if(typeof pData=='object'){if(this.responseData===null){this.responseData=JSON.stringify(pData);return true;}else if(typeof this.responseData=='string'){// TODO: Discuss best way to handle this / if to handle this
|
|
930
|
-
this.responseData+=this.responseData+JSON.stringify(pData);return true;}else{this.log(`Request ${this.requestGUID} has tried to send() an object value to be auto stringified after send()ing data type ${typeof this.responseData}.`,pData);return false;}}}}module.exports=OratorServiceServerIPCSynthesizedResponse;},{}],
|
|
979
|
+
this.responseData+=this.responseData+JSON.stringify(pData);return true;}else{this.log(`Request ${this.requestGUID} has tried to send() an object value to be auto stringified after send()ing data type ${typeof this.responseData}.`,pData);return false;}}}}module.exports=OratorServiceServerIPCSynthesizedResponse;},{}],69:[function(require,module,exports){const libOratorServiceServerBase=require('orator-serviceserver');// A synthesized response object, for simple IPC.
|
|
931
980
|
const libOratorServiceServerIPCSynthesizedResponse=require('./Orator-ServiceServer-IPC-SynthesizedResponse.js');// A simple constrainer for the find-my-way router since we aren't using any kind of headers to pass version or host
|
|
932
981
|
const libOratorServiceServerIPCCustomConstrainer=require('./Orator-ServiceServer-IPC-RouterConstrainer.js');// This library is the default router for our services
|
|
933
982
|
const libFindMyWay=require('find-my-way');//const libAsync = require('async');
|
|
934
|
-
const libAsyncWaterfall=require("async/waterfall");const libAsyncEachOfSeries=require('async/eachofseries');class OratorServiceServerIPC extends libOratorServiceServerBase{constructor(pOrator){super(pOrator);this.routerOptions=this.orator.settings.hasOwnProperty('router_options')&&typeof this.orator.settings.router_options=='object'?this.orator.settings.router_options:{};this.router=libFindMyWay(this.routerOptions);this.router.addConstraintStrategy(libOratorServiceServerIPCCustomConstrainer);this.URL='IPC';this.preBehaviorFunctions=[];this.behaviorMap={};this.postBehaviorFunctions=[];}executePreBehaviorFunctions(pRequest,pResponse,fNext){libAsyncEachOfSeries(this.preBehaviorFunctions,(fBehaviorFunction,pFunctionIndex,fCallback)=>{return fBehaviorFunction(pRequest,pResponse,fCallback);},pError=>{if(pError){this.log.error(`IPC Provider preBehaviorFunction ${pFunctionIndex} failed with error: ${pError}`,pError);}return fNext(pError);});}executePostBehaviorFunctions(pRequest,pResponse,fNext){libAsyncEachOfSeries(this.postBehaviorFunctions,(fBehaviorFunction,pFunctionIndex,fCallback)=>{return fBehaviorFunction(pRequest,pResponse,fCallback);},pError=>{if(pError){this.log.error(`IPC Provider postBehaviorFunction ${pFunctionIndex} failed with error: ${pError}`,pError);}return fNext(pError);});}/*
|
|
983
|
+
const libAsyncWaterfall=require("async/waterfall");const libAsyncEachOfSeries=require('async/eachofseries');class OratorServiceServerIPC extends libOratorServiceServerBase{constructor(pOrator){super(pOrator);this.routerOptions=this.orator.settings.hasOwnProperty('router_options')&&typeof this.orator.settings.router_options=='object'?this.orator.settings.router_options:{};this.router=libFindMyWay(this.routerOptions);this.router.addConstraintStrategy(libOratorServiceServerIPCCustomConstrainer);this.URL='IPC';this.preBehaviorFunctions=[];this.behaviorMap={};this.postBehaviorFunctions=[];}use(fHandlerFunction){if(!super.use(fHandlerFunction)){this.log.error(`IPC provider failed to map USE handler function!`);return false;}this.preBehaviorFunctions.push(fHandlerFunction);}addPostBehaviorFunction(fHandlerFunction){if(!super.use(fHandlerFunction)){this.log.error(`IPC provider failed to map USE handler function!`);return false;}this.preBehaviorFunctions.push(fHandlerFunction);}executePreBehaviorFunctions(pRequest,pResponse,fNext){libAsyncEachOfSeries(this.preBehaviorFunctions,(fBehaviorFunction,pFunctionIndex,fCallback)=>{return fBehaviorFunction(pRequest,pResponse,fCallback);},pError=>{if(pError){this.log.error(`IPC Provider preBehaviorFunction ${pFunctionIndex} failed with error: ${pError}`,pError);}return fNext(pError);});}addPostBehaviorFunction(fHandlerFunction){if(!super.use(fHandlerFunction)){this.log.error(`IPC provider failed to map USE handler function!`);return false;}this.preBehaviorFunctions.push(fHandlerFunction);}executePostBehaviorFunctions(pRequest,pResponse,fNext){libAsyncEachOfSeries(this.postBehaviorFunctions,(fBehaviorFunction,pFunctionIndex,fCallback)=>{return fBehaviorFunction(pRequest,pResponse,fCallback);},pError=>{if(pError){this.log.error(`IPC Provider postBehaviorFunction ${pFunctionIndex} failed with error: ${pError}`,pError);}return fNext(pError);});}/*
|
|
935
984
|
* Service Route Creation Functions
|
|
936
985
|
*
|
|
937
986
|
* These base functions provide basic validation for the routes, but don't actually
|
|
@@ -957,7 +1006,7 @@ let tmpCallback=typeof fCallback=='function'?fCallback:typeof pData=='function'?
|
|
|
957
1006
|
()=>{};// Create a bare minimum request object for IPC to pass to our router
|
|
958
1007
|
let tmpRequest={method:pMethod,url:pRoute,guid:this.orator.fable.getUUID()};// Create a container for the IPC response data to be aggregated to from send() methodds
|
|
959
1008
|
let tmpSynthesizedResponseData=new libOratorServiceServerIPCSynthesizedResponse(this.log,tmpRequest.guid);return this.router.lookup(tmpRequest,tmpSynthesizedResponseData,(pError,pResults)=>{if(pError){this.log.error(`IPC Request Error Request GUID [${tmpRequest.guid}] handling route [${pRoute}]: ${pError}`,{Error:pError,Route:pRoute,Data:pData});}// by default, send data back through
|
|
960
|
-
return tmpCallback(pError,tmpSynthesizedResponseData.responseData,tmpSynthesizedResponseData,pResults);});}}module.exports=OratorServiceServerIPC;},{"./Orator-ServiceServer-IPC-RouterConstrainer.js":
|
|
1009
|
+
return tmpCallback(pError,tmpSynthesizedResponseData.responseData,tmpSynthesizedResponseData,pResults);});}}module.exports=OratorServiceServerIPC;},{"./Orator-ServiceServer-IPC-RouterConstrainer.js":67,"./Orator-ServiceServer-IPC-SynthesizedResponse.js":68,"async/eachofseries":8,"async/waterfall":22,"find-my-way":44,"orator-serviceserver":52}],70:[function(require,module,exports){/**
|
|
961
1010
|
* Orator Service Abstraction
|
|
962
1011
|
*
|
|
963
1012
|
* @license MIT
|
|
@@ -983,4 +1032,4 @@ getWebServer(){// The old behavior was to lazily construct the service the first
|
|
|
983
1032
|
// this accessor function is called.
|
|
984
1033
|
if(!this.serviceServer){this.initializeServiceServer();}return this.serviceServer;}/*************************************************************************
|
|
985
1034
|
* End of Legacy Orator Functions
|
|
986
|
-
*/}module.exports=Orator;},{"./Orator-Default-Configuration.js":
|
|
1035
|
+
*/}module.exports=Orator;},{"./Orator-Default-Configuration.js":65,"./Orator-Default-ServiceServers-Node.js":66,"fable":35}]},{},[64])(64);});
|