diff --git a/dist/browser/asciidoctor-kroki.js b/dist/browser/asciidoctor-kroki.js index d12fab0..d312624 100644 --- a/dist/browser/asciidoctor-kroki.js +++ b/dist/browser/asciidoctor-kroki.js @@ -1933,7 +1933,7 @@ function numberIsNaN (obj) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":1,"buffer":3,"ieee754":7}],4:[function(require,module,exports){ +},{"base64-js":1,"buffer":3,"ieee754":16}],4:[function(require,module,exports){ module.exports = { "100": "Continue", "101": "Switching Protocols", @@ -2000,6 +2000,72 @@ module.exports = { } },{}],5:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + +},{"./":6,"get-intrinsic":10}],6:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + +},{"function-bind":9,"get-intrinsic":10}],7:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -2498,7 +2564,503 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { } } -},{}],6:[function(require,module,exports){ +},{}],8:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],9:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":8}],10:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('has'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"function-bind":9,"has":14,"has-proto":11,"has-symbols":12}],11:[function(require,module,exports){ +'use strict'; + +var test = { + foo: {} +}; + +var $Object = Object; + +module.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); +}; + +},{}],12:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":13}],13:[function(require,module,exports){ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + +var hasOwnProperty = {}.hasOwnProperty; +var call = Function.prototype.call; + +module.exports = call.bind ? call.bind(hasOwnProperty) : function (O, P) { + return call.call(hasOwnProperty, O, P); +}; + +},{}],15:[function(require,module,exports){ var http = require('http') var url = require('url') @@ -2531,7 +3093,7 @@ function validateParams (params) { return params } -},{"http":33,"url":54}],7:[function(require,module,exports){ +},{"http":46,"url":67}],16:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -2618,7 +3180,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],8:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -2647,7 +3209,7 @@ if (typeof Object.create === 'function') { } } -},{}],9:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : @@ -4386,77 +4948,595 @@ if (typeof Object.create === 'function') { }))); -},{}],10:[function(require,module,exports){ -// Top level file is just a mixin of submodules & constants -'use strict'; - -const { Deflate, deflate, deflateRaw, gzip } = require('./lib/deflate'); +},{}],19:[function(require,module,exports){ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} -const { Inflate, inflate, inflateRaw, ungzip } = require('./lib/inflate'); +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; -const constants = require('./lib/zlib/constants'); +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; -module.exports.Deflate = Deflate; -module.exports.deflate = deflate; -module.exports.deflateRaw = deflateRaw; -module.exports.gzip = gzip; -module.exports.Inflate = Inflate; -module.exports.inflate = inflate; -module.exports.inflateRaw = inflateRaw; -module.exports.ungzip = ungzip; -module.exports.constants = constants; + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } -},{"./lib/deflate":11,"./lib/inflate":12,"./lib/zlib/constants":16}],11:[function(require,module,exports){ -'use strict'; + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } -const zlib_deflate = require('./zlib/deflate'); -const utils = require('./utils/common'); -const strings = require('./utils/strings'); -const msg = require('./zlib/messages'); -const ZStream = require('./zlib/zstream'); + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } -const toString = Object.prototype.toString; + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } -/* Public constants ==========================================================*/ -/* ===========================================================================*/ + var indent = getIndent(opts, depth); -const { - Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH, - Z_OK, Z_STREAM_END, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_STRATEGY, - Z_DEFLATED -} = require('./zlib/constants'); + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } -/* ===========================================================================*/ + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overridden. - **/ +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} -/** - * Deflate.result -> Uint8Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param). - **/ +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } -/** - * Deflate.err -> Number - * +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + +},{"./util.inspect":2}],20:[function(require,module,exports){ +// Top level file is just a mixin of submodules & constants +'use strict'; + +const { Deflate, deflate, deflateRaw, gzip } = require('./lib/deflate'); + +const { Inflate, inflate, inflateRaw, ungzip } = require('./lib/inflate'); + +const constants = require('./lib/zlib/constants'); + +module.exports.Deflate = Deflate; +module.exports.deflate = deflate; +module.exports.deflateRaw = deflateRaw; +module.exports.gzip = gzip; +module.exports.Inflate = Inflate; +module.exports.inflate = inflate; +module.exports.inflateRaw = inflateRaw; +module.exports.ungzip = ungzip; +module.exports.constants = constants; + +},{"./lib/deflate":21,"./lib/inflate":22,"./lib/zlib/constants":26}],21:[function(require,module,exports){ +'use strict'; + + +const zlib_deflate = require('./zlib/deflate'); +const utils = require('./utils/common'); +const strings = require('./utils/strings'); +const msg = require('./zlib/messages'); +const ZStream = require('./zlib/zstream'); + +const toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +const { + Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH, + Z_OK, Z_STREAM_END, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_STRATEGY, + Z_DEFLATED +} = require('./zlib/constants'); + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param). + **/ + +/** + * Deflate.err -> Number + * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` @@ -4788,7 +5868,7 @@ module.exports.deflateRaw = deflateRaw; module.exports.gzip = gzip; module.exports.constants = require('./zlib/constants'); -},{"./utils/common":13,"./utils/strings":14,"./zlib/constants":16,"./zlib/deflate":18,"./zlib/messages":23,"./zlib/zstream":25}],12:[function(require,module,exports){ +},{"./utils/common":23,"./utils/strings":24,"./zlib/constants":26,"./zlib/deflate":28,"./zlib/messages":33,"./zlib/zstream":35}],22:[function(require,module,exports){ 'use strict'; @@ -5209,7 +6289,7 @@ module.exports.inflateRaw = inflateRaw; module.exports.ungzip = inflate; module.exports.constants = require('./zlib/constants'); -},{"./utils/common":13,"./utils/strings":14,"./zlib/constants":16,"./zlib/gzheader":19,"./zlib/inflate":21,"./zlib/messages":23,"./zlib/zstream":25}],13:[function(require,module,exports){ +},{"./utils/common":23,"./utils/strings":24,"./zlib/constants":26,"./zlib/gzheader":29,"./zlib/inflate":31,"./zlib/messages":33,"./zlib/zstream":35}],23:[function(require,module,exports){ 'use strict'; @@ -5259,7 +6339,7 @@ module.exports.flattenChunks = (chunks) => { return result; }; -},{}],14:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ // String encode/decode helpers 'use strict'; @@ -5435,7 +6515,7 @@ module.exports.utf8border = (buf, max) => { return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; -},{}],15:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. @@ -5488,7 +6568,7 @@ const adler32 = (adler, buf, len, pos) => { module.exports = adler32; -},{}],16:[function(require,module,exports){ +},{}],26:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -5558,7 +6638,7 @@ module.exports = { //Z_NULL: null // Use -1 or null inline, depending on var type }; -},{}],17:[function(require,module,exports){ +},{}],27:[function(require,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. @@ -5619,7 +6699,7 @@ const crc32 = (crc, buf, len, pos) => { module.exports = crc32; -},{}],18:[function(require,module,exports){ +},{}],28:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -7669,7 +8749,7 @@ module.exports.deflatePrime = deflatePrime; module.exports.deflateTune = deflateTune; */ -},{"./adler32":15,"./constants":16,"./crc32":17,"./messages":23,"./trees":24}],19:[function(require,module,exports){ +},{"./adler32":25,"./constants":26,"./crc32":27,"./messages":33,"./trees":34}],29:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -7729,7 +8809,7 @@ function GZheader() { module.exports = GZheader; -},{}],20:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -8075,7 +9155,7 @@ module.exports = function inflate_fast(strm, start) { return; }; -},{}],21:[function(require,module,exports){ +},{}],31:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -9649,7 +10729,7 @@ module.exports.inflateUndermine = inflateUndermine; module.exports.inflateValidate = inflateValidate; */ -},{"./adler32":15,"./constants":16,"./crc32":17,"./inffast":20,"./inftrees":22}],22:[function(require,module,exports){ +},{"./adler32":25,"./constants":26,"./crc32":27,"./inffast":30,"./inftrees":32}],32:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -9991,7 +11071,7 @@ const inflate_table = (type, lens, lens_index, codes, table, table_index, work, module.exports = inflate_table; -},{}],23:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -10025,7 +11105,7 @@ module.exports = { '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; -},{}],24:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -11206,7 +12286,7 @@ module.exports._tr_flush_block = _tr_flush_block; module.exports._tr_tally = _tr_tally; module.exports._tr_align = _tr_align; -},{}],25:[function(require,module,exports){ +},{}],35:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler @@ -11255,7 +12335,7 @@ function ZStream() { module.exports = ZStream; -},{}],26:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ (function (process){(function (){ // 'path' module extracted from Node.js v8.11.1 (only the posix part) // transplited with Babel @@ -11788,7 +12868,7 @@ posix.posix = posix; module.exports = posix; }).call(this)}).call(this,require('_process')) -},{"_process":27}],27:[function(require,module,exports){ +},{"_process":37}],37:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -11974,7 +13054,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],28:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ (function (global){(function (){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { @@ -12511,186 +13591,887 @@ process.umask = function() { return 0; }; }(this)); }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],29:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - +},{}],39:[function(require,module,exports){ 'use strict'; -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +var replace = String.prototype.replace; +var percentTwenties = /%20/g; -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; - var regexp = /\+/g; - qs = qs.split(sep); +},{}],40:[function(require,module,exports){ +'use strict'; - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; +},{"./formats":39,"./parse":41,"./stringify":42}],41:[function(require,module,exports){ +'use strict'; - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictNullHandling: false +}; - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); } - } - - return obj; -}; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; + return val; }; -},{}],30:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') - case 'boolean': - return v ? 'true' : 'false'; +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; - case 'number': - return isFinite(v) ? v : ''; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; - default: - return ''; - } + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; }; -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; - } + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); + return leaf; }; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); }; -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); }; -},{}],31:[function(require,module,exports){ +},{"./utils":43}],42:[function(require,module,exports){ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":39,"./utils":43,"side-channel":45}],43:[function(require,module,exports){ 'use strict'; -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; -},{"./decode":29,"./encode":30}],32:[function(require,module,exports){ + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; + +},{"./formats":39}],44:[function(require,module,exports){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') @@ -12750,14 +14531,140 @@ SafeBuffer.allocUnsafe = function (size) { return Buffer(size) } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":3}],45:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* + * This function traverses the list returning the node corresponding to the + * given key. + * + * That node is also moved to the head of the list, so that if it's accessed + * again we don't need to traverse the whole list. By doing so, all the recently + * used nodes can be accessed relatively quickly. + */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } +}; +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +module.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + /* + * Initialize the linked list as an empty node, so that we don't have + * to special-case handling of the first node: we can always refer to + * it as (previous node).next, instead of something like (list).head + */ + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; -},{"buffer":3}],33:[function(require,module,exports){ +},{"call-bind/callBound":5,"get-intrinsic":10,"object-inspect":19}],46:[function(require,module,exports){ (function (global){(function (){ var ClientRequest = require('./lib/request') var response = require('./lib/response') @@ -12845,7 +14752,7 @@ http.METHODS = [ 'UNSUBSCRIBE' ] }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./lib/request":35,"./lib/response":36,"builtin-status-codes":4,"url":54,"xtend":57}],34:[function(require,module,exports){ +},{"./lib/request":48,"./lib/response":49,"builtin-status-codes":4,"url":67,"xtend":69}],47:[function(require,module,exports){ (function (global){(function (){ exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) @@ -12908,7 +14815,7 @@ function isFunction (value) { xhr = null // Help gc }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],35:[function(require,module,exports){ +},{}],48:[function(require,module,exports){ (function (process,global,Buffer){(function (){ var capability = require('./capability') var inherits = require('inherits') @@ -13264,7 +15171,7 @@ var unsafeHeaders = [ ] }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./capability":34,"./response":36,"_process":27,"buffer":3,"inherits":8,"readable-stream":51}],36:[function(require,module,exports){ +},{"./capability":47,"./response":49,"_process":37,"buffer":3,"inherits":17,"readable-stream":64}],49:[function(require,module,exports){ (function (process,global,Buffer){(function (){ var capability = require('./capability') var inherits = require('inherits') @@ -13479,7 +15386,7 @@ IncomingMessage.prototype._onXHRProgress = function (resetTimers) { } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./capability":34,"_process":27,"buffer":3,"inherits":8,"readable-stream":51}],37:[function(require,module,exports){ +},{"./capability":47,"_process":37,"buffer":3,"inherits":17,"readable-stream":64}],50:[function(require,module,exports){ 'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } @@ -13608,7 +15515,7 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes; -},{}],38:[function(require,module,exports){ +},{}],51:[function(require,module,exports){ (function (process){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -13630,60 +15537,48 @@ module.exports.codes = codes; // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. + // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. + 'use strict'; -/**/ +/**/ var objectKeys = Object.keys || function (obj) { var keys = []; - - for (var key in obj) { - keys.push(key); - } - + for (var key in obj) keys.push(key); return keys; }; /**/ - module.exports = Duplex; - var Readable = require('./_stream_readable'); - var Writable = require('./_stream_writable'); - require('inherits')(Duplex, Readable); - { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } - function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; - if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } - Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -13710,20 +15605,20 @@ Object.defineProperty(Duplex.prototype, 'writableLength', { get: function get() { return this._writableState.length; } -}); // the no-half-open enforcer +}); +// the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + if (this._writableState.ended) return; + // no more data can be written. + // But allow more writes to happen in this tick. process.nextTick(onEndNT, this); } - function onEndNT(self) { self.end(); } - Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -13733,7 +15628,6 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { if (this._readableState === undefined || this._writableState === undefined) { return false; } - return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { @@ -13741,16 +15635,16 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; - } // backward compatibility, the user is explicitly - // managing destroyed - + } + // backward compatibility, the user is explicitly + // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); }).call(this)}).call(this,require('_process')) -},{"./_stream_readable":40,"./_stream_writable":42,"_process":27,"inherits":8}],39:[function(require,module,exports){ +},{"./_stream_readable":53,"./_stream_writable":55,"_process":37,"inherits":17}],52:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13771,26 +15665,24 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. + // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. + 'use strict'; module.exports = PassThrough; - var Transform = require('./_stream_transform'); - require('inherits')(PassThrough, Transform); - function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } - PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":41,"inherits":8}],40:[function(require,module,exports){ +},{"./_stream_transform":54,"inherits":17}],53:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -13812,49 +15704,40 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. + 'use strict'; module.exports = Readable; -/**/ +/**/ var Duplex; /**/ Readable.ReadableState = ReadableState; -/**/ +/**/ var EE = require('events').EventEmitter; - var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ - - var Stream = require('./internal/streams/stream'); /**/ - var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } - function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -/**/ - +/**/ var debugUtil = require('util'); - var debug; - if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { @@ -13862,60 +15745,57 @@ if (debugUtil && debugUtil.debuglog) { } /**/ - var BufferList = require('./internal/streams/buffer_list'); - var destroyImpl = require('./internal/streams/destroy'); - var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - + getHighWaterMark = _require.getHighWaterMark; var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; +// Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; - require('inherits')(Readable, Stream); - var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - function ReadableState(options, stream, isDuplex) { Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share + options = options || {}; + + // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to + // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() - this.buffer = new BufferList(); this.length = 0; this.pipes = null; @@ -13923,61 +15803,66 @@ function ReadableState(options, stream, isDuplex) { this.flowing = null; this.ended = false; this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. + this.sync = true; - this.sync = true; // whenever we return null, then we set a flag to say + // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. - this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + this.paused = true; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; - if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } - function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 + if (!(this instanceof Readable)) return new Readable(options); + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy + this._readableState = new ReadableState(options, this, isDuplex); + // legacy this.readable = true; - if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } - Stream.call(this); } - Object.defineProperty(Readable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -13987,7 +15872,6 @@ Object.defineProperty(Readable.prototype, 'destroyed', { if (this._readableState === undefined) { return false; } - return this._readableState.destroyed; }, set: function set(value) { @@ -13995,69 +15879,60 @@ Object.defineProperty(Readable.prototype, 'destroyed', { // has not been initialized yet if (!this._readableState) { return; - } // backward compatibility, the user is explicitly - // managing destroyed - + } + // backward compatibility, the user is explicitly + // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; - Readable.prototype._destroy = function (err, cb) { cb(err); -}; // Manually shove something into the read() buffer. +}; + +// Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. - - Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; - if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } - skipChunkCheck = true; } } else { skipChunkCheck = true; } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - +}; +// Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); var state = stream._readableState; - if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } - if (addToFront) { if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { @@ -14066,7 +15941,6 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { return false; } else { state.reading = false; - if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); @@ -14078,14 +15952,13 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { state.reading = false; maybeReadMore(stream, state); } - } // We can push more data if we are below the highWaterMark. + } + + // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { state.awaitDrain = 0; @@ -14096,50 +15969,42 @@ function addChunk(stream, state, chunk, addToFront) { if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } - maybeReadMore(stream, state); } - function chunkInvalid(state, chunk) { var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } - return er; } - Readable.prototype.isPaused = function () { return this._readableState.flowing === false; -}; // backwards compatibility. - +}; +// backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; - while (p !== null) { content += decoder.write(p.data); p = p.next; } - this._readableState.buffer.clear(); - if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; -}; // Don't raise the hwm > 1GB - +}; +// Don't raise the hwm > 1GB var MAX_HWM = 0x40000000; - function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. @@ -14155,55 +16020,54 @@ function computeNewHighWaterMark(n) { n |= n >>> 16; n++; } - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - +} +// This function is designed to be inlinable, so please take care when making +// changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; - if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - + } + // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - + if (n <= state.length) return n; + // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } - return state.length; -} // you can override either this method, or the async _read(n) below. - +} +// you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } + n = howMuchToRead(n, state); - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - + // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; - } // All the actual chunk generation logic needs to be + } + + // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change @@ -14224,40 +16088,37 @@ Readable.prototype.read = function (n) { // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - + // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + debug('need readable', doRead); + // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - + } + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); } - var ret; if (n > 0) ret = fromList(n, state);else ret = null; - if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; @@ -14265,34 +16126,28 @@ Readable.prototype.read = function (n) { state.length -= n; state.awaitDrain = 0; } - if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + if (!state.ended) state.needReadable = true; + // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } - if (ret !== null) this.emit('data', ret); return ret; }; - function onEofChunk(stream, state) { debug('onEofChunk'); if (state.ended) return; - if (state.decoder) { var chunk = state.decoder.end(); - if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } - state.ended = true; - if (state.sync) { // if we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() @@ -14301,61 +16156,56 @@ function onEofChunk(stream, state) { } else { // emit 'readable' now to make sure it gets picked up. state.needReadable = false; - if (!state.emittedReadable) { state.emittedReadable = true; emitReadable_(stream); } } -} // Don't emit readable right away in sync mode, because this can trigger +} + +// Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. - - function emitReadable(stream) { var state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; - if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; process.nextTick(emitReadable_, stream); } } - function emitReadable_(stream) { var state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); state.emittedReadable = false; - } // The stream needs another readable event if + } + + // The stream needs another readable event if // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); -} // at this point, the user has presumably seen the 'readable' event, +} + +// at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. - - function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(maybeReadMore_, stream, state); } } - function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // @@ -14384,49 +16234,42 @@ function maybeReadMore_(stream, state) { var len = state.length; debug('maybeReadMore read 0'); stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. + if (len === state.length) + // didn't get any data, stop spinning. break; } - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. +} + +// abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. - - Readable.prototype._read = function (n) { errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; - Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; - switch (state.pipesCount) { case 0: state.pipes = dest; break; - case 1: state.pipes = [state.pipes, dest]; break; - default: state.pipes.push(dest); break; } - state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { debug('onunpipe'); - if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; @@ -14434,23 +16277,21 @@ Readable.prototype.pipe = function (dest, pipeOpts) { } } } - function onend() { debug('onend'); dest.end(); - } // when the dest drains, it reduces the awaitDrain counter + } + + // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. - - var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - + debug('cleanup'); + // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); @@ -14459,22 +16300,20 @@ Readable.prototype.pipe = function (dest, pipeOpts) { src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this + cleanedUp = true; + + // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - src.on('data', ondata); - function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); debug('dest.write', ret); - if (ret === false) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write @@ -14484,87 +16323,84 @@ Readable.prototype.pipe = function (dest, pipeOpts) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; } - src.pause(); } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - + } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - + } - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } - dest.once('close', onclose); - function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } - dest.once('finish', onfinish); - function unpipe() { debug('unpipe'); src.unpipe(dest); - } // tell the dest that it's being piped to - + } - dest.emit('pipe', src); // start the flow if it hasn't been started already. + // tell the dest that it's being piped to + dest.emit('pipe', src); + // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } - return dest; }; - function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } - Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + }; - if (state.pipesCount === 0) return this; // just one destination. most common case. + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + if (!dest) dest = state.pipes; + // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; - } // slow case. multiple pipe destinations. + } + // slow case. multiple pipe destinations. if (!dest) { // remove all. @@ -14573,17 +16409,13 @@ Readable.prototype.unpipe = function (dest) { state.pipes = null; state.pipesCount = 0; state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); return this; - } // try to find the right one. - + } + // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); @@ -14591,19 +16423,19 @@ Readable.prototype.unpipe = function (dest) { if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - +}; +// set up data events if they are asked for +// Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); var state = this._readableState; - if (ev === 'data') { // update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + state.readableListening = this.listenerCount('readable') > 0; + // Try start flowing on next tick if stream isn't explicitly paused if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { @@ -14611,7 +16443,6 @@ Readable.prototype.on = function (ev, fn) { state.flowing = false; state.emittedReadable = false; debug('on readable', state.length, state.reading); - if (state.length) { emitReadable(this); } else if (!state.reading) { @@ -14619,15 +16450,11 @@ Readable.prototype.on = function (ev, fn) { } } } - return res; }; - Readable.prototype.addListener = Readable.prototype.on; - Readable.prototype.removeListener = function (ev, fn) { var res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen @@ -14637,13 +16464,10 @@ Readable.prototype.removeListener = function (ev, fn) { // effect. process.nextTick(updateReadableListening, this); } - return res; }; - Readable.prototype.removeAllListeners = function (ev) { var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen @@ -14653,121 +16477,103 @@ Readable.prototype.removeAllListeners = function (ev) { // effect. process.nextTick(updateReadableListening, this); } - return res; }; - function updateReadableListening(self) { var state = self._readableState; state.readableListening = self.listenerCount('readable') > 0; - if (state.resumeScheduled && !state.paused) { // flowing needs to be set to true now, otherwise // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume + state.flowing = true; + + // crude way to check if we should resume } else if (self.listenerCount('data') > 0) { self.resume(); } } - function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - +} +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening + debug('resume'); + // we flow only if there is no one listening // for readable, but we still have to call // resume() - state.flowing = !state.readableListening; resume(this, state); } - state.paused = false; return this; }; - function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; process.nextTick(resume_, stream, state); } } - function resume_(stream, state) { debug('resume', state.reading); - if (!state.reading) { stream.read(0); } - state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } - Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); - if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } - this._readableState.paused = true; return this; }; - function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. +// wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. - - Readable.prototype.wrap = function (stream) { var _this = this; - var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); - if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } - _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + if (state.decoder) chunk = state.decoder.write(chunk); + // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); - if (!ret) { paused = true; stream.pause(); } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + }); + // proxy all the other methods. + // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { @@ -14776,37 +16582,32 @@ Readable.prototype.wrap = function (stream) { }; }(i); } - } // proxy certain important events. - + } + // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - + } + // when we try to consume some more bytes, simply unpause the + // underlying stream. this._read = function (n) { debug('wrapped _read', n); - if (paused) { paused = false; stream.resume(); } }; - return this; }; - if (typeof Symbol === 'function') { Readable.prototype[Symbol.asyncIterator] = function () { if (createReadableStreamAsyncIterator === undefined) { createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); } - return createReadableStreamAsyncIterator(this); }; } - Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -14838,8 +16639,9 @@ Object.defineProperty(Readable.prototype, 'readableFlowing', { this._readableState.flowing = state; } } -}); // exposed for testing purposes only. +}); +// exposed for testing purposes only. Readable._fromList = fromList; Object.defineProperty(Readable.prototype, 'readableLength', { // making it explicit this property is not enumerable @@ -14849,11 +16651,12 @@ Object.defineProperty(Readable.prototype, 'readableLength', { get: function get() { return this._readableState.length; } -}); // Pluck off n bytes from an array of buffers. +}); + +// Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. - function fromList(n, state) { // nothing buffered if (state.length === 0) return null; @@ -14868,56 +16671,48 @@ function fromList(n, state) { } return ret; } - function endReadable(stream) { var state = stream._readableState; debug('endReadable', state.endEmitted); - if (!state.endEmitted) { state.ended = true; process.nextTick(endReadableNT, state, stream); } } - function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + debug('endReadableNT', state.endEmitted, state.length); + // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); - if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { stream.destroy(); } } } } - if (typeof Symbol === 'function') { Readable.from = function (iterable, opts) { if (from === undefined) { from = require('./internal/streams/from'); } - return from(Readable, iterable, opts); }; } - function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } - return -1; } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":37,"./_stream_duplex":38,"./internal/streams/async_iterator":43,"./internal/streams/buffer_list":44,"./internal/streams/destroy":45,"./internal/streams/from":47,"./internal/streams/state":49,"./internal/streams/stream":50,"_process":27,"buffer":3,"events":5,"inherits":8,"string_decoder/":52,"util":2}],41:[function(require,module,exports){ +},{"../errors":50,"./_stream_duplex":51,"./internal/streams/async_iterator":56,"./internal/streams/buffer_list":57,"./internal/streams/destroy":58,"./internal/streams/from":60,"./internal/streams/state":62,"./internal/streams/stream":63,"_process":37,"buffer":3,"events":7,"inherits":17,"string_decoder/":65,"util":2}],54:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -14938,6 +16733,7 @@ function indexOf(xs, x) { // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. + // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -14979,42 +16775,36 @@ function indexOf(xs, x) { // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. + 'use strict'; module.exports = Transform; - var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = require('./_stream_duplex'); - require('inherits')(Transform, Duplex); - function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; - if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - ts.writechunk = null; ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` + if (data != null) + // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } - function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); @@ -15025,26 +16815,25 @@ function Transform(options) { writecb: null, writechunk: null, writeencoding: null - }; // start out asking for a readable event once data is transformed. + }; - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. - this._readableState.sync = false; - if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - + } + // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } - function prefinish() { var _this = this; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); @@ -15053,11 +16842,12 @@ function prefinish() { done(this, null, null); } } - Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! +}; + +// This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // @@ -15067,33 +16857,27 @@ Transform.prototype.push = function (chunk, encoding) { // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. - - Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; - Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; - if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } -}; // Doesn't matter what the args are here. +}; + +// Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. - - Transform.prototype._read = function (n) { var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in @@ -15101,25 +16885,25 @@ Transform.prototype._read = function (n) { ts.needTransform = true; } }; - Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; - function done(stream, er, data) { if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } -},{"../errors":37,"./_stream_duplex":38,"inherits":8}],42:[function(require,module,exports){ +},{"../errors":50,"./_stream_duplex":51,"inherits":17}],55:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // @@ -15141,29 +16925,29 @@ function done(stream, er, data) { // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. + // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. + 'use strict'; module.exports = Writable; -/* */ +/* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - +} +// It seems a linked list but it is not +// there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; - this.next = null; this.entry = null; - this.finish = function () { onCorkedFinish(_this, state); }; @@ -15171,155 +16955,159 @@ function CorkedRequest(state) { /* */ /**/ - - var Duplex; /**/ Writable.WritableState = WritableState; -/**/ +/**/ var internalUtil = { deprecate: require('util-deprecate') }; /**/ /**/ - var Stream = require('./internal/streams/stream'); /**/ - var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } - function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } - var destroyImpl = require('./internal/streams/destroy'); - var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - + getHighWaterMark = _require.getHighWaterMark; var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; - require('inherits')(Writable, Stream); - function nop() {} - function WritableState(options, stream, isDuplex) { Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share + options = options || {}; + + // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // object stream flag to indicate whether or not this stream // contains buffers or objects. - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() + // if _final has been called + this.finalCalled = false; - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - this.finished = false; // has it been destroyed + // has it been destroyed + this.destroyed = false; - this.destroyed = false; // should we decode strings into buffers before passing to _write? + // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. + this.length = 0; - this.length = 0; // a flag to see when we're in the middle of a write. + // a flag to see when we're in the middle of a write. + this.writing = false; - this.writing = false; // when true all writes will be buffered until .uncork() call + // when true all writes will be buffered until .uncork() call + this.corked = 0; - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. + this.sync = true; - this.sync = true; // a flag to know if we're processing previously buffered items, which + // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - + // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - + }; - this.writecb = null; // the amount that is being written when _write is called. + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams + this.prefinished = false; - this.prefinished = false; // True if the error was already emitted and should not be thrown again + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; - this.autoDestroy = !!options.autoDestroy; // count buffered requests + // count buffered requests + this.bufferedRequestCount = 0; - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); } - WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; - while (current) { out.push(current); current = current.next; } - return out; }; - (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { @@ -15328,12 +17116,11 @@ WritableState.prototype.getBuffer = function getBuffer() { }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - +})(); +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. var realHasInstance; - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { @@ -15348,81 +17135,73 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot return object instanceof this; }; } - function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. + this._writableState = new WritableState(options, this, isDuplex); + // legacy. this.writable = true; - if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - +} +// Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular +} + +// Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. - - function validChunk(stream, state, chunk, cb) { var er; - if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } - if (er) { errorOrDestroy(stream, er); process.nextTick(cb, er); return false; } - return true; } - Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } - if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { @@ -15431,20 +17210,16 @@ Writable.prototype.write = function (chunk, encoding, cb) { } return ret; }; - Writable.prototype.cork = function () { this._writableState.corked++; }; - Writable.prototype.uncork = function () { var state = this._writableState; - if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); @@ -15452,7 +17227,6 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { this._writableState.defaultEncoding = encoding; return this; }; - Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -15462,15 +17236,12 @@ Object.defineProperty(Writable.prototype, 'writableBuffer', { return this._writableState && this._writableState.getBuffer(); } }); - function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } - return chunk; } - Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -15479,27 +17250,25 @@ Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { get: function get() { return this._writableState.highWaterMark; } -}); // if we're already writing something, then just put this +}); + +// if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } - var len = state.objectMode ? 1 : chunk.length; state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; - if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { @@ -15509,21 +17278,17 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { callback: cb, next: null }; - if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } - state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } - return ret; } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; @@ -15532,16 +17297,14 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) { if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } - function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; - if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen + process.nextTick(cb, er); + // this can emit finish, and it will always happen // after error - process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); @@ -15550,20 +17313,18 @@ function onwriteError(stream, state, sync, er, cb) { // it is async cb(er); stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must + errorOrDestroy(stream, er); + // this can emit finish, but finish must // always follow error - finishMaybe(stream, state); } } - function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } - function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; @@ -15573,11 +17334,9 @@ function onwrite(stream, er) { if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } - if (sync) { process.nextTick(afterWrite, stream, state, finished, cb); } else { @@ -15585,29 +17344,27 @@ function onwrite(stream, er) { } } } - function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't +} + +// Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. - - function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } -} // if there's something in the buffer waiting, then process it - +} +// if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; @@ -15616,28 +17373,25 @@ function clearBuffer(stream, state) { holder.entry = entry; var count = 0; var allBuffers = true; - while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; - if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } - state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one @@ -15648,32 +17402,26 @@ function clearBuffer(stream, state) { var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. - if (state.writing) { break; } } - if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequest = entry; state.bufferProcessing = false; } - Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; - Writable.prototype._writev = null; - Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; - if (typeof chunk === 'function') { cb = chunk; chunk = null; @@ -15682,19 +17430,18 @@ Writable.prototype.end = function (chunk, encoding, cb) { cb = encoding; encoding = null; } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - + // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); - } // ignore unnecessary end() calls. - + } + // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; - Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -15704,25 +17451,20 @@ Object.defineProperty(Writable.prototype, 'writableLength', { return this._writableState.length; } }); - function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; - if (err) { errorOrDestroy(stream, err); } - state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } - function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { @@ -15735,59 +17477,47 @@ function prefinish(stream, state) { } } } - function finishMaybe(stream, state) { var need = needFinish(state); - if (need) { prefinish(stream, state); - if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); - if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } - return need; } - function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); - if (cb) { if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } - state.ended = true; stream.writable = false; } - function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; - while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; - } // reuse the free corkReq. - + } + // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } - Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in @@ -15797,7 +17527,6 @@ Object.defineProperty(Writable.prototype, 'destroyed', { if (this._writableState === undefined) { return false; } - return this._writableState.destroyed; }, set: function set(value) { @@ -15805,30 +17534,28 @@ Object.defineProperty(Writable.prototype, 'destroyed', { // has not been initialized yet if (!this._writableState) { return; - } // backward compatibility, the user is explicitly - // managing destroyed - + } + // backward compatibility, the user is explicitly + // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function (err, cb) { cb(err); }; }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":37,"./_stream_duplex":38,"./internal/streams/destroy":45,"./internal/streams/state":49,"./internal/streams/stream":50,"_process":27,"buffer":3,"inherits":8,"util-deprecate":56}],43:[function(require,module,exports){ +},{"../errors":50,"./_stream_duplex":51,"./internal/streams/destroy":58,"./internal/streams/state":62,"./internal/streams/stream":63,"_process":37,"buffer":3,"inherits":17,"util-deprecate":68}],56:[function(require,module,exports){ (function (process){(function (){ 'use strict'; var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var finished = require('./end-of-stream'); - var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); @@ -15836,22 +17563,19 @@ var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); - function createIterResult(value, done) { return { value: value, done: done }; } - function readAndResolve(iter) { var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null + var data = iter[kStream].read(); + // we defer if data is null // we can be expecting either 'end' or // 'error' - if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; @@ -15860,13 +17584,11 @@ function readAndResolve(iter) { } } } - function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick process.nextTick(readAndResolve, iter); } - function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { @@ -15874,33 +17596,26 @@ function wrapForNext(lastPromise, iter) { resolve(createIterResult(undefined, true)); return; } - iter[kHandlePromise](resolve, reject); }, reject); }; } - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, - next: function next() { var _this = this; - // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; - if (error !== null) { return Promise.reject(error); } - if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } - if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and @@ -15915,29 +17630,25 @@ var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPro } }); }); - } // if we have multiple next() calls + } + + // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time - - var lastPromise = this[kLastPromise]; var promise; - if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); - if (data !== null) { return Promise.resolve(createIterResult(data, false)); } - promise = new Promise(this[kHandlePromise]); } - this[kLastPromise] = promise; return promise; } @@ -15945,7 +17656,6 @@ var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPro return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; - // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to @@ -15955,15 +17665,12 @@ var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPro reject(err); return; } - resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); - var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true @@ -15982,7 +17689,6 @@ var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterat }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); - if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; @@ -15998,75 +17704,58 @@ var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterat iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise // returned by next() and store the error - if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } - iterator[kError] = err; return; } - var resolve = iterator[kLastResolve]; - if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } - iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; - module.exports = createReadableStreamAsyncIterator; }).call(this)}).call(this,require('_process')) -},{"./end-of-stream":46,"_process":27}],44:[function(require,module,exports){ +},{"./end-of-stream":59,"_process":37}],57:[function(require,module,exports){ 'use strict'; -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var _require = require('buffer'), - Buffer = _require.Buffer; - + Buffer = _require.Buffer; var _require2 = require('util'), - inspect = _require2.inspect; - + inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; - function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } - -module.exports = -/*#__PURE__*/ -function () { +module.exports = /*#__PURE__*/function () { function BufferList() { _classCallCheck(this, BufferList); - this.head = null; this.tail = null; this.length = 0; } - _createClass(BufferList, [{ key: "push", value: function push(v) { @@ -16110,11 +17799,7 @@ function () { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - + while (p = p.next) ret += s + p.data; return ret; } }, { @@ -16124,21 +17809,19 @@ function () { var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; - while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. + } + // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; - if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); @@ -16150,15 +17833,15 @@ function () { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } - return ret; } }, { key: "first", value: function first() { return this.head.data; - } // Consumes a specified amount of characters from the buffered data. + } + // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { @@ -16166,13 +17849,11 @@ function () { var c = 1; var ret = p.data; n -= ret.length; - while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; - if (n === 0) { if (nb === str.length) { ++c; @@ -16181,17 +17862,15 @@ function () { this.head = p; p.data = str.slice(nb); } - break; } - ++c; } - this.length -= c; return ret; - } // Consumes a specified amount of bytes from the buffered data. + } + // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { @@ -16200,13 +17879,11 @@ function () { var c = 1; p.data.copy(ret); n -= p.data.length; - while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; - if (n === 0) { if (nb === buf.length) { ++c; @@ -16215,21 +17892,19 @@ function () { this.head = p; p.data = buf.slice(nb); } - break; } - ++c; } - this.length -= c; return ret; - } // Make sure the linked list only shows the minimal necessary information. + } + // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { // Only inspect one level. depth: 0, // It should not recurse. @@ -16237,19 +17912,17 @@ function () { })); } }]); - return BufferList; }(); -},{"buffer":3,"util":2}],45:[function(require,module,exports){ +},{"buffer":3,"util":2}],58:[function(require,module,exports){ (function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API +'use strict'; +// undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); @@ -16261,21 +17934,20 @@ function destroy(err, cb) { process.nextTick(emitErrorNT, this, err); } } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + } + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - + } + // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } - this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { @@ -16293,21 +17965,17 @@ function destroy(err, cb) { process.nextTick(emitCloseNT, _this); } }); - return this; } - function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } - function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } - function undestroy() { if (this._readableState) { this._readableState.destroyed = false; @@ -16315,7 +17983,6 @@ function undestroy() { this._readableState.ended = false; this._readableState.endEmitted = false; } - if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; @@ -16326,104 +17993,86 @@ function undestroy() { this._writableState.errorEmitted = false; } } - function emitErrorNT(self, err) { self.emit('error', err); } - function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. + var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } - module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy }; }).call(this)}).call(this,require('_process')) -},{"_process":27}],46:[function(require,module,exports){ +},{"_process":37}],59:[function(require,module,exports){ // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). + 'use strict'; var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - function once(callback) { var called = false; return function () { if (called) return; called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } - callback.apply(this, args); }; } - function noop() {} - function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } - function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; - var onerror = function onerror(err) { callback.call(stream, err); }; - var onclose = function onclose() { var err; - if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } - if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; - var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; - if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); @@ -16433,7 +18082,6 @@ function eos(stream, opts, callback) { stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } - stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); @@ -16451,20 +18099,19 @@ function eos(stream, opts, callback) { stream.removeListener('close', onclose); }; } - module.exports = eos; -},{"../../../errors":37}],47:[function(require,module,exports){ +},{"../../../errors":50}],60:[function(require,module,exports){ module.exports = function () { throw new Error('Readable.from is not available in the browser') }; -},{}],48:[function(require,module,exports){ +},{}],61:[function(require,module,exports){ // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). + 'use strict'; var eos; - function once(callback) { var called = false; return function () { @@ -16473,20 +18120,16 @@ function once(callback) { callback.apply(void 0, arguments); }; } - var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } - function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } - function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; @@ -16506,40 +18149,34 @@ function destroyer(stream, reading, writing, callback) { return function (err) { if (closed) return; if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want + destroyed = true; + // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } - function call(fn) { fn(); } - function pipe(from, to) { return from.pipe(to); } - function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } - function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } - var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } - var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; @@ -16554,40 +18191,34 @@ function pipeline() { }); return streams.reduce(pipe); } - module.exports = pipeline; -},{"../../../errors":37,"./end-of-stream":46}],49:[function(require,module,exports){ +},{"../../../errors":50,"./end-of-stream":59}],62:[function(require,module,exports){ 'use strict'; var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } - function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } - return Math.floor(hwm); - } // Default value - + } + // Default value return state.objectMode ? 16 : 16 * 1024; } - module.exports = { getHighWaterMark: getHighWaterMark }; -},{"../../../errors":37}],50:[function(require,module,exports){ +},{"../../../errors":50}],63:[function(require,module,exports){ module.exports = require('events').EventEmitter; -},{"events":5}],51:[function(require,module,exports){ +},{"events":7}],64:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -16598,7 +18229,7 @@ exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js'); -},{"./lib/_stream_duplex.js":38,"./lib/_stream_passthrough.js":39,"./lib/_stream_readable.js":40,"./lib/_stream_transform.js":41,"./lib/_stream_writable.js":42,"./lib/internal/streams/end-of-stream.js":46,"./lib/internal/streams/pipeline.js":48}],52:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":51,"./lib/_stream_passthrough.js":52,"./lib/_stream_readable.js":53,"./lib/_stream_transform.js":54,"./lib/_stream_writable.js":55,"./lib/internal/streams/end-of-stream.js":59,"./lib/internal/streams/pipeline.js":61}],65:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -16895,7 +18526,7 @@ function simpleWrite(buf) { function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } -},{"safe-buffer":32}],53:[function(require,module,exports){ +},{"safe-buffer":44}],66:[function(require,module,exports){ (function (process,Buffer,__dirname){(function (){ /** * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object. @@ -17553,39 +19184,33 @@ exports.XMLHttpRequest = function () { } }).call(this)}).call(this,require('_process'),require("buffer").Buffer,"/node_modules/unxhr/lib") -},{"_process":27,"buffer":3,"child_process":2,"fs":2,"http":33,"https":6,"path":26,"url":54}],54:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +},{"_process":37,"buffer":3,"child_process":2,"fs":2,"http":46,"https":15,"path":36,"url":67}],67:[function(require,module,exports){ +/* + * Copyright Joyent, Inc. and other Node contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ 'use strict'; var punycode = require('punycode'); -var util = require('./util'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; function Url() { this.protocol = null; @@ -17604,85 +19229,102 @@ function Url() { // Reference: RFC 3986, RFC 1808, RFC 2396 -// define these here so at least they only have to be -// compiled once on the first module load. +/* + * define these here so at least they only have to be + * compiled once on the first module load. + */ var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('qs'); function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; + if (url && typeof url === 'object' && url instanceof Url) { return url; } - var u = new Url; + var u = new Url(); u.parse(url, parseQueryString, slashesDenoteHost); return u; } -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { +Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { @@ -17715,11 +19357,13 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { rest = rest.substr(proto.length); } - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); @@ -17727,46 +19371,54 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { } } - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } } - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ atSign = rest.lastIndexOf('@', hostEnd); } - // Now we have a portion which is definitely the auth. - // Pull that off. + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); @@ -17777,12 +19429,10 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } } // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; + if (hostEnd === -1) { hostEnd = rest.length; } this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); @@ -17790,28 +19440,33 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { // pull out port. this.parseHost(); - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ this.hostname = this.hostname || ''; - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; - if (!part) continue; + if (!part) { continue; } if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ newpart += 'x'; } else { newpart += part[j]; @@ -17844,10 +19499,12 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { } if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ this.hostname = punycode.toASCII(this.hostname); } @@ -17856,8 +19513,10 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { this.host = h + p; this.href += this.host; - // strip [ and ] from the hostname - // the host field still retains them, though + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { @@ -17866,17 +19525,20 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { } } - // now rest is set to the post-host stuff. - // chop off any delim chars. + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ if (!unsafeProtocol[lowerProto]) { - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; + if (rest.indexOf(ae) === -1) { continue; } var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); @@ -17885,7 +19547,6 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { } } - // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { @@ -17906,13 +19567,12 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { this.search = ''; this.query = {}; } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } - //to support http.request + // to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; @@ -17926,16 +19586,18 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { // format a parsed object into a url string function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } return obj.format(); } -Url.prototype.format = function() { +Url.prototype.format = function () { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); @@ -17944,46 +19606,46 @@ Url.prototype.format = function() { } var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); } var search = this.search || (query && ('?' + query)) || ''; - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } } else if (!host) { host = ''; } - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } - pathname = pathname.replace(/[?#]/g, function(match) { + pathname = pathname.replace(/[?#]/g, function (match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); @@ -17995,17 +19657,17 @@ function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } -Url.prototype.resolve = function(relative) { +Url.prototype.resolve = function (relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { - if (!source) return relative; + if (!source) { return relative; } return urlParse(source, false, true).resolveObject(relative); } -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { +Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { var rel = new Url(); rel.parse(relative, false, true); relative = rel; @@ -18018,8 +19680,10 @@ Url.prototype.resolveObject = function(relative) { result[tkey] = this[tkey]; } - // hash is always overridden, no matter what. - // even href="" will remove it. + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. @@ -18034,14 +19698,13 @@ Url.prototype.resolveObject = function(relative) { var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } } - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; } result.href = result.format(); @@ -18049,14 +19712,16 @@ Url.prototype.resolveObject = function(relative) { } if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { @@ -18070,11 +19735,11 @@ Url.prototype.resolveObject = function(relative) { result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; @@ -18096,37 +19761,33 @@ Url.prototype.resolveObject = function(relative) { return result; } - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } } relative.host = null; } @@ -18135,54 +19796,60 @@ Url.prototype.resolveObject = function(relative) { if (isRelAbs) { // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; } } result.search = relative.search; result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ result.pathname = null; - //to support http.request + // to support http.request if (result.search) { result.path = '/' + result.search; } else { @@ -18192,16 +19859,18 @@ Url.prototype.resolveObject = function(relative) { return result; } - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; @@ -18223,8 +19892,7 @@ Url.prototype.resolveObject = function(relative) { } } - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } @@ -18232,21 +19900,22 @@ Url.prototype.resolveObject = function(relative) { srcPath.push(''); } - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; } } @@ -18256,17 +19925,16 @@ Url.prototype.resolveObject = function(relative) { srcPath.unshift(''); } - if (!srcPath.length) { + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { result.pathname = null; result.path = null; - } else { - result.pathname = srcPath.join('/'); } - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; @@ -18274,7 +19942,7 @@ Url.prototype.resolveObject = function(relative) { return result; }; -Url.prototype.parseHost = function() { +Url.prototype.parseHost = function () { var host = this.host; var port = portPattern.exec(host); if (port) { @@ -18284,28 +19952,17 @@ Url.prototype.parseHost = function() { } host = host.substr(0, host.length - port.length); } - if (host) this.hostname = host; + if (host) { this.hostname = host; } }; -},{"./util":55,"punycode":28,"querystring":31}],55:[function(require,module,exports){ -'use strict'; +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; -module.exports = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; - } -}; +exports.Url = Url; -},{}],56:[function(require,module,exports){ +},{"punycode":38,"qs":40}],68:[function(require,module,exports){ (function (global){(function (){ /** @@ -18376,7 +20033,7 @@ function config (name) { } }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],57:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; @@ -18397,7 +20054,7 @@ function extend() { return target } -},{}],58:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ module.exports={ "name": "asciidoctor-kroki", "version": "0.17.0", @@ -18431,11 +20088,11 @@ module.exports={ "unxhr": "1.2.0" }, "devDependencies": { - "@antora/site-generator-default": "~3.1.0", - "@asciidoctor/core": "^2.2", + "@antora/site-generator-default": "~3.1", + "@asciidoctor/core": ">=2.2 <4.0", "base64-js": "1.5.1", "browserify": "17.0.0", - "chai": "4.3.7", + "chai": "~4.3", "chai-string": "1.5.0", "cheerio": "1.0.0-rc.12", "dirty-chai": "2.0.1", @@ -18443,13 +20100,13 @@ module.exports={ "lodash": "4.17.21", "mocha": "10.2.0", "pacote": "12.0.2", - "puppeteer": "20.8.0", + "puppeteer": "~21.3", "shx": "0.3.4", - "sinon": "15.2.0", + "sinon": "~16.1", "standard": "17.1.0" }, "peerDependencies": { - "@asciidoctor/core": "~2.2" + "@asciidoctor/core": ">=2.2 <4.0" }, "repository": { "type": "git", @@ -18479,7 +20136,7 @@ module.exports={ } } -},{}],59:[function(require,module,exports){ +},{}],71:[function(require,module,exports){ /* global Opal */ // @ts-check const { KrokiDiagram, KrokiClient } = require('./kroki-client.js') @@ -18764,7 +20421,7 @@ module.exports.register = function register (registry, context = {}) { return registry } -},{"./antora-adapter.js":undefined,"./fetch.js":undefined,"./http/browser-http.js":60,"./http/node-http.js":62,"./kroki-client.js":63,"./node-fs.js":undefined,"./preprocess.js":64}],60:[function(require,module,exports){ +},{"./antora-adapter.js":undefined,"./fetch.js":undefined,"./http/browser-http.js":72,"./http/node-http.js":74,"./kroki-client.js":75,"./node-fs.js":undefined,"./preprocess.js":76}],72:[function(require,module,exports){ /* global XMLHttpRequest */ const httpClient = require('./http-client.js') @@ -18776,7 +20433,7 @@ module.exports = { post: httpPost } -},{"./http-client.js":61}],61:[function(require,module,exports){ +},{"./http-client.js":73}],73:[function(require,module,exports){ const httpRequest = (XMLHttpRequest, uri, method, headers, encoding = 'utf8', body) => { let data = '' let status = -1 @@ -18801,6 +20458,8 @@ const httpRequest = (XMLHttpRequest, uri, method, headers, encoding = 'utf8', bo } else { data = this.responseText } + } else if (encoding !== 'binary') { + data = this.responseText } }) if (body) { @@ -18811,11 +20470,15 @@ const httpRequest = (XMLHttpRequest, uri, method, headers, encoding = 'utf8', bo } catch (e) { throw new Error(`${method} ${uri} - error; reason: ${e.message}`) } - // assume that no data means it doesn't exist - if (status === 404 || !data) { - throw new Error(`${method} ${uri} - server returns an empty response or a 404 status code`) + if (status >= 200 && status < 400) { + // successful status + if (data) { + return data + } + throw new Error(`${method} ${uri} - server returns an empty response`) } - return data + + throw new Error(`${method} ${uri} - server returns ${status} status code; response: ${data}`) } const httpPost = (XMLHttpRequest, uri, body, headers, encoding = 'utf8') => { @@ -18831,7 +20494,7 @@ module.exports = { post: httpPost } -},{}],62:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ const XMLHttpRequest = require('unxhr').XMLHttpRequest const httpClient = require('./http-client.js') @@ -18843,7 +20506,7 @@ module.exports = { post: httpPost } -},{"./http-client.js":61,"unxhr":53}],63:[function(require,module,exports){ +},{"./http-client.js":73,"unxhr":66}],75:[function(require,module,exports){ (function (Buffer){(function (){ const { version } = require('../package.json') const pako = require('pako') @@ -18925,11 +20588,11 @@ module.exports.KrokiClient = class KrokiClient { } }).call(this)}).call(this,require("buffer").Buffer) -},{"../package.json":58,"buffer":3,"pako":10}],64:[function(require,module,exports){ +},{"../package.json":70,"buffer":3,"pako":20}],76:[function(require,module,exports){ // @ts-check // The previous line must be the first non-comment line in the file to enable TypeScript checks: // https://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html#ts-check -const path = require('path') +const { delimiter, posix: path } = require('path') /** * @param {string} diagramText @@ -19019,7 +20682,7 @@ module.exports.preprocessPlantUML = function (diagramText, context, diagramInclu const logger = 'logger' in context ? context.logger : console const includeOnce = [] const includeStack = [] - const includePaths = diagramIncludePaths ? diagramIncludePaths.split(path.delimiter) : [] + const includePaths = diagramIncludePaths ? diagramIncludePaths.split(delimiter) : [] diagramText = preprocessPlantUmlIncludes(diagramText, resource, includeOnce, includeStack, includePaths, context.vfs, logger) return removePlantUmlTags(diagramText) } @@ -19106,19 +20769,19 @@ function preprocessPlantUmlIncludes (diagramText, resource, includeOnce, include */ function resolveIncludeFile (includeFile, resource, includePaths, vfs) { const exists = typeof vfs !== 'undefined' && typeof vfs.exists === 'function' ? vfs.exists : require('./node-fs.js').exists - if (resource.dir) { - let filePath = includeFile - for (const includePath of [resource.dir, ...includePaths]) { - const localFilePath = path.join(includePath, includeFile) - if (exists(localFilePath)) { - filePath = localFilePath - break - } + if (resource.module) { + // antora resource id + return includeFile + } + let filePath = includeFile + for (const includePath of [resource.dir, ...includePaths]) { + const localFilePath = path.join(includePath, includeFile) + if (exists(localFilePath)) { + filePath = localFilePath + break } - return filePath } - // antora resource id - return includeFile + return filePath } function parseTarget (value) { @@ -19322,5 +20985,5 @@ function isLocalAndRelative (string) { } } -},{"./node-fs.js":undefined,"json5":9,"path":26}]},{},[59])(59) +},{"./node-fs.js":undefined,"json5":18,"path":36}]},{},[71])(71) }); diff --git a/src/preprocess.js b/src/preprocess.js index ba3ec6a..c37eb25 100644 --- a/src/preprocess.js +++ b/src/preprocess.js @@ -92,7 +92,6 @@ module.exports.preprocessPlantUML = function (diagramText, context, diagramInclu const includeOnce = [] const includeStack = [] const includePaths = diagramIncludePaths ? diagramIncludePaths.split(delimiter) : [] - console.log({ includePaths }) diagramText = preprocessPlantUmlIncludes(diagramText, resource, includeOnce, includeStack, includePaths, context.vfs, logger) return removePlantUmlTags(diagramText) } @@ -183,7 +182,6 @@ function resolveIncludeFile (includeFile, resource, includePaths, vfs) { // antora resource id return includeFile } - console.log('resolveIncludeFile', { includeFile, resource, paths: [resource.dir, ...includePaths] }) let filePath = includeFile for (const includePath of [resource.dir, ...includePaths]) { const localFilePath = path.join(includePath, includeFile) @@ -231,7 +229,6 @@ function readPlantUmlInclude (url, resource, includePaths, includeStack, vfs, lo logger.info(`Skipping preprocessing of PlantUML standard library include '${url}'`) skip = true } else if (includeStack.includes(url)) { - console.log({ includeStack, url }) const message = `Preprocessing of PlantUML include failed, because recursive reading already included referenced file '${url}'` throw new Error(message) } else { @@ -246,7 +243,6 @@ function readPlantUmlInclude (url, resource, includePaths, includeStack, vfs, lo } else { filePath = resolveIncludeFile(url, resource, includePaths, vfs) if (includeStack.includes(filePath)) { - console.log('after resolveIncludeFile', { includeStack, resource, includePaths, url }) const message = `Preprocessing of PlantUML include failed, because recursive reading already included referenced file '${filePath}'` throw new Error(message) } else { @@ -346,7 +342,6 @@ function getPlantUmlTextOrFirstBlock (text) { * @param {string[]} includeOnce */ function checkIncludeOnce (text, filePath, includeOnce) { - console.log('checkIncludeOnce', { filePath, includeOnce }) if (includeOnce.includes(filePath)) { const message = `Preprocessing of PlantUML include failed, because including multiple times referenced file '${filePath}' with '!include_once' guard` throw new Error(message) diff --git a/test/browser/index.html b/test/browser/index.html index 9eabf06..7b96414 100644 --- a/test/browser/index.html +++ b/test/browser/index.html @@ -1,20 +1,20 @@ - - - Asciidoctor Kroki Extension tests - - - - -
- - - - - - - - - + + + Asciidoctor Kroki Extension tests + + + + +
+ + - diff --git a/test/browser/run.js b/test/browser/run.js index d7bf931..cce4b53 100644 --- a/test/browser/run.js +++ b/test/browser/run.js @@ -39,7 +39,7 @@ const log = async (msg) => { if (args[0] && typeof args[0] === 'string') { if (args[0] === '%d failures') { process.exit(parseInt(args[1])) - } else if (args[0].startsWith('Unable to start the browser tests suite:')) { + } else if (args[0].startsWith('Unable to start the browser tests suite')) { process.exit(1) } } diff --git a/test/browser/test.js b/test/browser/test.js index 29329ee..3489cb9 100644 --- a/test/browser/test.js +++ b/test/browser/test.js @@ -1,4 +1,6 @@ -/* global it, describe, mocha, chai, Asciidoctor, AsciidoctorKroki, mochaOpts, pako, base64js */ +/* global it, describe, mocha, chai, XMLHttpRequest, AsciidoctorKroki, mochaOpts, pako, base64js */ +import Asciidoctor from '../../node_modules/@asciidoctor/core/dist/browser/asciidoctor.js' + const httpGet = (uri, encoding = 'utf8') => { let data = '' let status = -1 @@ -43,7 +45,7 @@ const httpGet = (uri, encoding = 'utf8') => { mocha.setup({ ui: 'bdd', checkLeaks: false, - reporter: reporter + reporter }) const expect = chai.expect @@ -96,7 +98,7 @@ alice -> bob expect(html).to.contain(`Diagram`) }).timeout(5000) it('should convert a diagram with a relative path to an image', () => { - const input = `plantuml::../fixtures/alice.puml[svg,role=sequence]` + const input = 'plantuml::../fixtures/alice.puml[svg,role=sequence]' const registry = asciidoctor.Extensions.create() AsciidoctorKroki.register(registry, { vfs: { @@ -124,5 +126,5 @@ alice -> bob } }) })().catch(err => { - console.error('Unable to start the browser tests suite', err) + console.error('Unable to start the browser tests suite', { message: err.message }) })