(function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = 'function' == typeof require && require; if (!f && c) return c(i, !0); if (u) return u(i, !0); var a = new Error("Cannot find module '" + i + "'"); throw ((a.code = 'MODULE_NOT_FOUND'), a); } var p = (n[i] = { exports: {} }); e[i][0].call( p.exports, function (r) { var n = e[i][1][r]; return o(n || r); }, p, p.exports, r, e, n, t, ); } return n[i].exports; } for ( var u = 'function' == typeof require && require, i = 0; i < t.length; i++ ) o(t[i]); return o; } return r; })()( { 1: [ function (require, module, exports) { 'use strict'; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; function getLens(b64) { var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('='); if (validLen === -1) validLen = len; var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4); return [validLen, placeHoldersLen]; } // base64 is 4/3 + up to two characters of the original data function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen; var i; for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; arr[curByte++] = (tmp >> 16) & 0xff; arr[curByte++] = (tmp >> 8) & 0xff; arr[curByte++] = tmp & 0xff; } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); arr[curByte++] = tmp & 0xff; } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); arr[curByte++] = (tmp >> 8) & 0xff; arr[curByte++] = tmp & 0xff; } return arr; } function tripletToBase64(num) { return ( lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f] ); } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xff0000) + ((uint8[i + 1] << 8) & 0xff00) + (uint8[i + 2] & 0xff); output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for ( var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength ) { parts.push( encodeChunk( uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength, ), ); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + '=='); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3f] + lookup[(tmp << 2) & 0x3f] + '=', ); } return parts.join(''); } }, {}, ], 2: [function (require, module, exports) {}, {}], 3: [ function (require, module, exports) { (function (Buffer) { (function () { /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict'; var base64 = require('base64-js'); var ieee754 = require('ieee754'); exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 0x7fffffff; exports.kMaxLength = K_MAX_LENGTH; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); if ( !Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function' ) { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.', ); } function typedArraySupport() { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1); arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42; }, }; return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined; return this.buffer; }, }); Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined; return this.byteOffset; }, }); function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError( 'The value "' + length + '" is invalid for option "size"', ); } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length); buf.__proto__ = Buffer.prototype; return buf; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number', ); } return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if ( typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer ) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false, }); } Buffer.poolSize = 8192; // not used by this implementation function from(value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset); } if (ArrayBuffer.isView(value)) { return fromArrayLike(value); } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value, ); } if ( isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer)) ) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number', ); } var valueOf = value.valueOf && value.valueOf(); if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length); } var b = fromObject(value); if (b) return b; if ( typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function' ) { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length, ); } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + typeof value, ); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number'); } else if (size < 0) { throw new RangeError( 'The value "' + size + '" is invalid for option "size"', ); } } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); } return createBuffer(size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } var length = byteLength(string, encoding) | 0; var buf = createBuffer(length); var actual = buf.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual); } return buf; } function fromArrayLike(array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; var buf = createBuffer(length); for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255; } return buf; } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds'); } var buf; if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array); } else if (length === undefined) { buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype; return buf; } function fromObject(obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0; var buf = createBuffer(len); if (buf.length === 0) { return buf; } obj.copy(buf, 0, 0, len); return buf; } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0); } return fromArrayLike(obj); } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data); } } function checked(length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError( 'Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes', ); } return length | 0; } function SlowBuffer(length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0; } return Buffer.alloc(+length); } Buffer.isBuffer = function isBuffer(b) { return ( b != null && b._isBuffer === true && b !== Buffer.prototype ); // so Buffer.isBuffer(Buffer.prototype) will be false }; Buffer.compare = function compare(a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array', ); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!Array.isArray(list)) { throw new TypeError( '"list" argument must be an Array of Buffers', ); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf); } if (!Buffer.isBuffer(buf)) { throw new TypeError( '"list" argument must be an Array of Buffers', ); } buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer.isBuffer(string)) { return string.length; } if ( ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer) ) { return string.byteLength; } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string, ); } var len = string.length; var mustMatch = arguments.length > 2 && arguments[2] === true; if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 } encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError( 'Buffer size must be a multiple of 16-bits', ); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError( 'Buffer size must be a multiple of 32-bits', ); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError( 'Buffer size must be a multiple of 64-bits', ); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; str = this.toString('hex', 0, max) .replace(/(.{2})/g, '$1 ') .trim(); if (this.length > max) str += ' ... '; return ''; }; Buffer.prototype.compare = function compare( target, start, end, thisStart, thisEnd, ) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength); } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + typeof target, ); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if ( start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length ) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf( buffer, val, byteOffset, encoding, dir, ) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1; else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xff; // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call( buffer, val, byteOffset, ); } else { return Uint8Array.prototype.lastIndexOf.call( buffer, val, byteOffset, ); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if ( encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le' ) { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if ( read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex) ) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes( val, byteOffset, encoding, ) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf( val, byteOffset, encoding, ) { return bidirectionalIndexOf( this, val, byteOffset, encoding, true, ); }; Buffer.prototype.lastIndexOf = function lastIndexOf( val, byteOffset, encoding, ) { return bidirectionalIndexOf( this, val, byteOffset, encoding, false, ); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } var strLen = string.length; if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer( utf8ToBytes(string, buf.length - offset), buf, offset, length, ); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function latin1Write(buf, string, offset, length) { return asciiWrite(buf, string, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer( utf16leToBytes(string, buf.length - offset), buf, offset, length, ); } Buffer.prototype.write = function write( string, offset, length, encoding, ) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported', ); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if ( (string.length > 0 && (length < 0 || offset < 0)) || offset > this.length ) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': return asciiWrite(this, string, offset, length); case 'latin1': case 'binary': return latin1Write(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0), }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf); } else { return base64.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xc0) === 0x80) { tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); if (tempCodePoint > 0x7f) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ( (secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 ) { tempCodePoint = ((firstByte & 0xf) << 0xc) | ((secondByte & 0x3f) << 0x6) | (thirdByte & 0x3f); if ( tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff) ) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ( (secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80 ) { tempCodePoint = ((firstByte & 0xf) << 0x12) | ((secondByte & 0x3f) << 0xc) | ((thirdByte & 0x3f) << 0x6) | (fourthByte & 0x3f); if ( tempCodePoint > 0xffff && tempCodePoint < 0x110000 ) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xfffd; bytesPerSequence = 1; } else if (codePoint > 0xffff) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); codePoint = 0xdc00 | (codePoint & 0x3ff); } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)), ); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7f); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype; return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUIntLE = function readUIntLE( offset, byteLength, noAssert, ) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUIntBE = function readUIntBE( offset, byteLength, noAssert, ) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUInt16LE = function readUInt16LE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8); }; Buffer.prototype.readUInt16BE = function readUInt16BE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1]; }; Buffer.prototype.readUInt32LE = function readUInt32LE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ( (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000 ); }; Buffer.prototype.readUInt32BE = function readUInt32BE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ( this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) ); }; Buffer.prototype.readIntLE = function readIntLE( offset, byteLength, noAssert, ) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE( offset, byteLength, noAssert, ) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return val & 0x8000 ? val | 0xffff0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return val & 0x8000 ? val | 0xffff0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ( this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) ); }; Buffer.prototype.readInt32BE = function readInt32BE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ( (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3] ); }; Buffer.prototype.readFloatLE = function readFloatLE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE( offset, noAssert, ) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError( '"buffer" argument must be a Buffer instance', ); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUIntLE = function writeUIntLE( value, offset, byteLength, noAssert, ) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xff; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xff; } return offset + byteLength; }; Buffer.prototype.writeUIntBE = function writeUIntBE( value, offset, byteLength, noAssert, ) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xff; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xff; } return offset + byteLength; }; Buffer.prototype.writeUInt8 = function writeUInt8( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeUInt16LE = function writeUInt16LE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeUInt16BE = function writeUInt16BE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeUInt32LE = function writeUInt32LE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; return offset + 4; }; Buffer.prototype.writeUInt32BE = function writeUInt32BE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE( value, offset, byteLength, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xff; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE( value, offset, byteLength, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xff; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE( value, offset, noAssert, ) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754( buf, value, offset, 4, 3.4028234663852886e38, -3.4028234663852886e38, ); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE( value, offset, noAssert, ) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE( value, offset, noAssert, ) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754( buf, value, offset, 8, 1.7976931348623157e308, -1.7976931348623157e308, ); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE( value, offset, noAssert, ) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE( value, offset, noAssert, ) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy( target, targetStart, start, end, ) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; if ( this === target && typeof Uint8Array.prototype.copyWithin === 'function' ) { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end); } else if ( this === target && start < targetStart && targetStart < end ) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart, ); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if ( typeof encoding === 'string' && !Buffer.isEncoding(encoding) ) { throw new TypeError('Unknown encoding: ' + encoding); } if (val.length === 1) { var code = val.charCodeAt(0); if ( (encoding === 'utf8' && code < 128) || encoding === 'latin1' ) { // Fast path: If `val` fits into a single byte, use that numeric value. val = code; } } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); var len = bytes.length; if (len === 0) { throw new TypeError( 'The value "' + val + '" is invalid for argument "value"', ); } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xd7ff && codePoint < 0xe000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xdbff) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xdc00) { if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push( (codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80, ); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push( (codePoint >> 0xc) | 0xe0, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80, ); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push( (codePoint >> 0x12) | 0xf0, ((codePoint >> 0xc) & 0x3f) | 0x80, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80, ); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xff); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance(obj, type) { return ( obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) ); } function numberIsNaN(obj) { // For IE11 support return obj !== obj; // eslint-disable-line no-self-compare } }).call(this); }).call(this, require('buffer').Buffer); }, { 'base64-js': 1, 'buffer': 3, 'ieee754': 30 }, ], 4: [ function (require, module, exports) { 'use strict'; var isMergeableObject = function isMergeableObject(value) { return isNonNullObject(value) && !isSpecial(value); }; function isNonNullObject(value) { return !!value && typeof value === 'object'; } function isSpecial(value) { var stringValue = Object.prototype.toString.call(value); return ( stringValue === '[object RegExp]' || stringValue === '[object Date]' || isReactElement(value) ); } // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 var canUseSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; function isReactElement(value) { return value.$$typeof === REACT_ELEMENT_TYPE; } function emptyTarget(val) { return Array.isArray(val) ? [] : {}; } function cloneUnlessOtherwiseSpecified(value, options) { return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value; } function defaultArrayMerge(target, source, options) { return target.concat(source).map(function (element) { return cloneUnlessOtherwiseSpecified(element, options); }); } function getMergeFunction(key, options) { if (!options.customMerge) { return deepmerge; } var customMerge = options.customMerge(key); return typeof customMerge === 'function' ? customMerge : deepmerge; } function getEnumerableOwnPropertySymbols(target) { return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function (symbol) { return Object.propertyIsEnumerable.call(target, symbol); }) : []; } function getKeys(target) { return Object.keys(target).concat( getEnumerableOwnPropertySymbols(target), ); } function propertyIsOnObject(object, property) { try { return property in object; } catch (_) { return false; } } // Protects from prototype poisoning and unexpected merging up the prototype chain. function propertyIsUnsafe(target, key) { return ( propertyIsOnObject(target, key) && // Properties are safe to merge if they don't exist in the target yet, !( Object.hasOwnProperty.call(target, key) && // unsafe if they exist up the prototype chain, Object.propertyIsEnumerable.call(target, key) ) ); // and also unsafe if they're nonenumerable. } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { getKeys(target).forEach(function (key) { destination[key] = cloneUnlessOtherwiseSpecified( target[key], options, ); }); } getKeys(source).forEach(function (key) { if (propertyIsUnsafe(target, key)) { return; } if ( propertyIsOnObject(target, key) && options.isMergeableObject(source[key]) ) { destination[key] = getMergeFunction(key, options)( target[key], source[key], options, ); } else { destination[key] = cloneUnlessOtherwiseSpecified( source[key], options, ); } }); return destination; } function deepmerge(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() // implementations can use it. The caller may not replace it. options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; var sourceIsArray = Array.isArray(source); var targetIsArray = Array.isArray(target); var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; if (!sourceAndTargetTypesMatch) { return cloneUnlessOtherwiseSpecified(source, options); } else if (sourceIsArray) { return options.arrayMerge(target, source, options); } else { return mergeObject(target, source, options); } } deepmerge.all = function deepmergeAll(array, options) { if (!Array.isArray(array)) { throw new Error('first argument should be an array'); } return array.reduce(function (prev, next) { return deepmerge(prev, next, options); }, {}); }; var deepmerge_1 = deepmerge; module.exports = deepmerge_1; }, {}, ], 5: [ function (require, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.attributeNames = exports.elementNames = void 0; exports.elementNames = new Map( [ 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'glyphRef', 'linearGradient', 'radialGradient', 'textPath', ].map(function (val) { return [val.toLowerCase(), val]; }), ); exports.attributeNames = new Map( [ 'definitionURL', 'attributeName', 'attributeType', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'diffuseConstant', 'edgeMode', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector', 'zoomAndPan', ].map(function (val) { return [val.toLowerCase(), val]; }), ); }, {}, ], 6: [ function (require, module, exports) { 'use strict'; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? function (o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if ( !desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) ) { desc = { enumerable: true, get: function () { return m[k]; }, }; } Object.defineProperty(o, k2, desc); } : function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? function (o, v) { Object.defineProperty(o, 'default', { enumerable: true, value: v, }); } : function (o, v) { o['default'] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if ( k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k) ) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, '__esModule', { value: true }); exports.render = void 0; /* * Module dependencies */ var ElementType = __importStar(require('domelementtype')); var entities_1 = require('entities'); /** * Mixed-case SVG and MathML tags & attributes * recognized by the HTML parser. * * @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign */ var foreignNames_js_1 = require('./foreignNames.js'); var unencodedElements = new Set([ 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript', ]); function replaceQuotes(value) { return value.replace(/"/g, '"'); } /** * Format attributes */ function formatAttributes(attributes, opts) { var _a; if (!attributes) return; var encode = ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) === false ? replaceQuotes : opts.xmlMode || opts.encodeEntities !== 'utf8' ? entities_1.encodeXML : entities_1.escapeAttribute; return Object.keys(attributes) .map(function (key) { var _a, _b; var value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : ''; if (opts.xmlMode === 'foreign') { /* Fix up mixed-case attribute names */ key = (_b = foreignNames_js_1.attributeNames.get(key)) !== null && _b !== void 0 ? _b : key; } if (!opts.emptyAttrs && !opts.xmlMode && value === '') { return key; } return ''.concat(key, '="').concat(encode(value), '"'); }) .join(' '); } /** * Self-enclosing tags */ var singleTag = new Set([ 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr', ]); /** * Renders a DOM node or an array of DOM nodes to a string. * * Can be thought of as the equivalent of the `outerHTML` of the passed node(s). * * @param node Node to be rendered. * @param options Changes serialization behavior */ function render(node, options) { if (options === void 0) { options = {}; } var nodes = 'length' in node ? node : [node]; var output = ''; for (var i = 0; i < nodes.length; i++) { output += renderNode(nodes[i], options); } return output; } exports.render = render; exports.default = render; function renderNode(node, options) { switch (node.type) { case ElementType.Root: return render(node.children, options); // @ts-expect-error We don't use `Doctype` yet case ElementType.Doctype: case ElementType.Directive: return renderDirective(node); case ElementType.Comment: return renderComment(node); case ElementType.CDATA: return renderCdata(node); case ElementType.Script: case ElementType.Style: case ElementType.Tag: return renderTag(node, options); case ElementType.Text: return renderText(node, options); } } var foreignModeIntegrationPoints = new Set([ 'mi', 'mo', 'mn', 'ms', 'mtext', 'annotation-xml', 'foreignObject', 'desc', 'title', ]); var foreignElements = new Set(['svg', 'math']); function renderTag(elem, opts) { var _a; // Handle SVG / MathML in HTML if (opts.xmlMode === 'foreign') { /* Fix up mixed-case element names */ elem.name = (_a = foreignNames_js_1.elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name; /* Exit foreign mode at integration points */ if ( elem.parent && foreignModeIntegrationPoints.has(elem.parent.name) ) { opts = __assign(__assign({}, opts), { xmlMode: false }); } } if (!opts.xmlMode && foreignElements.has(elem.name)) { opts = __assign(__assign({}, opts), { xmlMode: 'foreign' }); } var tag = '<'.concat(elem.name); var attribs = formatAttributes(elem.attribs, opts); if (attribs) { tag += ' '.concat(attribs); } if ( elem.children.length === 0 && (opts.xmlMode ? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags opts.selfClosingTags !== false : // User explicitly asked for self-closing tags, even in HTML mode opts.selfClosingTags && singleTag.has(elem.name)) ) { if (!opts.xmlMode) tag += ' '; tag += '/>'; } else { tag += '>'; if (elem.children.length > 0) { tag += render(elem.children, opts); } if (opts.xmlMode || !singleTag.has(elem.name)) { tag += ''); } } return tag; } function renderDirective(elem) { return '<'.concat(elem.data, '>'); } function renderText(elem, opts) { var _a; var data = elem.data || ''; // If entities weren't decoded, no need to encode them back if ( ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) !== false && !( !opts.xmlMode && elem.parent && unencodedElements.has(elem.parent.name) ) ) { data = opts.xmlMode || opts.encodeEntities !== 'utf8' ? (0, entities_1.encodeXML)(data) : (0, entities_1.escapeText)(data); } return data; } function renderCdata(elem) { return ''); } function renderComment(elem) { return ''); } }, { './foreignNames.js': 5, 'domelementtype': 7, 'entities': 25 }, ], 7: [ function (require, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.Doctype = exports.CDATA = exports.Tag = exports.Style = exports.Script = exports.Comment = exports.Directive = exports.Text = exports.Root = exports.isTag = exports.ElementType = void 0; /** Types of elements found in htmlparser2's DOM */ var ElementType; (function (ElementType) { /** Type for the root element of a document */ ElementType['Root'] = 'root'; /** Type for Text */ ElementType['Text'] = 'text'; /** Type for */ ElementType['Directive'] = 'directive'; /** Type for */ ElementType['Comment'] = 'comment'; /** Type for `. this.sequenceIndex = Number(c === CharCodes.Lt); } }; Tokenizer.prototype.stateCDATASequence = function (c) { if (c === Sequences.Cdata[this.sequenceIndex]) { if (++this.sequenceIndex === Sequences.Cdata.length) { this.state = State.InCommentLike; this.currentSequence = Sequences.CdataEnd; this.sequenceIndex = 0; this.sectionStart = this.index + 1; } } else { this.sequenceIndex = 0; this.state = State.InDeclaration; this.stateInDeclaration(c); // Reconsume the character } }; /** * When we wait for one specific character, we can speed things up * by skipping through the buffer until we find it. * * @returns Whether the character was found. */ Tokenizer.prototype.fastForwardTo = function (c) { while (++this.index < this.buffer.length + this.offset) { if (this.buffer.charCodeAt(this.index - this.offset) === c) { return true; } } /* * We increment the index at the end of the `parse` loop, * so set it to `buffer.length - 1` here. * * TODO: Refactor `parse` to increment index before calling states. */ this.index = this.buffer.length + this.offset - 1; return false; }; /** * Comments and CDATA end with `-->` and `]]>`. * * Their common qualities are: * - Their end sequences have a distinct character they start with. * - That character is then repeated, so we have to check multiple repeats. * - All characters but the start character of the sequence can be skipped. */ Tokenizer.prototype.stateInCommentLike = function (c) { if (c === this.currentSequence[this.sequenceIndex]) { if (++this.sequenceIndex === this.currentSequence.length) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, this.index, 2); } else { this.cbs.oncomment(this.sectionStart, this.index, 2); } this.sequenceIndex = 0; this.sectionStart = this.index + 1; this.state = State.Text; } } else if (this.sequenceIndex === 0) { // Fast-forward to the first character of the sequence if (this.fastForwardTo(this.currentSequence[0])) { this.sequenceIndex = 1; } } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { // Allow long sequences, eg. --->, ]]]> this.sequenceIndex = 0; } }; /** * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name. * * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar). * We allow anything that wouldn't end the tag. */ Tokenizer.prototype.isTagStartChar = function (c) { return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c); }; Tokenizer.prototype.startSpecial = function (sequence, offset) { this.isSpecial = true; this.currentSequence = sequence; this.sequenceIndex = offset; this.state = State.SpecialStartSequence; }; Tokenizer.prototype.stateBeforeTagName = function (c) { if (c === CharCodes.ExclamationMark) { this.state = State.BeforeDeclaration; this.sectionStart = this.index + 1; } else if (c === CharCodes.Questionmark) { this.state = State.InProcessingInstruction; this.sectionStart = this.index + 1; } else if (this.isTagStartChar(c)) { var lower = c | 0x20; this.sectionStart = this.index; if (!this.xmlMode && lower === Sequences.TitleEnd[2]) { this.startSpecial(Sequences.TitleEnd, 3); } else { this.state = !this.xmlMode && lower === Sequences.ScriptEnd[2] ? State.BeforeSpecialS : State.InTagName; } } else if (c === CharCodes.Slash) { this.state = State.BeforeClosingTagName; } else { this.state = State.Text; this.stateText(c); } }; Tokenizer.prototype.stateInTagName = function (c) { if (isEndOfTagSection(c)) { this.cbs.onopentagname(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } }; Tokenizer.prototype.stateBeforeClosingTagName = function (c) { if (isWhitespace(c)) { // Ignore } else if (c === CharCodes.Gt) { this.state = State.Text; } else { this.state = this.isTagStartChar(c) ? State.InClosingTagName : State.InSpecialComment; this.sectionStart = this.index; } }; Tokenizer.prototype.stateInClosingTagName = function (c) { if (c === CharCodes.Gt || isWhitespace(c)) { this.cbs.onclosetag(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.AfterClosingTagName; this.stateAfterClosingTagName(c); } }; Tokenizer.prototype.stateAfterClosingTagName = function (c) { // Skip everything until ">" if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.state = State.Text; this.baseState = State.Text; this.sectionStart = this.index + 1; } }; Tokenizer.prototype.stateBeforeAttributeName = function (c) { if (c === CharCodes.Gt) { this.cbs.onopentagend(this.index); if (this.isSpecial) { this.state = State.InSpecialTag; this.sequenceIndex = 0; } else { this.state = State.Text; } this.baseState = this.state; this.sectionStart = this.index + 1; } else if (c === CharCodes.Slash) { this.state = State.InSelfClosingTag; } else if (!isWhitespace(c)) { this.state = State.InAttributeName; this.sectionStart = this.index; } }; Tokenizer.prototype.stateInSelfClosingTag = function (c) { if (c === CharCodes.Gt) { this.cbs.onselfclosingtag(this.index); this.state = State.Text; this.baseState = State.Text; this.sectionStart = this.index + 1; this.isSpecial = false; // Reset special state, in case of self-closing special tags } else if (!isWhitespace(c)) { this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } }; Tokenizer.prototype.stateInAttributeName = function (c) { if (c === CharCodes.Eq || isEndOfTagSection(c)) { this.cbs.onattribname(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.AfterAttributeName; this.stateAfterAttributeName(c); } }; Tokenizer.prototype.stateAfterAttributeName = function (c) { if (c === CharCodes.Eq) { this.state = State.BeforeAttributeValue; } else if (c === CharCodes.Slash || c === CharCodes.Gt) { this.cbs.onattribend(QuoteType.NoValue, this.index); this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (!isWhitespace(c)) { this.cbs.onattribend(QuoteType.NoValue, this.index); this.state = State.InAttributeName; this.sectionStart = this.index; } }; Tokenizer.prototype.stateBeforeAttributeValue = function (c) { if (c === CharCodes.DoubleQuote) { this.state = State.InAttributeValueDq; this.sectionStart = this.index + 1; } else if (c === CharCodes.SingleQuote) { this.state = State.InAttributeValueSq; this.sectionStart = this.index + 1; } else if (!isWhitespace(c)) { this.sectionStart = this.index; this.state = State.InAttributeValueNq; this.stateInAttributeValueNoQuotes(c); // Reconsume token } }; Tokenizer.prototype.handleInAttributeValue = function (c, quote) { if ( c === quote || (!this.decodeEntities && this.fastForwardTo(quote)) ) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend( quote === CharCodes.DoubleQuote ? QuoteType.Double : QuoteType.Single, this.index, ); this.state = State.BeforeAttributeName; } else if (this.decodeEntities && c === CharCodes.Amp) { this.baseState = this.state; this.state = State.BeforeEntity; } }; Tokenizer.prototype.stateInAttributeValueDoubleQuotes = function (c) { this.handleInAttributeValue(c, CharCodes.DoubleQuote); }; Tokenizer.prototype.stateInAttributeValueSingleQuotes = function (c) { this.handleInAttributeValue(c, CharCodes.SingleQuote); }; Tokenizer.prototype.stateInAttributeValueNoQuotes = function (c) { if (isWhitespace(c) || c === CharCodes.Gt) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend(QuoteType.Unquoted, this.index); this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (this.decodeEntities && c === CharCodes.Amp) { this.baseState = this.state; this.state = State.BeforeEntity; } }; Tokenizer.prototype.stateBeforeDeclaration = function (c) { if (c === CharCodes.OpeningSquareBracket) { this.state = State.CDATASequence; this.sequenceIndex = 0; } else { this.state = c === CharCodes.Dash ? State.BeforeComment : State.InDeclaration; } }; Tokenizer.prototype.stateInDeclaration = function (c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.ondeclaration(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } }; Tokenizer.prototype.stateInProcessingInstruction = function (c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.onprocessinginstruction(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } }; Tokenizer.prototype.stateBeforeComment = function (c) { if (c === CharCodes.Dash) { this.state = State.InCommentLike; this.currentSequence = Sequences.CommentEnd; // Allow short comments (eg. ) this.sequenceIndex = 2; this.sectionStart = this.index + 1; } else { this.state = State.InDeclaration; } }; Tokenizer.prototype.stateInSpecialComment = function (c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.oncomment(this.sectionStart, this.index, 0); this.state = State.Text; this.sectionStart = this.index + 1; } }; Tokenizer.prototype.stateBeforeSpecialS = function (c) { var lower = c | 0x20; if (lower === Sequences.ScriptEnd[3]) { this.startSpecial(Sequences.ScriptEnd, 4); } else if (lower === Sequences.StyleEnd[3]) { this.startSpecial(Sequences.StyleEnd, 4); } else { this.state = State.InTagName; this.stateInTagName(c); // Consume the token again } }; Tokenizer.prototype.stateBeforeEntity = function (c) { // Start excess with 1 to include the '&' this.entityExcess = 1; this.entityResult = 0; if (c === CharCodes.Number) { this.state = State.BeforeNumericEntity; } else if (c === CharCodes.Amp) { // We have two `&` characters in a row. Stay in the current state. } else { this.trieIndex = 0; this.trieCurrent = this.entityTrie[0]; this.state = State.InNamedEntity; this.stateInNamedEntity(c); } }; Tokenizer.prototype.stateInNamedEntity = function (c) { this.entityExcess += 1; this.trieIndex = (0, decode_js_1.determineBranch)( this.entityTrie, this.trieCurrent, this.trieIndex + 1, c, ); if (this.trieIndex < 0) { this.emitNamedEntity(); this.index--; return; } this.trieCurrent = this.entityTrie[this.trieIndex]; var masked = this.trieCurrent & decode_js_1.BinTrieFlags.VALUE_LENGTH; // If the branch is a value, store it and continue if (masked) { // The mask is the number of bytes of the value, including the current byte. var valueLength = (masked >> 14) - 1; // If we have a legacy entity while parsing strictly, just skip the number of bytes if (!this.allowLegacyEntity() && c !== CharCodes.Semi) { this.trieIndex += valueLength; } else { // Add 1 as we have already incremented the excess var entityStart = this.index - this.entityExcess + 1; if (entityStart > this.sectionStart) { this.emitPartial(this.sectionStart, entityStart); } // If this is a surrogate pair, consume the next two bytes this.entityResult = this.trieIndex; this.trieIndex += valueLength; this.entityExcess = 0; this.sectionStart = this.index + 1; if (valueLength === 0) { this.emitNamedEntity(); } } } }; Tokenizer.prototype.emitNamedEntity = function () { this.state = this.baseState; if (this.entityResult === 0) { return; } var valueLength = (this.entityTrie[this.entityResult] & decode_js_1.BinTrieFlags.VALUE_LENGTH) >> 14; switch (valueLength) { case 1: { this.emitCodePoint( this.entityTrie[this.entityResult] & ~decode_js_1.BinTrieFlags.VALUE_LENGTH, ); break; } case 2: { this.emitCodePoint(this.entityTrie[this.entityResult + 1]); break; } case 3: { this.emitCodePoint(this.entityTrie[this.entityResult + 1]); this.emitCodePoint(this.entityTrie[this.entityResult + 2]); } } }; Tokenizer.prototype.stateBeforeNumericEntity = function (c) { if ((c | 0x20) === CharCodes.LowerX) { this.entityExcess++; this.state = State.InHexEntity; } else { this.state = State.InNumericEntity; this.stateInNumericEntity(c); } }; Tokenizer.prototype.emitNumericEntity = function (strict) { var entityStart = this.index - this.entityExcess - 1; var numberStart = entityStart + 2 + Number(this.state === State.InHexEntity); if (numberStart !== this.index) { // Emit leading data if any if (entityStart > this.sectionStart) { this.emitPartial(this.sectionStart, entityStart); } this.sectionStart = this.index + Number(strict); this.emitCodePoint( (0, decode_js_1.replaceCodePoint)(this.entityResult), ); } this.state = this.baseState; }; Tokenizer.prototype.stateInNumericEntity = function (c) { if (c === CharCodes.Semi) { this.emitNumericEntity(true); } else if (isNumber(c)) { this.entityResult = this.entityResult * 10 + (c - CharCodes.Zero); this.entityExcess++; } else { if (this.allowLegacyEntity()) { this.emitNumericEntity(false); } else { this.state = this.baseState; } this.index--; } }; Tokenizer.prototype.stateInHexEntity = function (c) { if (c === CharCodes.Semi) { this.emitNumericEntity(true); } else if (isNumber(c)) { this.entityResult = this.entityResult * 16 + (c - CharCodes.Zero); this.entityExcess++; } else if (isHexDigit(c)) { this.entityResult = this.entityResult * 16 + ((c | 0x20) - CharCodes.LowerA + 10); this.entityExcess++; } else { if (this.allowLegacyEntity()) { this.emitNumericEntity(false); } else { this.state = this.baseState; } this.index--; } }; Tokenizer.prototype.allowLegacyEntity = function () { return ( !this.xmlMode && (this.baseState === State.Text || this.baseState === State.InSpecialTag) ); }; /** * Remove data that has already been consumed from the buffer. */ Tokenizer.prototype.cleanup = function () { // If we are inside of text or attributes, emit what we already have. if (this.running && this.sectionStart !== this.index) { if ( this.state === State.Text || (this.state === State.InSpecialTag && this.sequenceIndex === 0) ) { this.cbs.ontext(this.sectionStart, this.index); this.sectionStart = this.index; } else if ( this.state === State.InAttributeValueDq || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueNq ) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = this.index; } } }; Tokenizer.prototype.shouldContinue = function () { return ( this.index < this.buffer.length + this.offset && this.running ); }; /** * Iterates through the buffer, calling the function corresponding to the current state. * * States that are more likely to be hit are higher up, as a performance improvement. */ Tokenizer.prototype.parse = function () { while (this.shouldContinue()) { var c = this.buffer.charCodeAt(this.index - this.offset); switch (this.state) { case State.Text: { this.stateText(c); break; } case State.SpecialStartSequence: { this.stateSpecialStartSequence(c); break; } case State.InSpecialTag: { this.stateInSpecialTag(c); break; } case State.CDATASequence: { this.stateCDATASequence(c); break; } case State.InAttributeValueDq: { this.stateInAttributeValueDoubleQuotes(c); break; } case State.InAttributeName: { this.stateInAttributeName(c); break; } case State.InCommentLike: { this.stateInCommentLike(c); break; } case State.InSpecialComment: { this.stateInSpecialComment(c); break; } case State.BeforeAttributeName: { this.stateBeforeAttributeName(c); break; } case State.InTagName: { this.stateInTagName(c); break; } case State.InClosingTagName: { this.stateInClosingTagName(c); break; } case State.BeforeTagName: { this.stateBeforeTagName(c); break; } case State.AfterAttributeName: { this.stateAfterAttributeName(c); break; } case State.InAttributeValueSq: { this.stateInAttributeValueSingleQuotes(c); break; } case State.BeforeAttributeValue: { this.stateBeforeAttributeValue(c); break; } case State.BeforeClosingTagName: { this.stateBeforeClosingTagName(c); break; } case State.AfterClosingTagName: { this.stateAfterClosingTagName(c); break; } case State.BeforeSpecialS: { this.stateBeforeSpecialS(c); break; } case State.InAttributeValueNq: { this.stateInAttributeValueNoQuotes(c); break; } case State.InSelfClosingTag: { this.stateInSelfClosingTag(c); break; } case State.InDeclaration: { this.stateInDeclaration(c); break; } case State.BeforeDeclaration: { this.stateBeforeDeclaration(c); break; } case State.BeforeComment: { this.stateBeforeComment(c); break; } case State.InProcessingInstruction: { this.stateInProcessingInstruction(c); break; } case State.InNamedEntity: { this.stateInNamedEntity(c); break; } case State.BeforeEntity: { this.stateBeforeEntity(c); break; } case State.InHexEntity: { this.stateInHexEntity(c); break; } case State.InNumericEntity: { this.stateInNumericEntity(c); break; } default: { // `this._state === State.BeforeNumericEntity` this.stateBeforeNumericEntity(c); } } this.index++; } this.cleanup(); }; Tokenizer.prototype.finish = function () { if (this.state === State.InNamedEntity) { this.emitNamedEntity(); } // If there is remaining data, emit it in a reasonable way if (this.sectionStart < this.index) { this.handleTrailingData(); } this.cbs.onend(); }; /** Handle any trailing data. */ Tokenizer.prototype.handleTrailingData = function () { var endIndex = this.buffer.length + this.offset; if (this.state === State.InCommentLike) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, endIndex, 0); } else { this.cbs.oncomment(this.sectionStart, endIndex, 0); } } else if ( this.state === State.InNumericEntity && this.allowLegacyEntity() ) { this.emitNumericEntity(false); // All trailing data will have been consumed } else if ( this.state === State.InHexEntity && this.allowLegacyEntity() ) { this.emitNumericEntity(false); // All trailing data will have been consumed } else if ( this.state === State.InTagName || this.state === State.BeforeAttributeName || this.state === State.BeforeAttributeValue || this.state === State.AfterAttributeName || this.state === State.InAttributeName || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueDq || this.state === State.InAttributeValueNq || this.state === State.InClosingTagName ) { /* * If we are currently in an opening or closing tag, us not calling the * respective callback signals that the tag should be ignored. */ } else { this.cbs.ontext(this.sectionStart, endIndex); } }; Tokenizer.prototype.emitPartial = function (start, endIndex) { if ( this.baseState !== State.Text && this.baseState !== State.InSpecialTag ) { this.cbs.onattribdata(start, endIndex); } else { this.cbs.ontext(start, endIndex); } }; Tokenizer.prototype.emitCodePoint = function (cp) { if ( this.baseState !== State.Text && this.baseState !== State.InSpecialTag ) { this.cbs.onattribentity(cp); } else { this.cbs.ontextentity(cp); } }; return Tokenizer; })(); exports.default = Tokenizer; }, { 'entities/lib/decode.js': 18 }, ], 29: [ function (require, module, exports) { 'use strict'; var __createBinding = (this && this.__createBinding) || (Object.create ? function (o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if ( !desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable) ) { desc = { enumerable: true, get: function () { return m[k]; }, }; } Object.defineProperty(o, k2, desc); } : function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? function (o, v) { Object.defineProperty(o, 'default', { enumerable: true, value: v, }); } : function (o, v) { o['default'] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if ( k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k) ) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { 'default': mod }; }; Object.defineProperty(exports, '__esModule', { value: true }); exports.DomUtils = exports.parseFeed = exports.getFeed = exports.ElementType = exports.Tokenizer = exports.createDomStream = exports.parseDOM = exports.parseDocument = exports.DefaultHandler = exports.DomHandler = exports.Parser = void 0; var Parser_js_1 = require('./Parser.js'); var Parser_js_2 = require('./Parser.js'); Object.defineProperty(exports, 'Parser', { enumerable: true, get: function () { return Parser_js_2.Parser; }, }); var domhandler_1 = require('domhandler'); var domhandler_2 = require('domhandler'); Object.defineProperty(exports, 'DomHandler', { enumerable: true, get: function () { return domhandler_2.DomHandler; }, }); // Old name for DomHandler Object.defineProperty(exports, 'DefaultHandler', { enumerable: true, get: function () { return domhandler_2.DomHandler; }, }); // Helper methods /** * Parses the data, returns the resulting document. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM builder. */ function parseDocument(data, options) { var handler = new domhandler_1.DomHandler(undefined, options); new Parser_js_1.Parser(handler, options).end(data); return handler.root; } exports.parseDocument = parseDocument; /** * Parses data, returns an array of the root nodes. * * Note that the root nodes still have a `Document` node as their parent. * Use `parseDocument` to get the `Document` node instead. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM builder. * @deprecated Use `parseDocument` instead. */ function parseDOM(data, options) { return parseDocument(data, options).children; } exports.parseDOM = parseDOM; /** * Creates a parser instance, with an attached DOM handler. * * @param callback A callback that will be called once parsing has been completed. * @param options Optional options for the parser and DOM builder. * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM. */ function createDomStream(callback, options, elementCallback) { var handler = new domhandler_1.DomHandler( callback, options, elementCallback, ); return new Parser_js_1.Parser(handler, options); } exports.createDomStream = createDomStream; var Tokenizer_js_1 = require('./Tokenizer.js'); Object.defineProperty(exports, 'Tokenizer', { enumerable: true, get: function () { return __importDefault(Tokenizer_js_1).default; }, }); /* * All of the following exports exist for backwards-compatibility. * They should probably be removed eventually. */ exports.ElementType = __importStar(require('domelementtype')); var domutils_1 = require('domutils'); var domutils_2 = require('domutils'); Object.defineProperty(exports, 'getFeed', { enumerable: true, get: function () { return domutils_2.getFeed; }, }); var parseFeedDefaultOptions = { xmlMode: true }; /** * Parse a feed. * * @param feed The feed that should be parsed, as a string. * @param options Optionally, options for parsing. When using this, you should set `xmlMode` to `true`. */ function parseFeed(feed, options) { if (options === void 0) { options = parseFeedDefaultOptions; } return (0, domutils_1.getFeed)(parseDOM(feed, options)); } exports.parseFeed = parseFeed; exports.DomUtils = __importStar(require('domutils')); }, { './Parser.js': 27, './Tokenizer.js': 28, 'domelementtype': 7, 'domhandler': 8, 'domutils': 12, }, ], 30: [ function (require, module, exports) { /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & ((1 << -nBits) - 1); s >>= -nBits; nBits += eLen; for ( ; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8 ) {} m = e & ((1 << -nBits) - 1); e >>= -nBits; nBits += mLen; for ( ; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8 ) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for ( ; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8 ) {} e = (e << mLen) | m; eLen += mLen; for ( ; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8 ) {} buffer[offset + i - d] |= s * 128; }; }, {}, ], 31: [ function (require, module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /*! * is-plain-object * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ function isObject(o) { return Object.prototype.toString.call(o) === '[object Object]'; } function isPlainObject(o) { var ctor, prot; if (isObject(o) === false) return false; // If has modified constructor ctor = o.constructor; if (ctor === undefined) return true; // If has modified prototype prot = ctor.prototype; if (isObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; } exports.isPlainObject = isPlainObject; }, {}, ], 32: [ function (require, module, exports) { let urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; let customAlphabet = (alphabet, defaultSize = 21) => { return (size = defaultSize) => { let id = ''; let i = size; while (i--) { id += alphabet[(Math.random() * alphabet.length) | 0]; } return id; }; }; let nanoid = (size = 21) => { let id = ''; let i = size; while (i--) { id += urlAlphabet[(Math.random() * 64) | 0]; } return id; }; module.exports = { nanoid, customAlphabet }; }, {}, ], 33: [ function (require, module, exports) { /** * Srcset Parser * * By Alex Bell | MIT License * * JS Parser for the string value that appears in markup * * @returns Array [{url: _, d: _, w: _, h:_}, ...] * * Based super duper closely on the reference algorithm at: * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute * * Most comments are copied in directly from the spec * (except for comments in parens). */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.parseSrcset = factory(); } })(this, function () { // 1. Let input be the value passed to this algorithm. return function (input) { // UTILITY FUNCTIONS // Manual is faster than RegEx // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript // http://jsperf.com/whitespace-character/5 function isSpace(c) { return ( c === '\u0020' || // space c === '\u0009' || // horizontal tab c === '\u000A' || // new line c === '\u000C' || // form feed c === '\u000D' ); // carriage return } function collectCharacters(regEx) { var chars, match = regEx.exec(input.substring(pos)); if (match) { chars = match[0]; pos += chars.length; return chars; } } var inputLength = input.length, // (Don't use \s, to avoid matching non-breaking space) regexLeadingSpaces = /^[ \t\n\r\u000c]+/, regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/, regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/, regexTrailingCommas = /[,]+$/, regexNonNegativeInteger = /^\d+$/, // ( Positive or negative or unsigned integers or decimals, without or without exponents. // Must include at least one digit. // According to spec tests any decimal point must be followed by a digit. // No leading plus sign is allowed.) // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/, url, descriptors, currentDescriptor, state, c, // 2. Let position be a pointer into input, initially pointing at the start // of the string. pos = 0, // 3. Let candidates be an initially empty source set. candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space // characters or U+002C COMMA characters. If any U+002C COMMA characters // were collected, that is a parse error. while (true) { collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps. if (pos >= inputLength) { return candidates; // (we're done, this is the sole return path) } // 6. Collect a sequence of characters that are not space characters, // and let that be url. url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list. descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps: // (1). Remove all trailing U+002C COMMA characters from url. If this removed // more than one character, that is a parse error. if (url.slice(-1) === ',') { url = url.replace(regexTrailingCommas, ''); // (Jump ahead to step 9 to skip tokenization and just push the candidate). parseDescriptors(); // Otherwise, follow these substeps: } else { tokenize(); } // (close else of step 8) // 16. Return to the step labeled splitting loop. } // (Close of big while loop.) /** * Tokenizes descriptor properties prior to parsing * Returns undefined. */ function tokenize() { // 8.1. Descriptor tokeniser: Skip whitespace collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string. currentDescriptor = ''; // 8.3. Let state be in descriptor. state = 'in descriptor'; while (true) { // 8.4. Let c be the character at position. c = input.charAt(pos); // Do the following depending on the value of state. // For the purpose of this step, "EOF" is a special character representing // that position is past the end of input. // In descriptor if (state === 'in descriptor') { // Do the following, depending on the value of c: // Space character // If current descriptor is not empty, append current descriptor to // descriptors and let current descriptor be the empty string. // Set state to after descriptor. if (isSpace(c)) { if (currentDescriptor) { descriptors.push(currentDescriptor); currentDescriptor = ''; state = 'after descriptor'; } // U+002C COMMA (,) // Advance position to the next character in input. If current descriptor // is not empty, append current descriptor to descriptors. Jump to the step // labeled descriptor parser. } else if (c === ',') { pos += 1; if (currentDescriptor) { descriptors.push(currentDescriptor); } parseDescriptors(); return; // U+0028 LEFT PARENTHESIS (() // Append c to current descriptor. Set state to in parens. } else if (c === '\u0028') { currentDescriptor = currentDescriptor + c; state = 'in parens'; // EOF // If current descriptor is not empty, append current descriptor to // descriptors. Jump to the step labeled descriptor parser. } else if (c === '') { if (currentDescriptor) { descriptors.push(currentDescriptor); } parseDescriptors(); return; // Anything else // Append c to current descriptor. } else { currentDescriptor = currentDescriptor + c; } // (end "in descriptor" // In parens } else if (state === 'in parens') { // U+0029 RIGHT PARENTHESIS ()) // Append c to current descriptor. Set state to in descriptor. if (c === ')') { currentDescriptor = currentDescriptor + c; state = 'in descriptor'; // EOF // Append current descriptor to descriptors. Jump to the step labeled // descriptor parser. } else if (c === '') { descriptors.push(currentDescriptor); parseDescriptors(); return; // Anything else // Append c to current descriptor. } else { currentDescriptor = currentDescriptor + c; } // After descriptor } else if (state === 'after descriptor') { // Do the following, depending on the value of c: // Space character: Stay in this state. if (isSpace(c)) { // EOF: Jump to the step labeled descriptor parser. } else if (c === '') { parseDescriptors(); return; // Anything else // Set state to in descriptor. Set position to the previous character in input. } else { state = 'in descriptor'; pos -= 1; } } // Advance position to the next character in input. pos += 1; // Repeat this step. } // (close while true loop) } /** * Adds descriptor properties to a candidate, pushes to the candidates array * @return undefined */ // Declared outside of the while loop so that it's only created once. function parseDescriptors() { // 9. Descriptor parser: Let error be no. var pError = false, // 10. Let width be absent. // 11. Let density be absent. // 12. Let future-compat-h be absent. (We're implementing it now as h) w, d, h, i, candidate = {}, desc, lastChar, value, intVal, floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps // from the following list: for (i = 0; i < descriptors.length; i++) { desc = descriptors[i]; lastChar = desc[desc.length - 1]; value = desc.substring(0, desc.length - 1); intVal = parseInt(value, 10); floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by // a U+0077 LATIN SMALL LETTER W character if (regexNonNegativeInteger.test(value) && lastChar === 'w') { // If width and density are not both absent, then let error be yes. if (w || d) { pError = true; } // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. // Otherwise, let width be the result. if (intVal === 0) { pError = true; } else { w = intVal; } // If the descriptor consists of a valid floating-point number followed by // a U+0078 LATIN SMALL LETTER X character } else if (regexFloatingPoint.test(value) && lastChar === 'x') { // If width, density and future-compat-h are not all absent, then let error // be yes. if (w || d || h) { pError = true; } // Apply the rules for parsing floating-point number values to the descriptor. // If the result is less than zero, let error be yes. Otherwise, let density // be the result. if (floatVal < 0) { pError = true; } else { d = floatVal; } // If the descriptor consists of a valid non-negative integer followed by // a U+0068 LATIN SMALL LETTER H character } else if ( regexNonNegativeInteger.test(value) && lastChar === 'h' ) { // If height and density are not both absent, then let error be yes. if (h || d) { pError = true; } // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. Otherwise, let future-compat-h // be the result. if (intVal === 0) { pError = true; } else { h = intVal; } // Anything else, Let error be yes. } else { pError = true; } } // (close step 13 for loop) // 15. If error is still no, then append a new image source to candidates whose // URL is url, associated with a width width if not absent and a pixel // density density if not absent. Otherwise, there is a parse error. if (!pError) { candidate.url = url; if (w) { candidate.w = w; } if (d) { candidate.d = d; } if (h) { candidate.h = h; } candidates.push(candidate); } else if (console && console.log) { console.log( "Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.", ); } } // (close parseDescriptors fn) }; }); }, {}, ], 34: [ function (require, module, exports) { var x = String; var create = function () { return { isColorSupported: false, reset: x, bold: x, dim: x, italic: x, underline: x, inverse: x, hidden: x, strikethrough: x, black: x, red: x, green: x, yellow: x, blue: x, magenta: x, cyan: x, white: x, gray: x, bgBlack: x, bgRed: x, bgGreen: x, bgYellow: x, bgBlue: x, bgMagenta: x, bgCyan: x, bgWhite: x, }; }; module.exports = create(); module.exports.createColors = create; }, {}, ], 35: [ function (require, module, exports) { 'use strict'; let Container = require('./container'); class AtRule extends Container { constructor(defaults) { super(defaults); this.type = 'atrule'; } append(...children) { if (!this.proxyOf.nodes) this.nodes = []; return super.append(...children); } prepend(...children) { if (!this.proxyOf.nodes) this.nodes = []; return super.prepend(...children); } } module.exports = AtRule; AtRule.default = AtRule; Container.registerAtRule(AtRule); }, { './container': 37 }, ], 36: [ function (require, module, exports) { 'use strict'; let Node = require('./node'); class Comment extends Node { constructor(defaults) { super(defaults); this.type = 'comment'; } } module.exports = Comment; Comment.default = Comment; }, { './node': 47 }, ], 37: [ function (require, module, exports) { 'use strict'; let { isClean, my } = require('./symbols'); let Declaration = require('./declaration'); let Comment = require('./comment'); let Node = require('./node'); let parse, Rule, AtRule, Root; function cleanSource(nodes) { return nodes.map(i => { if (i.nodes) i.nodes = cleanSource(i.nodes); delete i.source; return i; }); } function markDirtyUp(node) { node[isClean] = false; if (node.proxyOf.nodes) { for (let i of node.proxyOf.nodes) { markDirtyUp(i); } } } class Container extends Node { append(...children) { for (let child of children) { let nodes = this.normalize(child, this.last); for (let node of nodes) this.proxyOf.nodes.push(node); } this.markDirty(); return this; } cleanRaws(keepBetween) { super.cleanRaws(keepBetween); if (this.nodes) { for (let node of this.nodes) node.cleanRaws(keepBetween); } } each(callback) { if (!this.proxyOf.nodes) return undefined; let iterator = this.getIterator(); let index, result; while (this.indexes[iterator] < this.proxyOf.nodes.length) { index = this.indexes[iterator]; result = callback(this.proxyOf.nodes[index], index); if (result === false) break; this.indexes[iterator] += 1; } delete this.indexes[iterator]; return result; } every(condition) { return this.nodes.every(condition); } getIterator() { if (!this.lastEach) this.lastEach = 0; if (!this.indexes) this.indexes = {}; this.lastEach += 1; let iterator = this.lastEach; this.indexes[iterator] = 0; return iterator; } getProxyProcessor() { return { get(node, prop) { if (prop === 'proxyOf') { return node; } else if (!node[prop]) { return node[prop]; } else if ( prop === 'each' || (typeof prop === 'string' && prop.startsWith('walk')) ) { return (...args) => { return node[prop]( ...args.map(i => { if (typeof i === 'function') { return (child, index) => i(child.toProxy(), index); } else { return i; } }), ); }; } else if (prop === 'every' || prop === 'some') { return cb => { return node[prop]((child, ...other) => cb(child.toProxy(), ...other), ); }; } else if (prop === 'root') { return () => node.root().toProxy(); } else if (prop === 'nodes') { return node.nodes.map(i => i.toProxy()); } else if (prop === 'first' || prop === 'last') { return node[prop].toProxy(); } else { return node[prop]; } }, set(node, prop, value) { if (node[prop] === value) return true; node[prop] = value; if ( prop === 'name' || prop === 'params' || prop === 'selector' ) { node.markDirty(); } return true; }, }; } index(child) { if (typeof child === 'number') return child; if (child.proxyOf) child = child.proxyOf; return this.proxyOf.nodes.indexOf(child); } insertAfter(exist, add) { let existIndex = this.index(exist); let nodes = this.normalize( add, this.proxyOf.nodes[existIndex], ).reverse(); existIndex = this.index(exist); for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node); let index; for (let id in this.indexes) { index = this.indexes[id]; if (existIndex < index) { this.indexes[id] = index + nodes.length; } } this.markDirty(); return this; } insertBefore(exist, add) { let existIndex = this.index(exist); let type = existIndex === 0 ? 'prepend' : false; let nodes = this.normalize( add, this.proxyOf.nodes[existIndex], type, ).reverse(); existIndex = this.index(exist); for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node); let index; for (let id in this.indexes) { index = this.indexes[id]; if (existIndex <= index) { this.indexes[id] = index + nodes.length; } } this.markDirty(); return this; } normalize(nodes, sample) { if (typeof nodes === 'string') { nodes = cleanSource(parse(nodes).nodes); } else if (Array.isArray(nodes)) { nodes = nodes.slice(0); for (let i of nodes) { if (i.parent) i.parent.removeChild(i, 'ignore'); } } else if (nodes.type === 'root' && this.type !== 'document') { nodes = nodes.nodes.slice(0); for (let i of nodes) { if (i.parent) i.parent.removeChild(i, 'ignore'); } } else if (nodes.type) { nodes = [nodes]; } else if (nodes.prop) { if (typeof nodes.value === 'undefined') { throw new Error('Value field is missed in node creation'); } else if (typeof nodes.value !== 'string') { nodes.value = String(nodes.value); } nodes = [new Declaration(nodes)]; } else if (nodes.selector) { nodes = [new Rule(nodes)]; } else if (nodes.name) { nodes = [new AtRule(nodes)]; } else if (nodes.text) { nodes = [new Comment(nodes)]; } else { throw new Error('Unknown node type in node creation'); } let processed = nodes.map(i => { /* c8 ignore next */ if (!i[my]) Container.rebuild(i); i = i.proxyOf; if (i.parent) i.parent.removeChild(i); if (i[isClean]) markDirtyUp(i); if (typeof i.raws.before === 'undefined') { if (sample && typeof sample.raws.before !== 'undefined') { i.raws.before = sample.raws.before.replace(/\S/g, ''); } } i.parent = this.proxyOf; return i; }); return processed; } prepend(...children) { children = children.reverse(); for (let child of children) { let nodes = this.normalize( child, this.first, 'prepend', ).reverse(); for (let node of nodes) this.proxyOf.nodes.unshift(node); for (let id in this.indexes) { this.indexes[id] = this.indexes[id] + nodes.length; } } this.markDirty(); return this; } push(child) { child.parent = this; this.proxyOf.nodes.push(child); return this; } removeAll() { for (let node of this.proxyOf.nodes) node.parent = undefined; this.proxyOf.nodes = []; this.markDirty(); return this; } removeChild(child) { child = this.index(child); this.proxyOf.nodes[child].parent = undefined; this.proxyOf.nodes.splice(child, 1); let index; for (let id in this.indexes) { index = this.indexes[id]; if (index >= child) { this.indexes[id] = index - 1; } } this.markDirty(); return this; } replaceValues(pattern, opts, callback) { if (!callback) { callback = opts; opts = {}; } this.walkDecls(decl => { if (opts.props && !opts.props.includes(decl.prop)) return; if (opts.fast && !decl.value.includes(opts.fast)) return; decl.value = decl.value.replace(pattern, callback); }); this.markDirty(); return this; } some(condition) { return this.nodes.some(condition); } walk(callback) { return this.each((child, i) => { let result; try { result = callback(child, i); } catch (e) { throw child.addToError(e); } if (result !== false && child.walk) { result = child.walk(callback); } return result; }); } walkAtRules(name, callback) { if (!callback) { callback = name; return this.walk((child, i) => { if (child.type === 'atrule') { return callback(child, i); } }); } if (name instanceof RegExp) { return this.walk((child, i) => { if (child.type === 'atrule' && name.test(child.name)) { return callback(child, i); } }); } return this.walk((child, i) => { if (child.type === 'atrule' && child.name === name) { return callback(child, i); } }); } walkComments(callback) { return this.walk((child, i) => { if (child.type === 'comment') { return callback(child, i); } }); } walkDecls(prop, callback) { if (!callback) { callback = prop; return this.walk((child, i) => { if (child.type === 'decl') { return callback(child, i); } }); } if (prop instanceof RegExp) { return this.walk((child, i) => { if (child.type === 'decl' && prop.test(child.prop)) { return callback(child, i); } }); } return this.walk((child, i) => { if (child.type === 'decl' && child.prop === prop) { return callback(child, i); } }); } walkRules(selector, callback) { if (!callback) { callback = selector; return this.walk((child, i) => { if (child.type === 'rule') { return callback(child, i); } }); } if (selector instanceof RegExp) { return this.walk((child, i) => { if (child.type === 'rule' && selector.test(child.selector)) { return callback(child, i); } }); } return this.walk((child, i) => { if (child.type === 'rule' && child.selector === selector) { return callback(child, i); } }); } get first() { if (!this.proxyOf.nodes) return undefined; return this.proxyOf.nodes[0]; } get last() { if (!this.proxyOf.nodes) return undefined; return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]; } } Container.registerParse = dependant => { parse = dependant; }; Container.registerRule = dependant => { Rule = dependant; }; Container.registerAtRule = dependant => { AtRule = dependant; }; Container.registerRoot = dependant => { Root = dependant; }; module.exports = Container; Container.default = Container; /* c8 ignore start */ Container.rebuild = node => { if (node.type === 'atrule') { Object.setPrototypeOf(node, AtRule.prototype); } else if (node.type === 'rule') { Object.setPrototypeOf(node, Rule.prototype); } else if (node.type === 'decl') { Object.setPrototypeOf(node, Declaration.prototype); } else if (node.type === 'comment') { Object.setPrototypeOf(node, Comment.prototype); } else if (node.type === 'root') { Object.setPrototypeOf(node, Root.prototype); } node[my] = true; if (node.nodes) { node.nodes.forEach(child => { Container.rebuild(child); }); } }; /* c8 ignore stop */ }, { './comment': 36, './declaration': 39, './node': 47, './symbols': 58 }, ], 38: [ function (require, module, exports) { 'use strict'; let pico = require('picocolors'); let terminalHighlight = require('./terminal-highlight'); class CssSyntaxError extends Error { constructor(message, line, column, source, file, plugin) { super(message); this.name = 'CssSyntaxError'; this.reason = message; if (file) { this.file = file; } if (source) { this.source = source; } if (plugin) { this.plugin = plugin; } if (typeof line !== 'undefined' && typeof column !== 'undefined') { if (typeof line === 'number') { this.line = line; this.column = column; } else { this.line = line.line; this.column = line.column; this.endLine = column.line; this.endColumn = column.column; } } this.setMessage(); if (Error.captureStackTrace) { Error.captureStackTrace(this, CssSyntaxError); } } setMessage() { this.message = this.plugin ? this.plugin + ': ' : ''; this.message += this.file ? this.file : ''; if (typeof this.line !== 'undefined') { this.message += ':' + this.line + ':' + this.column; } this.message += ': ' + this.reason; } showSourceCode(color) { if (!this.source) return ''; let css = this.source; if (color == null) color = pico.isColorSupported; if (terminalHighlight) { if (color) css = terminalHighlight(css); } let lines = css.split(/\r?\n/); let start = Math.max(this.line - 3, 0); let end = Math.min(this.line + 2, lines.length); let maxWidth = String(end).length; let mark, aside; if (color) { let { bold, gray, red } = pico.createColors(true); mark = text => bold(red(text)); aside = text => gray(text); } else { mark = aside = str => str; } return lines .slice(start, end) .map((line, index) => { let number = start + 1 + index; let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '; if (number === this.line) { let spacing = aside(gutter.replace(/\d/g, ' ')) + line.slice(0, this.column - 1).replace(/[^\t]/g, ' '); return ( mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^') ); } return ' ' + aside(gutter) + line; }) .join('\n'); } toString() { let code = this.showSourceCode(); if (code) { code = '\n\n' + code + '\n'; } return this.name + ': ' + this.message + code; } } module.exports = CssSyntaxError; CssSyntaxError.default = CssSyntaxError; }, { './terminal-highlight': 2, 'picocolors': 34 }, ], 39: [ function (require, module, exports) { 'use strict'; let Node = require('./node'); class Declaration extends Node { constructor(defaults) { if ( defaults && typeof defaults.value !== 'undefined' && typeof defaults.value !== 'string' ) { defaults = { ...defaults, value: String(defaults.value) }; } super(defaults); this.type = 'decl'; } get variable() { return this.prop.startsWith('--') || this.prop[0] === '$'; } } module.exports = Declaration; Declaration.default = Declaration; }, { './node': 47 }, ], 40: [ function (require, module, exports) { 'use strict'; let Container = require('./container'); let LazyResult, Processor; class Document extends Container { constructor(defaults) { // type needs to be passed to super, otherwise child roots won't be normalized correctly super({ type: 'document', ...defaults }); if (!this.nodes) { this.nodes = []; } } toResult(opts = {}) { let lazy = new LazyResult(new Processor(), this, opts); return lazy.stringify(); } } Document.registerLazyResult = dependant => { LazyResult = dependant; }; Document.registerProcessor = dependant => { Processor = dependant; }; module.exports = Document; Document.default = Document; }, { './container': 37 }, ], 41: [ function (require, module, exports) { 'use strict'; let Declaration = require('./declaration'); let PreviousMap = require('./previous-map'); let Comment = require('./comment'); let AtRule = require('./at-rule'); let Input = require('./input'); let Root = require('./root'); let Rule = require('./rule'); function fromJSON(json, inputs) { if (Array.isArray(json)) return json.map(n => fromJSON(n)); let { inputs: ownInputs, ...defaults } = json; if (ownInputs) { inputs = []; for (let input of ownInputs) { let inputHydrated = { ...input, __proto__: Input.prototype }; if (inputHydrated.map) { inputHydrated.map = { ...inputHydrated.map, __proto__: PreviousMap.prototype, }; } inputs.push(inputHydrated); } } if (defaults.nodes) { defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)); } if (defaults.source) { let { inputId, ...source } = defaults.source; defaults.source = source; if (inputId != null) { defaults.source.input = inputs[inputId]; } } if (defaults.type === 'root') { return new Root(defaults); } else if (defaults.type === 'decl') { return new Declaration(defaults); } else if (defaults.type === 'rule') { return new Rule(defaults); } else if (defaults.type === 'comment') { return new Comment(defaults); } else if (defaults.type === 'atrule') { return new AtRule(defaults); } else { throw new Error('Unknown node type: ' + json.type); } } module.exports = fromJSON; fromJSON.default = fromJSON; }, { './at-rule': 35, './comment': 36, './declaration': 39, './input': 42, './previous-map': 51, './root': 54, './rule': 55, }, ], 42: [ function (require, module, exports) { 'use strict'; let { SourceMapConsumer, SourceMapGenerator, } = require('source-map-js'); let { fileURLToPath, pathToFileURL } = require('url'); let { isAbsolute, resolve } = require('path'); let { nanoid } = require('nanoid/non-secure'); let terminalHighlight = require('./terminal-highlight'); let CssSyntaxError = require('./css-syntax-error'); let PreviousMap = require('./previous-map'); let fromOffsetCache = Symbol('fromOffsetCache'); let sourceMapAvailable = Boolean( SourceMapConsumer && SourceMapGenerator, ); let pathAvailable = Boolean(resolve && isAbsolute); class Input { constructor(css, opts = {}) { if ( css === null || typeof css === 'undefined' || (typeof css === 'object' && !css.toString) ) { throw new Error(`PostCSS received ${css} instead of CSS string`); } this.css = css.toString(); if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { this.hasBOM = true; this.css = this.css.slice(1); } else { this.hasBOM = false; } if (opts.from) { if ( !pathAvailable || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from) ) { this.file = opts.from; } else { this.file = resolve(opts.from); } } if (pathAvailable && sourceMapAvailable) { let map = new PreviousMap(this.css, opts); if (map.text) { this.map = map; let file = map.consumer().file; if (!this.file && file) this.file = this.mapResolve(file); } } if (!this.file) { this.id = ''; } if (this.map) this.map.file = this.from; } error(message, line, column, opts = {}) { let result, endLine, endColumn; if (line && typeof line === 'object') { let start = line; let end = column; if (typeof start.offset === 'number') { let pos = this.fromOffset(start.offset); line = pos.line; column = pos.col; } else { line = start.line; column = start.column; } if (typeof end.offset === 'number') { let pos = this.fromOffset(end.offset); endLine = pos.line; endColumn = pos.col; } else { endLine = end.line; endColumn = end.column; } } else if (!column) { let pos = this.fromOffset(line); line = pos.line; column = pos.col; } let origin = this.origin(line, column, endLine, endColumn); if (origin) { result = new CssSyntaxError( message, origin.endLine === undefined ? origin.line : { column: origin.column, line: origin.line }, origin.endLine === undefined ? origin.column : { column: origin.endColumn, line: origin.endLine }, origin.source, origin.file, opts.plugin, ); } else { result = new CssSyntaxError( message, endLine === undefined ? line : { column, line }, endLine === undefined ? column : { column: endColumn, line: endLine }, this.css, this.file, opts.plugin, ); } result.input = { column, endColumn, endLine, line, source: this.css, }; if (this.file) { if (pathToFileURL) { result.input.url = pathToFileURL(this.file).toString(); } result.input.file = this.file; } return result; } fromOffset(offset) { let lastLine, lineToIndex; if (!this[fromOffsetCache]) { let lines = this.css.split('\n'); lineToIndex = new Array(lines.length); let prevIndex = 0; for (let i = 0, l = lines.length; i < l; i++) { lineToIndex[i] = prevIndex; prevIndex += lines[i].length + 1; } this[fromOffsetCache] = lineToIndex; } else { lineToIndex = this[fromOffsetCache]; } lastLine = lineToIndex[lineToIndex.length - 1]; let min = 0; if (offset >= lastLine) { min = lineToIndex.length - 1; } else { let max = lineToIndex.length - 2; let mid; while (min < max) { mid = min + ((max - min) >> 1); if (offset < lineToIndex[mid]) { max = mid - 1; } else if (offset >= lineToIndex[mid + 1]) { min = mid + 1; } else { min = mid; break; } } } return { col: offset - lineToIndex[min] + 1, line: min + 1, }; } mapResolve(file) { if (/^\w+:\/\//.test(file)) { return file; } return resolve( this.map.consumer().sourceRoot || this.map.root || '.', file, ); } origin(line, column, endLine, endColumn) { if (!this.map) return false; let consumer = this.map.consumer(); let from = consumer.originalPositionFor({ column, line }); if (!from.source) return false; let to; if (typeof endLine === 'number') { to = consumer.originalPositionFor({ column: endColumn, line: endLine, }); } let fromUrl; if (isAbsolute(from.source)) { fromUrl = pathToFileURL(from.source); } else { fromUrl = new URL( from.source, this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile), ); } let result = { column: from.column, endColumn: to && to.column, endLine: to && to.line, line: from.line, url: fromUrl.toString(), }; if (fromUrl.protocol === 'file:') { if (fileURLToPath) { result.file = fileURLToPath(fromUrl); } else { /* c8 ignore next 2 */ throw new Error( `file: protocol is not available in this PostCSS build`, ); } } let source = consumer.sourceContentFor(from.source); if (source) result.source = source; return result; } toJSON() { let json = {}; for (let name of ['hasBOM', 'css', 'file', 'id']) { if (this[name] != null) { json[name] = this[name]; } } if (this.map) { json.map = { ...this.map }; if (json.map.consumerCache) { json.map.consumerCache = undefined; } } return json; } get from() { return this.file || this.id; } } module.exports = Input; Input.default = Input; if (terminalHighlight && terminalHighlight.registerInput) { terminalHighlight.registerInput(Input); } }, { './css-syntax-error': 38, './previous-map': 51, './terminal-highlight': 2, 'nanoid/non-secure': 32, 'path': 2, 'source-map-js': 2, 'url': 2, }, ], 43: [ function (require, module, exports) { (function (process) { (function () { 'use strict'; let { isClean, my } = require('./symbols'); let MapGenerator = require('./map-generator'); let stringify = require('./stringify'); let Container = require('./container'); let Document = require('./document'); let warnOnce = require('./warn-once'); let Result = require('./result'); let parse = require('./parse'); let Root = require('./root'); const TYPE_TO_CLASS_NAME = { atrule: 'AtRule', comment: 'Comment', decl: 'Declaration', document: 'Document', root: 'Root', rule: 'Rule', }; const PLUGIN_PROPS = { AtRule: true, AtRuleExit: true, Comment: true, CommentExit: true, Declaration: true, DeclarationExit: true, Document: true, DocumentExit: true, Once: true, OnceExit: true, postcssPlugin: true, prepare: true, Root: true, RootExit: true, Rule: true, RuleExit: true, }; const NOT_VISITORS = { Once: true, postcssPlugin: true, prepare: true, }; const CHILDREN = 0; function isPromise(obj) { return typeof obj === 'object' && typeof obj.then === 'function'; } function getEvents(node) { let key = false; let type = TYPE_TO_CLASS_NAME[node.type]; if (node.type === 'decl') { key = node.prop.toLowerCase(); } else if (node.type === 'atrule') { key = node.name.toLowerCase(); } if (key && node.append) { return [ type, type + '-' + key, CHILDREN, type + 'Exit', type + 'Exit-' + key, ]; } else if (key) { return [ type, type + '-' + key, type + 'Exit', type + 'Exit-' + key, ]; } else if (node.append) { return [type, CHILDREN, type + 'Exit']; } else { return [type, type + 'Exit']; } } function toStack(node) { let events; if (node.type === 'document') { events = ['Document', CHILDREN, 'DocumentExit']; } else if (node.type === 'root') { events = ['Root', CHILDREN, 'RootExit']; } else { events = getEvents(node); } return { eventIndex: 0, events, iterator: 0, node, visitorIndex: 0, visitors: [], }; } function cleanMarks(node) { node[isClean] = false; if (node.nodes) node.nodes.forEach(i => cleanMarks(i)); return node; } let postcss = {}; class LazyResult { constructor(processor, css, opts) { this.stringified = false; this.processed = false; let root; if ( typeof css === 'object' && css !== null && (css.type === 'root' || css.type === 'document') ) { root = cleanMarks(css); } else if (css instanceof LazyResult || css instanceof Result) { root = cleanMarks(css.root); if (css.map) { if (typeof opts.map === 'undefined') opts.map = {}; if (!opts.map.inline) opts.map.inline = false; opts.map.prev = css.map; } } else { let parser = parse; if (opts.syntax) parser = opts.syntax.parse; if (opts.parser) parser = opts.parser; if (parser.parse) parser = parser.parse; try { root = parser(css, opts); } catch (error) { this.processed = true; this.error = error; } if (root && !root[my]) { /* c8 ignore next 2 */ Container.rebuild(root); } } this.result = new Result(processor, root, opts); this.helpers = { ...postcss, postcss, result: this.result }; this.plugins = this.processor.plugins.map(plugin => { if (typeof plugin === 'object' && plugin.prepare) { return { ...plugin, ...plugin.prepare(this.result) }; } else { return plugin; } }); } async() { if (this.error) return Promise.reject(this.error); if (this.processed) return Promise.resolve(this.result); if (!this.processing) { this.processing = this.runAsync(); } return this.processing; } catch(onRejected) { return this.async().catch(onRejected); } finally(onFinally) { return this.async().then(onFinally, onFinally); } getAsyncError() { throw new Error( 'Use process(css).then(cb) to work with async plugins', ); } handleError(error, node) { let plugin = this.result.lastPlugin; try { if (node) node.addToError(error); this.error = error; if (error.name === 'CssSyntaxError' && !error.plugin) { error.plugin = plugin.postcssPlugin; error.setMessage(); } else if (plugin.postcssVersion) { if (process.env.NODE_ENV !== 'production') { let pluginName = plugin.postcssPlugin; let pluginVer = plugin.postcssVersion; let runtimeVer = this.result.processor.version; let a = pluginVer.split('.'); let b = runtimeVer.split('.'); if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { // eslint-disable-next-line no-console console.error( 'Unknown error from PostCSS plugin. Your current PostCSS ' + 'version is ' + runtimeVer + ', but ' + pluginName + ' uses ' + pluginVer + '. Perhaps this is the source of the error below.', ); } } } } catch (err) { /* c8 ignore next 3 */ // eslint-disable-next-line no-console if (console && console.error) console.error(err); } return error; } prepareVisitors() { this.listeners = {}; let add = (plugin, type, cb) => { if (!this.listeners[type]) this.listeners[type] = []; this.listeners[type].push([plugin, cb]); }; for (let plugin of this.plugins) { if (typeof plugin === 'object') { for (let event in plugin) { if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { throw new Error( `Unknown event ${event} in ${plugin.postcssPlugin}. ` + `Try to update PostCSS (${this.processor.version} now).`, ); } if (!NOT_VISITORS[event]) { if (typeof plugin[event] === 'object') { for (let filter in plugin[event]) { if (filter === '*') { add(plugin, event, plugin[event][filter]); } else { add( plugin, event + '-' + filter.toLowerCase(), plugin[event][filter], ); } } } else if (typeof plugin[event] === 'function') { add(plugin, event, plugin[event]); } } } } } this.hasListener = Object.keys(this.listeners).length > 0; } async runAsync() { this.plugin = 0; for (let i = 0; i < this.plugins.length; i++) { let plugin = this.plugins[i]; let promise = this.runOnRoot(plugin); if (isPromise(promise)) { try { await promise; } catch (error) { throw this.handleError(error); } } } this.prepareVisitors(); if (this.hasListener) { let root = this.result.root; while (!root[isClean]) { root[isClean] = true; let stack = [toStack(root)]; while (stack.length > 0) { let promise = this.visitTick(stack); if (isPromise(promise)) { try { await promise; } catch (e) { let node = stack[stack.length - 1].node; throw this.handleError(e, node); } } } } if (this.listeners.OnceExit) { for (let [plugin, visitor] of this.listeners.OnceExit) { this.result.lastPlugin = plugin; try { if (root.type === 'document') { let roots = root.nodes.map(subRoot => visitor(subRoot, this.helpers), ); await Promise.all(roots); } else { await visitor(root, this.helpers); } } catch (e) { throw this.handleError(e); } } } } this.processed = true; return this.stringify(); } runOnRoot(plugin) { this.result.lastPlugin = plugin; try { if (typeof plugin === 'object' && plugin.Once) { if (this.result.root.type === 'document') { let roots = this.result.root.nodes.map(root => plugin.Once(root, this.helpers), ); if (isPromise(roots[0])) { return Promise.all(roots); } return roots; } return plugin.Once(this.result.root, this.helpers); } else if (typeof plugin === 'function') { return plugin(this.result.root, this.result); } } catch (error) { throw this.handleError(error); } } stringify() { if (this.error) throw this.error; if (this.stringified) return this.result; this.stringified = true; this.sync(); let opts = this.result.opts; let str = stringify; if (opts.syntax) str = opts.syntax.stringify; if (opts.stringifier) str = opts.stringifier; if (str.stringify) str = str.stringify; let map = new MapGenerator( str, this.result.root, this.result.opts, ); let data = map.generate(); this.result.css = data[0]; this.result.map = data[1]; return this.result; } sync() { if (this.error) throw this.error; if (this.processed) return this.result; this.processed = true; if (this.processing) { throw this.getAsyncError(); } for (let plugin of this.plugins) { let promise = this.runOnRoot(plugin); if (isPromise(promise)) { throw this.getAsyncError(); } } this.prepareVisitors(); if (this.hasListener) { let root = this.result.root; while (!root[isClean]) { root[isClean] = true; this.walkSync(root); } if (this.listeners.OnceExit) { if (root.type === 'document') { for (let subRoot of root.nodes) { this.visitSync(this.listeners.OnceExit, subRoot); } } else { this.visitSync(this.listeners.OnceExit, root); } } } return this.result; } then(onFulfilled, onRejected) { if (process.env.NODE_ENV !== 'production') { if (!('from' in this.opts)) { warnOnce( 'Without `from` option PostCSS could generate wrong source map ' + 'and will not find Browserslist config. Set it to CSS file path ' + 'or to `undefined` to prevent this warning.', ); } } return this.async().then(onFulfilled, onRejected); } toString() { return this.css; } visitSync(visitors, node) { for (let [plugin, visitor] of visitors) { this.result.lastPlugin = plugin; let promise; try { promise = visitor(node, this.helpers); } catch (e) { throw this.handleError(e, node.proxyOf); } if ( node.type !== 'root' && node.type !== 'document' && !node.parent ) { return true; } if (isPromise(promise)) { throw this.getAsyncError(); } } } visitTick(stack) { let visit = stack[stack.length - 1]; let { node, visitors } = visit; if ( node.type !== 'root' && node.type !== 'document' && !node.parent ) { stack.pop(); return; } if ( visitors.length > 0 && visit.visitorIndex < visitors.length ) { let [plugin, visitor] = visitors[visit.visitorIndex]; visit.visitorIndex += 1; if (visit.visitorIndex === visitors.length) { visit.visitors = []; visit.visitorIndex = 0; } this.result.lastPlugin = plugin; try { return visitor(node.toProxy(), this.helpers); } catch (e) { throw this.handleError(e, node); } } if (visit.iterator !== 0) { let iterator = visit.iterator; let child; while ((child = node.nodes[node.indexes[iterator]])) { node.indexes[iterator] += 1; if (!child[isClean]) { child[isClean] = true; stack.push(toStack(child)); return; } } visit.iterator = 0; delete node.indexes[iterator]; } let events = visit.events; while (visit.eventIndex < events.length) { let event = events[visit.eventIndex]; visit.eventIndex += 1; if (event === CHILDREN) { if (node.nodes && node.nodes.length) { node[isClean] = true; visit.iterator = node.getIterator(); } return; } else if (this.listeners[event]) { visit.visitors = this.listeners[event]; return; } } stack.pop(); } walkSync(node) { node[isClean] = true; let events = getEvents(node); for (let event of events) { if (event === CHILDREN) { if (node.nodes) { node.each(child => { if (!child[isClean]) this.walkSync(child); }); } } else { let visitors = this.listeners[event]; if (visitors) { if (this.visitSync(visitors, node.toProxy())) return; } } } } warnings() { return this.sync().warnings(); } get content() { return this.stringify().content; } get css() { return this.stringify().css; } get map() { return this.stringify().map; } get messages() { return this.sync().messages; } get opts() { return this.result.opts; } get processor() { return this.result.processor; } get root() { return this.sync().root; } get [Symbol.toStringTag]() { return 'LazyResult'; } } LazyResult.registerPostcss = dependant => { postcss = dependant; }; module.exports = LazyResult; LazyResult.default = LazyResult; Root.registerLazyResult(LazyResult); Document.registerLazyResult(LazyResult); }).call(this); }).call(this, require('_process')); }, { './container': 37, './document': 40, './map-generator': 45, './parse': 48, './result': 53, './root': 54, './stringify': 57, './symbols': 58, './warn-once': 60, '_process': 62, }, ], 44: [ function (require, module, exports) { 'use strict'; let list = { comma(string) { return list.split(string, [','], true); }, space(string) { let spaces = [' ', '\n', '\t']; return list.split(string, spaces); }, split(string, separators, last) { let array = []; let current = ''; let split = false; let func = 0; let inQuote = false; let prevQuote = ''; let escape = false; for (let letter of string) { if (escape) { escape = false; } else if (letter === '\\') { escape = true; } else if (inQuote) { if (letter === prevQuote) { inQuote = false; } } else if (letter === '"' || letter === "'") { inQuote = true; prevQuote = letter; } else if (letter === '(') { func += 1; } else if (letter === ')') { if (func > 0) func -= 1; } else if (func === 0) { if (separators.includes(letter)) split = true; } if (split) { if (current !== '') array.push(current.trim()); current = ''; split = false; } else { current += letter; } } if (last || current !== '') array.push(current.trim()); return array; }, }; module.exports = list; list.default = list; }, {}, ], 45: [ function (require, module, exports) { (function (Buffer) { (function () { 'use strict'; let { SourceMapConsumer, SourceMapGenerator, } = require('source-map-js'); let { dirname, relative, resolve, sep } = require('path'); let { pathToFileURL } = require('url'); let Input = require('./input'); let sourceMapAvailable = Boolean( SourceMapConsumer && SourceMapGenerator, ); let pathAvailable = Boolean(dirname && resolve && relative && sep); class MapGenerator { constructor(stringify, root, opts, cssString) { this.stringify = stringify; this.mapOpts = opts.map || {}; this.root = root; this.opts = opts; this.css = cssString; this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute; this.memoizedFileURLs = new Map(); this.memoizedPaths = new Map(); this.memoizedURLs = new Map(); } addAnnotation() { let content; if (this.isInline()) { content = 'data:application/json;base64,' + this.toBase64(this.map.toString()); } else if (typeof this.mapOpts.annotation === 'string') { content = this.mapOpts.annotation; } else if (typeof this.mapOpts.annotation === 'function') { content = this.mapOpts.annotation(this.opts.to, this.root); } else { content = this.outputFile() + '.map'; } let eol = '\n'; if (this.css.includes('\r\n')) eol = '\r\n'; this.css += eol + '/*# sourceMappingURL=' + content + ' */'; } applyPrevMaps() { for (let prev of this.previous()) { let from = this.toUrl(this.path(prev.file)); let root = prev.root || dirname(prev.file); let map; if (this.mapOpts.sourcesContent === false) { map = new SourceMapConsumer(prev.text); if (map.sourcesContent) { map.sourcesContent = map.sourcesContent.map(() => null); } } else { map = prev.consumer(); } this.map.applySourceMap( map, from, this.toUrl(this.path(root)), ); } } clearAnnotation() { if (this.mapOpts.annotation === false) return; if (this.root) { let node; for (let i = this.root.nodes.length - 1; i >= 0; i--) { node = this.root.nodes[i]; if (node.type !== 'comment') continue; if (node.text.indexOf('# sourceMappingURL=') === 0) { this.root.removeChild(i); } } } else if (this.css) { this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, ''); } } generate() { this.clearAnnotation(); if (pathAvailable && sourceMapAvailable && this.isMap()) { return this.generateMap(); } else { let result = ''; this.stringify(this.root, i => { result += i; }); return [result]; } } generateMap() { if (this.root) { this.generateString(); } else if (this.previous().length === 1) { let prev = this.previous()[0].consumer(); prev.file = this.outputFile(); this.map = SourceMapGenerator.fromSourceMap(prev); } else { this.map = new SourceMapGenerator({ file: this.outputFile(), }); this.map.addMapping({ generated: { column: 0, line: 1 }, original: { column: 0, line: 1 }, source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : '', }); } if (this.isSourcesContent()) this.setSourcesContent(); if (this.root && this.previous().length > 0) this.applyPrevMaps(); if (this.isAnnotation()) this.addAnnotation(); if (this.isInline()) { return [this.css]; } else { return [this.css, this.map]; } } generateString() { this.css = ''; this.map = new SourceMapGenerator({ file: this.outputFile() }); let line = 1; let column = 1; let noSource = ''; let mapping = { generated: { column: 0, line: 0 }, original: { column: 0, line: 0 }, source: '', }; let lines, last; this.stringify(this.root, (str, node, type) => { this.css += str; if (node && type !== 'end') { mapping.generated.line = line; mapping.generated.column = column - 1; if (node.source && node.source.start) { mapping.source = this.sourcePath(node); mapping.original.line = node.source.start.line; mapping.original.column = node.source.start.column - 1; this.map.addMapping(mapping); } else { mapping.source = noSource; mapping.original.line = 1; mapping.original.column = 0; this.map.addMapping(mapping); } } lines = str.match(/\n/g); if (lines) { line += lines.length; last = str.lastIndexOf('\n'); column = str.length - last; } else { column += str.length; } if (node && type !== 'start') { let p = node.parent || { raws: {} }; let childless = node.type === 'decl' || (node.type === 'atrule' && !node.nodes); if (!childless || node !== p.last || p.raws.semicolon) { if (node.source && node.source.end) { mapping.source = this.sourcePath(node); mapping.original.line = node.source.end.line; mapping.original.column = node.source.end.column - 1; mapping.generated.line = line; mapping.generated.column = column - 2; this.map.addMapping(mapping); } else { mapping.source = noSource; mapping.original.line = 1; mapping.original.column = 0; mapping.generated.line = line; mapping.generated.column = column - 1; this.map.addMapping(mapping); } } } }); } isAnnotation() { if (this.isInline()) { return true; } if (typeof this.mapOpts.annotation !== 'undefined') { return this.mapOpts.annotation; } if (this.previous().length) { return this.previous().some(i => i.annotation); } return true; } isInline() { if (typeof this.mapOpts.inline !== 'undefined') { return this.mapOpts.inline; } let annotation = this.mapOpts.annotation; if (typeof annotation !== 'undefined' && annotation !== true) { return false; } if (this.previous().length) { return this.previous().some(i => i.inline); } return true; } isMap() { if (typeof this.opts.map !== 'undefined') { return !!this.opts.map; } return this.previous().length > 0; } isSourcesContent() { if (typeof this.mapOpts.sourcesContent !== 'undefined') { return this.mapOpts.sourcesContent; } if (this.previous().length) { return this.previous().some(i => i.withContent()); } return true; } outputFile() { if (this.opts.to) { return this.path(this.opts.to); } else if (this.opts.from) { return this.path(this.opts.from); } else { return 'to.css'; } } path(file) { if (this.mapOpts.absolute) return file; if (file.charCodeAt(0) === 60 /* `<` */) return file; if (/^\w+:\/\//.test(file)) return file; let cached = this.memoizedPaths.get(file); if (cached) return cached; let from = this.opts.to ? dirname(this.opts.to) : '.'; if (typeof this.mapOpts.annotation === 'string') { from = dirname(resolve(from, this.mapOpts.annotation)); } let path = relative(from, file); this.memoizedPaths.set(file, path); return path; } previous() { if (!this.previousMaps) { this.previousMaps = []; if (this.root) { this.root.walk(node => { if (node.source && node.source.input.map) { let map = node.source.input.map; if (!this.previousMaps.includes(map)) { this.previousMaps.push(map); } } }); } else { let input = new Input(this.css, this.opts); if (input.map) this.previousMaps.push(input.map); } } return this.previousMaps; } setSourcesContent() { let already = {}; if (this.root) { this.root.walk(node => { if (node.source) { let from = node.source.input.from; if (from && !already[from]) { already[from] = true; let fromUrl = this.usesFileUrls ? this.toFileUrl(from) : this.toUrl(this.path(from)); this.map.setSourceContent( fromUrl, node.source.input.css, ); } } }); } else if (this.css) { let from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : ''; this.map.setSourceContent(from, this.css); } } sourcePath(node) { if (this.mapOpts.from) { return this.toUrl(this.mapOpts.from); } else if (this.usesFileUrls) { return this.toFileUrl(node.source.input.from); } else { return this.toUrl(this.path(node.source.input.from)); } } toBase64(str) { if (Buffer) { return Buffer.from(str).toString('base64'); } else { return window.btoa(unescape(encodeURIComponent(str))); } } toFileUrl(path) { let cached = this.memoizedFileURLs.get(path); if (cached) return cached; if (pathToFileURL) { let fileURL = pathToFileURL(path).toString(); this.memoizedFileURLs.set(path, fileURL); return fileURL; } else { throw new Error( '`map.absolute` option is not available in this PostCSS build', ); } } toUrl(path) { let cached = this.memoizedURLs.get(path); if (cached) return cached; if (sep === '\\') { path = path.replace(/\\/g, '/'); } let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent); this.memoizedURLs.set(path, url); return url; } } module.exports = MapGenerator; }).call(this); }).call(this, require('buffer').Buffer); }, { './input': 42, 'buffer': 3, 'path': 2, 'source-map-js': 2, 'url': 2 }, ], 46: [ function (require, module, exports) { (function (process) { (function () { 'use strict'; let MapGenerator = require('./map-generator'); let stringify = require('./stringify'); let warnOnce = require('./warn-once'); let parse = require('./parse'); const Result = require('./result'); class NoWorkResult { constructor(processor, css, opts) { css = css.toString(); this.stringified = false; this._processor = processor; this._css = css; this._opts = opts; this._map = undefined; let root; let str = stringify; this.result = new Result(this._processor, root, this._opts); this.result.css = css; let self = this; Object.defineProperty(this.result, 'root', { get() { return self.root; }, }); let map = new MapGenerator(str, root, this._opts, css); if (map.isMap()) { let [generatedCSS, generatedMap] = map.generate(); if (generatedCSS) { this.result.css = generatedCSS; } if (generatedMap) { this.result.map = generatedMap; } } } async() { if (this.error) return Promise.reject(this.error); return Promise.resolve(this.result); } catch(onRejected) { return this.async().catch(onRejected); } finally(onFinally) { return this.async().then(onFinally, onFinally); } sync() { if (this.error) throw this.error; return this.result; } then(onFulfilled, onRejected) { if (process.env.NODE_ENV !== 'production') { if (!('from' in this._opts)) { warnOnce( 'Without `from` option PostCSS could generate wrong source map ' + 'and will not find Browserslist config. Set it to CSS file path ' + 'or to `undefined` to prevent this warning.', ); } } return this.async().then(onFulfilled, onRejected); } toString() { return this._css; } warnings() { return []; } get content() { return this.result.css; } get css() { return this.result.css; } get map() { return this.result.map; } get messages() { return []; } get opts() { return this.result.opts; } get processor() { return this.result.processor; } get root() { if (this._root) { return this._root; } let root; let parser = parse; try { root = parser(this._css, this._opts); } catch (error) { this.error = error; } if (this.error) { throw this.error; } else { this._root = root; return root; } } get [Symbol.toStringTag]() { return 'NoWorkResult'; } } module.exports = NoWorkResult; NoWorkResult.default = NoWorkResult; }).call(this); }).call(this, require('_process')); }, { './map-generator': 45, './parse': 48, './result': 53, './stringify': 57, './warn-once': 60, '_process': 62, }, ], 47: [ function (require, module, exports) { 'use strict'; let { isClean, my } = require('./symbols'); let CssSyntaxError = require('./css-syntax-error'); let Stringifier = require('./stringifier'); let stringify = require('./stringify'); function cloneNode(obj, parent) { let cloned = new obj.constructor(); for (let i in obj) { if (!Object.prototype.hasOwnProperty.call(obj, i)) { /* c8 ignore next 2 */ continue; } if (i === 'proxyCache') continue; let value = obj[i]; let type = typeof value; if (i === 'parent' && type === 'object') { if (parent) cloned[i] = parent; } else if (i === 'source') { cloned[i] = value; } else if (Array.isArray(value)) { cloned[i] = value.map(j => cloneNode(j, cloned)); } else { if (type === 'object' && value !== null) value = cloneNode(value); cloned[i] = value; } } return cloned; } class Node { constructor(defaults = {}) { this.raws = {}; this[isClean] = false; this[my] = true; for (let name in defaults) { if (name === 'nodes') { this.nodes = []; for (let node of defaults[name]) { if (typeof node.clone === 'function') { this.append(node.clone()); } else { this.append(node); } } } else { this[name] = defaults[name]; } } } addToError(error) { error.postcssNode = this; if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { let s = this.source; error.stack = error.stack.replace( /\n\s{4}at /, `$&${s.input.from}:${s.start.line}:${s.start.column}$&`, ); } return error; } after(add) { this.parent.insertAfter(this, add); return this; } assign(overrides = {}) { for (let name in overrides) { this[name] = overrides[name]; } return this; } before(add) { this.parent.insertBefore(this, add); return this; } cleanRaws(keepBetween) { delete this.raws.before; delete this.raws.after; if (!keepBetween) delete this.raws.between; } clone(overrides = {}) { let cloned = cloneNode(this); for (let name in overrides) { cloned[name] = overrides[name]; } return cloned; } cloneAfter(overrides = {}) { let cloned = this.clone(overrides); this.parent.insertAfter(this, cloned); return cloned; } cloneBefore(overrides = {}) { let cloned = this.clone(overrides); this.parent.insertBefore(this, cloned); return cloned; } error(message, opts = {}) { if (this.source) { let { end, start } = this.rangeBy(opts); return this.source.input.error( message, { column: start.column, line: start.line }, { column: end.column, line: end.line }, opts, ); } return new CssSyntaxError(message); } getProxyProcessor() { return { get(node, prop) { if (prop === 'proxyOf') { return node; } else if (prop === 'root') { return () => node.root().toProxy(); } else { return node[prop]; } }, set(node, prop, value) { if (node[prop] === value) return true; node[prop] = value; if ( prop === 'prop' || prop === 'value' || prop === 'name' || prop === 'params' || prop === 'important' || /* c8 ignore next */ prop === 'text' ) { node.markDirty(); } return true; }, }; } markDirty() { if (this[isClean]) { this[isClean] = false; let next = this; while ((next = next.parent)) { next[isClean] = false; } } } next() { if (!this.parent) return undefined; let index = this.parent.index(this); return this.parent.nodes[index + 1]; } positionBy(opts, stringRepresentation) { let pos = this.source.start; if (opts.index) { pos = this.positionInside(opts.index, stringRepresentation); } else if (opts.word) { stringRepresentation = this.toString(); let index = stringRepresentation.indexOf(opts.word); if (index !== -1) pos = this.positionInside(index, stringRepresentation); } return pos; } positionInside(index, stringRepresentation) { let string = stringRepresentation || this.toString(); let column = this.source.start.column; let line = this.source.start.line; for (let i = 0; i < index; i++) { if (string[i] === '\n') { column = 1; line += 1; } else { column += 1; } } return { column, line }; } prev() { if (!this.parent) return undefined; let index = this.parent.index(this); return this.parent.nodes[index - 1]; } rangeBy(opts) { let start = { column: this.source.start.column, line: this.source.start.line, }; let end = this.source.end ? { column: this.source.end.column + 1, line: this.source.end.line, } : { column: start.column + 1, line: start.line, }; if (opts.word) { let stringRepresentation = this.toString(); let index = stringRepresentation.indexOf(opts.word); if (index !== -1) { start = this.positionInside(index, stringRepresentation); end = this.positionInside( index + opts.word.length, stringRepresentation, ); } } else { if (opts.start) { start = { column: opts.start.column, line: opts.start.line, }; } else if (opts.index) { start = this.positionInside(opts.index); } if (opts.end) { end = { column: opts.end.column, line: opts.end.line, }; } else if (opts.endIndex) { end = this.positionInside(opts.endIndex); } else if (opts.index) { end = this.positionInside(opts.index + 1); } } if ( end.line < start.line || (end.line === start.line && end.column <= start.column) ) { end = { column: start.column + 1, line: start.line }; } return { end, start }; } raw(prop, defaultType) { let str = new Stringifier(); return str.raw(this, prop, defaultType); } remove() { if (this.parent) { this.parent.removeChild(this); } this.parent = undefined; return this; } replaceWith(...nodes) { if (this.parent) { let bookmark = this; let foundSelf = false; for (let node of nodes) { if (node === this) { foundSelf = true; } else if (foundSelf) { this.parent.insertAfter(bookmark, node); bookmark = node; } else { this.parent.insertBefore(bookmark, node); } } if (!foundSelf) { this.remove(); } } return this; } root() { let result = this; while (result.parent && result.parent.type !== 'document') { result = result.parent; } return result; } toJSON(_, inputs) { let fixed = {}; let emitInputs = inputs == null; inputs = inputs || new Map(); let inputsNextIndex = 0; for (let name in this) { if (!Object.prototype.hasOwnProperty.call(this, name)) { /* c8 ignore next 2 */ continue; } if (name === 'parent' || name === 'proxyCache') continue; let value = this[name]; if (Array.isArray(value)) { fixed[name] = value.map(i => { if (typeof i === 'object' && i.toJSON) { return i.toJSON(null, inputs); } else { return i; } }); } else if (typeof value === 'object' && value.toJSON) { fixed[name] = value.toJSON(null, inputs); } else if (name === 'source') { let inputId = inputs.get(value.input); if (inputId == null) { inputId = inputsNextIndex; inputs.set(value.input, inputsNextIndex); inputsNextIndex++; } fixed[name] = { end: value.end, inputId, start: value.start, }; } else { fixed[name] = value; } } if (emitInputs) { fixed.inputs = [...inputs.keys()].map(input => input.toJSON()); } return fixed; } toProxy() { if (!this.proxyCache) { this.proxyCache = new Proxy(this, this.getProxyProcessor()); } return this.proxyCache; } toString(stringifier = stringify) { if (stringifier.stringify) stringifier = stringifier.stringify; let result = ''; stringifier(this, i => { result += i; }); return result; } warn(result, text, opts) { let data = { node: this }; for (let i in opts) data[i] = opts[i]; return result.warn(text, data); } get proxyOf() { return this; } } module.exports = Node; Node.default = Node; }, { './css-syntax-error': 38, './stringifier': 56, './stringify': 57, './symbols': 58, }, ], 48: [ function (require, module, exports) { (function (process) { (function () { 'use strict'; let Container = require('./container'); let Parser = require('./parser'); let Input = require('./input'); function parse(css, opts) { let input = new Input(css, opts); let parser = new Parser(input); try { parser.parse(); } catch (e) { if (process.env.NODE_ENV !== 'production') { if (e.name === 'CssSyntaxError' && opts && opts.from) { if (/\.scss$/i.test(opts.from)) { e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser'; } else if (/\.sass/i.test(opts.from)) { e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser'; } else if (/\.less$/i.test(opts.from)) { e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser'; } } } throw e; } return parser.root; } module.exports = parse; parse.default = parse; Container.registerParse(parse); }).call(this); }).call(this, require('_process')); }, { './container': 37, './input': 42, './parser': 49, '_process': 62 }, ], 49: [ function (require, module, exports) { 'use strict'; let Declaration = require('./declaration'); let tokenizer = require('./tokenize'); let Comment = require('./comment'); let AtRule = require('./at-rule'); let Root = require('./root'); let Rule = require('./rule'); const SAFE_COMMENT_NEIGHBOR = { empty: true, space: true, }; function findLastWithPosition(tokens) { for (let i = tokens.length - 1; i >= 0; i--) { let token = tokens[i]; let pos = token[3] || token[2]; if (pos) return pos; } } class Parser { constructor(input) { this.input = input; this.root = new Root(); this.current = this.root; this.spaces = ''; this.semicolon = false; this.customProperty = false; this.createTokenizer(); this.root.source = { input, start: { column: 1, line: 1, offset: 0 }, }; } atrule(token) { let node = new AtRule(); node.name = token[1].slice(1); if (node.name === '') { this.unnamedAtrule(node, token); } this.init(node, token[2]); let type; let prev; let shift; let last = false; let open = false; let params = []; let brackets = []; while (!this.tokenizer.endOfFile()) { token = this.tokenizer.nextToken(); type = token[0]; if (type === '(' || type === '[') { brackets.push(type === '(' ? ')' : ']'); } else if (type === '{' && brackets.length > 0) { brackets.push('}'); } else if (type === brackets[brackets.length - 1]) { brackets.pop(); } if (brackets.length === 0) { if (type === ';') { node.source.end = this.getPosition(token[2]); node.source.end.offset++; this.semicolon = true; break; } else if (type === '{') { open = true; break; } else if (type === '}') { if (params.length > 0) { shift = params.length - 1; prev = params[shift]; while (prev && prev[0] === 'space') { prev = params[--shift]; } if (prev) { node.source.end = this.getPosition(prev[3] || prev[2]); node.source.end.offset++; } } this.end(token); break; } else { params.push(token); } } else { params.push(token); } if (this.tokenizer.endOfFile()) { last = true; break; } } node.raws.between = this.spacesAndCommentsFromEnd(params); if (params.length) { node.raws.afterName = this.spacesAndCommentsFromStart(params); this.raw(node, 'params', params); if (last) { token = params[params.length - 1]; node.source.end = this.getPosition(token[3] || token[2]); node.source.end.offset++; this.spaces = node.raws.between; node.raws.between = ''; } } else { node.raws.afterName = ''; node.params = ''; } if (open) { node.nodes = []; this.current = node; } } checkMissedSemicolon(tokens) { let colon = this.colon(tokens); if (colon === false) return; let founded = 0; let token; for (let j = colon - 1; j >= 0; j--) { token = tokens[j]; if (token[0] !== 'space') { founded += 1; if (founded === 2) break; } } // If the token is a word, e.g. `!important`, `red` or any other valid property's value. // Then we need to return the colon after that word token. [3] is the "end" colon of that word. // And because we need it after that one we do +1 to get the next one. throw this.input.error( 'Missed semicolon', token[0] === 'word' ? token[3] + 1 : token[2], ); } colon(tokens) { let brackets = 0; let token, type, prev; for (let [i, element] of tokens.entries()) { token = element; type = token[0]; if (type === '(') { brackets += 1; } if (type === ')') { brackets -= 1; } if (brackets === 0 && type === ':') { if (!prev) { this.doubleColon(token); } else if (prev[0] === 'word' && prev[1] === 'progid') { continue; } else { return i; } } prev = token; } return false; } comment(token) { let node = new Comment(); this.init(node, token[2]); node.source.end = this.getPosition(token[3] || token[2]); node.source.end.offset++; let text = token[1].slice(2, -2); if (/^\s*$/.test(text)) { node.text = ''; node.raws.left = text; node.raws.right = ''; } else { let match = text.match(/^(\s*)([^]*\S)(\s*)$/); node.text = match[2]; node.raws.left = match[1]; node.raws.right = match[3]; } } createTokenizer() { this.tokenizer = tokenizer(this.input); } decl(tokens, customProperty) { let node = new Declaration(); this.init(node, tokens[0][2]); let last = tokens[tokens.length - 1]; if (last[0] === ';') { this.semicolon = true; tokens.pop(); } node.source.end = this.getPosition( last[3] || last[2] || findLastWithPosition(tokens), ); node.source.end.offset++; while (tokens[0][0] !== 'word') { if (tokens.length === 1) this.unknownWord(tokens); node.raws.before += tokens.shift()[1]; } node.source.start = this.getPosition(tokens[0][2]); node.prop = ''; while (tokens.length) { let type = tokens[0][0]; if (type === ':' || type === 'space' || type === 'comment') { break; } node.prop += tokens.shift()[1]; } node.raws.between = ''; let token; while (tokens.length) { token = tokens.shift(); if (token[0] === ':') { node.raws.between += token[1]; break; } else { if (token[0] === 'word' && /\w/.test(token[1])) { this.unknownWord([token]); } node.raws.between += token[1]; } } if (node.prop[0] === '_' || node.prop[0] === '*') { node.raws.before += node.prop[0]; node.prop = node.prop.slice(1); } let firstSpaces = []; let next; while (tokens.length) { next = tokens[0][0]; if (next !== 'space' && next !== 'comment') break; firstSpaces.push(tokens.shift()); } this.precheckMissedSemicolon(tokens); for (let i = tokens.length - 1; i >= 0; i--) { token = tokens[i]; if (token[1].toLowerCase() === '!important') { node.important = true; let string = this.stringFrom(tokens, i); string = this.spacesFromEnd(tokens) + string; if (string !== ' !important') node.raws.important = string; break; } else if (token[1].toLowerCase() === 'important') { let cache = tokens.slice(0); let str = ''; for (let j = i; j > 0; j--) { let type = cache[j][0]; if (str.trim().indexOf('!') === 0 && type !== 'space') { break; } str = cache.pop()[1] + str; } if (str.trim().indexOf('!') === 0) { node.important = true; node.raws.important = str; tokens = cache; } } if (token[0] !== 'space' && token[0] !== 'comment') { break; } } let hasWord = tokens.some( i => i[0] !== 'space' && i[0] !== 'comment', ); if (hasWord) { node.raws.between += firstSpaces.map(i => i[1]).join(''); firstSpaces = []; } this.raw(node, 'value', firstSpaces.concat(tokens), customProperty); if (node.value.includes(':') && !customProperty) { this.checkMissedSemicolon(tokens); } } doubleColon(token) { throw this.input.error( 'Double colon', { offset: token[2] }, { offset: token[2] + token[1].length }, ); } emptyRule(token) { let node = new Rule(); this.init(node, token[2]); node.selector = ''; node.raws.between = ''; this.current = node; } end(token) { if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.semicolon = false; this.current.raws.after = (this.current.raws.after || '') + this.spaces; this.spaces = ''; if (this.current.parent) { this.current.source.end = this.getPosition(token[2]); this.current.source.end.offset++; this.current = this.current.parent; } else { this.unexpectedClose(token); } } endFile() { if (this.current.parent) this.unclosedBlock(); if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.current.raws.after = (this.current.raws.after || '') + this.spaces; this.root.source.end = this.getPosition(this.tokenizer.position()); } freeSemicolon(token) { this.spaces += token[1]; if (this.current.nodes) { let prev = this.current.nodes[this.current.nodes.length - 1]; if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { prev.raws.ownSemicolon = this.spaces; this.spaces = ''; } } } // Helpers getPosition(offset) { let pos = this.input.fromOffset(offset); return { column: pos.col, line: pos.line, offset, }; } init(node, offset) { this.current.push(node); node.source = { input: this.input, start: this.getPosition(offset), }; node.raws.before = this.spaces; this.spaces = ''; if (node.type !== 'comment') this.semicolon = false; } other(start) { let end = false; let type = null; let colon = false; let bracket = null; let brackets = []; let customProperty = start[1].startsWith('--'); let tokens = []; let token = start; while (token) { type = token[0]; tokens.push(token); if (type === '(' || type === '[') { if (!bracket) bracket = token; brackets.push(type === '(' ? ')' : ']'); } else if (customProperty && colon && type === '{') { if (!bracket) bracket = token; brackets.push('}'); } else if (brackets.length === 0) { if (type === ';') { if (colon) { this.decl(tokens, customProperty); return; } else { break; } } else if (type === '{') { this.rule(tokens); return; } else if (type === '}') { this.tokenizer.back(tokens.pop()); end = true; break; } else if (type === ':') { colon = true; } } else if (type === brackets[brackets.length - 1]) { brackets.pop(); if (brackets.length === 0) bracket = null; } token = this.tokenizer.nextToken(); } if (this.tokenizer.endOfFile()) end = true; if (brackets.length > 0) this.unclosedBracket(bracket); if (end && colon) { if (!customProperty) { while (tokens.length) { token = tokens[tokens.length - 1][0]; if (token !== 'space' && token !== 'comment') break; this.tokenizer.back(tokens.pop()); } } this.decl(tokens, customProperty); } else { this.unknownWord(tokens); } } parse() { let token; while (!this.tokenizer.endOfFile()) { token = this.tokenizer.nextToken(); switch (token[0]) { case 'space': this.spaces += token[1]; break; case ';': this.freeSemicolon(token); break; case '}': this.end(token); break; case 'comment': this.comment(token); break; case 'at-word': this.atrule(token); break; case '{': this.emptyRule(token); break; default: this.other(token); break; } } this.endFile(); } precheckMissedSemicolon(/* tokens */) { // Hook for Safe Parser } raw(node, prop, tokens, customProperty) { let token, type; let length = tokens.length; let value = ''; let clean = true; let next, prev; for (let i = 0; i < length; i += 1) { token = tokens[i]; type = token[0]; if (type === 'space' && i === length - 1 && !customProperty) { clean = false; } else if (type === 'comment') { prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty'; next = tokens[i + 1] ? tokens[i + 1][0] : 'empty'; if ( !SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next] ) { if (value.slice(-1) === ',') { clean = false; } else { value += token[1]; } } else { clean = false; } } else { value += token[1]; } } if (!clean) { let raw = tokens.reduce((all, i) => all + i[1], ''); node.raws[prop] = { raw, value }; } node[prop] = value; } rule(tokens) { tokens.pop(); let node = new Rule(); this.init(node, tokens[0][2]); node.raws.between = this.spacesAndCommentsFromEnd(tokens); this.raw(node, 'selector', tokens); this.current = node; } spacesAndCommentsFromEnd(tokens) { let lastTokenType; let spaces = ''; while (tokens.length) { lastTokenType = tokens[tokens.length - 1][0]; if (lastTokenType !== 'space' && lastTokenType !== 'comment') break; spaces = tokens.pop()[1] + spaces; } return spaces; } // Errors spacesAndCommentsFromStart(tokens) { let next; let spaces = ''; while (tokens.length) { next = tokens[0][0]; if (next !== 'space' && next !== 'comment') break; spaces += tokens.shift()[1]; } return spaces; } spacesFromEnd(tokens) { let lastTokenType; let spaces = ''; while (tokens.length) { lastTokenType = tokens[tokens.length - 1][0]; if (lastTokenType !== 'space') break; spaces = tokens.pop()[1] + spaces; } return spaces; } stringFrom(tokens, from) { let result = ''; for (let i = from; i < tokens.length; i++) { result += tokens[i][1]; } tokens.splice(from, tokens.length - from); return result; } unclosedBlock() { let pos = this.current.source.start; throw this.input.error('Unclosed block', pos.line, pos.column); } unclosedBracket(bracket) { throw this.input.error( 'Unclosed bracket', { offset: bracket[2] }, { offset: bracket[2] + 1 }, ); } unexpectedClose(token) { throw this.input.error( 'Unexpected }', { offset: token[2] }, { offset: token[2] + 1 }, ); } unknownWord(tokens) { throw this.input.error( 'Unknown word', { offset: tokens[0][2] }, { offset: tokens[0][2] + tokens[0][1].length }, ); } unnamedAtrule(node, token) { throw this.input.error( 'At-rule without name', { offset: token[2] }, { offset: token[2] + token[1].length }, ); } } module.exports = Parser; }, { './at-rule': 35, './comment': 36, './declaration': 39, './root': 54, './rule': 55, './tokenize': 59, }, ], 50: [ function (require, module, exports) { (function (process) { (function () { 'use strict'; let CssSyntaxError = require('./css-syntax-error'); let Declaration = require('./declaration'); let LazyResult = require('./lazy-result'); let Container = require('./container'); let Processor = require('./processor'); let stringify = require('./stringify'); let fromJSON = require('./fromJSON'); let Document = require('./document'); let Warning = require('./warning'); let Comment = require('./comment'); let AtRule = require('./at-rule'); let Result = require('./result.js'); let Input = require('./input'); let parse = require('./parse'); let list = require('./list'); let Rule = require('./rule'); let Root = require('./root'); let Node = require('./node'); function postcss(...plugins) { if (plugins.length === 1 && Array.isArray(plugins[0])) { plugins = plugins[0]; } return new Processor(plugins); } postcss.plugin = function plugin(name, initializer) { let warningPrinted = false; function creator(...args) { // eslint-disable-next-line no-console if (console && console.warn && !warningPrinted) { warningPrinted = true; // eslint-disable-next-line no-console console.warn( name + ': postcss.plugin was deprecated. Migration guide:\n' + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration', ); if (process.env.LANG && process.env.LANG.startsWith('cn')) { /* c8 ignore next 7 */ // eslint-disable-next-line no-console console.warn( name + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + 'https://www.w3ctech.com/topic/2226', ); } } let transformer = initializer(...args); transformer.postcssPlugin = name; transformer.postcssVersion = new Processor().version; return transformer; } let cache; Object.defineProperty(creator, 'postcss', { get() { if (!cache) cache = creator(); return cache; }, }); creator.process = function (css, processOpts, pluginOpts) { return postcss([creator(pluginOpts)]).process(css, processOpts); }; return creator; }; postcss.stringify = stringify; postcss.parse = parse; postcss.fromJSON = fromJSON; postcss.list = list; postcss.comment = defaults => new Comment(defaults); postcss.atRule = defaults => new AtRule(defaults); postcss.decl = defaults => new Declaration(defaults); postcss.rule = defaults => new Rule(defaults); postcss.root = defaults => new Root(defaults); postcss.document = defaults => new Document(defaults); postcss.CssSyntaxError = CssSyntaxError; postcss.Declaration = Declaration; postcss.Container = Container; postcss.Processor = Processor; postcss.Document = Document; postcss.Comment = Comment; postcss.Warning = Warning; postcss.AtRule = AtRule; postcss.Result = Result; postcss.Input = Input; postcss.Rule = Rule; postcss.Root = Root; postcss.Node = Node; LazyResult.registerPostcss(postcss); module.exports = postcss; postcss.default = postcss; }).call(this); }).call(this, require('_process')); }, { './at-rule': 35, './comment': 36, './container': 37, './css-syntax-error': 38, './declaration': 39, './document': 40, './fromJSON': 41, './input': 42, './lazy-result': 43, './list': 44, './node': 47, './parse': 48, './processor': 52, './result.js': 53, './root': 54, './rule': 55, './stringify': 57, './warning': 61, '_process': 62, }, ], 51: [ function (require, module, exports) { (function (Buffer) { (function () { 'use strict'; let { SourceMapConsumer, SourceMapGenerator, } = require('source-map-js'); let { existsSync, readFileSync } = require('fs'); let { dirname, join } = require('path'); function fromBase64(str) { if (Buffer) { return Buffer.from(str, 'base64').toString(); } else { /* c8 ignore next 2 */ return window.atob(str); } } class PreviousMap { constructor(css, opts) { if (opts.map === false) return; this.loadAnnotation(css); this.inline = this.startWith(this.annotation, 'data:'); let prev = opts.map ? opts.map.prev : undefined; let text = this.loadMap(opts.from, prev); if (!this.mapFile && opts.from) { this.mapFile = opts.from; } if (this.mapFile) this.root = dirname(this.mapFile); if (text) this.text = text; } consumer() { if (!this.consumerCache) { this.consumerCache = new SourceMapConsumer(this.text); } return this.consumerCache; } decodeInline(text) { let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/; let baseUri = /^data:application\/json;base64,/; let charsetUri = /^data:application\/json;charset=utf-?8,/; let uri = /^data:application\/json,/; if (charsetUri.test(text) || uri.test(text)) { return decodeURIComponent( text.substr(RegExp.lastMatch.length), ); } if (baseCharsetUri.test(text) || baseUri.test(text)) { return fromBase64(text.substr(RegExp.lastMatch.length)); } let encoding = text.match(/data:application\/json;([^,]+),/)[1]; throw new Error('Unsupported source map encoding ' + encoding); } getAnnotationURL(sourceMapString) { return sourceMapString .replace(/^\/\*\s*# sourceMappingURL=/, '') .trim(); } isMap(map) { if (typeof map !== 'object') return false; return ( typeof map.mappings === 'string' || typeof map._mappings === 'string' || Array.isArray(map.sections) ); } loadAnnotation(css) { let comments = css.match(/\/\*\s*# sourceMappingURL=/gm); if (!comments) return; // sourceMappingURLs from comments, strings, etc. let start = css.lastIndexOf(comments.pop()); let end = css.indexOf('*/', start); if (start > -1 && end > -1) { // Locate the last sourceMappingURL to avoid pickin this.annotation = this.getAnnotationURL( css.substring(start, end), ); } } loadFile(path) { this.root = dirname(path); if (existsSync(path)) { this.mapFile = path; return readFileSync(path, 'utf-8').toString().trim(); } } loadMap(file, prev) { if (prev === false) return false; if (prev) { if (typeof prev === 'string') { return prev; } else if (typeof prev === 'function') { let prevPath = prev(file); if (prevPath) { let map = this.loadFile(prevPath); if (!map) { throw new Error( 'Unable to load previous source map: ' + prevPath.toString(), ); } return map; } } else if (prev instanceof SourceMapConsumer) { return SourceMapGenerator.fromSourceMap(prev).toString(); } else if (prev instanceof SourceMapGenerator) { return prev.toString(); } else if (this.isMap(prev)) { return JSON.stringify(prev); } else { throw new Error( 'Unsupported previous source map format: ' + prev.toString(), ); } } else if (this.inline) { return this.decodeInline(this.annotation); } else if (this.annotation) { let map = this.annotation; if (file) map = join(dirname(file), map); return this.loadFile(map); } } startWith(string, start) { if (!string) return false; return string.substr(0, start.length) === start; } withContent() { return !!( this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0 ); } } module.exports = PreviousMap; PreviousMap.default = PreviousMap; }).call(this); }).call(this, require('buffer').Buffer); }, { 'buffer': 3, 'fs': 2, 'path': 2, 'source-map-js': 2 }, ], 52: [ function (require, module, exports) { (function (process) { (function () { 'use strict'; let NoWorkResult = require('./no-work-result'); let LazyResult = require('./lazy-result'); let Document = require('./document'); let Root = require('./root'); class Processor { constructor(plugins = []) { this.version = '8.4.31'; this.plugins = this.normalize(plugins); } normalize(plugins) { let normalized = []; for (let i of plugins) { if (i.postcss === true) { i = i(); } else if (i.postcss) { i = i.postcss; } if (typeof i === 'object' && Array.isArray(i.plugins)) { normalized = normalized.concat(i.plugins); } else if (typeof i === 'object' && i.postcssPlugin) { normalized.push(i); } else if (typeof i === 'function') { normalized.push(i); } else if ( typeof i === 'object' && (i.parse || i.stringify) ) { if (process.env.NODE_ENV !== 'production') { throw new Error( 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + 'one of the syntax/parser/stringifier options as outlined ' + 'in your PostCSS runner documentation.', ); } } else { throw new Error(i + ' is not a PostCSS plugin'); } } return normalized; } process(css, opts = {}) { if ( this.plugins.length === 0 && typeof opts.parser === 'undefined' && typeof opts.stringifier === 'undefined' && typeof opts.syntax === 'undefined' ) { return new NoWorkResult(this, css, opts); } else { return new LazyResult(this, css, opts); } } use(plugin) { this.plugins = this.plugins.concat(this.normalize([plugin])); return this; } } module.exports = Processor; Processor.default = Processor; Root.registerProcessor(Processor); Document.registerProcessor(Processor); }).call(this); }).call(this, require('_process')); }, { './document': 40, './lazy-result': 43, './no-work-result': 46, './root': 54, '_process': 62, }, ], 53: [ function (require, module, exports) { 'use strict'; let Warning = require('./warning'); class Result { constructor(processor, root, opts) { this.processor = processor; this.messages = []; this.root = root; this.opts = opts; this.css = undefined; this.map = undefined; } toString() { return this.css; } warn(text, opts = {}) { if (!opts.plugin) { if (this.lastPlugin && this.lastPlugin.postcssPlugin) { opts.plugin = this.lastPlugin.postcssPlugin; } } let warning = new Warning(text, opts); this.messages.push(warning); return warning; } warnings() { return this.messages.filter(i => i.type === 'warning'); } get content() { return this.css; } } module.exports = Result; Result.default = Result; }, { './warning': 61 }, ], 54: [ function (require, module, exports) { 'use strict'; let Container = require('./container'); let LazyResult, Processor; class Root extends Container { constructor(defaults) { super(defaults); this.type = 'root'; if (!this.nodes) this.nodes = []; } normalize(child, sample, type) { let nodes = super.normalize(child); if (sample) { if (type === 'prepend') { if (this.nodes.length > 1) { sample.raws.before = this.nodes[1].raws.before; } else { delete sample.raws.before; } } else if (this.first !== sample) { for (let node of nodes) { node.raws.before = sample.raws.before; } } } return nodes; } removeChild(child, ignore) { let index = this.index(child); if (!ignore && index === 0 && this.nodes.length > 1) { this.nodes[1].raws.before = this.nodes[index].raws.before; } return super.removeChild(child); } toResult(opts = {}) { let lazy = new LazyResult(new Processor(), this, opts); return lazy.stringify(); } } Root.registerLazyResult = dependant => { LazyResult = dependant; }; Root.registerProcessor = dependant => { Processor = dependant; }; module.exports = Root; Root.default = Root; Container.registerRoot(Root); }, { './container': 37 }, ], 55: [ function (require, module, exports) { 'use strict'; let Container = require('./container'); let list = require('./list'); class Rule extends Container { constructor(defaults) { super(defaults); this.type = 'rule'; if (!this.nodes) this.nodes = []; } get selectors() { return list.comma(this.selector); } set selectors(values) { let match = this.selector ? this.selector.match(/,\s*/) : null; let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen'); this.selector = values.join(sep); } } module.exports = Rule; Rule.default = Rule; Container.registerRule(Rule); }, { './container': 37, './list': 44 }, ], 56: [ function (require, module, exports) { 'use strict'; const DEFAULT_RAW = { after: '\n', beforeClose: '\n', beforeComment: '\n', beforeDecl: '\n', beforeOpen: ' ', beforeRule: '\n', colon: ': ', commentLeft: ' ', commentRight: ' ', emptyBody: '', indent: ' ', semicolon: false, }; function capitalize(str) { return str[0].toUpperCase() + str.slice(1); } class Stringifier { constructor(builder) { this.builder = builder; } atrule(node, semicolon) { let name = '@' + node.name; let params = node.params ? this.rawValue(node, 'params') : ''; if (typeof node.raws.afterName !== 'undefined') { name += node.raws.afterName; } else if (params) { name += ' '; } if (node.nodes) { this.block(node, name + params); } else { let end = (node.raws.between || '') + (semicolon ? ';' : ''); this.builder(name + params + end, node); } } beforeAfter(node, detect) { let value; if (node.type === 'decl') { value = this.raw(node, null, 'beforeDecl'); } else if (node.type === 'comment') { value = this.raw(node, null, 'beforeComment'); } else if (detect === 'before') { value = this.raw(node, null, 'beforeRule'); } else { value = this.raw(node, null, 'beforeClose'); } let buf = node.parent; let depth = 0; while (buf && buf.type !== 'root') { depth += 1; buf = buf.parent; } if (value.includes('\n')) { let indent = this.raw(node, null, 'indent'); if (indent.length) { for (let step = 0; step < depth; step++) value += indent; } } return value; } block(node, start) { let between = this.raw(node, 'between', 'beforeOpen'); this.builder(start + between + '{', node, 'start'); let after; if (node.nodes && node.nodes.length) { this.body(node); after = this.raw(node, 'after'); } else { after = this.raw(node, 'after', 'emptyBody'); } if (after) this.builder(after); this.builder('}', node, 'end'); } body(node) { let last = node.nodes.length - 1; while (last > 0) { if (node.nodes[last].type !== 'comment') break; last -= 1; } let semicolon = this.raw(node, 'semicolon'); for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; let before = this.raw(child, 'before'); if (before) this.builder(before); this.stringify(child, last !== i || semicolon); } } comment(node) { let left = this.raw(node, 'left', 'commentLeft'); let right = this.raw(node, 'right', 'commentRight'); this.builder('/*' + left + node.text + right + '*/', node); } decl(node, semicolon) { let between = this.raw(node, 'between', 'colon'); let string = node.prop + between + this.rawValue(node, 'value'); if (node.important) { string += node.raws.important || ' !important'; } if (semicolon) string += ';'; this.builder(string, node); } document(node) { this.body(node); } raw(node, own, detect) { let value; if (!detect) detect = own; // Already had if (own) { value = node.raws[own]; if (typeof value !== 'undefined') return value; } let parent = node.parent; if (detect === 'before') { // Hack for first rule in CSS if ( !parent || (parent.type === 'root' && parent.first === node) ) { return ''; } // `root` nodes in `document` should use only their own raws if (parent && parent.type === 'document') { return ''; } } // Floating child without parent if (!parent) return DEFAULT_RAW[detect]; // Detect style by other nodes let root = node.root(); if (!root.rawCache) root.rawCache = {}; if (typeof root.rawCache[detect] !== 'undefined') { return root.rawCache[detect]; } if (detect === 'before' || detect === 'after') { return this.beforeAfter(node, detect); } else { let method = 'raw' + capitalize(detect); if (this[method]) { value = this[method](root, node); } else { root.walk(i => { value = i.raws[own]; if (typeof value !== 'undefined') return false; }); } } if (typeof value === 'undefined') value = DEFAULT_RAW[detect]; root.rawCache[detect] = value; return value; } rawBeforeClose(root) { let value; root.walk(i => { if (i.nodes && i.nodes.length > 0) { if (typeof i.raws.after !== 'undefined') { value = i.raws.after; if (value.includes('\n')) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); if (value) value = value.replace(/\S/g, ''); return value; } rawBeforeComment(root, node) { let value; root.walkComments(i => { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.includes('\n')) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeDecl'); } else if (value) { value = value.replace(/\S/g, ''); } return value; } rawBeforeDecl(root, node) { let value; root.walkDecls(i => { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.includes('\n')) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeRule'); } else if (value) { value = value.replace(/\S/g, ''); } return value; } rawBeforeOpen(root) { let value; root.walk(i => { if (i.type !== 'decl') { value = i.raws.between; if (typeof value !== 'undefined') return false; } }); return value; } rawBeforeRule(root) { let value; root.walk(i => { if (i.nodes && (i.parent !== root || root.first !== i)) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.includes('\n')) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); if (value) value = value.replace(/\S/g, ''); return value; } rawColon(root) { let value; root.walkDecls(i => { if (typeof i.raws.between !== 'undefined') { value = i.raws.between.replace(/[^\s:]/g, ''); return false; } }); return value; } rawEmptyBody(root) { let value; root.walk(i => { if (i.nodes && i.nodes.length === 0) { value = i.raws.after; if (typeof value !== 'undefined') return false; } }); return value; } rawIndent(root) { if (root.raws.indent) return root.raws.indent; let value; root.walk(i => { let p = i.parent; if (p && p !== root && p.parent && p.parent === root) { if (typeof i.raws.before !== 'undefined') { let parts = i.raws.before.split('\n'); value = parts[parts.length - 1]; value = value.replace(/\S/g, ''); return false; } } }); return value; } rawSemicolon(root) { let value; root.walk(i => { if (i.nodes && i.nodes.length && i.last.type === 'decl') { value = i.raws.semicolon; if (typeof value !== 'undefined') return false; } }); return value; } rawValue(node, prop) { let value = node[prop]; let raw = node.raws[prop]; if (raw && raw.value === value) { return raw.raw; } return value; } root(node) { this.body(node); if (node.raws.after) this.builder(node.raws.after); } rule(node) { this.block(node, this.rawValue(node, 'selector')); if (node.raws.ownSemicolon) { this.builder(node.raws.ownSemicolon, node, 'end'); } } stringify(node, semicolon) { /* c8 ignore start */ if (!this[node.type]) { throw new Error( 'Unknown AST node type ' + node.type + '. ' + 'Maybe you need to change PostCSS stringifier.', ); } /* c8 ignore stop */ this[node.type](node, semicolon); } } module.exports = Stringifier; Stringifier.default = Stringifier; }, {}, ], 57: [ function (require, module, exports) { 'use strict'; let Stringifier = require('./stringifier'); function stringify(node, builder) { let str = new Stringifier(builder); str.stringify(node); } module.exports = stringify; stringify.default = stringify; }, { './stringifier': 56 }, ], 58: [ function (require, module, exports) { 'use strict'; module.exports.isClean = Symbol('isClean'); module.exports.my = Symbol('my'); }, {}, ], 59: [ function (require, module, exports) { 'use strict'; const SINGLE_QUOTE = "'".charCodeAt(0); const DOUBLE_QUOTE = '"'.charCodeAt(0); const BACKSLASH = '\\'.charCodeAt(0); const SLASH = '/'.charCodeAt(0); const NEWLINE = '\n'.charCodeAt(0); const SPACE = ' '.charCodeAt(0); const FEED = '\f'.charCodeAt(0); const TAB = '\t'.charCodeAt(0); const CR = '\r'.charCodeAt(0); const OPEN_SQUARE = '['.charCodeAt(0); const CLOSE_SQUARE = ']'.charCodeAt(0); const OPEN_PARENTHESES = '('.charCodeAt(0); const CLOSE_PARENTHESES = ')'.charCodeAt(0); const OPEN_CURLY = '{'.charCodeAt(0); const CLOSE_CURLY = '}'.charCodeAt(0); const SEMICOLON = ';'.charCodeAt(0); const ASTERISK = '*'.charCodeAt(0); const COLON = ':'.charCodeAt(0); const AT = '@'.charCodeAt(0); const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g; const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g; const RE_BAD_BRACKET = /.[\r\n"'(/\\]/; const RE_HEX_ESCAPE = /[\da-f]/i; module.exports = function tokenizer(input, options = {}) { let css = input.css.valueOf(); let ignore = options.ignoreErrors; let code, next, quote, content, escape; let escaped, escapePos, prev, n, currentToken; let length = css.length; let pos = 0; let buffer = []; let returned = []; function position() { return pos; } function unclosed(what) { throw input.error('Unclosed ' + what, pos); } function endOfFile() { return returned.length === 0 && pos >= length; } function nextToken(opts) { if (returned.length) return returned.pop(); if (pos >= length) return; let ignoreUnclosed = opts ? opts.ignoreUnclosed : false; code = css.charCodeAt(pos); switch (code) { case NEWLINE: case SPACE: case TAB: case CR: case FEED: { next = pos; do { next += 1; code = css.charCodeAt(next); } while ( code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED ); currentToken = ['space', css.slice(pos, next)]; pos = next - 1; break; } case OPEN_SQUARE: case CLOSE_SQUARE: case OPEN_CURLY: case CLOSE_CURLY: case COLON: case SEMICOLON: case CLOSE_PARENTHESES: { let controlChar = String.fromCharCode(code); currentToken = [controlChar, controlChar, pos]; break; } case OPEN_PARENTHESES: { prev = buffer.length ? buffer.pop()[1] : ''; n = css.charCodeAt(pos + 1); if ( prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR ) { next = pos; do { escaped = false; next = css.indexOf(')', next + 1); if (next === -1) { if (ignore || ignoreUnclosed) { next = pos; break; } else { unclosed('bracket'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); currentToken = [ 'brackets', css.slice(pos, next + 1), pos, next, ]; pos = next; } else { next = css.indexOf(')', pos + 1); content = css.slice(pos, next + 1); if (next === -1 || RE_BAD_BRACKET.test(content)) { currentToken = ['(', '(', pos]; } else { currentToken = ['brackets', content, pos, next]; pos = next; } } break; } case SINGLE_QUOTE: case DOUBLE_QUOTE: { quote = code === SINGLE_QUOTE ? "'" : '"'; next = pos; do { escaped = false; next = css.indexOf(quote, next + 1); if (next === -1) { if (ignore || ignoreUnclosed) { next = pos + 1; break; } else { unclosed('string'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); currentToken = ['string', css.slice(pos, next + 1), pos, next]; pos = next; break; } case AT: { RE_AT_END.lastIndex = pos + 1; RE_AT_END.test(css); if (RE_AT_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_AT_END.lastIndex - 2; } currentToken = ['at-word', css.slice(pos, next + 1), pos, next]; pos = next; break; } case BACKSLASH: { next = pos; escape = true; while (css.charCodeAt(next + 1) === BACKSLASH) { next += 1; escape = !escape; } code = css.charCodeAt(next + 1); if ( escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED ) { next += 1; if (RE_HEX_ESCAPE.test(css.charAt(next))) { while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { next += 1; } if (css.charCodeAt(next + 1) === SPACE) { next += 1; } } } currentToken = ['word', css.slice(pos, next + 1), pos, next]; pos = next; break; } default: { if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { next = css.indexOf('*/', pos + 2) + 1; if (next === 0) { if (ignore || ignoreUnclosed) { next = css.length; } else { unclosed('comment'); } } currentToken = [ 'comment', css.slice(pos, next + 1), pos, next, ]; pos = next; } else { RE_WORD_END.lastIndex = pos + 1; RE_WORD_END.test(css); if (RE_WORD_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_WORD_END.lastIndex - 2; } currentToken = ['word', css.slice(pos, next + 1), pos, next]; buffer.push(currentToken); pos = next; } break; } } pos++; return currentToken; } function back(token) { returned.push(token); } return { back, endOfFile, nextToken, position, }; }; }, {}, ], 60: [ function (require, module, exports) { /* eslint-disable no-console */ 'use strict'; let printed = {}; module.exports = function warnOnce(message) { if (printed[message]) return; printed[message] = true; if (typeof console !== 'undefined' && console.warn) { console.warn(message); } }; }, {}, ], 61: [ function (require, module, exports) { 'use strict'; class Warning { constructor(text, opts = {}) { this.type = 'warning'; this.text = text; if (opts.node && opts.node.source) { let range = opts.node.rangeBy(opts); this.line = range.start.line; this.column = range.start.column; this.endLine = range.end.line; this.endColumn = range.end.column; } for (let opt in opts) this[opt] = opts[opt]; } toString() { if (this.node) { return this.node.error(this.text, { index: this.index, plugin: this.plugin, word: this.word, }).message; } if (this.plugin) { return this.plugin + ': ' + this.text; } return this.text; } } module.exports = Warning; Warning.default = Warning; }, {}, ], 62: [ function (require, module, exports) { // shim for using process in browser var process = (module.exports = {}); // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ( (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout ) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ( (cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout ) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return []; }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; }, {}, ], 63: [ function (require, module, exports) { const htmlparser = require('htmlparser2'); const escapeStringRegexp = require('escape-string-regexp'); const { isPlainObject } = require('is-plain-object'); const deepmerge = require('deepmerge'); const parseSrcset = require('parse-srcset'); const { parse: postcssParse } = require('postcss'); // Tags that can conceivably represent stand-alone media. const mediaTags = [ 'img', 'audio', 'video', 'picture', 'svg', 'object', 'map', 'iframe', 'embed', ]; // Tags that are inherently vulnerable to being used in XSS attacks. const vulnerableTags = ['script', 'style']; function each(obj, cb) { if (obj) { Object.keys(obj).forEach(function (key) { cb(obj[key], key); }); } } // Avoid false positives with .__proto__, .hasOwnProperty, etc. function has(obj, key) { return {}.hasOwnProperty.call(obj, key); } // Returns those elements of `a` for which `cb(a)` returns truthy function filter(a, cb) { const n = []; each(a, function (v) { if (cb(v)) { n.push(v); } }); return n; } function isEmptyObject(obj) { for (const key in obj) { if (has(obj, key)) { return false; } } return true; } function stringifySrcset(parsedSrcset) { return parsedSrcset .map(function (part) { if (!part.url) { throw new Error('URL missing'); } return ( part.url + (part.w ? ` ${part.w}w` : '') + (part.h ? ` ${part.h}h` : '') + (part.d ? ` ${part.d}x` : '') ); }) .join(', '); } module.exports = sanitizeHtml; // A valid attribute name. // We use a tolerant definition based on the set of strings defined by // html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state // and html.spec.whatwg.org/multipage/parsing.html#attribute-name-state . // The characters accepted are ones which can be appended to the attribute // name buffer without triggering a parse error: // * unexpected-equals-sign-before-attribute-name // * unexpected-null-character // * unexpected-character-in-attribute-name // We exclude the empty string because it's impossible to get to the after // attribute name state with an empty attribute name buffer. const VALID_HTML_ATTRIBUTE_NAME = /^[^\0\t\n\f\r /<=>]+$/; // Ignore the _recursing flag; it's there for recursive // invocation as a guard against this exploit: // https://github.com/fb55/htmlparser2/issues/105 function sanitizeHtml(html, options, _recursing) { if (html == null) { return ''; } if (typeof html === 'number') { html = html.toString(); } let result = ''; // Used for hot swapping the result variable with an empty string in order to "capture" the text written to it. let tempResult = ''; function Frame(tag, attribs) { const that = this; this.tag = tag; this.attribs = attribs || {}; this.tagPosition = result.length; this.text = ''; // Node inner text this.mediaChildren = []; this.updateParentNodeText = function () { if (stack.length) { const parentFrame = stack[stack.length - 1]; parentFrame.text += that.text; } }; this.updateParentNodeMediaChildren = function () { if (stack.length && mediaTags.includes(this.tag)) { const parentFrame = stack[stack.length - 1]; parentFrame.mediaChildren.push(this.tag); } }; } options = Object.assign({}, sanitizeHtml.defaults, options); options.parser = Object.assign( {}, htmlParserDefaults, options.parser, ); const tagAllowed = function (name) { return ( options.allowedTags === false || (options.allowedTags || []).indexOf(name) > -1 ); }; // vulnerableTags vulnerableTags.forEach(function (tag) { if (tagAllowed(tag) && !options.allowVulnerableTags) { console.warn( `\n\n⚠️ Your \`allowedTags\` option includes, \`${tag}\`, which is inherently\nvulnerable to XSS attacks. Please remove it from \`allowedTags\`.\nOr, to disable this warning, add the \`allowVulnerableTags\` option\nand ensure you are accounting for this risk.\n\n`, ); } }); // Tags that contain something other than HTML, or where discarding // the text when the tag is disallowed makes sense for other reasons. // If we are not allowing these tags, we should drop their content too. // For other tags you would drop the tag but keep its content. const nonTextTagsArray = options.nonTextTags || [ 'script', 'style', 'textarea', 'option', ]; let allowedAttributesMap; let allowedAttributesGlobMap; if (options.allowedAttributes) { allowedAttributesMap = {}; allowedAttributesGlobMap = {}; each(options.allowedAttributes, function (attributes, tag) { allowedAttributesMap[tag] = []; const globRegex = []; attributes.forEach(function (obj) { if (typeof obj === 'string' && obj.indexOf('*') >= 0) { globRegex.push( escapeStringRegexp(obj).replace(/\\\*/g, '.*'), ); } else { allowedAttributesMap[tag].push(obj); } }); if (globRegex.length) { allowedAttributesGlobMap[tag] = new RegExp( '^(' + globRegex.join('|') + ')$', ); } }); } const allowedClassesMap = {}; const allowedClassesGlobMap = {}; const allowedClassesRegexMap = {}; each(options.allowedClasses, function (classes, tag) { // Implicitly allows the class attribute if (allowedAttributesMap) { if (!has(allowedAttributesMap, tag)) { allowedAttributesMap[tag] = []; } allowedAttributesMap[tag].push('class'); } allowedClassesMap[tag] = classes; if (Array.isArray(classes)) { const globRegex = []; allowedClassesMap[tag] = []; allowedClassesRegexMap[tag] = []; classes.forEach(function (obj) { if (typeof obj === 'string' && obj.indexOf('*') >= 0) { globRegex.push( escapeStringRegexp(obj).replace(/\\\*/g, '.*'), ); } else if (obj instanceof RegExp) { allowedClassesRegexMap[tag].push(obj); } else { allowedClassesMap[tag].push(obj); } }); if (globRegex.length) { allowedClassesGlobMap[tag] = new RegExp( '^(' + globRegex.join('|') + ')$', ); } } }); const transformTagsMap = {}; let transformTagsAll; each(options.transformTags, function (transform, tag) { let transFun; if (typeof transform === 'function') { transFun = transform; } else if (typeof transform === 'string') { transFun = sanitizeHtml.simpleTransform(transform); } if (tag === '*') { transformTagsAll = transFun; } else { transformTagsMap[tag] = transFun; } }); let depth; let stack; let skipMap; let transformMap; let skipText; let skipTextDepth; let addedText = false; initializeState(); const parser = new htmlparser.Parser( { onopentag: function (name, attribs) { // If `enforceHtmlBoundary` is `true` and this has found the opening // `html` tag, reset the state. if (options.enforceHtmlBoundary && name === 'html') { initializeState(); } if (skipText) { skipTextDepth++; return; } const frame = new Frame(name, attribs); stack.push(frame); let skip = false; const hasText = !!frame.text; let transformedTag; if (has(transformTagsMap, name)) { transformedTag = transformTagsMap[name](name, attribs); frame.attribs = attribs = transformedTag.attribs; if (transformedTag.text !== undefined) { frame.innerText = transformedTag.text; } if (name !== transformedTag.tagName) { frame.name = name = transformedTag.tagName; transformMap[depth] = transformedTag.tagName; } } if (transformTagsAll) { transformedTag = transformTagsAll(name, attribs); frame.attribs = attribs = transformedTag.attribs; if (name !== transformedTag.tagName) { frame.name = name = transformedTag.tagName; transformMap[depth] = transformedTag.tagName; } } if ( !tagAllowed(name) || (options.disallowedTagsMode === 'recursiveEscape' && !isEmptyObject(skipMap)) || (options.nestingLimit != null && depth >= options.nestingLimit) ) { skip = true; skipMap[depth] = true; if (options.disallowedTagsMode === 'discard') { if (nonTextTagsArray.indexOf(name) !== -1) { skipText = true; skipTextDepth = 1; } } skipMap[depth] = true; } depth++; if (skip) { if (options.disallowedTagsMode === 'discard') { // We want the contents but not this tag return; } tempResult = result; result = ''; } result += '<' + name; if (name === 'script') { if ( options.allowedScriptHostnames || options.allowedScriptDomains ) { frame.innerText = ''; } } if ( !allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*'] ) { each(attribs, function (value, a) { if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) { // This prevents part of an attribute name in the output from being // interpreted as the end of an attribute, or end of a tag. delete frame.attribs[a]; return; } // If the value is empty, and this is a known non-boolean attribute, delete it // List taken from https://html.spec.whatwg.org/multipage/indices.html#attributes-3 if ( value === '' && (options.nonBooleanAttributes.includes(a) || options.nonBooleanAttributes.includes('*')) ) { delete frame.attribs[a]; return; } // check allowedAttributesMap for the element and attribute and modify the value // as necessary if there are specific values defined. let passedAllowedAttributesMapCheck = false; if ( !allowedAttributesMap || (has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1) || (allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1) || (has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a)) || (allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a)) ) { passedAllowedAttributesMapCheck = true; } else if ( allowedAttributesMap && allowedAttributesMap[name] ) { for (const o of allowedAttributesMap[name]) { if (isPlainObject(o) && o.name && o.name === a) { passedAllowedAttributesMapCheck = true; let newValue = ''; if (o.multiple === true) { // verify the values that are allowed const splitStrArray = value.split(' '); for (const s of splitStrArray) { if (o.values.indexOf(s) !== -1) { if (newValue === '') { newValue = s; } else { newValue += ' ' + s; } } } } else if (o.values.indexOf(value) >= 0) { // verified an allowed value matches the entire attribute value newValue = value; } value = newValue; } } } if (passedAllowedAttributesMapCheck) { if ( options.allowedSchemesAppliedToAttributes.indexOf(a) !== -1 ) { if (naughtyHref(name, value)) { delete frame.attribs[a]; return; } } if (name === 'script' && a === 'src') { let allowed = true; try { const parsed = parseUrl(value); if ( options.allowedScriptHostnames || options.allowedScriptDomains ) { const allowedHostname = ( options.allowedScriptHostnames || [] ).find(function (hostname) { return hostname === parsed.url.hostname; }); const allowedDomain = ( options.allowedScriptDomains || [] ).find(function (domain) { return ( parsed.url.hostname === domain || parsed.url.hostname.endsWith(`.${domain}`) ); }); allowed = allowedHostname || allowedDomain; } } catch (e) { allowed = false; } if (!allowed) { delete frame.attribs[a]; return; } } if (name === 'iframe' && a === 'src') { let allowed = true; try { const parsed = parseUrl(value); if (parsed.isRelativeUrl) { // default value of allowIframeRelativeUrls is true // unless allowedIframeHostnames or allowedIframeDomains specified allowed = has(options, 'allowIframeRelativeUrls') ? options.allowIframeRelativeUrls : !options.allowedIframeHostnames && !options.allowedIframeDomains; } else if ( options.allowedIframeHostnames || options.allowedIframeDomains ) { const allowedHostname = ( options.allowedIframeHostnames || [] ).find(function (hostname) { return hostname === parsed.url.hostname; }); const allowedDomain = ( options.allowedIframeDomains || [] ).find(function (domain) { return ( parsed.url.hostname === domain || parsed.url.hostname.endsWith(`.${domain}`) ); }); allowed = allowedHostname || allowedDomain; } } catch (e) { // Unparseable iframe src allowed = false; } if (!allowed) { delete frame.attribs[a]; return; } } if (a === 'srcset') { try { let parsed = parseSrcset(value); parsed.forEach(function (value) { if (naughtyHref('srcset', value.url)) { value.evil = true; } }); parsed = filter(parsed, function (v) { return !v.evil; }); if (!parsed.length) { delete frame.attribs[a]; return; } else { value = stringifySrcset( filter(parsed, function (v) { return !v.evil; }), ); frame.attribs[a] = value; } } catch (e) { // Unparseable srcset delete frame.attribs[a]; return; } } if (a === 'class') { const allowedSpecificClasses = allowedClassesMap[name]; const allowedWildcardClasses = allowedClassesMap['*']; const allowedSpecificClassesGlob = allowedClassesGlobMap[name]; const allowedSpecificClassesRegex = allowedClassesRegexMap[name]; const allowedWildcardClassesGlob = allowedClassesGlobMap['*']; const allowedClassesGlobs = [ allowedSpecificClassesGlob, allowedWildcardClassesGlob, ] .concat(allowedSpecificClassesRegex) .filter(function (t) { return t; }); if (allowedSpecificClasses && allowedWildcardClasses) { value = filterClasses( value, deepmerge( allowedSpecificClasses, allowedWildcardClasses, ), allowedClassesGlobs, ); } else { value = filterClasses( value, allowedSpecificClasses || allowedWildcardClasses, allowedClassesGlobs, ); } if (!value.length) { delete frame.attribs[a]; return; } } if (a === 'style') { if (options.parseStyleAttributes) { try { const abstractSyntaxTree = postcssParse( name + ' {' + value + '}', ); const filteredAST = filterCss( abstractSyntaxTree, options.allowedStyles, ); value = stringifyStyleAttributes(filteredAST); if (value.length === 0) { delete frame.attribs[a]; return; } } catch (e) { if (typeof window !== 'undefined') { console.warn( 'Failed to parse "' + name + ' {' + value + '}' + '", If you\'re running this in a browser, we recommend to disable style parsing: options.parseStyleAttributes: false, since this only works in a node environment due to a postcss dependency, More info: https://github.com/apostrophecms/sanitize-html/issues/547', ); } delete frame.attribs[a]; return; } } else if (options.allowedStyles) { throw new Error( 'allowedStyles option cannot be used together with parseStyleAttributes: false.', ); } } result += ' ' + a; if (value && value.length) { result += '="' + escapeHtml(value, true) + '"'; } } else { delete frame.attribs[a]; } }); } if (options.selfClosing.indexOf(name) !== -1) { result += ' />'; } else { result += '>'; if (frame.innerText && !hasText && !options.textFilter) { result += escapeHtml(frame.innerText); addedText = true; } } if (skip) { result = tempResult + escapeHtml(result); tempResult = ''; } }, ontext: function (text) { if (skipText) { return; } const lastFrame = stack[stack.length - 1]; let tag; if (lastFrame) { tag = lastFrame.tag; // If inner text was set by transform function then let's use it text = lastFrame.innerText !== undefined ? lastFrame.innerText : text; } if ( options.disallowedTagsMode === 'discard' && (tag === 'script' || tag === 'style') ) { // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing // script tags is, by definition, game over for XSS protection, so if that's // your concern, don't allow them. The same is essentially true for style tags // which have their own collection of XSS vectors. result += text; } else { const escaped = escapeHtml(text, false); if (options.textFilter && !addedText) { result += options.textFilter(escaped, tag); } else if (!addedText) { result += escaped; } } if (stack.length) { const frame = stack[stack.length - 1]; frame.text += text; } }, onclosetag: function (name, isImplied) { if (skipText) { skipTextDepth--; if (!skipTextDepth) { skipText = false; } else { return; } } const frame = stack.pop(); if (!frame) { // Do not crash on bad markup return; } if (frame.tag !== name) { // Another case of bad markup. // Push to stack, so that it will be used in future closing tags. stack.push(frame); return; } skipText = options.enforceHtmlBoundary ? name === 'html' : false; depth--; const skip = skipMap[depth]; if (skip) { delete skipMap[depth]; if (options.disallowedTagsMode === 'discard') { frame.updateParentNodeText(); return; } tempResult = result; result = ''; } if (transformMap[depth]) { name = transformMap[depth]; delete transformMap[depth]; } if (options.exclusiveFilter && options.exclusiveFilter(frame)) { result = result.substr(0, frame.tagPosition); return; } frame.updateParentNodeMediaChildren(); frame.updateParentNodeText(); if ( // Already output /> options.selfClosing.indexOf(name) !== -1 || // Escaped tag, closing tag is implied (isImplied && !tagAllowed(name) && ['escape', 'recursiveEscape'].indexOf( options.disallowedTagsMode, ) >= 0) ) { if (skip) { result = tempResult; tempResult = ''; } return; } result += ''; if (skip) { result = tempResult + escapeHtml(result); tempResult = ''; } addedText = false; }, }, options.parser, ); parser.write(html); parser.end(); return result; function initializeState() { result = ''; depth = 0; stack = []; skipMap = {}; transformMap = {}; skipText = false; skipTextDepth = 0; } function escapeHtml(s, quote) { if (typeof s !== 'string') { s = s + ''; } if (options.parser.decodeEntities) { s = s .replace(/&/g, '&') .replace(//g, '>'); if (quote) { s = s.replace(/"/g, '"'); } } // TODO: this is inadequate because it will pass `&0;`. This approach // will not work, each & must be considered with regard to whether it // is followed by a 100% syntactically valid entity or not, and escaped // if it is not. If this bothers you, don't set parser.decodeEntities // to false. (The default is true.) s = s .replace(/&(?![a-zA-Z0-9#]{1,20};)/g, '&') // Match ampersands not part of existing HTML entity .replace(//g, '>'); if (quote) { s = s.replace(/"/g, '"'); } return s; } function naughtyHref(name, href) { // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab // eslint-disable-next-line no-control-regex href = href.replace(/[\x00-\x20]+/g, ''); // Clobber any comments in URLs, which the browser might // interpret inside an XML data island, allowing // a javascript: URL to be snuck through while (true) { const firstIndex = href.indexOf('', firstIndex + 4); if (lastIndex === -1) { break; } href = href.substring(0, firstIndex) + href.substring(lastIndex + 3); } // Case insensitive so we don't get faked out by JAVASCRIPT #1 // Allow more characters after the first so we don't get faked // out by certain schemes browsers accept const matches = href.match(/^([a-zA-Z][a-zA-Z0-9.\-+]*):/); if (!matches) { // Protocol-relative URL starting with any combination of '/' and '\' if (href.match(/^[/\\]{2}/)) { return !options.allowProtocolRelative; } // No scheme return false; } const scheme = matches[1].toLowerCase(); if (has(options.allowedSchemesByTag, name)) { return options.allowedSchemesByTag[name].indexOf(scheme) === -1; } return ( !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1 ); } function parseUrl(value) { value = value.replace(/^(\w+:)?\s*[\\/]\s*[\\/]/, '$1//'); if (value.startsWith('relative:')) { // An attempt to exploit our workaround for base URLs being // mandatory for relative URL validation in the WHATWG // URL parser, reject it throw new Error('relative: exploit attempt'); } // naughtyHref is in charge of whether protocol relative URLs // are cool. Here we are concerned just with allowed hostnames and // whether to allow relative URLs. // // Build a placeholder "base URL" against which any reasonable // relative URL may be parsed successfully let base = 'relative://relative-site'; for (let i = 0; i < 100; i++) { base += `/${i}`; } const parsed = new URL(value, base); const isRelativeUrl = parsed && parsed.hostname === 'relative-site' && parsed.protocol === 'relative:'; return { isRelativeUrl, url: parsed, }; } /** * Filters user input css properties by allowlisted regex attributes. * Modifies the abstractSyntaxTree object. * * @param {object} abstractSyntaxTree - Object representation of CSS attributes. * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }. * @param {object} allowedStyles - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i). * @return {object} - The modified tree. */ function filterCss(abstractSyntaxTree, allowedStyles) { if (!allowedStyles) { return abstractSyntaxTree; } const astRules = abstractSyntaxTree.nodes[0]; let selectedRule; // Merge global and tag-specific styles into new AST. if (allowedStyles[astRules.selector] && allowedStyles['*']) { selectedRule = deepmerge( allowedStyles[astRules.selector], allowedStyles['*'], ); } else { selectedRule = allowedStyles[astRules.selector] || allowedStyles['*']; } if (selectedRule) { abstractSyntaxTree.nodes[0].nodes = astRules.nodes.reduce( filterDeclarations(selectedRule), [], ); } return abstractSyntaxTree; } /** * Extracts the style attributes from an AbstractSyntaxTree and formats those * values in the inline style attribute format. * * @param {AbstractSyntaxTree} filteredAST * @return {string} - Example: "color:yellow;text-align:center !important;font-family:helvetica;" */ function stringifyStyleAttributes(filteredAST) { return filteredAST.nodes[0].nodes .reduce(function (extractedAttributes, attrObject) { extractedAttributes.push( `${attrObject.prop}:${attrObject.value}${attrObject.important ? ' !important' : ''}`, ); return extractedAttributes; }, []) .join(';'); } /** * Filters the existing attributes for the given property. Discards any attributes * which don't match the allowlist. * * @param {object} selectedRule - Example: { color: red, font-family: helvetica } * @param {array} allowedDeclarationsList - List of declarations which pass the allowlist. * @param {object} attributeObject - Object representing the current css property. * @property {string} attributeObject.type - Typically 'declaration'. * @property {string} attributeObject.prop - The CSS property, i.e 'color'. * @property {string} attributeObject.value - The corresponding value to the css property, i.e 'red'. * @return {function} - When used in Array.reduce, will return an array of Declaration objects */ function filterDeclarations(selectedRule) { return function (allowedDeclarationsList, attributeObject) { // If this property is allowlisted... if (has(selectedRule, attributeObject.prop)) { const matchesRegex = selectedRule[attributeObject.prop].some( function (regularExpression) { return regularExpression.test(attributeObject.value); }, ); if (matchesRegex) { allowedDeclarationsList.push(attributeObject); } } return allowedDeclarationsList; }; } function filterClasses(classes, allowed, allowedGlobs) { if (!allowed) { // The class attribute is allowed without filtering on this tag return classes; } classes = classes.split(/\s+/); return classes .filter(function (clss) { return ( allowed.indexOf(clss) !== -1 || allowedGlobs.some(function (glob) { return glob.test(clss); }) ); }) .join(' '); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish const htmlParserDefaults = { decodeEntities: true, }; sanitizeHtml.defaults = { allowedTags: [ // Sections derived from MDN element categories and limited to the more // benign categories. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element // Content sectioning 'address', 'article', 'aside', 'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'main', 'nav', 'section', // Text content 'blockquote', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'hr', 'li', 'main', 'ol', 'p', 'pre', 'ul', // Inline text semantics 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'data', 'dfn', 'em', 'i', 'kbd', 'mark', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', // Table content 'caption', 'col', 'colgroup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', ], // Tags that cannot be boolean nonBooleanAttributes: [ 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', 'blocking', 'charset', 'cite', 'class', 'color', 'cols', 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'name', 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap', // Event handlers 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', 'onrejectionhandled', 'onscroll', 'onscrollend', 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', 'onvolumechange', 'onwaiting', 'onwheel', ], disallowedTagsMode: 'discard', allowedAttributes: { a: ['href', 'name', 'target'], // We don't currently allow img itself by default, but // these attributes would make sense if we did. img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading', ], }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta', ], // URL schemes we permit allowedSchemes: ['http', 'https', 'ftp', 'mailto', 'tel'], allowedSchemesByTag: {}, allowedSchemesAppliedToAttributes: ['href', 'src', 'cite'], allowProtocolRelative: true, enforceHtmlBoundary: false, parseStyleAttributes: true, }; sanitizeHtml.simpleTransform = function ( newTagName, newAttribs, merge, ) { merge = merge === undefined ? true : merge; newAttribs = newAttribs || {}; return function (tagName, attribs) { let attrib; if (merge) { for (attrib in newAttribs) { attribs[attrib] = newAttribs[attrib]; } } else { attribs = newAttribs; } return { tagName: newTagName, attribs: attribs, }; }; }; }, { 'deepmerge': 4, 'escape-string-regexp': 26, 'htmlparser2': 29, 'is-plain-object': 31, 'parse-srcset': 33, 'postcss': 50, }, ], 64: [ function (require, module, exports) { const sanitizeHtml = require('sanitize-html'); /** @typedef {{removeExtraParagraphSpacing?: boolean}} Options */ const loadingGif = 'https://raw.githubusercontent.com/LNReader/lnreader/plugins/android/app/src/main/assets/images/loading.gif'; /** * * @param {string} html * @param {Options?} options */ window.sanitizeChapterText = (html, options) => { if (html) { html = html.replace(/</g, '<').replace(/>/g, '>'); } let text = sanitizeHtml(html, { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img', 'i', 'em', 'b', 'a', 'div', ]), allowedAttributes: { img: ['src'], a: ['href'], }, allowedSchemes: ['data', 'http', 'https', 'file'], }); if (text) { if (options?.removeExtraParagraphSpacing) { text = text .replace(/<\s*br[^>]*>/gi, '\n') .replace(/\n{2,}/g, '\n\n'); } const imgHandlerRegex = /]*src="[^"]+"[^>]*)>/g; const ttsHandlerRegex = /(< *\w+ *>[^<.?!]+< *\/\w+ *>|< *a *href *= *"[^"]+" *>\s*(]+>|[^<]+|(< *\w+ *>[^]+< *\/\w+ *>)*)\s*< *\/a *>|< *img[^>]+>|[^<>.?!]+[.?!])/g; // first -> match whole tags which dont have attribute and [.?!] inside // second -> match a tags and its childs // third -> match img tags // match sentence split by [.?!] text = text .replace( imgHandlerRegex, `Plugin can't fetch this img`, ) .replace(ttsHandlerRegex, '$1'); } else { text = 'HTML is empty'; } return text; }; }, { 'sanitize-html': 63 }, ], }, {}, [64], );