(function initHammerheadClient () { (function () { var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn) { var module = { exports: {} }; return fn(module, module.exports), module.exports; } var PENDING = 'pending'; var SETTLED = 'settled'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function () {}; var isNode = typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.process !== 'undefined' && typeof commonjsGlobal.process.emit === 'function'; var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; var asyncQueue = []; var asyncTimer; function asyncFlush() { // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) { asyncQueue[i][0](asyncQueue[i][1]); } // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg) { asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner._state; var value = owner._data; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) { resolve(promise, value); } if (settled === REJECTED) { reject(promise, value); } } } function handleThenable(promise, value) { var resolved; try { if (promise === value) { throw new TypeError('A promises callback cannot return that same promise.'); } if (value && (typeof value === 'function' || typeof value === 'object')) { // then should be retrieved only once var then = value.then; if (typeof then === 'function') { then.call(value, function (val) { if (!resolved) { resolved = true; if (value === val) { fulfill(promise, val); } else { resolve(promise, val); } } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) { reject(promise, e); } return true; } return false; } function resolve(promise, value) { if (promise === value || !handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise._state === PENDING) { promise._state = SETTLED; promise._data = reason; asyncCall(publishRejection, promise); } } function publish(promise) { promise._then = promise._then.forEach(invokeCallback); } function publishFulfillment(promise) { promise._state = FULFILLED; publish(promise); } function publishRejection(promise) { promise._state = REJECTED; publish(promise); if (!promise._handled && isNode) { commonjsGlobal.process.emit('unhandledRejection', promise._data, promise); } } function notifyRejectionHandled(promise) { commonjsGlobal.process.emit('rejectionHandled', promise); } /** * @class */ function Promise$1(resolver) { if (typeof resolver !== 'function') { throw new TypeError('Promise resolver ' + resolver + ' is not a function'); } if (this instanceof Promise$1 === false) { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); } this._then = []; invokeResolver(resolver, this); } Promise$1.prototype = { constructor: Promise$1, _state: PENDING, _then: null, _data: undefined, _handled: false, then: function (onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if ((onRejection || onFulfillment) && !this._handled) { this._handled = true; if (this._state === REJECTED && isNode) { asyncCall(notifyRejectionHandled, this); } } if (this._state === FULFILLED || this._state === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this._then.push(subscriber); } return subscriber.then; }, catch: function (onRejection) { return this.then(null, onRejection); } }; Promise$1.all = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.all().'); } return new Promise$1(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (!--remaining) { resolve(results); } }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolver(i), reject); } else { results[i] = promise; } } if (!remaining) { resolve(results); } }); }; Promise$1.race = function (promises) { if (!Array.isArray(promises)) { throw new TypeError('You must pass an array to Promise.race().'); } return new Promise$1(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); }; Promise$1.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise$1) { return value; } return new Promise$1(function (resolve) { resolve(value); }); }; Promise$1.reject = function (reason) { return new Promise$1(function (resolve, reject) { reject(reason); }); }; var pinkie = Promise$1; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- var INTERNAL_PROPS = { processDomMethodName: 'hammerhead|process-dom-method', processedContext: 'hammerhead|processed-context', documentWasCleaned: 'hammerhead|document-was-cleaned', documentCharset: 'hammerhead|document-charset', iframeNativeMethods: 'hammerhead|iframe-native-methods', hammerhead: '%hammerhead%', selection: 'hammerhead|selection', shadowUIElement: 'hammerhead|shadow-ui-element', forceProxySrcForImage: 'hammerhead|image|force-proxy-src-flag', skipNextLoadEventForImage: 'hammerhead|image|skip-next-load-event-flag', cachedImage: 'hammerhead|image|cached-image', sandboxIsReattached: 'hammerhead|sandbox-is-reattached', nativeStrRepresentation: 'hammerhead|native-string-representation', currentBaseUrl: 'hammerhead|current-base-url', }; var isInWorker = typeof window === 'undefined' && typeof self === 'object'; var global$1 = (isInWorker ? self : window); var globalContextInfo = { isInWorker: isInWorker, global: global$1, isServiceWorker: isInWorker && !global$1.XMLHttpRequest, }; function replaceNativeAccessor(descriptor, accessorName, newAccessor) { if (newAccessor && descriptor[accessorName]) { var stringifiedNativeAccessor_1 = descriptor[accessorName].toString(); newAccessor.toString = function () { return stringifiedNativeAccessor_1; }; } descriptor[accessorName] = newAccessor; } function createOverriddenDescriptor(obj, prop, _a) { var getter = _a.getter, setter = _a.setter, value = _a.value; var descriptor = nativeMethods.objectGetOwnPropertyDescriptor(obj, prop); if ((getter || setter) && value) throw new Error('Cannot both specify accessors and a value or writable attribute.'); if (!descriptor) return void 0; if (value) { if (!nativeMethods.objectHasOwnProperty.call(descriptor, 'writable')) { descriptor.writable = !!descriptor.set; delete descriptor.get; delete descriptor.set; } descriptor.value = value; // eslint-disable-line no-restricted-properties } else { if (nativeMethods.objectHasOwnProperty.call(descriptor, 'writable')) { delete descriptor.value; // eslint-disable-line no-restricted-properties delete descriptor.writable; } if (getter !== null) replaceNativeAccessor(descriptor, 'get', getter); if (setter !== null) replaceNativeAccessor(descriptor, 'set', setter); } return descriptor; } function overrideDescriptor(obj, prop, propertyAccessors) { if (!obj) return; var descriptor = createOverriddenDescriptor(obj, prop, propertyAccessors); if (descriptor) nativeMethods.objectDefineProperty(obj, prop, descriptor); else overrideDescriptor(nativeMethods.objectGetPrototypeOf(obj), prop, propertyAccessors); } function overrideFunctionName(fn, name) { var nameDescriptor = nativeMethods.objectGetOwnPropertyDescriptor(fn, 'name'); if (!nameDescriptor) return; nameDescriptor.value = name; // eslint-disable-line no-restricted-properties nativeMethods.objectDefineProperty(fn, 'name', nameDescriptor); } function overrideToString(nativeFnWrapper, nativeFn) { nativeMethods.objectDefineProperty(nativeFnWrapper, INTERNAL_PROPS.nativeStrRepresentation, { value: nativeMethods.Function.prototype.toString.call(nativeFn), configurable: true, }); } // TODO: this function should not be used outside this file // for now it's used to flag cases in which we assign our wrapper to a native function when it is missing function overrideStringRepresentation(nativeFnWrapper, nativeFn) { overrideFunctionName(nativeFnWrapper, nativeFn.name); overrideToString(nativeFnWrapper, nativeFn); } function isNativeFunction(fn) { return !nativeMethods.objectHasOwnProperty.call(fn, INTERNAL_PROPS.nativeStrRepresentation); } function overrideFunction(obj, fnName, wrapper) { var fn = obj[fnName]; if (isNativeFunction(fn)) { overrideStringRepresentation(wrapper, fn); obj[fnName] = wrapper; } } function overrideConstructor(obj, fnName, wrapper, overrideProtoConstructor) { if (overrideProtoConstructor === void 0) { overrideProtoConstructor = false; } var nativePrototype = obj[fnName]['prototype']; overrideFunction(obj, fnName, wrapper); // NOTE: restore native prototype (to make `instanceof` work as expected) wrapper.prototype = nativePrototype; // NOTE: we need to override the `constructor` property of a prototype // because sometimes native constructor can be retrieved from it if (overrideProtoConstructor) nativePrototype.constructor = wrapper; } var overridingUtils = /*#__PURE__*/Object.freeze({ __proto__: null, createOverriddenDescriptor: createOverriddenDescriptor, overrideDescriptor: overrideDescriptor, overrideStringRepresentation: overrideStringRepresentation, isNativeFunction: isNativeFunction, overrideFunction: overrideFunction, overrideConstructor: overrideConstructor }); /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ var bowser = createCommonjsModule(function (module) { !function (root, name, definition) { if (module.exports) module.exports = definition(); else root[name] = definition(); }(commonjsGlobal, 'bowser', function () { /** * See useragents.js for examples of navigator.userAgent */ var t = true; function detect(ua) { function getFirstMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[1]) || ''; } function getSecondMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[2]) || ''; } var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase() , likeAndroid = /like android/i.test(ua) , android = !likeAndroid && /android/i.test(ua) , nexusMobile = /nexus\s*[0-6]\s*/i.test(ua) , nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua) , chromeos = /CrOS/.test(ua) , silk = /silk/i.test(ua) , sailfish = /sailfish/i.test(ua) , tizen = /tizen/i.test(ua) , webos = /(web|hpw)os/i.test(ua) , windowsphone = /windows phone/i.test(ua) ; /SamsungBrowser/i.test(ua) ; var windows = !windowsphone && /windows/i.test(ua) , mac = !iosdevice && !silk && /macintosh/i.test(ua) , linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua) , edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i) , versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i) , tablet = /tablet/i.test(ua) , mobile = !tablet && /[^-]mobi/i.test(ua) , xbox = /xbox/i.test(ua) , result; if (/opera/i.test(ua)) { // an old Opera result = { name: 'Opera' , opera: t , version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i) }; } else if (/opr|opios/i.test(ua)) { // a new Opera result = { name: 'Opera' , opera: t , version: getFirstMatch(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/SamsungBrowser/i.test(ua)) { result = { name: 'Samsung Internet for Android' , samsungBrowser: t , version: versionIdentifier || getFirstMatch(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i) }; } else if (/coast/i.test(ua)) { result = { name: 'Opera Coast' , coast: t , version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i) }; } else if (/yabrowser/i.test(ua)) { result = { name: 'Yandex Browser' , yandexbrowser: t , version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i) }; } else if (/ucbrowser/i.test(ua)) { result = { name: 'UC Browser' , ucbrowser: t , version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/mxios/i.test(ua)) { result = { name: 'Maxthon' , maxthon: t , version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/epiphany/i.test(ua)) { result = { name: 'Epiphany' , epiphany: t , version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/puffin/i.test(ua)) { result = { name: 'Puffin' , puffin: t , version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i) }; } else if (/sleipnir/i.test(ua)) { result = { name: 'Sleipnir' , sleipnir: t , version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/k-meleon/i.test(ua)) { result = { name: 'K-Meleon' , kMeleon: t , version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (windowsphone) { result = { name: 'Windows Phone' , windowsphone: t }; if (edgeVersion) { result.msedge = t; result.version = edgeVersion; } else { result.msie = t; result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i); } } else if (/msie|trident/i.test(ua)) { result = { name: 'Internet Explorer' , msie: t , version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) }; } else if (chromeos) { result = { name: 'Chrome' , chromeos: t , chromeBook: t , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) }; } else if (/chrome.+? edge/i.test(ua)) { result = { name: 'Microsoft Edge' , msedge: t , version: edgeVersion }; } else if (/vivaldi/i.test(ua)) { result = { name: 'Vivaldi' , vivaldi: t , version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (sailfish) { result = { name: 'Sailfish' , sailfish: t , version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) }; } else if (/seamonkey\//i.test(ua)) { result = { name: 'SeaMonkey' , seamonkey: t , version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) }; } else if (/firefox|iceweasel|fxios/i.test(ua)) { result = { name: 'Firefox' , firefox: t , version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i) }; if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { result.firefoxos = t; } } else if (silk) { result = { name: 'Amazon Silk' , silk: t , version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i) }; } else if (/phantom/i.test(ua)) { result = { name: 'PhantomJS' , phantom: t , version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) }; } else if (/slimerjs/i.test(ua)) { result = { name: 'SlimerJS' , slimer: t , version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i) }; } else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { result = { name: 'BlackBerry' , blackberry: t , version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) }; } else if (webos) { result = { name: 'WebOS' , webos: t , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) }; /touchpad\//i.test(ua) && (result.touchpad = t); } else if (/bada/i.test(ua)) { result = { name: 'Bada' , bada: t , version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) }; } else if (tizen) { result = { name: 'Tizen' , tizen: t , version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/qupzilla/i.test(ua)) { result = { name: 'QupZilla' , qupzilla: t , version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier }; } else if (/chromium/i.test(ua)) { result = { name: 'Chromium' , chromium: t , version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier }; } else if (/chrome|crios|crmo/i.test(ua)) { result = { name: 'Chrome' , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) }; } else if (android) { result = { name: 'Android' , version: versionIdentifier }; } else if (/safari|applewebkit/i.test(ua)) { result = { name: 'Safari' , safari: t }; if (versionIdentifier) { result.version = versionIdentifier; } } else if (iosdevice) { result = { name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' }; // WTF: version is not part of user agent in web apps if (versionIdentifier) { result.version = versionIdentifier; } } else if(/googlebot/i.test(ua)) { result = { name: 'Googlebot' , googlebot: t , version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier }; } else { result = { name: getFirstMatch(/^(.*)\/(.*) /), version: getSecondMatch(/^(.*)\/(.*) /) }; } // set webkit or gecko flag for browsers based on these engines if (!result.msedge && /(apple)?webkit/i.test(ua)) { if (/(apple)?webkit\/537\.36/i.test(ua)) { result.name = result.name || "Blink"; result.blink = t; } else { result.name = result.name || "Webkit"; result.webkit = t; } if (!result.version && versionIdentifier) { result.version = versionIdentifier; } } else if (!result.opera && /gecko\//i.test(ua)) { result.name = result.name || "Gecko"; result.gecko = t; result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i); } // set OS flags for platforms that have multiple browsers if (!result.windowsphone && !result.msedge && (android || result.silk)) { result.android = t; } else if (!result.windowsphone && !result.msedge && iosdevice) { result[iosdevice] = t; result.ios = t; } else if (mac) { result.mac = t; } else if (xbox) { result.xbox = t; } else if (windows) { result.windows = t; } else if (linux) { result.linux = t; } // OS version extraction var osVersion = ''; if (result.windowsphone) { osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); } else if (iosdevice) { osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (android) { osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); } else if (result.webos) { osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); } else if (result.blackberry) { osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); } else if (result.bada) { osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); } else if (result.tizen) { osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); } if (osVersion) { result.osversion = osVersion; } // device type extraction var osMajorVersion = osVersion.split('.')[0]; if ( tablet || nexusTablet || iosdevice == 'ipad' || (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile))) || result.silk ) { result.tablet = t; } else if ( mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || nexusMobile || result.blackberry || result.webos || result.bada ) { result.mobile = t; } // Graded Browser Support // http://developer.yahoo.com/yui/articles/gbs if (result.msedge || (result.msie && result.version >= 10) || (result.yandexbrowser && result.version >= 15) || (result.vivaldi && result.version >= 1.0) || (result.chrome && result.version >= 20) || (result.samsungBrowser && result.version >= 4) || (result.firefox && result.version >= 20.0) || (result.safari && result.version >= 6) || (result.opera && result.version >= 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] >= 6) || (result.blackberry && result.version >= 10.1) || (result.chromium && result.version >= 20) ) { result.a = t; } else if ((result.msie && result.version < 10) || (result.chrome && result.version < 20) || (result.firefox && result.version < 20.0) || (result.safari && result.version < 6) || (result.opera && result.version < 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] < 6) || (result.chromium && result.version < 20) ) { result.c = t; } else result.x = t; return result } var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent || '' : ''); bowser.test = function (browserList) { for (var i = 0; i < browserList.length; ++i) { var browserItem = browserList[i]; if (typeof browserItem=== 'string') { if (browserItem in bowser) { return true; } } } return false; }; /** * Get version precisions count * * @example * getVersionPrecision("1.10.3") // 3 * * @param {string} version * @return {number} */ function getVersionPrecision(version) { return version.split(".").length; } /** * Array::map polyfill * * @param {Array} arr * @param {Function} iterator * @return {Array} */ function map(arr, iterator) { var result = [], i; if (Array.prototype.map) { return Array.prototype.map.call(arr, iterator); } for (i = 0; i < arr.length; i++) { result.push(iterator(arr[i])); } return result; } /** * Calculate browser version weight * * @example * compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1 * compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1 * compareVersions(['1.10.2.1', '1.10.2.1']); // 0 * compareVersions(['1.10.2.1', '1.0800.2']); // -1 * * @param {Array} versions versions to compare * @return {Number} comparison result */ function compareVersions(versions) { // 1) get common precision for both versions, for example for "10.0" and "9" it should be 2 var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1])); var chunks = map(versions, function (version) { var delta = precision - getVersionPrecision(version); // 2) "9" -> "9.0" (for precision = 2) version = version + new Array(delta + 1).join(".0"); // 3) "9.0" -> ["000000000"", "000000009"] return map(version.split("."), function (chunk) { return new Array(20 - chunk.length).join("0") + chunk; }).reverse(); }); // iterate in reverse order by reversed chunks array while (--precision >= 0) { // 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true) if (chunks[0][precision] > chunks[1][precision]) { return 1; } else if (chunks[0][precision] === chunks[1][precision]) { if (precision === 0) { // all version chunks are same return 0; } } else { return -1; } } } /** * Check if browser is unsupported * * @example * bowser.isUnsupportedBrowser({ * msie: "10", * firefox: "23", * chrome: "29", * safari: "5.1", * opera: "16", * phantom: "534" * }); * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @param {String} [ua] user agent string * @return {Boolean} */ function isUnsupportedBrowser(minVersions, strictMode, ua) { var _bowser = bowser; // make strictMode param optional with ua param usage if (typeof strictMode === 'string') { ua = strictMode; strictMode = void(0); } if (strictMode === void(0)) { strictMode = false; } if (ua) { _bowser = detect(ua); } var version = "" + _bowser.version; for (var browser in minVersions) { if (minVersions.hasOwnProperty(browser)) { if (_bowser[browser]) { if (typeof minVersions[browser] !== 'string') { throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions)); } // browser version and min supported version. return compareVersions([version, minVersions[browser]]) < 0; } } } return strictMode; // not found } /** * Check if browser is supported * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @param {String} [ua] user agent string * @return {Boolean} */ function check(minVersions, strictMode, ua) { return !isUnsupportedBrowser(minVersions, strictMode, ua); } bowser.isUnsupportedBrowser = isUnsupportedBrowser; bowser.compareVersions = compareVersions; bowser.check = check; /* * Set our detect method to the main bowser object so we can * reuse it to test other user agents. * This is needed to implement future tests. */ bowser._detect = detect; return bowser }); }); var userAgent = navigator.userAgent.toLowerCase(); //@ts-ignore var info = bowser._detect(userAgent); var webkitVersionMatch = userAgent.match(/applewebkit\/(\d+(:?\.\d+)*)/); //Helper //@ts-ignore var compareVersions = bowser.compareVersions; //Platforms var isMacPlatform = !!info.mac; var isAndroid = !!info.android; var isIOS = !!info.ios; var isMobile = !!info.mobile; var isTablet = !!info.tablet; //Browsers var version = parseInt(info.version, 10); var fullVersion = info.version; var webkitVersion = webkitVersionMatch && webkitVersionMatch[1] || ''; var isIE = !!(info.msie || info.msedge); var isIE11 = isIE && version === 11; var isIE10 = isIE && version === 10; var isIE9 = isIE && version === 9; var isFirefox = !!info.firefox; var isMSEdge = !!info.msedge; var isChrome = !!info.chrome; var isSafari = !!info.safari; var isWebKit = !!(info.webkit || info.blink); var isElectron = /electron/g.test(userAgent); var browserUtils = /*#__PURE__*/Object.freeze({ __proto__: null, compareVersions: compareVersions, isMacPlatform: isMacPlatform, isAndroid: isAndroid, isIOS: isIOS, isMobile: isMobile, isTablet: isTablet, version: version, fullVersion: fullVersion, webkitVersion: webkitVersion, isIE: isIE, isIE11: isIE11, isIE10: isIE10, isIE9: isIE9, isFirefox: isFirefox, isMSEdge: isMSEdge, isChrome: isChrome, isSafari: isSafari, isWebKit: isWebKit, isElectron: isElectron }); function inaccessibleTypeToStr(obj) { return obj === null ? 'null' : 'undefined'; } function isNullOrUndefined(obj) { return obj === null || obj === void 0; } function isPrimitiveType(obj) { var objType = typeof obj; return objType !== 'object' && objType !== 'function'; } function isNull(obj) { //Some times IE cannot compare null correctly return isIE // eslint-disable-next-line eqeqeq ? obj == null : obj === null; } function isNumber(val) { return typeof val === 'number'; } function isFunction(val) { return typeof val === 'function'; } var typeUtils = /*#__PURE__*/Object.freeze({ __proto__: null, inaccessibleTypeToStr: inaccessibleTypeToStr, isNullOrUndefined: isNullOrUndefined, isPrimitiveType: isPrimitiveType, isNull: isNull, isNumber: isNumber, isFunction: isFunction }); /*global Document, Window */ var NATIVE_CODE_RE = /\[native code]/; var NativeMethods = /** @class */ (function () { function NativeMethods(doc, win) { win = win || globalContextInfo.global; this.refreshWindowMeths(win, globalContextInfo.isInWorker); this.refreshWorkerMeths(win); if (globalContextInfo.isInWorker) return; this.refreshDocumentMeths(doc, win); this.refreshElementMeths(doc, win); } NativeMethods._getDocumentPropOwnerName = function (docPrototype, propName) { return docPrototype.hasOwnProperty(propName) ? 'Document' : 'HTMLDocument'; // eslint-disable-line no-prototype-builtins }; NativeMethods.prototype.getStoragesPropsOwner = function (win) { return this.isStoragePropsLocatedInProto ? win.Window.prototype : win; }; NativeMethods.prototype.refreshWorkerMeths = function (scope /* WorkerGlobalScope */) { this.importScripts = scope.importScripts; }; NativeMethods.prototype.refreshDocumentMeths = function (doc, win) { doc = doc || document; win = win || window; var docPrototype = win.Document.prototype; // Dom this.createDocumentFragment = docPrototype.createDocumentFragment; this.createElement = docPrototype.createElement; this.createElementNS = docPrototype.createElementNS; this.createTextNode = docPrototype.createTextNode; this.documentOpenPropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'open'); this.documentClosePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'close'); this.documentWritePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'write'); this.documentWriteLnPropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'writeln'); this.documentOpen = win[this.documentOpenPropOwnerName].prototype.open; this.documentClose = win[this.documentClosePropOwnerName].prototype.close; this.documentWrite = win[this.documentWritePropOwnerName].prototype.write; this.documentWriteLn = win[this.documentWriteLnPropOwnerName].prototype.writeln; this.elementFromPoint = docPrototype.elementFromPoint; this.caretRangeFromPoint = docPrototype.caretRangeFromPoint; // @ts-ignore Experimental method in Firefox this.caretPositionFromPoint = docPrototype.caretPositionFromPoint; this.getElementById = docPrototype.getElementById; this.getElementsByClassName = docPrototype.getElementsByClassName; this.getElementsByName = docPrototype.getElementsByName; this.getElementsByTagName = docPrototype.getElementsByTagName; this.querySelector = docPrototype.querySelector; this.querySelectorAll = docPrototype.querySelectorAll; this.createHTMLDocument = win.DOMImplementation.prototype.createHTMLDocument; // @ts-ignore if (doc.registerElement) { // @ts-ignore this.registerElement = docPrototype.registerElement; } // Event // NOTE: IE11 has no EventTarget so we should save "Event" methods separately if (!win.EventTarget) { this.documentAddEventListener = docPrototype.addEventListener; this.documentRemoveEventListener = docPrototype.removeEventListener; } this.documentCreateEvent = docPrototype.createEvent; // @ts-ignore Deprecated this.documentCreateTouch = docPrototype.createTouch; // @ts-ignore Deprecated this.documentCreateTouchList = docPrototype.createTouchList; // getters/setters this.documentCookiePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'cookie'); var documentCookieDescriptor = win.Object.getOwnPropertyDescriptor(win[this.documentCookiePropOwnerName].prototype, 'cookie'); // TODO: remove this condition after the GH-1649 fix if (!this.isNativeCode(documentCookieDescriptor.get) || !this.isNativeCode(documentCookieDescriptor.get.toString)) { try { var parentNativeMethods = win.parent['%hammerhead%'].nativeMethods; documentCookieDescriptor.get = parentNativeMethods.documentCookieGetter; documentCookieDescriptor.set = parentNativeMethods.documentCookieSetter; } catch (_a) { } // eslint-disable-line no-empty } this.documentReferrerGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'referrer').get; this.documentStyleSheetsGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'styleSheets').get; this.documentActiveElementGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'activeElement').get; this.documentCookieGetter = documentCookieDescriptor.get; this.documentCookieSetter = documentCookieDescriptor.set; var documentDocumentURIDescriptor = win.Object.getOwnPropertyDescriptor(docPrototype, 'documentURI'); if (documentDocumentURIDescriptor) this.documentDocumentURIGetter = documentDocumentURIDescriptor.get; var documentTitleDescriptor = win.Object.getOwnPropertyDescriptor(docPrototype, 'title'); this.documentTitleGetter = documentTitleDescriptor.get; this.documentTitleSetter = documentTitleDescriptor.set; }; NativeMethods.prototype.refreshElementMeths = function (doc, win) { var _this = this; win = win || window; var createElement = (function (tagName) { return _this.createElement.call(doc || document, tagName); }); var nativeElement = createElement('div'); var createTextNode = function (data) { return _this.createTextNode.call(doc || document, data); }; var textNode = createTextNode('text'); // Dom this.appendChild = win.Node.prototype.appendChild; this.append = win.Element.prototype.append; this.prepend = win.Element.prototype.prepend; this.after = win.Element.prototype.after; this.attachShadow = win.Element.prototype.attachShadow; this.replaceChild = nativeElement.replaceChild; this.cloneNode = nativeElement.cloneNode; this.elementGetElementsByClassName = nativeElement.getElementsByClassName; this.elementGetElementsByTagName = nativeElement.getElementsByTagName; this.elementQuerySelector = nativeElement.querySelector; this.elementQuerySelectorAll = nativeElement.querySelectorAll; this.getAttribute = nativeElement.getAttribute; this.getAttributeNS = nativeElement.getAttributeNS; this.getAttributeNode = nativeElement.getAttributeNode; this.getAttributeNodeNS = nativeElement.getAttributeNodeNS; this.insertBefore = nativeElement.insertBefore; this.insertCell = createElement('tr').insertCell; this.insertTableRow = createElement('table').insertRow; this.insertTBodyRow = createElement('tbody').insertRow; this.removeAttribute = nativeElement.removeAttribute; this.removeAttributeNS = nativeElement.removeAttributeNS; this.removeAttributeNode = nativeElement.removeAttributeNode; this.removeChild = win.Node.prototype.removeChild; this.remove = win.Element.prototype.remove; this.elementReplaceWith = win.Element.prototype.replaceWith; this.setAttribute = nativeElement.setAttribute; this.setAttributeNS = nativeElement.setAttributeNS; this.hasAttribute = nativeElement.hasAttribute; this.hasAttributeNS = nativeElement.hasAttributeNS; this.hasAttributes = nativeElement.hasAttributes; this.anchorToString = win.HTMLAnchorElement.prototype.toString; this.matches = nativeElement.matches || nativeElement.msMatchesSelector; this.closest = nativeElement.closest; // NOTE: The 'insertAdjacent...' methods is located in HTMLElement prototype in IE11 only this.insertAdjacentMethodsOwner = win.Element.prototype.hasOwnProperty('insertAdjacentElement') // eslint-disable-line no-prototype-builtins ? win.Element.prototype : win.HTMLElement.prototype; this.insertAdjacentElement = this.insertAdjacentMethodsOwner.insertAdjacentElement; this.insertAdjacentHTML = this.insertAdjacentMethodsOwner.insertAdjacentHTML; this.insertAdjacentText = this.insertAdjacentMethodsOwner.insertAdjacentText; // Text node this.appendData = textNode.appendData; // TODO: remove this condition after the GH-1649 fix if (!this.isNativeCode(this.elementGetElementsByTagName)) { try { var parentNativeMethods = win.parent['%hammerhead%'].nativeMethods; this.elementGetElementsByTagName = parentNativeMethods.elementGetElementsByTagName; } // eslint-disable-next-line no-empty catch (e) { } } // Event if (win.EventTarget) { this.addEventListener = win.EventTarget.prototype.addEventListener; this.removeEventListener = win.EventTarget.prototype.removeEventListener; this.dispatchEvent = win.EventTarget.prototype.dispatchEvent; } // NOTE: IE11 has no EventTarget else { this.addEventListener = nativeElement.addEventListener; this.removeEventListener = nativeElement.removeEventListener; this.dispatchEvent = nativeElement.dispatchEvent; } this.blur = nativeElement.blur; this.click = nativeElement.click; this.focus = nativeElement.focus; // @ts-ignore this.select = window.TextRange ? createElement('body').createTextRange().select : null; this.setSelectionRange = createElement('input').setSelectionRange; this.textAreaSetSelectionRange = createElement('textarea').setSelectionRange; this.svgFocus = win.SVGElement ? win.SVGElement.prototype.focus : this.focus; this.svgBlur = win.SVGElement ? win.SVGElement.prototype.blur : this.blur; // Style // NOTE: The 'style' descriptor is located in the Element.prototype in the Safari on IOS this.htmlElementStylePropOwnerName = win.Element.prototype.hasOwnProperty('style') ? 'Element' : 'HTMLElement'; // eslint-disable-line no-prototype-builtins var htmlElementStyleDescriptor = win.Object.getOwnPropertyDescriptor(win[this.htmlElementStylePropOwnerName].prototype, 'style'); this.htmlElementStyleGetter = htmlElementStyleDescriptor.get; // NOTE: IE does not allow to set a style property if (htmlElementStyleDescriptor.set) this.htmlElementStyleSetter = htmlElementStyleDescriptor.set; var styleCssTextDescriptor = win.Object.getOwnPropertyDescriptor(win.CSSStyleDeclaration.prototype, 'cssText'); this.styleCssTextGetter = styleCssTextDescriptor.get; this.styleCssTextSetter = styleCssTextDescriptor.set; }; NativeMethods.prototype._refreshGettersAndSetters = function (win, isInWorker) { if (isInWorker === void 0) { isInWorker = false; } win = win || window; var winProto = win.constructor.prototype; // NOTE: Event properties is located in window prototype only in IE11 this.isEventPropsLocatedInProto = winProto.hasOwnProperty('onerror'); // eslint-disable-line no-prototype-builtins var eventPropsOwner = this.isEventPropsLocatedInProto ? winProto : win; var winOnBeforeUnloadDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onbeforeunload'); var winOnUnloadDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onunload'); var winOnPageHideDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onpagehide'); var winOnMessageDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onmessage'); var winOnErrorDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onerror'); var winOnHashChangeDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onhashchange'); this.winOnBeforeUnloadSetter = winOnBeforeUnloadDescriptor && winOnBeforeUnloadDescriptor.set; this.winOnUnloadSetter = winOnUnloadDescriptor && winOnUnloadDescriptor.set; this.winOnPageHideSetter = winOnPageHideDescriptor && winOnPageHideDescriptor.set; this.winOnMessageSetter = winOnMessageDescriptor && winOnMessageDescriptor.set; this.winOnErrorSetter = winOnErrorDescriptor && winOnErrorDescriptor.set; this.winOnHashChangeSetter = winOnHashChangeDescriptor && winOnHashChangeDescriptor.set; var winOnUnhandledRejectionDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onunhandledrejection'); if (winOnUnhandledRejectionDescriptor) this.winOnUnhandledRejectionSetter = winOnUnhandledRejectionDescriptor.set; // Getters if (win.WebSocket) { var urlPropDescriptor = win.Object.getOwnPropertyDescriptor(win.WebSocket.prototype, 'url'); if (urlPropDescriptor && urlPropDescriptor.get && urlPropDescriptor.configurable) this.webSocketUrlGetter = urlPropDescriptor.get; } this.messageEventOriginGetter = win.Object.getOwnPropertyDescriptor(win.MessageEvent.prototype, 'origin').get; // NOTE: At present we proxy only the PerformanceNavigationTiming. // Another types of the PerformanceEntry will be fixed later // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry if (win.PerformanceNavigationTiming) this.performanceEntryNameGetter = win.Object.getOwnPropertyDescriptor(win.PerformanceEntry.prototype, 'name').get; var dataPropDescriptor = win.Object.getOwnPropertyDescriptor(win.MessageEvent.prototype, 'data'); // NOTE: This condition is used for the Android 6.0 browser if (dataPropDescriptor) this.messageEventDataGetter = dataPropDescriptor.get; if (win.fetch) { this.responseStatusGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'status').get; this.responseTypeGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'type').get; this.responseUrlGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'url').get; this.requestUrlGetter = win.Object.getOwnPropertyDescriptor(win.Request.prototype, 'url').get; this.requestReferrerGetter = win.Object.getOwnPropertyDescriptor(win.Request.prototype, 'referrer').get; } if (win.XMLHttpRequest) { var xhrResponseURLDescriptor = win.Object.getOwnPropertyDescriptor(win.XMLHttpRequest.prototype, 'responseURL'); // NOTE: IE doesn't support the 'responseURL' property if (xhrResponseURLDescriptor) this.xhrResponseURLGetter = xhrResponseURLDescriptor.get; } // eslint-disable-next-line no-restricted-properties if (win.Window) { // NOTE: The 'localStorage' and 'sessionStorage' properties is located in window prototype only in IE11 this.isStoragePropsLocatedInProto = win.Window.prototype.hasOwnProperty('localStorage'); // eslint-disable-line no-prototype-builtins var storagesPropsOwner = this.getStoragesPropsOwner(win); this.winLocalStorageGetter = win.Object.getOwnPropertyDescriptor(storagesPropsOwner, 'localStorage').get; this.winSessionStorageGetter = win.Object.getOwnPropertyDescriptor(storagesPropsOwner, 'sessionStorage').get; } if (isInWorker) return; this.storageGetItem = win.Storage.prototype.getItem; this.storageSetItem = win.Storage.prototype.setItem; this.storageRemoveItem = win.Storage.prototype.removeItem; this.storageClear = win.Storage.prototype.clear; this.storageKey = win.Storage.prototype.key; this.storageLengthGetter = win.Object.getOwnPropertyDescriptor(win.Storage.prototype, 'length'); var objectDataDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLObjectElement.prototype, 'data'); var inputTypeDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'type'); var inputValueDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'value'); var inputDisabledDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'disabled'); var inputRequiredDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'required'); var textAreaValueDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLTextAreaElement.prototype, 'value'); var imageSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLImageElement.prototype, 'src'); var imageSrcsetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLImageElement.prototype, 'srcset'); var scriptSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'src'); var scriptIntegrityDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'integrity'); var embedSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLEmbedElement.prototype, 'src'); var sourceSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLSourceElement.prototype, 'src'); var mediaSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLMediaElement.prototype, 'src'); var inputSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'src'); var frameSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFrameElement.prototype, 'src'); var iframeSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'src'); var anchorHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'href'); var linkHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'href'); var linkIntegrityDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'integrity'); var linkRelDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'rel'); var linkAsDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'as'); var areaHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAreaElement.prototype, 'href'); var baseHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLBaseElement.prototype, 'href'); var anchorHostDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'host'); var anchorHostnameDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'hostname'); var anchorPathnameDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'pathname'); var anchorPortDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'port'); var anchorProtocolDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'protocol'); var anchorSearchDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'search'); var anchorTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'target'); var formTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFormElement.prototype, 'target'); var areaTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAreaElement.prototype, 'target'); var baseTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLBaseElement.prototype, 'target'); var inputFormTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'formTarget'); var buttonFormTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLButtonElement.prototype, 'formTarget'); var svgImageHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGImageElement.prototype, 'href'); var svgAnimStrAnimValDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGAnimatedString.prototype, 'animVal'); var svgAnimStrBaseValDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGAnimatedString.prototype, 'baseVal'); var inputAutocompleteDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'autocomplete'); var formActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFormElement.prototype, 'action'); var inputFormActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'formAction'); var buttonFormActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLButtonElement.prototype, 'formAction'); var nodeTextContentDescriptor = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'textContent'); var htmlElementInnerTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'innerText'); var scriptTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'text'); var anchorTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'text'); var titleElementTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLTitleElement.prototype, 'text'); var iframeSandboxDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'sandbox'); var metaHttpEquivDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLMetaElement.prototype, 'httpEquiv'); var windowOriginDescriptor = win.Object.getOwnPropertyDescriptor(win, 'origin'); if (windowOriginDescriptor) { this.windowOriginGetter = windowOriginDescriptor.get; this.windowOriginSetter = windowOriginDescriptor.set; } // NOTE: We need 'disabled' property only for Chrome. // In Chrome it's located in HTMLInputElement.prototype // But in IE11 it's located in HTMLElement.prototype // So we need the null check if (inputDisabledDescriptor) { this.inputDisabledSetter = inputDisabledDescriptor.set; this.inputDisabledGetter = inputDisabledDescriptor.get; } // NOTE: Html properties is located in HTMLElement prototype in IE11 only this.elementHTMLPropOwnerName = win.Element.prototype.hasOwnProperty('innerHTML') ? 'Element' : 'HTMLElement'; // eslint-disable-line no-prototype-builtins var elementInnerHTMLDescriptor = win.Object.getOwnPropertyDescriptor(win[this.elementHTMLPropOwnerName].prototype, 'innerHTML'); var elementOuterHTMLDescriptor = win.Object.getOwnPropertyDescriptor(win[this.elementHTMLPropOwnerName].prototype, 'outerHTML'); // Setters this.objectDataSetter = objectDataDescriptor.set; this.inputTypeSetter = inputTypeDescriptor.set; this.inputValueSetter = inputValueDescriptor.set; this.inputRequiredSetter = inputRequiredDescriptor.set; this.textAreaValueSetter = textAreaValueDescriptor.set; this.imageSrcSetter = imageSrcDescriptor.set; this.scriptSrcSetter = scriptSrcDescriptor.set; this.embedSrcSetter = embedSrcDescriptor.set; this.sourceSrcSetter = sourceSrcDescriptor.set; this.mediaSrcSetter = mediaSrcDescriptor.set; this.inputSrcSetter = inputSrcDescriptor.set; this.frameSrcSetter = frameSrcDescriptor.set; this.iframeSrcSetter = iframeSrcDescriptor.set; this.anchorHrefSetter = anchorHrefDescriptor.set; this.linkHrefSetter = linkHrefDescriptor.set; this.linkRelSetter = linkRelDescriptor.set; this.linkAsSetter = linkAsDescriptor && linkAsDescriptor.set; this.areaHrefSetter = areaHrefDescriptor.set; this.baseHrefSetter = baseHrefDescriptor.set; this.anchorHostSetter = anchorHostDescriptor.set; this.anchorHostnameSetter = anchorHostnameDescriptor.set; this.anchorPathnameSetter = anchorPathnameDescriptor.set; this.anchorPortSetter = anchorPortDescriptor.set; this.anchorProtocolSetter = anchorProtocolDescriptor.set; this.anchorSearchSetter = anchorSearchDescriptor.set; this.anchorTargetSetter = anchorTargetDescriptor.set; this.formTargetSetter = formTargetDescriptor.set; this.areaTargetSetter = areaTargetDescriptor.set; this.baseTargetSetter = baseTargetDescriptor.set; this.inputFormTargetSetter = inputFormTargetDescriptor.set; this.buttonFormTargetSetter = buttonFormTargetDescriptor.set; this.svgAnimStrBaseValSetter = svgAnimStrBaseValDescriptor.set; this.inputAutocompleteSetter = inputAutocompleteDescriptor.set; this.formActionSetter = formActionDescriptor.set; this.inputFormActionSetter = inputFormActionDescriptor.set; this.buttonFormActionSetter = buttonFormActionDescriptor.set; this.iframeSandboxSetter = iframeSandboxDescriptor.set; this.metaHttpEquivSetter = metaHttpEquivDescriptor.set; this.htmlElementOnloadSetter = win.Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onload').set; this.nodeTextContentSetter = nodeTextContentDescriptor.set; this.htmlElementInnerTextSetter = htmlElementInnerTextDescriptor.set; this.scriptTextSetter = scriptTextDescriptor.set; this.anchorTextSetter = anchorTextDescriptor.set; this.elementInnerHTMLSetter = elementInnerHTMLDescriptor.set; this.elementOuterHTMLSetter = elementOuterHTMLDescriptor.set; // NOTE: Some browsers (for example, Edge, Internet Explorer 11, Safari) don't support the 'integrity' property. if (scriptIntegrityDescriptor && linkIntegrityDescriptor) { this.scriptIntegritySetter = scriptIntegrityDescriptor.set; this.linkIntegritySetter = linkIntegrityDescriptor.set; } this.titleElementTextSetter = titleElementTextDescriptor.set; // NOTE: the classList property is located in HTMLElement prototype in IE11 this.elementClassListPropOwnerName = win.Element.prototype.hasOwnProperty('classList') ? 'Element' : 'HTMLElement'; // eslint-disable-line no-prototype-builtins this.elementClassListGetter = win.Object.getOwnPropertyDescriptor(win[this.elementClassListPropOwnerName].prototype, 'classList').get; this.htmlCollectionLengthGetter = win.Object.getOwnPropertyDescriptor(win.HTMLCollection.prototype, 'length').get; this.nodeListLengthGetter = win.Object.getOwnPropertyDescriptor(win.NodeList.prototype, 'length').get; this.elementChildElementCountGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'childElementCount').get; this.inputFilesGetter = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'files').get; this.styleSheetHrefGetter = win.Object.getOwnPropertyDescriptor(win.StyleSheet.prototype, 'href').get; this.objectDataGetter = objectDataDescriptor.get; this.inputTypeGetter = inputTypeDescriptor.get; this.inputValueGetter = inputValueDescriptor.get; this.inputRequiredGetter = inputRequiredDescriptor.get; this.textAreaValueGetter = textAreaValueDescriptor.get; this.imageSrcGetter = imageSrcDescriptor.get; this.scriptSrcGetter = scriptSrcDescriptor.get; this.embedSrcGetter = embedSrcDescriptor.get; this.sourceSrcGetter = sourceSrcDescriptor.get; this.mediaSrcGetter = mediaSrcDescriptor.get; this.inputSrcGetter = inputSrcDescriptor.get; this.frameSrcGetter = frameSrcDescriptor.get; this.iframeSrcGetter = iframeSrcDescriptor.get; this.anchorHrefGetter = anchorHrefDescriptor.get; this.linkHrefGetter = linkHrefDescriptor.get; this.linkRelGetter = linkRelDescriptor.get; this.areaHrefGetter = areaHrefDescriptor.get; this.baseHrefGetter = baseHrefDescriptor.get; this.anchorHostGetter = anchorHostDescriptor.get; this.anchorHostnameGetter = anchorHostnameDescriptor.get; this.anchorPathnameGetter = anchorPathnameDescriptor.get; this.anchorPortGetter = anchorPortDescriptor.get; this.anchorProtocolGetter = anchorProtocolDescriptor.get; this.anchorSearchGetter = anchorSearchDescriptor.get; this.anchorTargetGetter = anchorTargetDescriptor.get; this.formTargetGetter = formTargetDescriptor.get; this.areaTargetGetter = areaTargetDescriptor.get; this.baseTargetGetter = baseTargetDescriptor.get; this.inputFormTargetGetter = inputFormTargetDescriptor.get; this.buttonFormTargetGetter = buttonFormTargetDescriptor.get; this.svgImageHrefGetter = svgImageHrefDescriptor.get; this.svgAnimStrAnimValGetter = svgAnimStrAnimValDescriptor.get; this.svgAnimStrBaseValGetter = svgAnimStrBaseValDescriptor.get; this.inputAutocompleteGetter = inputAutocompleteDescriptor.get; this.formActionGetter = formActionDescriptor.get; this.inputFormActionGetter = inputFormActionDescriptor.get; this.buttonFormActionGetter = buttonFormActionDescriptor.get; this.iframeSandboxGetter = iframeSandboxDescriptor.get; this.metaHttpEquivGetter = metaHttpEquivDescriptor.get; this.contentWindowGetter = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'contentWindow').get; this.contentDocumentGetter = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'contentDocument').get; this.frameContentWindowGetter = win.Object.getOwnPropertyDescriptor(win.HTMLFrameElement.prototype, 'contentWindow').get; this.nodeTextContentGetter = nodeTextContentDescriptor.get; this.htmlElementInnerTextGetter = htmlElementInnerTextDescriptor.get; this.scriptTextGetter = scriptTextDescriptor.get; this.anchorTextGetter = anchorTextDescriptor.get; this.elementInnerHTMLGetter = elementInnerHTMLDescriptor.get; this.elementOuterHTMLGetter = elementOuterHTMLDescriptor.get; this.nodeFirstChildGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'firstChild').get; this.nodeLastChildGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'lastChild').get; this.nodeNextSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'nextSibling').get; this.nodePrevSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'previousSibling').get; this.nodeParentNodeGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'parentNode').get; this.nodeChildNodesGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'childNodes').get; this.elementFirstElementChildGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'firstElementChild').get; this.elementLastElementChildGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'lastElementChild').get; this.elementNextElementSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'nextElementSibling').get; this.elementPrevElementSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'previousElementSibling').get; // NOTE: Some browsers (for example, Edge, Internet Explorer 11, Safari) don't support the 'integrity' property. if (scriptIntegrityDescriptor && linkIntegrityDescriptor) { this.scriptIntegrityGetter = scriptIntegrityDescriptor.get; this.linkIntegrityGetter = linkIntegrityDescriptor.get; } // NOTE: In the Internet Explorer 11 the children property is located in HTMLElement. var childrenPropOwner = win.Element.prototype.hasOwnProperty('children') // eslint-disable-line no-prototype-builtins ? win.Element.prototype : win.HTMLElement.prototype; this.elementChildrenGetter = win.Object.getOwnPropertyDescriptor(childrenPropOwner, 'children').get; var anchorOriginDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'origin'); // NOTE: IE and Edge don't support origin property if (anchorOriginDescriptor) this.anchorOriginGetter = anchorOriginDescriptor.get; var iframeSrcdocDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'srcdoc'); // NOTE: IE11 doesn't support the 'srcdoc' property if (iframeSrcdocDescriptor) { this.iframeSrcdocGetter = iframeSrcdocDescriptor.get; this.iframeSrcdocSetter = iframeSrcdocDescriptor.set; } var cssStyleSheetHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.CSSStyleSheet.prototype, 'href'); // NOTE: IE11 doesn't support the 'href' property if (cssStyleSheetHrefDescriptor) this.cssStyleSheetHrefGetter = cssStyleSheetHrefDescriptor.get; var nodeBaseURIDescriptor = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'baseURI'); // NOTE: IE11 doesn't support the 'baseURI' property if (nodeBaseURIDescriptor) this.nodeBaseURIGetter = nodeBaseURIDescriptor.get; // NOTE: The 'attributes' property is located in Node prototype in IE11 only this.elementAttributesPropOwnerName = win.Element.prototype.hasOwnProperty('attributes') ? 'Element' : 'Node'; // eslint-disable-line no-prototype-builtins this.elementAttributesGetter = win.Object.getOwnPropertyDescriptor(win[this.elementAttributesPropOwnerName].prototype, 'attributes').get; var htmlManifestDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLHtmlElement.prototype, 'manifest'); // NOTE: Only the Safari browser supports the 'manifest' property if (htmlManifestDescriptor) { this.htmlManifestGetter = htmlManifestDescriptor.get; this.htmlManifestSetter = htmlManifestDescriptor.set; } // NOTE: IE11 doesn't support the 'srcset' property if (iframeSrcdocDescriptor) { this.imageSrcsetSetter = imageSrcsetDescriptor.set; this.imageSrcsetGetter = imageSrcsetDescriptor.get; } this.titleElementTextGetter = titleElementTextDescriptor.get; // MutationRecord this.mutationRecordNextSiblingGetter = win.Object.getOwnPropertyDescriptor(win.MutationRecord.prototype, 'nextSibling').get; this.mutationRecordPrevSiblingGetter = win.Object.getOwnPropertyDescriptor(win.MutationRecord.prototype, 'previousSibling').get; }; NativeMethods.prototype.refreshWindowMeths = function (win, isInWorker) { if (isInWorker === void 0) { isInWorker = false; } win = win || window; var winProto = win.constructor.prototype; // Dom this.eval = win.eval; this.formSubmit = win.HTMLFormElement && win.HTMLFormElement.prototype.submit; this.documentFragmentQuerySelector = win.DocumentFragment && win.DocumentFragment.prototype.querySelector; this.documentFragmentQuerySelectorAll = win.DocumentFragment && win.DocumentFragment.prototype.querySelectorAll; this.preventDefault = win.Event.prototype.preventDefault; this.historyPushState = win.history && win.history.pushState; this.historyReplaceState = win.history && win.history.replaceState; this.postMessage = win.postMessage || winProto.postMessage; this.windowOpen = win.open || winProto.open; this.setTimeout = win.setTimeout || winProto.setTimeout; this.setInterval = win.setInterval || winProto.setInterval; this.clearTimeout = win.clearTimeout || winProto.clearTimeout; this.clearInterval = win.clearInterval || winProto.clearInterval; this.registerProtocolHandler = win.navigator.registerProtocolHandler; this.sendBeacon = win.Navigator && win.Navigator.prototype.sendBeacon; if (win.XMLHttpRequest) { // NOTE: IE11 has no EventTarget so we should save "Event" methods separately var xhrEventProto = (win.EventTarget || win.XMLHttpRequest).prototype; this.xhrAbort = win.XMLHttpRequest.prototype.abort; this.xhrOpen = win.XMLHttpRequest.prototype.open; this.xhrSend = win.XMLHttpRequest.prototype.send; this.xhrAddEventListener = xhrEventProto.addEventListener; this.xhrRemoveEventListener = xhrEventProto.removeEventListener; this.xhrDispatchEvent = xhrEventProto.dispatchEvent; this.xhrGetResponseHeader = win.XMLHttpRequest.prototype.getResponseHeader; this.xhrGetAllResponseHeaders = win.XMLHttpRequest.prototype.getAllResponseHeaders; this.xhrSetRequestHeader = win.XMLHttpRequest.prototype.setRequestHeader; this.xhrOverrideMimeType = win.XMLHttpRequest.prototype.overrideMimeType; } try { this.registerServiceWorker = win.navigator.serviceWorker.register; this.getRegistrationServiceWorker = win.navigator.serviceWorker.getRegistration; } catch (e) { this.registerServiceWorker = null; this.getRegistrationServiceWorker = null; } this.createContextualFragment = win.Range && win.Range.prototype.createContextualFragment; var nativePerformance = win.performance; if (nativePerformance) { // eslint-disable-next-line no-restricted-properties var nativePerformanceNow_1 = win.performance.now || win.Performance.prototype.now; this.performanceNow = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return nativePerformanceNow_1.apply(nativePerformance, args); }; } // Fetch this.fetch = win.fetch; this.Request = win.Request; if (win.Headers) { this.Headers = win.Headers; this.headersSet = win.Headers.prototype.set; this.headersGet = win.Headers.prototype.get; this.headersDelete = win.Headers.prototype.delete; this.headersEntries = win.Headers.prototype.entries; this.headersForEach = win.Headers.prototype.forEach; this.headersValues = win.Headers.prototype.values; } // Event this.windowAddEventListener = win.addEventListener || winProto.addEventListener; this.windowRemoveEventListener = win.removeEventListener || winProto.removeEventListener; this.windowDispatchEvent = win.dispatchEvent; this.WindowPointerEvent = win.PointerEvent || winProto.PointerEvent; this.WindowMSPointerEvent = win.MSPointerEvent || winProto.MSPointerEvent; this.WindowTouch = win.Touch || winProto.Touch; this.WindowTouchEvent = win.TouchEvent || winProto.TouchEvent; this.WindowKeyboardEvent = win.KeyboardEvent || winProto.KeyboardEvent; this.WindowFocusEvent = win.FocusEvent || winProto.FocusEvent; this.WindowTextEvent = win.TextEvent || winProto.TextEvent; this.WindowInputEvent = win.InputEvent || winProto.InputEvent; this.WindowMouseEvent = win.MouseEvent || winProto.MouseEvent; this.eventTargetGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, 'target').get; this.canvasContextDrawImage = win.CanvasRenderingContext2D && win.CanvasRenderingContext2D.prototype.drawImage; // FormData this.formDataAppend = win.FormData && win.FormData.prototype.append; // DateTime this.date = win.Date; this.dateNow = win.Date.now; // eslint-disable-line no-restricted-properties // Math this.math = win.Math; this.mathRandom = win.Math.random; // Object this.objectToString = win.Object.prototype.toString; this.objectAssign = win.Object.assign; this.objectKeys = win.Object.keys; this.objectDefineProperty = win.Object.defineProperty; this.objectDefineProperties = win.Object.defineProperties; this.objectCreate = win.Object.create; this.objectIsExtensible = win.Object.isExtensible; this.objectIsFrozen = win.Object.isFrozen; this.objectGetOwnPropertyDescriptor = win.Object.getOwnPropertyDescriptor; this.objectHasOwnProperty = win.Object.hasOwnProperty; this.objectGetOwnPropertyNames = win.Object.getOwnPropertyNames; this.objectGetPrototypeOf = win.Object.getPrototypeOf; this.objectSetPrototypeOf = win.Object.setPrototypeOf; this.objectGetOwnPropertySymbols = win.Object.getOwnPropertySymbols; // Array this.arraySlice = win.Array.prototype.slice; this.arrayConcat = win.Array.prototype.concat; this.arrayFilter = win.Array.prototype.filter; this.arrayFind = win.Array.prototype.find; this.arrayMap = win.Array.prototype.map; this.arrayJoin = win.Array.prototype.join; this.arraySplice = win.Array.prototype.splice; this.arrayUnshift = win.Array.prototype.unshift; this.arrayForEach = win.Array.prototype.forEach; this.arrayIndexOf = win.Array.prototype.indexOf; this.arraySome = win.Array.prototype.some; this.arrayEvery = win.Array.prototype.every; this.arrayReverse = win.Array.prototype.reverse; this.arrayReduce = win.Array.prototype.reduce; this.arrayFrom = win.Array.from; this.isArray = win.Array.isArray; this.DOMParserParseFromString = win.DOMParser && win.DOMParser.prototype.parseFromString; this.arrayBufferIsView = win.ArrayBuffer.prototype.constructor.isView; // NOTE: this section relates to getting properties from DOM classes if (!isInWorker) { // DOMTokenList this.tokenListAdd = win.DOMTokenList.prototype.add; this.tokenListRemove = win.DOMTokenList.prototype.remove; this.tokenListReplace = win.DOMTokenList.prototype.replace; this.tokenListSupports = win.DOMTokenList.prototype.supports; this.tokenListToggle = win.DOMTokenList.prototype.toggle; this.tokenListContains = win.DOMTokenList.prototype.contains; var tokenListValueDescriptor = win.Object.getOwnPropertyDescriptor(win.DOMTokenList.prototype, 'value'); // NOTE: IE11 doesn't support the 'value' property of the DOMTokenList interface if (tokenListValueDescriptor) this.tokenListValueSetter = tokenListValueDescriptor.set; // Stylesheets this.styleGetPropertyValue = win.CSSStyleDeclaration.prototype.getPropertyValue; this.styleSetProperty = win.CSSStyleDeclaration.prototype.setProperty; this.styleRemoveProperty = win.CSSStyleDeclaration.prototype.removeProperty; this.styleInsertRule = win.CSSStyleSheet.prototype.insertRule; this.scrollTo = win.scrollTo; } if (win.Promise) { this.promiseThen = win.Promise.prototype.then; this.promiseReject = win.Promise.reject; } // Console this.console = win.console; if (this.console) { this.consoleMeths = { log: win.console.log, warn: win.console.warn, error: win.console.error, info: win.console.info, }; } this.crypto = win.crypto || win.msCrypto; this.cryptoGetRandomValues = this.crypto && this.crypto.getRandomValues; this.refreshClasses(win); this._refreshGettersAndSetters(win, isInWorker); }; NativeMethods.prototype.refreshClasses = function (win) { this.windowClass = win.Window; this.documentClass = win.Document; this.locationClass = win.Location; this.elementClass = win.Element; this.svgElementClass = win.SVGElement; this.Worker = win.Worker; this.MessageChannel = win.MessageChannel; this.Array = win.Array; this.ArrayBuffer = win.ArrayBuffer; this.Uint8Array = win.Uint8Array; this.Uint16Array = win.Uint16Array; this.Uint32Array = win.Uint32Array; this.DataView = win.DataView; this.Blob = win.Blob; this.XMLHttpRequest = win.XMLHttpRequest; this.Image = win.Image; this.Function = win.Function; this.functionToString = win.Function.prototype.toString; this.functionBind = win.Function.prototype.bind; this.Error = win.Error; this.FontFace = win.FontFace; this.StorageEvent = win.StorageEvent; this.MutationObserver = win.MutationObserver; this.EventSource = win.EventSource; this.Proxy = win.Proxy; this.WebSocket = win.WebSocket; this.HTMLCollection = win.HTMLCollection; this.NodeList = win.NodeList; this.Node = win.Node; this.URL = win.URL; this.DataTransfer = win.DataTransfer; this.DataTransferItemList = win.DataTransferItemList; this.DataTransferItem = win.DataTransferItem; this.FileList = win.FileList; // NOTE: non-IE11 case. window.File in IE11 is not constructable. if (win.File && isFunction(win.File)) this.File = win.File; }; NativeMethods.prototype.refreshElectronMeths = function (vmModule) { if (this.createScript && isNativeFunction(vmModule.createScript)) return false; this.createScript = vmModule.createScript; this.runInDebugContext = vmModule.runInDebugContext; this.runInContext = vmModule.runInContext; this.runInNewContext = vmModule.runInNewContext; this.runInThisContext = vmModule.runInThisContext; return true; }; NativeMethods._ensureDocumentMethodRestore = function (document, prototype, methodName, savedNativeMethod) { prototype[methodName] = savedNativeMethod; if (document[methodName] !== prototype[methodName]) document[methodName] = savedNativeMethod; }; NativeMethods.prototype.restoreDocumentMeths = function (window, document) { var docPrototype = window.Document.prototype; NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createDocumentFragment', this.createDocumentFragment); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createElement', this.createElement); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createElementNS', this.createElementNS); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'elementFromPoint', this.elementFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'caretRangeFromPoint', this.caretRangeFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'caretPositionFromPoint', this.caretPositionFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementById', this.getElementById); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByClassName', this.getElementsByClassName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByName', this.getElementsByName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByTagName', this.getElementsByTagName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'querySelector', this.querySelector); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'querySelectorAll', this.querySelectorAll); // Event // NOTE: IE11 has no EventTarget if (!window.EventTarget) { NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'addEventListener', this.documentAddEventListener); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'removeEventListener', this.documentRemoveEventListener); } NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createEvent', this.documentCreateEvent); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createTouch', this.documentCreateTouch); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createTouchList', this.documentCreateTouchList); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentOpenPropOwnerName].prototype, 'open', this.documentOpen); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentClosePropOwnerName].prototype, 'close', this.documentClose); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentWritePropOwnerName].prototype, 'write', this.documentWrite); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentWriteLnPropOwnerName].prototype, 'writeln', this.documentWriteLn); }; NativeMethods.prototype.refreshIfNecessary = function (doc, win) { var _this = this; var tryToExecuteCode = function (func) { try { return func(); } catch (e) { return true; } }; var needToRefreshDocumentMethods = tryToExecuteCode(function () { return !doc.createElement || isNativeFunction(document.createElement); }); var needToRefreshElementMethods = tryToExecuteCode(function () { var nativeElement = _this.createElement.call(doc, 'div'); return isNativeFunction(nativeElement.getAttribute); }); var needToRefreshWindowMethods = tryToExecuteCode(function () { _this.setTimeout.call(win, function () { return void 0; }, 0); return isNativeFunction(win.XMLHttpRequest.prototype.open); }); // NOTE: T173709 if (needToRefreshDocumentMethods) this.refreshDocumentMeths(doc, win); if (needToRefreshElementMethods) this.refreshElementMeths(doc, win); // NOTE: T239109 if (needToRefreshWindowMethods) this.refreshWindowMeths(win); }; NativeMethods.prototype.isNativeCode = function (fn) { return NATIVE_CODE_RE.test(this.functionToString.call(fn)); }; return NativeMethods; }()); var nativeMethods = new NativeMethods(); var EventEmitter = /** @class */ (function () { function EventEmitter() { this.eventsListeners = nativeMethods.objectCreate(null); } EventEmitter.prototype.emit = function (evt) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var listeners = this.eventsListeners[evt]; if (!listeners) return; var index = 0; while (listeners[index]) { // HACK: For IE: after calling document.write, the IFrameSandbox event handler throws the // 'Can't execute code from a freed script' exception because the document has been // recreated. if (isIE) { try { listeners[index].toString(); } catch (e) { nativeMethods.arraySplice.call(listeners, index, 1); continue; } } listeners[index++].apply(this, args); } }; EventEmitter.prototype.off = function (evt, listener) { var listeners = this.eventsListeners[evt]; if (!listeners) return; this.eventsListeners[evt] = nativeMethods.arrayFilter.call(listeners, function (currentListener) { return currentListener !== listener; }); }; EventEmitter.prototype.on = function (evt, listener) { this.eventsListeners[evt] = this.eventsListeners[evt] || []; if (this.eventsListeners[evt].indexOf(listener) === -1) this.eventsListeners[evt].push(listener); return listener; }; return EventEmitter; }()); // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- var INTERNAL_ATTRIBUTES = { storedAttrPostfix: '-hammerhead-stored-value', hoverPseudoClass: 'data-hammerhead-hovered', focusPseudoClass: 'data-hammerhead-focused', uploadInfoHiddenInputName: 'hammerhead|upload-info-hidden-input-name', }; // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- /* eslint hammerhead/proto-methods: 2 */ var POSTFIX = '-hammerhead-shadow-ui'; var SHADOW_UI_CLASS_NAME = { postfix: POSTFIX, charset: 'charset' + POSTFIX, script: 'script' + POSTFIX, selfRemovingScript: 'self-removing-script' + POSTFIX, uiStylesheet: 'ui-stylesheet' + POSTFIX, }; // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- // NOTE: Some websites override the String.prototype.trim method. When we use this function // in our scripts, we expect it to have the default behavior. Therefore, in order to protect // ourselves from spoofing, we must use our own implementation. Also, we cannot use the // String.prototype.trim method because on the client-side it is the same in the top window and // an iframe window. The client code may override this method in the top window before the // iframe is initialized, so that the iframe will lose access to the native method. function trim$1 (str) { return typeof str === 'string' ? str.replace(/(^\s+)|(\s+$)/g, '') : str; } // ------------------------------------------------------------- var URL_RE = /^\s*([\w-]+?:)?(?:\/\/(?:([^/]+)@)?(([^/%?;#: ]*)(?::(\d+))?))?(.*?)\s*$/; var PROTOCOL_RE = /^([\w-]+?:)(\/\/|[^\\/]|$)/; var QUERY_AND_HASH_RE = /(\?.+|#[^#]*)$/; var PATH_AFTER_HOST_RE = /^\/([^/]+?)\/([\S\s]+)$/; var HTTP_RE = /^https?:/; var FILE_RE = /^file:/i; var SHORT_ORIGIN_RE = /^http(s)?:\/\//; var IS_SECURE_ORIGIN_RE = /^s\*/; var META_REFRESH_RE = /^(.+?[;,]\s*(?:url\s*=\s*)?(['"])?)(.+?)?(\2)?$/i; var SUPPORTED_PROTOCOL_RE = /^(?:https?|file):/i; var HASH_RE$1 = /^#/; var REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1 = '!'; var REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR = '*'; var TRAILING_SLASH_RE = /\/$/; var SPECIAL_BLANK_PAGE = 'about:blank'; var SPECIAL_ERROR_PAGE = 'about:error'; var SPECIAL_PAGES = [SPECIAL_BLANK_PAGE, SPECIAL_ERROR_PAGE]; var HTTP_DEFAULT_PORT = '80'; var HTTPS_DEFAULT_PORT = '443'; var Credentials; (function (Credentials) { Credentials[Credentials["include"] = 0] = "include"; Credentials[Credentials["sameOrigin"] = 1] = "sameOrigin"; Credentials[Credentials["omit"] = 2] = "omit"; Credentials[Credentials["unknown"] = 3] = "unknown"; })(Credentials || (Credentials = {})); // eslint-disable-line no-shadow var SPECIAL_PAGE_DEST_RESOURCE_INFO = { protocol: 'about:', host: '', hostname: '', port: '', partAfterHost: '', }; var RESOURCE_TYPES = [ { name: 'isIframe', flag: 'i' }, { name: 'isForm', flag: 'f' }, { name: 'isScript', flag: 's' }, { name: 'isEventSource', flag: 'e' }, { name: 'isHtmlImport', flag: 'h' }, { name: 'isWebSocket', flag: 'w' }, { name: 'isServiceWorker', flag: 'c' }, { name: 'isAjax', flag: 'a' }, { name: 'isObject', flag: 'o' }, ]; function parseResourceType$1(resourceType) { var parsedResourceType = {}; if (!resourceType) return parsedResourceType; for (var _i = 0, RESOURCE_TYPES_1 = RESOURCE_TYPES; _i < RESOURCE_TYPES_1.length; _i++) { var _a = RESOURCE_TYPES_1[_i], name_1 = _a.name, flag = _a.flag; if (resourceType.indexOf(flag) > -1) parsedResourceType[name_1] = true; } return parsedResourceType; } function getResourceTypeString(parsedResourceType) { if (!parsedResourceType) return null; var resourceType = ''; for (var _i = 0, RESOURCE_TYPES_2 = RESOURCE_TYPES; _i < RESOURCE_TYPES_2.length; _i++) { var _a = RESOURCE_TYPES_2[_i], name_2 = _a.name, flag = _a.flag; if (parsedResourceType[name_2]) resourceType += flag; } return resourceType || null; } function makeShortOrigin(origin) { return origin === 'null' ? '' : origin.replace(SHORT_ORIGIN_RE, function (_, secure) { return secure ? 's*' : ''; }); } function restoreShortOrigin(origin) { if (!origin) return 'null'; return IS_SECURE_ORIGIN_RE.test(origin) ? origin.replace(IS_SECURE_ORIGIN_RE, 'https://') : 'http://' + origin; } function isSubDomain$1(domain, subDomain) { domain = domain.replace(/^www./i, ''); subDomain = subDomain.replace(/^www./i, ''); if (domain === subDomain) return true; var index = subDomain.lastIndexOf(domain); return subDomain[index - 1] === '.' && subDomain.length === index + domain.length; } function sameOriginCheck$1(location, checkedUrl) { if (!checkedUrl) return true; var parsedCheckedUrl = parseUrl$1(checkedUrl); var isRelative = !parsedCheckedUrl.host; if (isRelative) return true; var parsedLocation = parseUrl$1(location); var parsedProxyLocation = parseProxyUrl$1(location); if (parsedCheckedUrl.host === parsedLocation.host && parsedCheckedUrl.protocol === parsedLocation.protocol) return true; var parsedDestUrl = parsedProxyLocation ? parsedProxyLocation.destResourceInfo : parsedLocation; if (!parsedDestUrl) return false; var isSameProtocol = !parsedCheckedUrl.protocol || parsedCheckedUrl.protocol === parsedDestUrl.protocol; var portsEq = !parsedDestUrl.port && !parsedCheckedUrl.port || parsedDestUrl.port && parsedDestUrl.port.toString() === parsedCheckedUrl.port; return isSameProtocol && !!portsEq && parsedDestUrl.hostname === parsedCheckedUrl.hostname; } // NOTE: Convert the destination protocol and hostname to the lower case. (GH-1) function convertHostToLowerCase(url) { var parsedUrl = parseUrl$1(url); parsedUrl.protocol = parsedUrl.protocol && parsedUrl.protocol.toLowerCase(); parsedUrl.host = parsedUrl.host && parsedUrl.host.toLowerCase(); return formatUrl$1(parsedUrl); } function getURLString(url) { // TODO: fix it // eslint-disable-next-line no-undef if (url === null && /iPad|iPhone/i.test(window.navigator.userAgent)) return ''; return String(url).replace(/[\n\t]/g, ''); } function getProxyUrl$1(url, opts) { var sessionInfo = [opts.sessionId]; if (opts.windowId) sessionInfo.push(opts.windowId); var params = [sessionInfo.join(REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR)]; if (opts.resourceType) params.push(opts.resourceType); if (opts.charset) params.push(opts.charset.toLowerCase()); if (typeof opts.credentials === 'number') params.push(opts.credentials.toString()); if (opts.reqOrigin) params.push(encodeURIComponent(makeShortOrigin(opts.reqOrigin))); var descriptor = params.join(REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1); var proxyProtocol = opts.proxyProtocol || 'http:'; return "".concat(proxyProtocol, "//").concat(opts.proxyHostname, ":").concat(opts.proxyPort, "/").concat(descriptor, "/").concat(convertHostToLowerCase(url)); } function getDomain(parsed) { if (parsed.protocol === 'file:') return 'null'; return formatUrl$1({ protocol: parsed.protocol, host: parsed.host, hostname: parsed.hostname, port: String(parsed.port || ''), }); } function parseRequestDescriptor(desc) { var _a = desc.split(REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1), sessionInfo = _a[0], resourceType = _a[1], resourceData = _a.slice(2); if (!sessionInfo) return null; var _b = sessionInfo.split(REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR), sessionId = _b[0], windowId = _b[1]; var parsedDesc = { sessionId: sessionId, resourceType: resourceType || null }; if (windowId) parsedDesc.windowId = windowId; if (resourceType && resourceData.length) { var parsedResourceType = parseResourceType$1(resourceType); if (parsedResourceType.isScript || parsedResourceType.isServiceWorker) parsedDesc.charset = resourceData[0]; else if (parsedResourceType.isWebSocket) parsedDesc.reqOrigin = decodeURIComponent(restoreShortOrigin(resourceData[0])); else if (parsedResourceType.isIframe && resourceData[0]) parsedDesc.reqOrigin = decodeURIComponent(restoreShortOrigin(resourceData[0])); else if (parsedResourceType.isAjax) { parsedDesc.credentials = parseInt(resourceData[0], 10); if (resourceData.length === 2) parsedDesc.reqOrigin = decodeURIComponent(restoreShortOrigin(resourceData[1])); } } return parsedDesc; } function parseProxyUrl$1(proxyUrl) { // TODO: Remove it. var parsedUrl = parseUrl$1(proxyUrl); if (!parsedUrl.partAfterHost) return null; var match = parsedUrl.partAfterHost.match(PATH_AFTER_HOST_RE); if (!match) return null; var parsedDesc = parseRequestDescriptor(match[1]); // NOTE: We should have, at least, the job uid and the owner token. if (!parsedDesc) return null; var destUrl = match[2]; // Browser can redirect to a special page with hash (GH-1671) var destUrlWithoutHash = destUrl.replace(/#[\S\s]*$/, ''); if (!isSpecialPage$1(destUrlWithoutHash) && !SUPPORTED_PROTOCOL_RE.test(destUrl)) return null; var destResourceInfo; if (isSpecialPage$1(destUrlWithoutHash)) destResourceInfo = SPECIAL_PAGE_DEST_RESOURCE_INFO; else { destUrl = omitDefaultPort(destUrl); destResourceInfo = parseUrl$1(destUrl); } return { destUrl: destUrl, destResourceInfo: destResourceInfo, partAfterHost: parsedUrl.partAfterHost, proxy: { hostname: parsedUrl.hostname || '', port: parsedUrl.port || '', }, sessionId: parsedDesc.sessionId, resourceType: parsedDesc.resourceType, charset: parsedDesc.charset, reqOrigin: parsedDesc.reqOrigin, windowId: parsedDesc.windowId, credentials: parsedDesc.credentials, }; } function getPathname(path) { return path.replace(QUERY_AND_HASH_RE, ''); } function parseUrl$1(url) { url = processSpecialChars(url); if (!url) return {}; var urlMatch = url.match(URL_RE); return urlMatch ? { protocol: urlMatch[1], auth: urlMatch[2], host: urlMatch[3], hostname: urlMatch[4], port: urlMatch[5], partAfterHost: urlMatch[6], } : {}; } function isSupportedProtocol$1(url) { url = trim$1(url || ''); var isHash = HASH_RE$1.test(url); if (isHash) return false; var protocol = url.match(PROTOCOL_RE); if (!protocol) return true; return SUPPORTED_PROTOCOL_RE.test(protocol[0]); } function resolveUrlAsDest$1(url, getProxyUrlMeth, isUrlsSet) { if (isUrlsSet === void 0) { isUrlsSet = false; } if (isUrlsSet) return handleUrlsSet(resolveUrlAsDest$1, url, getProxyUrlMeth); getProxyUrlMeth = getProxyUrlMeth || getProxyUrl$1; if (isSupportedProtocol$1(url)) { var proxyUrl = getProxyUrlMeth(url); var parsedProxyUrl = parseProxyUrl$1(proxyUrl); return parsedProxyUrl ? formatUrl$1(parsedProxyUrl.destResourceInfo) : url; } return url; } function formatUrl$1(parsedUrl) { // NOTE: the URL is relative. if (parsedUrl.protocol !== 'file:' && parsedUrl.protocol !== 'about:' && !parsedUrl.host && (!parsedUrl.hostname || !parsedUrl.port)) return parsedUrl.partAfterHost || ''; var url = parsedUrl.protocol || ''; if (parsedUrl.protocol !== 'about:') url += '//'; if (parsedUrl.auth) url += parsedUrl.auth + '@'; if (parsedUrl.host) url += parsedUrl.host; else if (parsedUrl.hostname) { url += parsedUrl.hostname; if (parsedUrl.port) url += ':' + parsedUrl.port; } if (parsedUrl.partAfterHost) url += parsedUrl.partAfterHost; return url; } function handleUrlsSet(handler, url) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } var resourceUrls = url.split(','); var replacedUrls = []; for (var _a = 0, resourceUrls_1 = resourceUrls; _a < resourceUrls_1.length; _a++) { var fullUrlStr = resourceUrls_1[_a]; var _b = fullUrlStr.replace(/ +/g, ' ').trim().split(' '), urlStr = _b[0], postUrlStr = _b[1]; if (urlStr) { var replacedUrl = handler.apply(void 0, __spreadArray([urlStr], args, false)); replacedUrls.push(replacedUrl + (postUrlStr ? " ".concat(postUrlStr) : '')); } } return replacedUrls.join(','); } function correctMultipleSlashes(url, pageProtocol) { if (pageProtocol === void 0) { pageProtocol = ''; } // NOTE: Remove unnecessary slashes from the beginning of the url and after scheme. // For example: // "//////example.com" -> "//example.com" (scheme-less HTTP(S) URL) // "////home/testcafe/documents" -> "///home/testcafe/documents" (scheme-less unix file URL) // "http:///example.com" -> "http://example.com" // // And add missing slashes after the file scheme. // "file://C:/document.txt" -> "file:///C:/document.txt" if (url.match(FILE_RE) || pageProtocol.match(FILE_RE)) { return url .replace(/^(file:)?\/+(\/\/\/.*$)/i, '$1$2') .replace(/^(file:)?\/*([A-Za-z]):/i, '$1///$2:'); } return url.replace(/^(https?:)?\/+(\/\/.*$)/i, '$1$2'); } function processSpecialChars(url) { return correctMultipleSlashes(getURLString(url)); } function ensureTrailingSlash(srcUrl, processedUrl) { if (!isValidUrl(processedUrl)) return processedUrl; var srcUrlEndsWithTrailingSlash = TRAILING_SLASH_RE.test(srcUrl); var processedUrlEndsWithTrailingSlash = TRAILING_SLASH_RE.test(processedUrl); if (srcUrlEndsWithTrailingSlash && !processedUrlEndsWithTrailingSlash) processedUrl += '/'; else if (srcUrl && !srcUrlEndsWithTrailingSlash && processedUrlEndsWithTrailingSlash) processedUrl = processedUrl.replace(TRAILING_SLASH_RE, ''); return processedUrl; } function isSpecialPage$1(url) { return SPECIAL_PAGES.indexOf(url) !== -1; } function isRelativeUrl(url) { var parsedUrl = parseUrl$1(url); return parsedUrl.protocol !== 'file:' && !parsedUrl.host; } function isValidPort(port) { var parsedPort = parseInt(port, 10); return parsedPort > 0 && parsedPort <= 65535; } function isValidUrl(url) { var parsedUrl = parseUrl$1(url); return parsedUrl.protocol === 'file:' || parsedUrl.protocol === 'about:' || !!parsedUrl.hostname && (!parsedUrl.port || isValidPort(parsedUrl.port)); } function ensureOriginTrailingSlash(url) { // NOTE: If you request an url containing only port, host and protocol // then browser adds the trailing slash itself. var parsedUrl = parseUrl$1(url); if (!parsedUrl.partAfterHost && parsedUrl.protocol && HTTP_RE.test(parsedUrl.protocol)) return url + '/'; return url; } function omitDefaultPort(url) { // NOTE: If you request an url containing default port // then browser remove this one itself. var parsedUrl = parseUrl$1(url); var hasDefaultPort = parsedUrl.protocol === 'https:' && parsedUrl.port === HTTPS_DEFAULT_PORT || parsedUrl.protocol === 'http:' && parsedUrl.port === HTTP_DEFAULT_PORT; if (hasDefaultPort) { parsedUrl.host = parsedUrl.hostname; parsedUrl.port = ''; return formatUrl$1(parsedUrl); } return url; } function prepareUrl(url) { url = omitDefaultPort(url); url = ensureOriginTrailingSlash(url); return url; } function updateScriptImportUrls(cachedScript, serverInfo, sessionId, windowId) { var regExp = new RegExp('(' + serverInfo.protocol + '//' + serverInfo.hostname + ':(?:' + serverInfo.port + '|' + serverInfo.crossDomainPort + ')/)[^/' + REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1 + ']+', 'g'); var pattern = '$1' + sessionId + (windowId ? REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR + windowId : ''); return cachedScript.replace(regExp, pattern); } function processMetaRefreshContent(content, urlReplacer) { var match = content.match(META_REFRESH_RE); if (!match || !match[3]) return content; return match[1] + urlReplacer(match[3]) + (match[4] || ''); } var sharedUrlUtils = /*#__PURE__*/Object.freeze({ __proto__: null, SUPPORTED_PROTOCOL_RE: SUPPORTED_PROTOCOL_RE, HASH_RE: HASH_RE$1, REQUEST_DESCRIPTOR_VALUES_SEPARATOR: REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1, REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR: REQUEST_DESCRIPTOR_SESSION_INFO_VALUES_SEPARATOR, TRAILING_SLASH_RE: TRAILING_SLASH_RE, SPECIAL_BLANK_PAGE: SPECIAL_BLANK_PAGE, SPECIAL_ERROR_PAGE: SPECIAL_ERROR_PAGE, SPECIAL_PAGES: SPECIAL_PAGES, HTTP_DEFAULT_PORT: HTTP_DEFAULT_PORT, HTTPS_DEFAULT_PORT: HTTPS_DEFAULT_PORT, get Credentials () { return Credentials; }, parseResourceType: parseResourceType$1, getResourceTypeString: getResourceTypeString, restoreShortOrigin: restoreShortOrigin, isSubDomain: isSubDomain$1, sameOriginCheck: sameOriginCheck$1, getURLString: getURLString, getProxyUrl: getProxyUrl$1, getDomain: getDomain, parseProxyUrl: parseProxyUrl$1, getPathname: getPathname, parseUrl: parseUrl$1, isSupportedProtocol: isSupportedProtocol$1, resolveUrlAsDest: resolveUrlAsDest$1, formatUrl: formatUrl$1, handleUrlsSet: handleUrlsSet, correctMultipleSlashes: correctMultipleSlashes, processSpecialChars: processSpecialChars, ensureTrailingSlash: ensureTrailingSlash, isSpecialPage: isSpecialPage$1, isRelativeUrl: isRelativeUrl, isValidUrl: isValidUrl, ensureOriginTrailingSlash: ensureOriginTrailingSlash, omitDefaultPort: omitDefaultPort, prepareUrl: prepareUrl, updateScriptImportUrls: updateScriptImportUrls, processMetaRefreshContent: processMetaRefreshContent }); var DOCUMENT_URL_RESOLVER = 'hammerhead|document-url-resolver'; var urlResolver = { _createResolver: function (doc) { var htmlDocument = nativeMethods.createHTMLDocument.call(doc.implementation, 'title'); var a = nativeMethods.createElement.call(htmlDocument, 'a'); var base = nativeMethods.createElement.call(htmlDocument, 'base'); nativeMethods.appendChild.call(htmlDocument.body, a); nativeMethods.appendChild.call(htmlDocument.head, base); return htmlDocument; }, _getResolver: function (doc) { // NOTE: Once a document is recreated (document.open, document.write is called), nativeMethods will be refreshed. // If we call urlResolve.updateBase after this, // we will use native methods from an actual document. // However, a document that contains an element for url resolving is created using a previous version of nativeMethods. if (!doc[DOCUMENT_URL_RESOLVER]) { nativeMethods.objectDefineProperty(doc, DOCUMENT_URL_RESOLVER, { value: this._createResolver(doc), writable: true, }); } return doc[DOCUMENT_URL_RESOLVER]; }, _isNestedIframeWithoutSrc: function (win) { if (!win || !win.parent || win.parent === win || win.parent.parent === win.parent) return false; var iframeElement = getFrameElement(window); return !!iframeElement && isIframeWithoutSrc(iframeElement); }, init: function (doc) { this.updateBase(get$2(), doc); }, getResolverElement: function (doc) { return nativeMethods.nodeFirstChildGetter.call(this._getResolver(doc).body); }, resolve: function (url, doc) { var resolver = this.getResolverElement(doc); var href = null; if (url === null) nativeMethods.removeAttribute.call(resolver, 'href'); else { nativeMethods.anchorHrefSetter.call(resolver, url); href = nativeMethods.anchorHrefGetter.call(resolver); // NOTE: It looks like a Chrome bug: in a nested iframe without src (when an iframe is placed into another // iframe) you cannot set a relative link href while the iframe loading is not completed. So, we'll do it with // the parent's urlResolver Safari demonstrates similar behavior, but urlResolver.href has a relative URL value. var needUseParentResolver = url && (!href || href.charAt(0) === '/') && this._isNestedIframeWithoutSrc(doc.defaultView); if (needUseParentResolver) return this.resolve(url, window.parent.document); } return ensureTrailingSlash(url, href); }, updateBase: function (url, doc) { if (this.proxyless) return; var resolverDocument = this._getResolver(doc); var baseElement = nativeMethods.elementGetElementsByTagName.call(resolverDocument.head, 'base')[0]; url = url || get$2(); /*eslint-disable no-restricted-properties*/ var parsedUrl = parseUrl$1(url); var isRelativeUrl = parsedUrl.protocol !== 'file:' && parsedUrl.protocol !== 'about:' && !parsedUrl.host; var isProtocolRelativeUrl = /^\/\//.test(url) && !!parsedUrl.host; /*eslint-enable no-restricted-properties*/ if (isRelativeUrl || isProtocolRelativeUrl) { var destinationLocation = get$2(); this.updateBase(destinationLocation, doc); url = this.resolve(url, doc); } nativeMethods.setAttribute.call(baseElement, 'href', url); }, getBaseUrl: function (doc) { var baseElement = nativeMethods.elementGetElementsByTagName.call(this._getResolver(doc).head, 'base')[0]; return nativeMethods.getAttribute.call(baseElement, 'href'); }, changeUrlPart: function (url, nativePropSetter, value, doc) { var resolver = this.getResolverElement(doc); nativeMethods.anchorHrefSetter.call(resolver, url); nativePropSetter.call(resolver, value); return nativeMethods.anchorHrefGetter.call(resolver); }, dispose: function (doc) { doc[DOCUMENT_URL_RESOLVER] = null; }, get proxyless() { return this._proxyless; }, set proxyless(value) { this._proxyless = value; }, }; var Settings = /** @class */ (function () { function Settings() { this._settings = { isFirstPageLoad: true, sessionId: '', forceProxySrcForImage: false, crossDomainProxyPort: '', referer: '', serviceMsgUrl: '', transportWorkerUrl: '', iframeTaskScriptTemplate: '', cookie: '', allowMultipleWindows: false, isRecordMode: false, windowId: '', proxyless: false, disableCrossDomain: false, }; } Settings.prototype.set = function (value) { this._settings = value; }; Settings.prototype.get = function () { return this._settings; }; return Settings; }()); var settings = new Settings(); var forcedLocation = null; // NOTE: exposed only for tests function getLocation() { // NOTE: Used for testing. Unfortunately, we cannot override the 'getLocation' method in a test. if (forcedLocation) return forcedLocation; var frameElement = getFrameElement(globalContextInfo.global); // NOTE: Fallback to the owner page's URL if we are in an iframe without src. if (frameElement && isIframeWithoutSrc(frameElement)) return settings.get().referer; return globalContextInfo.global.location.toString(); } // NOTE: We need to be able to force the page location. During the test, Hammerhead should think that it is on the // proxied page, not in the test environment. Unfortunately, we cannot do it in any other way. function forceLocation(url) { forcedLocation = url; } function sameOriginCheck(location, checkedUrl) { if (checkedUrl) checkedUrl = resolveUrl(checkedUrl); return settings.get().disableCrossDomain || sameOriginCheck$1(location, checkedUrl); } function resolveUrl(url, doc) { var preProcessedUrl = getURLString(url); if (preProcessedUrl && preProcessedUrl.indexOf('//') === 0) { // eslint-disable-next-line no-restricted-properties var pageProtocol = getParsed().protocol; preProcessedUrl = pageProtocol + correctMultipleSlashes(preProcessedUrl, pageProtocol); } else preProcessedUrl = correctMultipleSlashes(preProcessedUrl); if (globalContextInfo.isInWorker) { if (self.location.protocol !== 'blob:') // eslint-disable-line no-restricted-properties return new nativeMethods.URL(preProcessedUrl, get$2()).href; // eslint-disable-line no-restricted-properties return String(url); } return urlResolver.resolve(preProcessedUrl, doc || document); } var get$2 = function () { var location = getLocation(); var parsedProxyUrl = parseProxyUrl$1(location); return parsedProxyUrl ? parsedProxyUrl.destUrl : location; }; function getReferrer() { var location = getLocation(); var parsedProxyUrl = parseProxyUrl$1(location); return (parsedProxyUrl === null || parsedProxyUrl === void 0 ? void 0 : parsedProxyUrl.reqOrigin) ? parsedProxyUrl.reqOrigin + '/' : ''; } function overrideGet(func) { get$2 = func; } function withHash(hash) { var location = get$2(); // NOTE: Remove the previous hash if there is any. location = location.replace(/(#.*)$/, ''); return location + hash; } function parseLocationThroughAnchor(url) { var resolver = urlResolver.getResolverElement(document); // eslint-disable-next-line no-restricted-properties var destPort = parseUrl$1(url).port; // NOTE: IE browser adds the default port for the https protocol while resolving. nativeMethods.anchorHrefSetter.call(resolver, get$2()); var hostname = nativeMethods.anchorHostnameGetter.call(resolver); var pathname = nativeMethods.anchorPathnameGetter.call(resolver); // NOTE: IE ignores the first '/' symbol in the pathname. if (pathname.charAt(0) !== '/') pathname = '/' + pathname; // TODO: Describe default ports logic. return { protocol: nativeMethods.anchorProtocolGetter.call(resolver), // NOTE: Remove the default port. port: destPort ? nativeMethods.anchorPortGetter.call(resolver) : '', hostname: hostname, // NOTE: Remove the default port from the host. host: destPort ? nativeMethods.anchorHostGetter.call(resolver) : hostname, pathname: pathname, hash: resolver.hash, search: nativeMethods.anchorSearchGetter.call(resolver), }; } function parseLocationThroughURL(url) { var parsedUrl = new nativeMethods.URL(url); /* eslint-disable no-restricted-properties */ return { protocol: parsedUrl.protocol, port: parsedUrl.port, hostname: parsedUrl.hostname, host: parsedUrl.host, pathname: parsedUrl.pathname, hash: parsedUrl.hash, search: parsedUrl.search, }; /* eslint-enable no-restricted-properties */ } function getParsed() { var dest = get$2(); return globalContextInfo.isInWorker ? parseLocationThroughURL(dest) : parseLocationThroughAnchor(dest); } function getOriginHeader() { return getDomain(getParsed()); } var destLocationUtils = /*#__PURE__*/Object.freeze({ __proto__: null, getLocation: getLocation, forceLocation: forceLocation, sameOriginCheck: sameOriginCheck, resolveUrl: resolveUrl, get get () { return get$2; }, getReferrer: getReferrer, overrideGet: overrideGet, withHash: withHash, getParsed: getParsed, getOriginHeader: getOriginHeader }); var HASH_RE = /#[\S\s]*$/; var SUPPORTED_WEB_SOCKET_PROTOCOL_RE = /^wss?:/i; var SCOPE_RE = /\/[^/]*$/; // NOTE: The window.location equals 'about:blank' in iframes without src // therefore we need to find a window with src to get the proxy settings var DEFAULT_PROXY_SETTINGS = (function () { /*eslint-disable no-restricted-properties*/ var locationWindow = globalContextInfo.isInWorker ? { location: parseUrl(self.location.origin), parent: null } : window; var proxyLocation = locationWindow.location; while (!proxyLocation.hostname) { // about:blank page in proxyless mode if (!globalContextInfo.isInWorker && locationWindow === locationWindow.top) break; locationWindow = locationWindow.parent; proxyLocation = locationWindow.location; } return { hostname: proxyLocation.hostname, port: proxyLocation.port.toString(), protocol: proxyLocation.protocol, }; /*eslint-enable no-restricted-properties*/ })(); var REQUEST_DESCRIPTOR_VALUES_SEPARATOR = REQUEST_DESCRIPTOR_VALUES_SEPARATOR$1; function getCharsetFromDocument(parsedResourceType) { if (!parsedResourceType.isScript && !parsedResourceType.isServiceWorker) return null; return self.document && document[INTERNAL_PROPS.documentCharset] || null; } var getProxyUrl = function (url, opts, proxyless) { if (opts === void 0) { opts = {}; } if (proxyless === void 0) { proxyless = false; } if (opts.isUrlsSet) { opts.isUrlsSet = false; return handleUrlsSet(getProxyUrl, String(url), opts, proxyless); } if (proxyless) return String(url); url = getURLString(url); var resourceType = opts && opts.resourceType; var parsedResourceType = parseResourceType$1(resourceType); if (!parsedResourceType.isWebSocket && !isSupportedProtocol(url) && !isSpecialPage(url)) return url; // NOTE: Resolves relative URLs. var resolvedUrl = resolveUrl(url, opts && opts.doc); if (parsedResourceType.isWebSocket && !isValidWebSocketUrl(resolvedUrl) || !isValidUrl(resolvedUrl)) return url; /*eslint-disable no-restricted-properties*/ var proxyHostname = opts && opts.proxyHostname || DEFAULT_PROXY_SETTINGS.hostname; var proxyPort = opts && opts.proxyPort || DEFAULT_PROXY_SETTINGS.port; var proxyServerProtocol = opts && opts.proxyProtocol || DEFAULT_PROXY_SETTINGS.protocol; /*eslint-enable no-restricted-properties*/ var proxyProtocol = parsedResourceType.isWebSocket ? proxyServerProtocol.replace('http', 'ws') : proxyServerProtocol; var sessionId = opts && opts.sessionId || settings.get().sessionId; var windowId = opts && opts.windowId || settings.get().windowId; var credentials = opts && opts.credentials; var charset = opts && opts.charset; var reqOrigin = opts && opts.reqOrigin; var crossDomainPort = getCrossDomainProxyPort(proxyPort); // NOTE: If the relative URL contains no slash (e.g. 'img123'), the resolver will keep // the original proxy information, so that we can return such URL as is. // TODO: Implement the isProxyURL function. var parsedProxyUrl = parseProxyUrl$1(resolvedUrl); /*eslint-disable no-restricted-properties*/ var isValidProxyUrl = !!parsedProxyUrl && parsedProxyUrl.proxy.hostname === proxyHostname && (parsedProxyUrl.proxy.port === proxyPort || parsedProxyUrl.proxy.port === crossDomainPort); /*eslint-enable no-restricted-properties*/ if (isValidProxyUrl) { if (resourceType && parsedProxyUrl.resourceType === resourceType) return resolvedUrl; // NOTE: Need to change the proxy URL resource type. var destUrl = formatUrl$1(parsedProxyUrl.destResourceInfo); return getProxyUrl(destUrl, { proxyProtocol: proxyProtocol, proxyHostname: proxyHostname, proxyPort: proxyPort, sessionId: sessionId, resourceType: resourceType, charset: charset, reqOrigin: reqOrigin, credentials: credentials, }); } var parsedUrl = parseUrl$1(resolvedUrl); if (!parsedUrl.protocol) // eslint-disable-line no-restricted-properties return url; charset = charset || getCharsetFromDocument(parsedResourceType); // NOTE: It seems that the relative URL had the leading slash or dots, so that the proxy info path part was // removed by the resolver and we have an origin URL with the incorrect host and protocol. /*eslint-disable no-restricted-properties*/ if (parsedUrl.protocol === proxyServerProtocol && parsedUrl.hostname === proxyHostname && parsedUrl.port === proxyPort) { var parsedDestLocation = getParsed(); parsedUrl.protocol = parsedDestLocation.protocol; parsedUrl.host = parsedDestLocation.host; parsedUrl.hostname = parsedDestLocation.hostname; parsedUrl.port = parsedDestLocation.port || ''; resolvedUrl = formatUrl$1(parsedUrl); } /*eslint-enable no-restricted-properties*/ if (parsedResourceType.isWebSocket) { // eslint-disable-next-line no-restricted-properties parsedUrl.protocol = parsedUrl.protocol.replace('ws', 'http'); resolvedUrl = formatUrl$1(parsedUrl); reqOrigin = reqOrigin || getOriginHeader(); } if (parsedResourceType.isIframe && proxyPort === settings.get().crossDomainProxyPort) reqOrigin = reqOrigin || getOriginHeader(); return getProxyUrl$1(resolvedUrl, { proxyProtocol: proxyProtocol, proxyHostname: proxyHostname, proxyPort: proxyPort, sessionId: sessionId, resourceType: resourceType, charset: charset, reqOrigin: reqOrigin, windowId: windowId, credentials: credentials, }); }; function overrideGetProxyUrl(func) { getProxyUrl = func; } function getProxyNavigationUrl(url, win) { // NOTE: For the 'about:blank' page, we perform url proxing only for the top window, 'location' object and links. // For images and iframes, we keep urls as they were. // See details in https://github.com/DevExpress/testcafe-hammerhead/issues/339 var destinationLocation = null; var isIframe = win.top !== win; var winLocation = win.location.toString(); if (isIframe) destinationLocation = winLocation; else { var parsedProxyUrl = parseProxyUrl(winLocation); destinationLocation = parsedProxyUrl && parsedProxyUrl.destUrl; } if (isSpecialPage(destinationLocation) && isRelativeUrl(url)) return ''; url = prepareUrl(url); return getProxyUrl(url); } function getNavigationUrl(url, win, proxyless) { if (proxyless === void 0) { proxyless = false; } return proxyless ? url : getProxyNavigationUrl(url, win); } var getCrossDomainIframeProxyUrl = function (url) { return getProxyUrl(url, { proxyPort: settings.get().crossDomainProxyPort, resourceType: getResourceTypeString({ isIframe: true }), }); }; function overrideGetCrossDomainIframeProxyUrl(func) { getCrossDomainIframeProxyUrl = func; } function getPageProxyUrl(url, windowId) { var parsedProxyUrl = parseProxyUrl(url); var resourceType = null; if (parsedProxyUrl) { url = parsedProxyUrl.destUrl; resourceType = parsedProxyUrl.resourceType; } if (resourceType) { var parsedResourceType = parseResourceType(resourceType); parsedResourceType.isIframe = false; resourceType = stringifyResourceType(parsedResourceType); } var isCrossDomainUrl = !sameOriginCheck(getLocation(), url); var proxyPort = isCrossDomainUrl ? settings.get().crossDomainProxyPort : location.port.toString(); // eslint-disable-line no-restricted-properties return getProxyUrl(url, { windowId: windowId, proxyPort: proxyPort, resourceType: resourceType }); } function getCrossDomainProxyPort(proxyPort) { return settings.get().crossDomainProxyPort === proxyPort // eslint-disable-next-line no-restricted-properties ? location.port.toString() : settings.get().crossDomainProxyPort; } var resolveUrlAsDest = function (url, isUrlsSet) { if (isUrlsSet === void 0) { isUrlsSet = false; } return resolveUrlAsDest$1(url, getProxyUrl, isUrlsSet); }; function overrideResolveUrlAsDest(func) { resolveUrlAsDest = func; } function formatUrl(parsedUrl) { return formatUrl$1(parsedUrl); } var parseProxyUrl = function (proxyUrl) { return parseProxyUrl$1(proxyUrl); }; function overrideParseProxyUrl(func) { parseProxyUrl = func; } function parseUrl(url) { return parseUrl$1(url); } var convertToProxyUrl = function (url, resourceType, charset, isCrossDomain) { if (isCrossDomain === void 0) { isCrossDomain = false; } return getProxyUrl(url, { resourceType: resourceType, charset: charset, // eslint-disable-next-line no-restricted-properties proxyPort: isCrossDomain ? settings.get().crossDomainProxyPort : DEFAULT_PROXY_SETTINGS.port, }); }; function getCrossDomainProxyOrigin() { return getDomain({ protocol: location.protocol, hostname: location.hostname, port: settings.get().crossDomainProxyPort, }); } function overrideConvertToProxyUrl(func) { convertToProxyUrl = func; } function changeDestUrlPart(proxyUrl, nativePropSetter, value, resourceType) { var parsed = parseProxyUrl$1(proxyUrl); if (parsed) { var sessionId = parsed.sessionId; var proxy = parsed.proxy; var destUrl = urlResolver.changeUrlPart(parsed.destUrl, nativePropSetter, value, document); return getProxyUrl(destUrl, { /*eslint-disable no-restricted-properties*/ proxyHostname: proxy.hostname, proxyPort: proxy.port, /*eslint-enable no-restricted-properties*/ sessionId: sessionId, resourceType: resourceType, }); } return proxyUrl; } function isValidWebSocketUrl(url) { var resolvedUrl = resolveUrlAsDest(url); return SUPPORTED_WEB_SOCKET_PROTOCOL_RE.test(resolvedUrl); } function isSubDomain(domain, subDomain) { return isSubDomain$1(domain, subDomain); } function isSupportedProtocol(url) { return isSupportedProtocol$1(url); } function isSpecialPage(url) { return isSpecialPage$1(url); } function parseResourceType(resourceType) { return parseResourceType$1(resourceType); } function stringifyResourceType(resourceType) { return getResourceTypeString(resourceType); } function isChangedOnlyHash(currentUrl, newUrl) { // NOTE: we compare proxied urls because urls passed into the function may be proxied, non-proxied // or relative. The getProxyUrl function solves all the corresponding problems. return getProxyUrl(currentUrl).replace(HASH_RE, '') === getProxyUrl(newUrl).replace(HASH_RE, ''); } function getDestinationUrl(proxyUrl) { var parsedProxyUrl = parseProxyUrl(proxyUrl); return parsedProxyUrl ? parsedProxyUrl.destUrl : proxyUrl; } function getScope(url) { if (!isSupportedProtocol(url)) return null; var parsedUrl = parseUrl(resolveUrlAsDest(url)); if (!parsedUrl) return null; // NOTE: Delete query and hash parts. These parts are not related to the scope (GH-2524) var partAfterHostWithoutQueryAndHash = getPathname(parsedUrl.partAfterHost); return partAfterHostWithoutQueryAndHash.replace(SCOPE_RE, '/') || '/'; } function getAjaxProxyUrl(url, credentials, proxyless) { if (proxyless === void 0) { proxyless = false; } if (proxyless) return String(url); var isCrossDomain = !sameOriginCheck(getLocation(), url); var opts = { resourceType: stringifyResourceType({ isAjax: true }), credentials: credentials }; if (isCrossDomain) { opts.proxyPort = settings.get().crossDomainProxyPort; opts.reqOrigin = getOriginHeader(); } return getProxyUrl(url, opts); } var urlUtils = /*#__PURE__*/Object.freeze({ __proto__: null, DEFAULT_PROXY_SETTINGS: DEFAULT_PROXY_SETTINGS, REQUEST_DESCRIPTOR_VALUES_SEPARATOR: REQUEST_DESCRIPTOR_VALUES_SEPARATOR, get getProxyUrl () { return getProxyUrl; }, overrideGetProxyUrl: overrideGetProxyUrl, getNavigationUrl: getNavigationUrl, get getCrossDomainIframeProxyUrl () { return getCrossDomainIframeProxyUrl; }, overrideGetCrossDomainIframeProxyUrl: overrideGetCrossDomainIframeProxyUrl, getPageProxyUrl: getPageProxyUrl, getCrossDomainProxyPort: getCrossDomainProxyPort, get resolveUrlAsDest () { return resolveUrlAsDest; }, overrideResolveUrlAsDest: overrideResolveUrlAsDest, formatUrl: formatUrl, get parseProxyUrl () { return parseProxyUrl; }, overrideParseProxyUrl: overrideParseProxyUrl, parseUrl: parseUrl, get convertToProxyUrl () { return convertToProxyUrl; }, getCrossDomainProxyOrigin: getCrossDomainProxyOrigin, overrideConvertToProxyUrl: overrideConvertToProxyUrl, changeDestUrlPart: changeDestUrlPart, isValidWebSocketUrl: isValidWebSocketUrl, isSubDomain: isSubDomain, isSupportedProtocol: isSupportedProtocol, isSpecialPage: isSpecialPage, parseResourceType: parseResourceType, stringifyResourceType: stringifyResourceType, isChangedOnlyHash: isChangedOnlyHash, getDestinationUrl: getDestinationUrl, getScope: getScope, getAjaxProxyUrl: getAjaxProxyUrl }); var emptyActionAttrFallbacksToTheLocation = false; var instanceAndPrototypeToStringAreEqual = false; var hasTouchEvents = false; var hasTouchPoints = false; var isTouchDevice = false; var hasDataTransfer = false; var attrGetNamedItemIsNotEnumerable = false; var getElementsByNameReturnsHTMLCollection = false; if (nativeMethods.createElement) { var form = nativeMethods.createElement.call(document, 'form'); var elements = nativeMethods.getElementsByName.call(document, ''); // NOTE: In some browsers, elements without the url attribute return the location url // when accessing this attribute directly. See form.action in Edge 25 as an example. emptyActionAttrFallbacksToTheLocation = nativeMethods.formActionGetter.call(form) === window.location.toString(); // NOTE: In Chrome, toString(window) equals '[object Window]' and toString(Window.prototype) equals '[object Blob]', // this condition is also satisfied for Blob, Document, XMLHttpRequest, etc instanceAndPrototypeToStringAreEqual = nativeMethods.objectToString.call(window) === nativeMethods.objectToString.call(Window.prototype); hasTouchEvents = 'ontouchstart' in window; // NOTE: We need to check touch points only for IE, because it has PointerEvent and MSPointerEvent (IE10, IE11) // instead of TouchEvent (T109295). hasTouchPoints = isIE && navigator.maxTouchPoints > 0; isTouchDevice = (isMobile || isTablet) && hasTouchEvents; // @ts-ignore hasDataTransfer = !!window.DataTransfer; // NOTE: In the Edge 17, the getNamedItem method of attributes object is not enumerable attrGetNamedItemIsNotEnumerable = !!nativeMethods.objectGetOwnPropertyDescriptor.call(window.Object, NamedNodeMap.prototype, 'getNamedItem'); // Both IE and Edge return an HTMLCollection, not a NodeList // @ts-ignore getElementsByNameReturnsHTMLCollection = nativeMethods.objectGetPrototypeOf.call(window.Object, elements) === nativeMethods.HTMLCollection.prototype; } var featureDetection = /*#__PURE__*/Object.freeze({ __proto__: null, get emptyActionAttrFallbacksToTheLocation () { return emptyActionAttrFallbacksToTheLocation; }, get instanceAndPrototypeToStringAreEqual () { return instanceAndPrototypeToStringAreEqual; }, get hasTouchEvents () { return hasTouchEvents; }, get hasTouchPoints () { return hasTouchPoints; }, get isTouchDevice () { return isTouchDevice; }, get hasDataTransfer () { return hasDataTransfer; }, get attrGetNamedItemIsNotEnumerable () { return attrGetNamedItemIsNotEnumerable; }, get getElementsByNameReturnsHTMLCollection () { return getElementsByNameReturnsHTMLCollection; } }); // NOTE: For Chrome. var MIN_SELECT_SIZE_VALUE = 4; function getParsedValue(value, parseFn) { value = value || ''; var parsedValue = parseFn(value.replace('px', ''), 10); return isNaN(parsedValue) ? 0 : parsedValue; } function getIntValue(value) { return getParsedValue(value, parseInt); } function getFloatValue(value) { return getParsedValue(value, parseFloat); } function get$1(el, property, doc, win) { el = el.documentElement || el; var computedStyle = getComputedStyle(el, doc, win); return computedStyle && computedStyle[property]; } function set(el, property, value) { el = el.documentElement || el; el.style[property] = value; } function getBordersWidthInternal(el, parseFn) { return { bottom: parseFn(get$1(el, 'borderBottomWidth')), left: parseFn(get$1(el, 'borderLeftWidth')), right: parseFn(get$1(el, 'borderRightWidth')), top: parseFn(get$1(el, 'borderTopWidth')), }; } function getBordersWidth(el) { return getBordersWidthInternal(el, getIntValue); } function getBordersWidthFloat(el) { return getBordersWidthInternal(el, getFloatValue); } function getComputedStyle(el, doc, win) { // NOTE: In Firefox, after calling the 'document.write' function for nested iframes with html src value // document.defaultView equals 'null'. But 'window.document' equals 'document'. // This is why, we are forced to calculate the targetWindow instead of use document.defaultView. doc = doc || document; win = win || window; var targetWin = doc.defaultView || win; return targetWin.getComputedStyle(el, null); } function getElementMargin(el) { return { bottom: getIntValue(get$1(el, 'marginBottom')), left: getIntValue(get$1(el, 'marginLeft')), right: getIntValue(get$1(el, 'marginRight')), top: getIntValue(get$1(el, 'marginTop')), }; } function getElementPaddingInternal(el, parseFn) { return { bottom: parseFn(get$1(el, 'paddingBottom')), left: parseFn(get$1(el, 'paddingLeft')), right: parseFn(get$1(el, 'paddingRight')), top: parseFn(get$1(el, 'paddingTop')), }; } function getElementPadding(el) { return getElementPaddingInternal(el, getIntValue); } function getElementPaddingFloat(el) { return getElementPaddingInternal(el, getFloatValue); } function getElementScroll(el) { var isHtmlElement$1 = isHtmlElement(el); var currentWindow = window; if (isHtmlElement$1 && isElementInIframe(el)) { var currentIframe = getIframeByElement(el); if (currentIframe) currentWindow = nativeMethods.contentWindowGetter.call(currentIframe); } var targetEl = isHtmlElement$1 ? currentWindow : el; return { left: getScrollLeft(targetEl), top: getScrollTop(targetEl), }; } function getWidth(el) { if (!el) return null; if (isWindow(el)) return el.document.documentElement.clientWidth; if (isDocument(el)) { var doc = el.documentElement; var clientProp = 'clientWidth'; var scrollProp = 'scrollWidth'; var offsetProp = 'offsetWidth'; if (doc[clientProp] >= doc[scrollProp]) return doc[clientProp]; return Math.max(el.body[scrollProp], doc[scrollProp], el.body[offsetProp], doc[offsetProp]); } var value = el.offsetWidth; value -= getIntValue(get$1(el, 'paddingLeft')); value -= getIntValue(get$1(el, 'paddingRight')); value -= getIntValue(get$1(el, 'borderLeftWidth')); value -= getIntValue(get$1(el, 'borderRightWidth')); return value; } function getHeight(el) { if (!el) return null; if (isWindow(el)) return el.document.documentElement.clientHeight; if (isDocument(el)) { var doc = el.documentElement; var clientProp = 'clientHeight'; var scrollProp = 'scrollHeight'; var offsetProp = 'offsetHeight'; if (doc[clientProp] >= doc[scrollProp]) return doc[clientProp]; return Math.max(el.body[scrollProp], doc[scrollProp], el.body[offsetProp], doc[offsetProp]); } var value = el.offsetHeight; value -= getIntValue(get$1(el, 'paddingTop')); value -= getIntValue(get$1(el, 'paddingBottom')); value -= getIntValue(get$1(el, 'borderTopWidth')); value -= getIntValue(get$1(el, 'borderBottomWidth')); return value; } function getInnerWidth(el) { if (!el) return null; if (isWindow(el)) return el.document.documentElement.clientWidth; if (isDocument(el)) return el.documentElement.clientWidth; var value = el.offsetWidth; value -= getIntValue(get$1(el, 'borderLeftWidth')); value -= getIntValue(get$1(el, 'borderRightWidth')); return value; } function getInnerHeight(el) { if (!el) return null; if (isWindow(el)) return el.document.documentElement.clientHeight; if (isDocument(el)) return el.documentElement.clientHeight; var value = el.offsetHeight; value -= getIntValue(get$1(el, 'borderTopWidth')); value -= getIntValue(get$1(el, 'borderBottomWidth')); return value; } function getOptionHeight(select) { var realSizeValue = getSelectElementSize(select); var selectPadding = getElementPadding(select); var selectScrollHeight = select.scrollHeight - (selectPadding.top + selectPadding.bottom); var childrenCount = getSelectVisibleChildren(select).length; if (realSizeValue === 1) return getHeight(select); return isIE && realSizeValue > childrenCount ? Math.round(selectScrollHeight / childrenCount) : Math.round(selectScrollHeight / Math.max(childrenCount, realSizeValue)); } function getSelectElementSize(select) { // NOTE: iOS and Android ignore 'size' and 'multiple' attributes, // all select elements behave like a select with size=1. if (isSafari && hasTouchEvents || isAndroid) return 1; var sizeAttr = nativeMethods.getAttribute.call(select, 'size'); var multipleAttr = nativeMethods.hasAttribute.call(select, 'multiple'); var size = !sizeAttr ? 1 : parseInt(sizeAttr, 10); if (multipleAttr && (!sizeAttr || size < 1)) size = MIN_SELECT_SIZE_VALUE; return size; } function isVisibleChild(el) { var select = getSelectParent(el); var tagName = getTagName(el); return isSelectElement(select) && getSelectElementSize(select) > 1 && (tagName === 'option' || tagName === 'optgroup') && // NOTE: Firefox does not display groups without a label or with an empty label. (!isFirefox || el.label); } function getScrollLeft(el) { if (!el) return null; if (isWindow(el)) return el.pageXOffset; if (isDocument(el)) return el.defaultView.pageXOffset; return el.scrollLeft; } function getScrollTop(el) { if (!el) return null; if (isWindow(el)) return el.pageYOffset; if (isDocument(el)) return el.defaultView.pageYOffset; return el.scrollTop; } function setScrollLeft(el, value) { if (!el) return; if (isWindow(el) || isDocument(el)) { var win = findDocument(el).defaultView; var scrollTop = getScrollTop(el); nativeMethods.scrollTo.call(win, value, scrollTop); } else el.scrollLeft = value; } function setScrollTop(el, value) { if (!el) return; if (isWindow(el) || isDocument(el)) { var win = findDocument(el).defaultView; var scrollLeft = getScrollLeft(el); nativeMethods.scrollTo.call(win, scrollLeft, value); } else el.scrollTop = value; } function getOffsetParent(el) { if (el) { var offsetParent = el.offsetParent || document.body; while (offsetParent && (!/^(?:body|html)$/i.test(offsetParent.nodeName) && get$1(offsetParent, 'position') === 'static')) offsetParent = offsetParent.offsetParent; return offsetParent; } return void 0; } function getOffset(el) { if (!el || isWindow(el) || isDocument(el)) return null; var clientRect = el.getBoundingClientRect(); // NOTE: A detached node or documentElement. var doc = el.ownerDocument; var docElement = doc.documentElement; if (!docElement.contains(el) || el === docElement) { return { top: clientRect.top, left: clientRect.left, }; } var win = doc.defaultView; var clientTop = docElement.clientTop || doc.body.clientTop || 0; var clientLeft = docElement.clientLeft || doc.body.clientLeft || 0; var scrollTop = win.pageYOffset || docElement.scrollTop || doc.body.scrollTop; var scrollLeft = win.pageXOffset || docElement.scrollLeft || doc.body.scrollLeft; clientRect = el.getBoundingClientRect(); return { top: clientRect.top + scrollTop - clientTop, left: clientRect.left + scrollLeft - clientLeft, }; } function isElementVisible(el, doc) { if (!isElementInDocument(el, doc)) return false; while (el) { if (get$1(el, 'display', doc) === 'none' || get$1(el, 'visibility', doc) === 'hidden') return false; el = getParentExceptShadowRoot(el); } return true; } function isElementInInvisibleIframe(el) { var frameElement = getIframeByElement(el); return frameElement && !isElementVisible(frameElement, findDocument(frameElement)); } var styleUtils = /*#__PURE__*/Object.freeze({ __proto__: null, get: get$1, set: set, getBordersWidthInternal: getBordersWidthInternal, getBordersWidth: getBordersWidth, getBordersWidthFloat: getBordersWidthFloat, getComputedStyle: getComputedStyle, getElementMargin: getElementMargin, getElementPaddingInternal: getElementPaddingInternal, getElementPadding: getElementPadding, getElementPaddingFloat: getElementPaddingFloat, getElementScroll: getElementScroll, getWidth: getWidth, getHeight: getHeight, getInnerWidth: getInnerWidth, getInnerHeight: getInnerHeight, getOptionHeight: getOptionHeight, getSelectElementSize: getSelectElementSize, isVisibleChild: isVisibleChild, getScrollLeft: getScrollLeft, getScrollTop: getScrollTop, setScrollLeft: setScrollLeft, setScrollTop: setScrollTop, getOffsetParent: getOffsetParent, getOffset: getOffset, isElementVisible: isElementVisible, isElementInInvisibleIframe: isElementInInvisibleIframe }); function getNativeQuerySelector(el) { if (isDomElement(el)) return nativeMethods.elementQuerySelector; return isDocumentFragmentNode(el) || isShadowRoot(el) ? nativeMethods.documentFragmentQuerySelector : nativeMethods.querySelector; } function getNativeQuerySelectorAll(el) { // NOTE: Do not return the isDocument function instead of the isDomElement // it leads to the `Invalid calling object` error in some cases in IE11 (GH-1846) if (isDomElement(el)) return nativeMethods.elementQuerySelectorAll; return isDocumentFragmentNode(el) || isShadowRoot(el) ? nativeMethods.documentFragmentQuerySelectorAll : nativeMethods.querySelectorAll; } var scrollbarSize = 0; var NATIVE_MAP_ELEMENT_STRINGS = [ '[object HTMLMapElement]', '[object HTMLAreaElement]', ]; var WINDOW_IS_UNDEFINED = typeof window === 'undefined'; var NATIVE_WINDOW_STR = WINDOW_IS_UNDEFINED ? '' : instanceToString(window); var IS_DOCUMENT_RE = /^\[object .*?Document]$/i; var IS_PROCESSING_INSTRUCTION_RE = /^\[object .*?ProcessingInstruction]$/i; var IS_SVG_ELEMENT_RE = /^\[object SVG\w+?Element]$/i; var IS_HTML_ELEMENT_RE = /^\[object HTML.*?Element]$/i; var IS_ARRAY_BUFFER_RE = /^\[object ArrayBuffer]$/i; var IS_DATA_VIEW_RE = /^\[object DataView]$/i; var NATIVE_TABLE_CELL_STR = WINDOW_IS_UNDEFINED ? '' : instanceToString(nativeMethods.createElement.call(document, 'td')); var ELEMENT_NODE_TYPE = WINDOW_IS_UNDEFINED ? -1 : Node.ELEMENT_NODE; var NOT_CONTENT_EDITABLE_ELEMENTS_RE = /^(select|option|applet|area|audio|canvas|datalist|keygen|map|meter|object|progress|source|track|video|img)$/; var INPUT_ELEMENTS_RE = /^(input|textarea|button)$/; var SCRIPT_OR_STYLE_RE = /^(script|style)$/i; var EDITABLE_INPUT_TYPES_RE = /^(email|number|password|search|tel|text|url)$/; var NUMBER_OR_EMAIL_INPUT_RE = /^(number|email)$/; // NOTE: input with 'file' type processed separately in 'UploadSandbox' var INPUT_WITH_NATIVE_DIALOG = /^(color|date|datetime-local|month|week)$/; // NOTE: We don't take into account the case of embedded contentEditable elements, and we // specify the contentEditable attribute for focusable elements. var FOCUSABLE_SELECTOR = 'input, select, textarea, button, body, iframe, [contenteditable="true"], [contenteditable=""], [tabIndex]'; function isHidden(el) { return el.offsetWidth <= 0 && el.offsetHeight <= 0; } function isAlwaysNotEditableElement(el) { var tagName = getTagName(el); return !!tagName && (NOT_CONTENT_EDITABLE_ELEMENTS_RE.test(tagName) || INPUT_ELEMENTS_RE.test(tagName)); } function isLocationByProto(instance) { var instanceCtor = null; try { // eslint-disable-next-line no-proto instanceCtor = instance.__proto__; } catch (e) { // NOTE: Try to detect cross-domain window location. // A cross-domain location has no the "assign" function in Safari, Chrome and FireFox. var shouldNotHaveAssign = isSafari || isChrome || isFirefox; return instance.replace && (shouldNotHaveAssign || !!instance.assign); } if (!instanceCtor) return false; var stringifiedInstanceCtor = nativeMethods.objectToString.call(instanceCtor); return stringifiedInstanceCtor === '[object LocationPrototype]' || stringifiedInstanceCtor === '[object Location]'; // NOTE: "iPhone" Chrome device emulation case (GH-2080) } function closestFallback(el, selector) { while (el) { if (matches(el, selector)) return el; el = nativeMethods.nodeParentNodeGetter.call(el); } return null; } function instanceToString(instance) { if (!instanceAndPrototypeToStringAreEqual) return nativeMethods.objectToString.call(instance); return instance && typeof instance === 'object' ? nativeMethods.objectToString.call(nativeMethods.objectGetPrototypeOf(instance)) : ''; } function getActiveElement(currentDocument) { // NOTE: Sometimes document.activeElement returns an empty object or null (IE11). // https://github.com/DevExpress/testcafe-hammerhead/issues/768 var doc = currentDocument || document; var activeElement = nativeMethods.documentActiveElementGetter.call(doc); var el = isDomElement(activeElement) ? activeElement : doc.body; while (el && el.shadowRoot) { // eslint-disable-next-line no-restricted-properties var shadowEl = el.shadowRoot.activeElement; if (!shadowEl) break; el = shadowEl; } return el; } function getChildVisibleIndex(select, child) { var childrenArray = getSelectVisibleChildren(select); return childrenArray.indexOf(child); } function getIframeByElement(el) { var elWindow = el[INTERNAL_PROPS.processedContext]; return getFrameElement(elWindow); } function getIframeLocation(iframe) { var documentLocation = null; try { // eslint-disable-next-line no-restricted-properties documentLocation = nativeMethods.contentDocumentGetter.call(iframe).location.href; } catch (e) { documentLocation = null; } var srcLocation = nativeMethods.getAttribute.call(iframe, 'src' + INTERNAL_ATTRIBUTES.storedAttrPostfix) || nativeMethods.getAttribute.call(iframe, 'src') || nativeMethods.iframeSrcGetter.call(iframe); var parsedProxyDocumentLocation = documentLocation && isSupportedProtocol(documentLocation) && parseProxyUrl(documentLocation); var parsedProxySrcLocation = srcLocation && isSupportedProtocol(srcLocation) && parseProxyUrl(srcLocation); return { documentLocation: parsedProxyDocumentLocation ? parsedProxyDocumentLocation.destUrl : documentLocation, srcLocation: parsedProxySrcLocation ? parsedProxySrcLocation.destUrl : srcLocation, }; } function getFrameElement(win) { try { return win.frameElement; } catch (e) { return null; } } function getMapContainer(el) { var closestMap = closest(el, 'map'); var closestMapName = nativeMethods.getAttribute.call(closestMap, 'name'); var containerSelector = '[usemap="#' + closestMapName + '"]'; return nativeMethods.querySelector.call(findDocument(el), containerSelector); } function getParentWindowWithSrc(window) { var parent = window.parent; var parentFrameElement = null; if (window === window.top) return window; if (parent === window.top || isCrossDomainWindows(window, parent)) return parent; try { parentFrameElement = parent.frameElement; } catch (e) { parentFrameElement = null; } if (parentFrameElement === null || !isIframeWithoutSrc(parentFrameElement)) return parent; return getParentWindowWithSrc(parent); } function getScrollbarSize() { if (!scrollbarSize) { var scrollDiv = nativeMethods.createElement.call(document, 'div'); scrollDiv.style.height = '100px'; scrollDiv.style.overflow = 'scroll'; scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '100px'; nativeMethods.appendChild.call(document.body, scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; scrollbarSize = scrollbarWidth; var parent_1 = nativeMethods.nodeParentNodeGetter.call(scrollDiv); parent_1.removeChild(scrollDiv); } return scrollbarSize; } function getSelectParent(child) { var parent = nativeMethods.nodeParentNodeGetter.call(child); return closest(parent, 'select'); } function getSelectVisibleChildren(select) { var children = nativeMethods.elementQuerySelectorAll.call(select, 'optgroup, option'); var result = []; var length = nativeMethods.nodeListLengthGetter.call(children); for (var i = 0; i < length; i++) { var child = children[i]; // NOTE: Firefox does not display groups without a label and with an empty label. var shouldAdd = isFirefox ? getTagName(child) !== 'optgroup' || child.label : true; if (shouldAdd) result.push(child); } return result; } function getTopSameDomainWindow(window) { var result = window; var currentWindow = window.parent; if (result === window.top) return result; while (currentWindow) { if (!isCrossDomainWindows(window, currentWindow)) { var frameElement_1 = getFrameElement(currentWindow); if (!frameElement_1 || !isIframeWithoutSrc(frameElement_1)) result = currentWindow; } currentWindow = currentWindow !== window.top ? currentWindow.parent : null; } return result; } function find(parent, selector, handler) { var nodeList = getNativeQuerySelectorAll(parent).call(parent, selector); if (handler) { var length_1 = nativeMethods.nodeListLengthGetter.call(nodeList); for (var i = 0; i < length_1; i++) handler(nodeList[i]); } return nodeList; } function findDocument(el) { if (el.documentElement) return el; if (el.ownerDocument && el.ownerDocument.defaultView) return el.ownerDocument; var parent = isElementNode(el) && nativeMethods.nodeParentNodeGetter.call(el); return parent ? findDocument(parent) : document; } function isContentEditableElement(el) { var isContentEditable = false; var element = null; if (isTextNode(el)) element = el.parentElement || nativeMethods.nodeParentNodeGetter.call(el); else element = el; if (element) { isContentEditable = element.isContentEditable && !isAlwaysNotEditableElement(element); return isRenderedNode(element) && (isContentEditable || findDocument(el).designMode === 'on'); } return false; } function isCrossDomainIframe(iframe, bySrc) { var iframeLocation = getIframeLocation(iframe); if (!bySrc && iframeLocation.documentLocation === null) return true; var currentLocation = bySrc ? iframeLocation.srcLocation : iframeLocation.documentLocation; if (currentLocation && isSupportedProtocol(currentLocation)) return !sameOriginCheck(location.toString(), currentLocation); return false; } function isCrossDomainWindows(window1, window2) { try { if (window1 === window2) return false; var window1Location = window1.location.toString(); var window2Location = window2.location.toString(); if (!isSupportedProtocol(window1Location) || !isSupportedProtocol(window2Location)) return false; return !sameOriginCheck(window1Location, window2Location); } catch (e) { return true; } } function isIframeWindow(wnd) { return wnd !== wnd.top; } function isDomElement(el) { if (el instanceof nativeMethods.elementClass) return true; return el && IS_HTML_ELEMENT_RE.test(instanceToString(el)) && isElementNode(el) && el.tagName; } function getTagName(el) { // NOTE: Check for tagName being a string, because it may be a function in an Angular app (T175340). return el && typeof el.tagName === 'string' ? el.tagName.toLowerCase() : ''; } var SHADOW_ROOT_PARENT_ELEMENT = 'hammerhead|element|shadow-root-parent'; function getNodeShadowRootParent(el) { var parent = nativeMethods.nodeParentNodeGetter.call(el); while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) parent = nativeMethods.nodeParentNodeGetter.call(parent); return parent && parent[SHADOW_ROOT_PARENT_ELEMENT]; } function getParentExceptShadowRoot(el) { var parent = nativeMethods.nodeParentNodeGetter.call(el); return parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE && parent[SHADOW_ROOT_PARENT_ELEMENT] ? parent[SHADOW_ROOT_PARENT_ELEMENT] : parent; } function isElementInDocument(el, currentDocument) { var doc = currentDocument || document; if (!doc.documentElement) return false; if (doc.documentElement.contains(el)) return true; var shadowRootParent = getNodeShadowRootParent(el); return shadowRootParent ? isElementInDocument(shadowRootParent) : false; } function isElementInIframe(el, currentDocument) { var doc = currentDocument || findDocument(el); return window.document !== doc; } function isHammerheadAttr(attr) { return attr === INTERNAL_ATTRIBUTES.focusPseudoClass || attr === INTERNAL_ATTRIBUTES.hoverPseudoClass || attr.indexOf(INTERNAL_ATTRIBUTES.storedAttrPostfix) !== -1; } function isIframeElement(el) { return instanceToString(el) === '[object HTMLIFrameElement]'; } function isFrameElement(el) { return instanceToString(el) === '[object HTMLFrameElement]'; } function isIframeWithoutSrc(iframe) { var iframeLocation = getIframeLocation(iframe); var iframeSrcLocation = iframeLocation.srcLocation; var iframeDocumentLocation = iframeLocation.documentLocation; // NOTE: is a cross-domain iframe if (iframeDocumentLocation === null) return false; // NOTE: after 'document.write' or 'document.open' call for iframe with/without src // we will process it as iframe without src if (nativeMethods.contentWindowGetter.call(iframe)[INTERNAL_PROPS.documentWasCleaned]) return true; var iframeDocumentLocationHaveSupportedProtocol = isSupportedProtocol(iframeDocumentLocation); // NOTE: When an iframe has an empty src attribute () or has no src attribute (), // the iframe.src property is not empty but has different values in different browsers. // Its document location is 'about:blank'. Therefore, we should check the src attribute. if (!iframeDocumentLocationHaveSupportedProtocol && !nativeMethods.getAttribute.call(iframe, 'src')) return true; // In Chrome, when an iframe with the src attribute is added to DOM, // its documentLocation is set to "about:blank" until the iframe has been loaded. // So, we should check srcLocation in this case. if (iframeSrcLocation && isSupportedProtocol(iframeSrcLocation)) return false; return !iframeDocumentLocationHaveSupportedProtocol; } function isIframeWithSrcdoc(iframe) { return nativeMethods.iframeSrcdocGetter && nativeMethods.hasAttribute.call(iframe, 'srcdoc'); } function isImgElement(el) { return instanceToString(el) === '[object HTMLImageElement]'; } function isInputElement(el) { return instanceToString(el) === '[object HTMLInputElement]'; } function isTitleElement(el) { return instanceToString(el) === '[object HTMLTitleElement]'; } function isButtonElement(el) { return instanceToString(el) === '[object HTMLButtonElement]'; } function isFieldSetElement(el) { return instanceToString(el) === '[object HTMLFieldSetElement]'; } function isOptGroupElement(el) { return instanceToString(el) === '[object HTMLOptGroupElement]'; } function isHtmlElement(el) { return instanceToString(el) === '[object HTMLHtmlElement]'; } function isBodyElement(el) { return instanceToString(el) === '[object HTMLBodyElement]'; } function isPageBody(el) { var _a; var parent = nativeMethods.nodeParentNodeGetter.call(el); return getTagName(parent) === 'html' && ((_a = nativeMethods.nodeParentNodeGetter.call(parent)) === null || _a === void 0 ? void 0 : _a.nodeName) === '#document'; } function isHeadElement(el) { return instanceToString(el) === '[object HTMLHeadElement]'; } function isHeadOrBodyElement(el) { var elString = instanceToString(el); return elString === '[object HTMLHeadElement]' || elString === '[object HTMLBodyElement]'; } function isHeadOrBodyOrHtmlElement(el) { var elString = instanceToString(el); return elString === '[object HTMLHeadElement]' || elString === '[object HTMLBodyElement]' || elString === '[object HTMLHtmlElement]'; } function isBaseElement(el) { return instanceToString(el) === '[object HTMLBaseElement]'; } function isScriptElement(el) { return instanceToString(el) === '[object HTMLScriptElement]'; } function isStyleElement(el) { return instanceToString(el) === '[object HTMLStyleElement]'; } function isLabelElement(el) { return instanceToString(el) === '[object HTMLLabelElement]'; } function isTextAreaElement(el) { return instanceToString(el) === '[object HTMLTextAreaElement]'; } function isOptionElement(el) { return instanceToString(el) === '[object HTMLOptionElement]'; } function isRadioButtonElement(el) { return isInputElement(el) && el.type.toLowerCase() === 'radio'; } function isColorInputElement(el) { return isInputElement(el) && el.type.toLowerCase() === 'color'; } function isCheckboxElement(el) { return isInputElement(el) && el.type.toLowerCase() === 'checkbox'; } function isSelectElement(el) { return instanceToString(el) === '[object HTMLSelectElement]'; } function isFormElement(el) { return instanceToString(el) === '[object HTMLFormElement]'; } function isFileInput(el) { return isInputElement(el) && el.type.toLowerCase() === 'file'; } function isInputWithNativeDialog(el) { return isInputElement(el) && INPUT_WITH_NATIVE_DIALOG.test(el.type.toLowerCase()); } function isBodyElementWithChildren(el) { return isBodyElement(el) && isPageBody(el) && nativeMethods.htmlCollectionLengthGetter.call(nativeMethods.elementChildrenGetter.call(el)); } function isMapElement(el) { return NATIVE_MAP_ELEMENT_STRINGS.indexOf(instanceToString(el)) !== -1; } function isRenderedNode(node) { return !(isProcessingInstructionNode(node) || isCommentNode(node) || SCRIPT_OR_STYLE_RE.test(node.nodeName)); } function getTabIndex(el) { // NOTE: we obtain the tabIndex value from an attribute because the el.tabIndex // property returns -1 for some elements (e.g. for body) with no tabIndex assigned var tabIndex = nativeMethods.getAttribute.call(el, 'tabIndex'); tabIndex = parseInt(tabIndex, 10); return isNaN(tabIndex) ? null : tabIndex; } function isElementDisabled(el) { return matches(el, ':disabled'); } function isElementFocusable(el) { if (!el) return false; var tabIndex = getTabIndex(el); var isDisabledElement = isElementDisabled(el); var isInvisibleElement = get$1(el, 'visibility') === 'hidden'; var isNotDisplayedElement = get$1(el, 'display') === 'none'; var isHiddenElement = isWebKit ? isHidden(el) && !isOptionElement(el) : isHidden(el); if (isDisabledElement || isInvisibleElement || isNotDisplayedElement || isHiddenElement) return false; if (isOptionElement(el) && isIE) return false; if (isAnchorElement(el)) { if (tabIndex !== null) return true; return matches(el, 'a[href]'); } if (isTableDataCellElement(el) && isIE) return true; return matches(el, FOCUSABLE_SELECTOR) || tabIndex !== null; } function isShadowUIElement(element) { // @ts-ignore return !!element[INTERNAL_PROPS.shadowUIElement]; } function isWindow(instance) { try { // NOTE: The instanceToString call result has a strange values for the MessageEvent.target property: // * [object DispHTMLWindow2] for IE11 // * [object Object] for MSEdge. if ((isIE || isMSEdge) && instance && instance === instance.window) instance = instance.window; if (!instance || !instance.toString || NATIVE_WINDOW_STR !== instanceToString(instance)) return false; } catch (e) { try { // NOTE: If a cross-domain object has the 'top' field, this object is a window // (not a document or location). return !!instance.top; } catch (_a) { return false; } } try { nativeMethods.winLocalStorageGetter.call(instance); } catch (_b) { return false; } return true; } function isDocument(instance) { if (instance instanceof nativeMethods.documentClass) return true; try { return instance && IS_DOCUMENT_RE.test(instanceToString(instance)); } catch (e) { // NOTE: For cross-domain objects (windows, documents or locations), we return false because // it's impossible to work with them in any case. return false; } } function isBlob(instance) { return instance && instanceToString(instance) === '[object Blob]'; } function isLocation(instance) { if (!instance) return false; if (isIE || isSafari || isChrome || isFirefox) return isLocationByProto(instance); return instance instanceof nativeMethods.locationClass || nativeMethods.objectToString.call(instance) === '[object Location]'; } function isSVGElement(instance) { if (instance instanceof nativeMethods.svgElementClass) return true; return instance && IS_SVG_ELEMENT_RE.test(instanceToString(instance)); } function isSVGElementOrChild(el) { return !!closest(el, 'svg'); } function isFetchHeaders(instance) { if (nativeMethods.Headers && instance instanceof nativeMethods.Headers) return true; return instance && instanceToString(instance) === '[object Headers]'; } function isFetchRequest(instance) { if (nativeMethods.Request && instance instanceof nativeMethods.Request) return true; return instance && instanceToString(instance) === '[object Request]'; } function isElementReadOnly(el) { return el.readOnly || el.getAttribute('readonly') === 'readonly'; } function isTextEditableInput(el) { var attrType = el.getAttribute('type'); return isInputElement(el) && attrType ? EDITABLE_INPUT_TYPES_RE.test(attrType) : EDITABLE_INPUT_TYPES_RE.test(el.type); } function isTextEditableElement(el) { return isTextEditableInput(el) || isTextAreaElement(el); } function isTextEditableElementAndEditingAllowed(el) { return isTextEditableElement(el) && !isElementReadOnly(el); } function isElementNode(node) { return node && node.nodeType === ELEMENT_NODE_TYPE; } function isTextNode(node) { return instanceToString(node) === '[object Text]'; } function isProcessingInstructionNode(node) { return IS_PROCESSING_INSTRUCTION_RE.test(instanceToString(node)); } function isCommentNode(node) { return instanceToString(node) === '[object Comment]'; } function isDocumentFragmentNode(node) { return instanceToString(node) === '[object DocumentFragment]'; } function isShadowRoot(root) { return instanceToString(root) === '[object ShadowRoot]'; } function isAnchorElement(el) { return instanceToString(el) === '[object HTMLAnchorElement]'; } function isTableElement(el) { return instanceToString(el) === '[object HTMLTableElement]'; } function isTableDataCellElement(el) { return instanceToString(el) === NATIVE_TABLE_CELL_STR; } function isWebSocket(ws) { return instanceToString(ws) === '[object WebSocket]'; } function isMessageEvent(e) { return instanceToString(e) === '[object MessageEvent]'; } function isPerformanceNavigationTiming(entry) { return instanceToString(entry) === '[object PerformanceNavigationTiming]'; } function isArrayBuffer(data) { if (data instanceof nativeMethods.ArrayBuffer) return true; return data && IS_ARRAY_BUFFER_RE.test(instanceToString(data)); } function isArrayBufferView(data) { return data && nativeMethods.arrayBufferIsView(data); } function isDataView(data) { if (data instanceof nativeMethods.DataView) return true; return data && IS_DATA_VIEW_RE.test(instanceToString(data)); } function matches(el, selector) { if (!isElementNode(el)) return false; return nativeMethods.matches.call(el, selector); } function closest(el, selector) { if (!isElementNode(el)) return null; if (nativeMethods.closest) return nativeMethods.closest.call(el, selector); return closestFallback(el, selector); } function addClass(el, className) { if (!el) return; var classNames = className.split(/\s+/); for (var _i = 0, classNames_1 = classNames; _i < classNames_1.length; _i++) { var currentClassName = classNames_1[_i]; nativeMethods.tokenListAdd.call(nativeMethods.elementClassListGetter.call(el), currentClassName); } } function removeClass(el, className) { if (!el) return; var classNames = className.split(/\s+/); for (var _i = 0, classNames_2 = classNames; _i < classNames_2.length; _i++) { var currentClassName = classNames_2[_i]; nativeMethods.tokenListRemove.call(nativeMethods.elementClassListGetter.call(el), currentClassName); } } function hasClass(el, className) { if (!el) return false; return nativeMethods.tokenListContains.call(nativeMethods.elementClassListGetter.call(el), className); } function parseDocumentCharset() { var metaCharset = nativeMethods.querySelector.call(document, '.' + SHADOW_UI_CLASS_NAME.charset); return metaCharset && metaCharset.getAttribute('charset'); } function getParents(el, selector) { var parents = []; var parent = getParent(el); while (parent) { if (!selector && isElementNode(parent) || selector && matches(parent, selector)) parents.push(parent); parent = getParent(parent); } return parents; } function getParent(el) { el = el.assignedSlot || el; // eslint-disable-next-line no-restricted-properties return nativeMethods.nodeParentNodeGetter.call(el) || el.host; } function findParent(node, includeSelf, predicate) { if (includeSelf === void 0) { includeSelf = false; } if (!includeSelf) node = getParent(node); while (node) { if (!isFunction(predicate) || predicate(node)) return node; node = getParent(node); } return null; } function nodeListToArray(nodeList) { var result = []; var length = nativeMethods.nodeListLengthGetter.call(nodeList); for (var i = 0; i < length; i++) result.push(nodeList[i]); return result; } function getFileInputs(el) { return isFileInput(el) ? [el] : nodeListToArray(getNativeQuerySelectorAll(el).call(el, 'input[type=file]')); } function getIframes(el) { return isIframeElement(el) ? [el] : nodeListToArray(getNativeQuerySelectorAll(el).call(el, 'iframe,frame')); } function getScripts(el) { return isScriptElement(el) ? [el] : nodeListToArray(getNativeQuerySelectorAll(el).call(el, 'script')); } function isNumberOrEmailInput(el) { return isInputElement(el) && NUMBER_OR_EMAIL_INPUT_RE.test(el.type); } function isInputWithoutSelectionProperties(el) { if (!isNumberOrEmailInput(el)) return false; var hasSelectionProperties = isNumber(el.selectionStart) && isNumber(el.selectionEnd); return !hasSelectionProperties; } function getAssociatedElement(el) { if (!isLabelElement(el)) return null; var doc = findDocument(el); return el.control || el.htmlFor && nativeMethods.getElementById.call(doc, el.htmlFor); } var domUtils = /*#__PURE__*/Object.freeze({ __proto__: null, instanceToString: instanceToString, getActiveElement: getActiveElement, getChildVisibleIndex: getChildVisibleIndex, getIframeByElement: getIframeByElement, getIframeLocation: getIframeLocation, getFrameElement: getFrameElement, getMapContainer: getMapContainer, getParentWindowWithSrc: getParentWindowWithSrc, getScrollbarSize: getScrollbarSize, getSelectParent: getSelectParent, getSelectVisibleChildren: getSelectVisibleChildren, getTopSameDomainWindow: getTopSameDomainWindow, find: find, findDocument: findDocument, isContentEditableElement: isContentEditableElement, isCrossDomainIframe: isCrossDomainIframe, isCrossDomainWindows: isCrossDomainWindows, isIframeWindow: isIframeWindow, isDomElement: isDomElement, getTagName: getTagName, SHADOW_ROOT_PARENT_ELEMENT: SHADOW_ROOT_PARENT_ELEMENT, getNodeShadowRootParent: getNodeShadowRootParent, getParentExceptShadowRoot: getParentExceptShadowRoot, isElementInDocument: isElementInDocument, isElementInIframe: isElementInIframe, isHammerheadAttr: isHammerheadAttr, isIframeElement: isIframeElement, isFrameElement: isFrameElement, isIframeWithoutSrc: isIframeWithoutSrc, isIframeWithSrcdoc: isIframeWithSrcdoc, isImgElement: isImgElement, isInputElement: isInputElement, isTitleElement: isTitleElement, isButtonElement: isButtonElement, isFieldSetElement: isFieldSetElement, isOptGroupElement: isOptGroupElement, isHtmlElement: isHtmlElement, isBodyElement: isBodyElement, isPageBody: isPageBody, isHeadElement: isHeadElement, isHeadOrBodyElement: isHeadOrBodyElement, isHeadOrBodyOrHtmlElement: isHeadOrBodyOrHtmlElement, isBaseElement: isBaseElement, isScriptElement: isScriptElement, isStyleElement: isStyleElement, isLabelElement: isLabelElement, isTextAreaElement: isTextAreaElement, isOptionElement: isOptionElement, isRadioButtonElement: isRadioButtonElement, isColorInputElement: isColorInputElement, isCheckboxElement: isCheckboxElement, isSelectElement: isSelectElement, isFormElement: isFormElement, isFileInput: isFileInput, isInputWithNativeDialog: isInputWithNativeDialog, isBodyElementWithChildren: isBodyElementWithChildren, isMapElement: isMapElement, isRenderedNode: isRenderedNode, getTabIndex: getTabIndex, isElementDisabled: isElementDisabled, isElementFocusable: isElementFocusable, isShadowUIElement: isShadowUIElement, isWindow: isWindow, isDocument: isDocument, isBlob: isBlob, isLocation: isLocation, isSVGElement: isSVGElement, isSVGElementOrChild: isSVGElementOrChild, isFetchHeaders: isFetchHeaders, isFetchRequest: isFetchRequest, isElementReadOnly: isElementReadOnly, isTextEditableInput: isTextEditableInput, isTextEditableElement: isTextEditableElement, isTextEditableElementAndEditingAllowed: isTextEditableElementAndEditingAllowed, isElementNode: isElementNode, isTextNode: isTextNode, isProcessingInstructionNode: isProcessingInstructionNode, isCommentNode: isCommentNode, isDocumentFragmentNode: isDocumentFragmentNode, isShadowRoot: isShadowRoot, isAnchorElement: isAnchorElement, isTableElement: isTableElement, isTableDataCellElement: isTableDataCellElement, isWebSocket: isWebSocket, isMessageEvent: isMessageEvent, isPerformanceNavigationTiming: isPerformanceNavigationTiming, isArrayBuffer: isArrayBuffer, isArrayBufferView: isArrayBufferView, isDataView: isDataView, matches: matches, closest: closest, addClass: addClass, removeClass: removeClass, hasClass: hasClass, parseDocumentCharset: parseDocumentCharset, getParents: getParents, findParent: findParent, nodeListToArray: nodeListToArray, getFileInputs: getFileInputs, getIframes: getIframes, getScripts: getScripts, isNumberOrEmailInput: isNumberOrEmailInput, isInputWithoutSelectionProperties: isInputWithoutSelectionProperties, getAssociatedElement: getAssociatedElement }); var SandboxBase = /** @class */ (function (_super) { __extends(SandboxBase, _super); function SandboxBase() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.window = null; _this.nativeMethods = nativeMethods; _this.document = null; _this.proxyless = false; return _this; } // NOTE: The sandbox is deactivated when its window is removed from the DOM. SandboxBase.prototype.isDeactivated = function () { try { // NOTE: In IE11, a situation when the document is not active may occur. // eslint-disable-next-line no-unused-expressions this.document.body; if (this.window[INTERNAL_PROPS.hammerhead]) { var frameElement_1 = getFrameElement(this.window); return !!frameElement_1 && !isElementInDocument(frameElement_1, findDocument(frameElement_1)); } } catch (e) { // eslint-disable-line no-empty } return true; }; SandboxBase.prototype.attach = function (window, document) { this.window = window; this.document = document || window.document; this.proxyless = !!settings.get().proxyless; }; return SandboxBase; }(EventEmitter)); // ------------------------------------------------------------- var isArray, json$1, renumber, hexadecimal, quotes, escapeless, parentheses, semicolons, safeConcatenation, directive, extra; var Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DirectiveStatement: 'DirectiveStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportDeclaration: 'ExportDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', GeneratorExpression: 'GeneratorExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportExpression: 'ImportExpression', ImportSpecifier: 'ImportSpecifier', ImportDeclaration: 'ImportDeclaration', ChainExpression: 'ChainExpression', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', ModuleDeclaration: 'ModuleDeclaration', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; var Syntax_1 = Syntax; var Precedence = { Sequence: 0, Yield: 1, Assignment: 1, Conditional: 2, ArrowFunction: 2, Coalesce: 3, LogicalOR: 3, LogicalAND: 4, BitwiseOR: 5, BitwiseXOR: 6, BitwiseAND: 7, Equality: 8, Relational: 9, BitwiseSHIFT: 10, Additive: 11, Multiplicative: 12, Unary: 13, Exponentiation: 14, Postfix: 14, Await: 14, Call: 15, New: 16, TaggedTemplate: 17, OptionalChaining: 17, Member: 18, Primary: 19 }; var BinaryPrecedence = { '||': Precedence.LogicalOR, '&&': Precedence.LogicalAND, '|': Precedence.BitwiseOR, '^': Precedence.BitwiseXOR, '&': Precedence.BitwiseAND, '==': Precedence.Equality, '!=': Precedence.Equality, '===': Precedence.Equality, '!==': Precedence.Equality, 'is': Precedence.Equality, 'isnt': Precedence.Equality, '<': Precedence.Relational, '>': Precedence.Relational, '<=': Precedence.Relational, '>=': Precedence.Relational, 'in': Precedence.Relational, 'instanceof': Precedence.Relational, '<<': Precedence.BitwiseSHIFT, '>>': Precedence.BitwiseSHIFT, '>>>': Precedence.BitwiseSHIFT, '+': Precedence.Additive, '-': Precedence.Additive, '*': Precedence.Multiplicative, '%': Precedence.Multiplicative, '/': Precedence.Multiplicative, '??': Precedence.Coalesce, '**': Precedence.Exponentiation }; function getDefaultOptions () { // default options return { indent: null, base: null, parse: null, format: { indent: { style: ' ', base: 0 }, newline: '\n', space: ' ', json: false, renumber: false, hexadecimal: false, quotes: 'single', escapeless: false, compact: false, parentheses: true, semicolons: true, safeConcatenation: false }, directive: false, raw: true, verbatim: null }; } //-------------------------------------------------===------------------------------------------------------ // Lexical utils //-------------------------------------------------===------------------------------------------------------ //Const var NON_ASCII_WHITESPACES = [ 0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF ]; //Regular expressions var NON_ASCII_IDENTIFIER_CHARACTERS_REGEXP = new RegExp( '[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376' + '\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-' + '\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA' + '\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-' + '\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-' + '\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-' + '\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-' + '\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38' + '\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83' + '\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9' + '\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-' + '\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-' + '\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E' + '\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-' + '\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-' + '\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-' + '\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE' + '\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44' + '\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-' + '\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A' + '\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-' + '\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9' + '\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84' + '\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-' + '\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5' + '\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-' + '\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-' + '\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD' + '\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B' + '\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E' + '\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-' + '\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-' + '\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-' + '\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F' + '\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115' + '\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188' + '\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-' + '\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-' + '\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A' + '\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5' + '\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697' + '\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873' + '\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-' + '\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-' + '\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC' + '\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-' + '\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D' + '\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74' + '\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-' + '\uFFD7\uFFDA-\uFFDC]' ); //Methods function isIdentifierCh (cp) { if (cp < 0x80) { return cp >= 97 && cp <= 122 || // a..z cp >= 65 && cp <= 90 || // A..Z cp >= 48 && cp <= 57 || // 0..9 cp === 36 || cp === 95 || // $ (dollar) and _ (underscore) cp === 92; // \ (backslash) } var ch = String.fromCharCode(cp); return NON_ASCII_IDENTIFIER_CHARACTERS_REGEXP.test(ch); } function isLineTerminator (cp) { return cp === 0x0A || cp === 0x0D || cp === 0x2028 || cp === 0x2029; } function isWhitespace (cp) { return cp === 0x20 || cp === 0x09 || isLineTerminator(cp) || cp === 0x0B || cp === 0x0C || cp === 0xA0 || (cp >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(cp) >= 0); } function isDecimalDigit (cp) { return cp >= 48 && cp <= 57; } function stringRepeat (str, num) { var result = ''; for (num |= 0; num > 0; num >>>= 1, str += str) { if (num & 1) { result += str; } } return result; } isArray = Array.isArray; if (!isArray) { isArray = function isArray (array) { return Object.prototype.toString.call(array) === '[object Array]'; }; } function updateDeeply (target, override) { var key, val; function isHashObject (target) { return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); } for (key in override) { if (override.hasOwnProperty(key)) { val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; } function generateNumber (value) { var result, point, temp, exponent, pos; if (value === 1 / 0) { return json$1 ? 'null' : renumber ? '1e400' : '1e+400'; } result = '' + value; if (!renumber || result.length < 3) { return result; } point = result.indexOf('.'); //NOTE: 0x30 == '0' if (!json$1 && result.charCodeAt(0) === 0x30 && point === 1) { point = 0; result = result.slice(1); } temp = result; result = result.replace('e+', 'e'); exponent = 0; if ((pos = temp.indexOf('e')) > 0) { exponent = +temp.slice(pos + 1); temp = temp.slice(0, pos); } if (point >= 0) { exponent -= temp.length - point - 1; temp = +(temp.slice(0, point) + temp.slice(point + 1)) + ''; } pos = 0; //NOTE: 0x30 == '0' while (temp.charCodeAt(temp.length + pos - 1) === 0x30) { --pos; } if (pos !== 0) { exponent -= pos; temp = temp.slice(0, pos); } if (exponent !== 0) { temp += 'e' + exponent; } if ((temp.length < result.length || (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) && +temp === value) { result = temp; } return result; } // Generate valid RegExp expression. // This function is based on https://github.com/Constellation/iv Engine function escapeRegExpCharacter (ch, previousIsBackslash) { // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence if ((ch & ~1) === 0x2028) { return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029'); } else if (ch === 10 || ch === 13) { // \n, \r return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r'); } return String.fromCharCode(ch); } function generateRegExp (reg) { var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash; result = reg.toString(); if (reg.source) { // extract flag from toString result match = result.match(/\/([^/]*)$/); if (!match) { return result; } flags = match[1]; result = ''; characterInBrack = false; previousIsBackslash = false; for (i = 0, iz = reg.source.length; i < iz; ++i) { ch = reg.source.charCodeAt(i); if (!previousIsBackslash) { if (characterInBrack) { if (ch === 93) { // ] characterInBrack = false; } } else { if (ch === 47) { // / result += '\\'; } else if (ch === 91) { // [ characterInBrack = true; } } result += escapeRegExpCharacter(ch, previousIsBackslash); previousIsBackslash = ch === 92; // \ } else { // if new RegExp("\\\n') is provided, create /\n/ result += escapeRegExpCharacter(ch, previousIsBackslash); // prevent like /\\[/]/ previousIsBackslash = false; } } return '/' + result + '/' + flags; } return result; } function escapeAllowedCharacter (code, next) { var hex, result = '\\'; switch (code) { case 0x08: // \b result += 'b'; break; case 0x0C: // \f result += 'f'; break; case 0x09: // \t result += 't'; break; default: hex = code.toString(16).toUpperCase(); if (json$1 || code > 0xFF) { result += 'u' + '0000'.slice(hex.length) + hex; } else if (code === 0x0000 && !isDecimalDigit(next)) { result += '0'; } else if (code === 0x000B) { // \v result += 'x0B'; } else { result += 'x' + '00'.slice(hex.length) + hex; } break; } return result; } function escapeDisallowedCharacter (code) { var result = '\\'; switch (code) { case 0x5C // \ : result += '\\'; break; case 0x0A // \n : result += 'n'; break; case 0x0D // \r : result += 'r'; break; case 0x2028: result += 'u2028'; break; case 0x2029: result += 'u2029'; break; } return result; } function escapeDirective (str) { var i, iz, code, quote; quote = quotes === 'double' ? '"' : '\''; for (i = 0, iz = str.length; i < iz; ++i) { code = str.charCodeAt(i); if (code === 0x27) { // ' quote = '"'; break; } else if (code === 0x22) { // " quote = '\''; break; } else if (code === 0x5C) { // \ ++i; } } return quote + str + quote; } function escapeString (str) { var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote; //TODO http://jsperf.com/character-counting/8 for (i = 0, len = str.length; i < len; ++i) { code = str.charCodeAt(i); if (code === 0x27) { // ' ++singleQuotes; } else if (code === 0x22) { // " ++doubleQuotes; } else if (code === 0x2F && json$1) { // / result += '\\'; } else if (isLineTerminator(code) || code === 0x5C) { // \ result += escapeDisallowedCharacter(code); continue; } else if ((json$1 && code < 0x20) || // SP !(json$1 || escapeless || (code >= 0x20 && code <= 0x7E))) { // SP, ~ result += escapeAllowedCharacter(code, str.charCodeAt(i + 1)); continue; } result += String.fromCharCode(code); } single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes)); quote = single ? '\'' : '"'; if (!(single ? singleQuotes : doubleQuotes)) { return quote + result + quote; } str = result; result = quote; for (i = 0, len = str.length; i < len; ++i) { code = str.charCodeAt(i); if ((code === 0x27 && single) || (code === 0x22 && !single)) { // ', " result += '\\'; } result += String.fromCharCode(code); } return result + quote; } function join (l, r) { if (!l.length) return r; if (!r.length) return l; var lCp = l.charCodeAt(l.length - 1), rCp = r.charCodeAt(0); if (isIdentifierCh(lCp) && isIdentifierCh(rCp) || lCp === rCp && (lCp === 0x2B || lCp === 0x2D) || // + +, - - lCp === 0x2F && rCp === 0x69) { // /re/ instanceof foo return l + _.space + r; } else if (isWhitespace(lCp) || isWhitespace(rCp)) return l + r; return l + _.optSpace + r; } function shiftIndent () { var prevIndent = _.indent; _.indent += _.indentUnit; return prevIndent; } function adoptionPrefix ($stmt) { if ($stmt.type === Syntax.BlockStatement) return _.optSpace; if ($stmt.type === Syntax.EmptyStatement) return ''; return _.newline + _.indent + _.indentUnit; } function adoptionSuffix ($stmt) { if ($stmt.type === Syntax.BlockStatement) return _.optSpace; return _.newline + _.indent; } //Subentities generators function generateVerbatim ($expr, settings) { var verbatim = $expr[extra.verbatim], strVerbatim = typeof verbatim === 'string', precedence = !strVerbatim && verbatim.precedence !== void 0 ? verbatim.precedence : Precedence.Sequence, parenthesize = precedence < settings.precedence, content = strVerbatim ? verbatim : verbatim.content, chunks = content.split(/\r\n|\n/), chunkCount = chunks.length; if (parenthesize) _.js += '('; _.js += chunks[0]; for (var i = 1; i < chunkCount; i++) _.js += _.newline + _.indent + chunks[i]; if (parenthesize) _.js += ')'; } function generateFunctionParams ($node) { var $params = $node.params, paramCount = $params.length, lastParamIdx = paramCount - 1, arrowFuncWithoutParentheses = $node.type === Syntax.ArrowFunctionExpression && paramCount === 1 && $params[0].type === Syntax.Identifier; //NOTE: arg => { } case if (arrowFuncWithoutParentheses) _.js += $params[0].name; else { _.js += '('; for (var i = 0; i < paramCount; ++i) { var $param = $params[i]; if ($params[i].type === Syntax.Identifier) _.js += $param.name; else ExprGen[$param.type]($param, Preset.e4); if (i !== lastParamIdx) _.js += ',' + _.optSpace; } _.js += ')'; } } function generateFunctionBody ($node) { var $body = $node.body; generateFunctionParams($node); if ($node.type === Syntax.ArrowFunctionExpression) _.js += _.optSpace + '=>'; if ($node.expression) { _.js += _.optSpace; var exprJs = exprToJs($body, Preset.e4); if (exprJs.charAt(0) === '{') exprJs = '(' + exprJs + ')'; _.js += exprJs; } else { _.js += adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s8); } } //-------------------------------------------------===------------------------------------------------------ // Syntactic entities generation presets //-------------------------------------------------===------------------------------------------------------ var Preset = { e1: function (allowIn) { return { precedence: Precedence.Assignment, allowIn: allowIn, allowCall: true, allowUnparenthesizedNew: true }; }, e2: function (allowIn) { return { precedence: Precedence.LogicalOR, allowIn: allowIn, allowCall: true, allowUnparenthesizedNew: true }; }, e3: { precedence: Precedence.Call, allowIn: true, allowCall: true, allowUnparenthesizedNew: false }, e4: { precedence: Precedence.Assignment, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e5: { precedence: Precedence.Sequence, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e6: function (allowUnparenthesizedNew) { return { precedence: Precedence.New, allowIn: true, allowCall: false, allowUnparenthesizedNew: allowUnparenthesizedNew }; }, e7: { precedence: Precedence.Unary, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e8: { precedence: Precedence.Postfix, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e9: { precedence: void 0, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e10: { precedence: Precedence.Call, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e11: function (allowCall) { return { precedence: Precedence.Call, allowIn: true, allowCall: allowCall, allowUnparenthesizedNew: false }; }, e12: { precedence: Precedence.Primary, allowIn: false, allowCall: false, allowUnparenthesizedNew: true }, e13: { precedence: Precedence.Primary, allowIn: true, allowCall: true, allowUnparenthesizedNew: true }, e14: { precedence: Precedence.Sequence, allowIn: false, allowCall: true, allowUnparenthesizedNew: true }, e15: function (allowCall) { return { precedence: Precedence.Sequence, allowIn: true, allowCall: allowCall, allowUnparenthesizedNew: true }; }, e16: function (precedence, allowIn) { return { precedence: precedence, allowIn: allowIn, allowCall: true, allowUnparenthesizedNew: true }; }, e17: function (allowIn) { return { precedence: Precedence.Call, allowIn: allowIn, allowCall: true, allowUnparenthesizedNew: true } }, e18: function (allowIn) { return { precedence: Precedence.Assignment, allowIn: allowIn, allowCall: true, allowUnparenthesizedNew: true } }, e19: { precedence: Precedence.Sequence, allowIn: true, allowCall: true, semicolonOptional: false }, e20: { precedence: Precedence.Await, allowCall: true }, s1: function (functionBody, semicolonOptional) { return { allowIn: true, functionBody: false, directiveContext: functionBody, semicolonOptional: semicolonOptional }; }, s2: { allowIn: true, functionBody: false, directiveContext: false, semicolonOptional: true }, s3: function (allowIn) { return { allowIn: allowIn, functionBody: false, directiveContext: false, semicolonOptional: false }; }, s4: function (semicolonOptional) { return { allowIn: true, functionBody: false, directiveContext: false, semicolonOptional: semicolonOptional }; }, s5: function (semicolonOptional) { return { allowIn: true, functionBody: false, directiveContext: true, semicolonOptional: semicolonOptional, }; }, s6: { allowIn: false, functionBody: false, directiveContext: false, semicolonOptional: false }, s7: { allowIn: true, functionBody: false, directiveContext: false, semicolonOptional: false }, s8: { allowIn: true, functionBody: true, directiveContext: false, semicolonOptional: false } }; //-------------------------------------------------===------------------------------------------------------- // Expressions //-------------------------------------------------===------------------------------------------------------- //Regular expressions var FLOATING_OR_OCTAL_REGEXP = /[.eExX]|^0[0-9]+/, LAST_DECIMAL_DIGIT_REGEXP = /[0-9]$/; //Common expression generators function isLogicalExpression(node) { if (!node) return false; return node.type === Syntax.LogicalExpression; } function needParensForLogicalExpression (node, parent) { switch (node.operator) { case "||": if (!isLogicalExpression(parent)) return false; return parent.operator === "??" || parent.operator === "&&"; case "&&": return isLogicalExpression(parent); case "??": return isLogicalExpression(parent) && parent.operator !== "??"; } } function generateLogicalOrBinaryExpression ($expr, settings, $parent) { var op = $expr.operator, precedence = BinaryPrecedence[$expr.operator], parenthesize = precedence < settings.precedence, allowIn = settings.allowIn || parenthesize, operandGenSettings = Preset.e16(precedence, allowIn), exprJs = exprToJs($expr.left, operandGenSettings, $expr); parenthesize |= op === 'in' && !allowIn; var needParens = needParensForLogicalExpression($expr, $parent); if (parenthesize || needParens) _.js += '('; // 0x2F = '/' if (exprJs.charCodeAt(exprJs.length - 1) === 0x2F && isIdentifierCh(op.charCodeAt(0))) exprJs = exprJs + _.space + op; else exprJs = join(exprJs, op); operandGenSettings.precedence++; var rightJs = exprToJs($expr.right, operandGenSettings, $expr); //NOTE: If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start if (op === '/' && rightJs.charAt(0) === '/' || op.slice(-1) === '<' && rightJs.slice(0, 3) === '!--') exprJs += _.space + rightJs; else exprJs = join(exprJs, rightJs); _.js += exprJs; if (parenthesize || needParens) _.js += ')'; } function generateArrayPatternOrExpression ($expr) { var $elems = $expr.elements, elemCount = $elems.length; if (elemCount) { var lastElemIdx = elemCount - 1, multiline = elemCount > 1, prevIndent = shiftIndent(), itemPrefix = _.newline + _.indent; _.js += '['; for (var i = 0; i < elemCount; i++) { var $elem = $elems[i]; if (multiline) _.js += itemPrefix; if ($elem) ExprGen[$elem.type]($elem, Preset.e4); if (i !== lastElemIdx || !$elem) _.js += ','; } _.indent = prevIndent; if (multiline) _.js += _.newline + _.indent; _.js += ']'; } else _.js += '[]'; } function generateGeneratorOrComprehensionExpression ($expr) { //NOTE: GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...] var $blocks = $expr.blocks, $filter = $expr.filter, isGenerator = $expr.type === Syntax.GeneratorExpression, exprJs = isGenerator ? '(' : '[', bodyJs = exprToJs($expr.body, Preset.e4); if ($blocks) { var prevIndent = shiftIndent(), blockCount = $blocks.length; for (var i = 0; i < blockCount; ++i) { var blockJs = exprToJs($blocks[i], Preset.e5); exprJs = i > 0 ? join(exprJs, blockJs) : (exprJs + blockJs); } _.indent = prevIndent; } if ($filter) { var filterJs = exprToJs($filter, Preset.e5); exprJs = join(exprJs, 'if' + _.optSpace); exprJs = join(exprJs, '(' + filterJs + ')'); } exprJs = join(exprJs, bodyJs); exprJs += isGenerator ? ')' : ']'; _.js += exprJs; } //Expression raw generator dictionary var ExprRawGen = { SequenceExpression: function generateSequenceExpression ($expr, settings) { var $children = $expr.expressions, childrenCount = $children.length, lastChildIdx = childrenCount - 1, parenthesize = Precedence.Sequence < settings.precedence, exprGenSettings = Preset.e1(settings.allowIn || parenthesize); if (parenthesize) _.js += '('; for (var i = 0; i < childrenCount; i++) { var $child = $children[i]; ExprGen[$child.type]($child, exprGenSettings); if (i !== lastChildIdx) _.js += ',' + _.optSpace; } if (parenthesize) _.js += ')'; }, AssignmentExpression: function generateAssignmentExpression ($expr, settings) { var $left = $expr.left, $right = $expr.right, parenthesize = Precedence.Assignment < settings.precedence, allowIn = settings.allowIn || parenthesize; if (parenthesize) _.js += '('; ExprGen[$left.type]($left, Preset.e17(allowIn)); _.js += _.optSpace + $expr.operator + _.optSpace; ExprGen[$right.type]($right, Preset.e18(allowIn)); if (parenthesize) _.js += ')'; }, AssignmentPattern: function generateAssignmentPattern ($node) { var $fakeAssign = { left: $node.left, right: $node.right, operator: '=' }; ExprGen.AssignmentExpression($fakeAssign, Preset.e4); }, ArrowFunctionExpression: function generateArrowFunctionExpression ($expr, settings) { var parenthesize = Precedence.ArrowFunction < settings.precedence; if (parenthesize) _.js += '('; if ($expr.async) _.js += 'async '; generateFunctionBody($expr); if (parenthesize) _.js += ')'; }, AwaitExpression: function generateAwaitExpression ($expr, settings) { var parenthesize = Precedence.Await < settings.precedence; if (parenthesize) _.js += '('; _.js += $expr.all ? 'await* ' : 'await '; ExprGen[$expr.argument.type]($expr.argument, Preset.e20); if (parenthesize) _.js += ')'; }, ConditionalExpression: function generateConditionalExpression ($expr, settings) { var $test = $expr.test, $conseq = $expr.consequent, $alt = $expr.alternate, parenthesize = Precedence.Conditional < settings.precedence, allowIn = settings.allowIn || parenthesize, testGenSettings = Preset.e2(allowIn), branchGenSettings = Preset.e1(allowIn); if (parenthesize) _.js += '('; ExprGen[$test.type]($test, testGenSettings); _.js += _.optSpace + '?' + _.optSpace; ExprGen[$conseq.type]($conseq, branchGenSettings); _.js += _.optSpace + ':' + _.optSpace; ExprGen[$alt.type]($alt, branchGenSettings); if (parenthesize) _.js += ')'; }, LogicalExpression: generateLogicalOrBinaryExpression, BinaryExpression: generateLogicalOrBinaryExpression, CallExpression: function generateCallExpression ($expr, settings) { var $callee = $expr.callee, $args = $expr['arguments'], argCount = $args.length, lastArgIdx = argCount - 1, parenthesize = !settings.allowCall || Precedence.Call < settings.precedence; if (parenthesize) _.js += '('; ExprGen[$callee.type]($callee, Preset.e3); if ($expr.optional) _.js += '?.'; _.js += '('; for (var i = 0; i < argCount; ++i) { var $arg = $args[i]; ExprGen[$arg.type]($arg, Preset.e4); if (i !== lastArgIdx) _.js += ',' + _.optSpace; } _.js += ')'; if (parenthesize) _.js += ')'; }, NewExpression: function generateNewExpression ($expr, settings) { var $args = $expr['arguments'], parenthesize = Precedence.New < settings.precedence, argCount = $args.length, lastArgIdx = argCount - 1, withCall = !settings.allowUnparenthesizedNew || parentheses || argCount > 0, calleeJs = exprToJs($expr.callee, Preset.e6(!withCall)); if (parenthesize) _.js += '('; _.js += join('new', calleeJs); if (withCall) { _.js += '('; for (var i = 0; i < argCount; ++i) { var $arg = $args[i]; ExprGen[$arg.type]($arg, Preset.e4); if (i !== lastArgIdx) _.js += ',' + _.optSpace; } _.js += ')'; } if (parenthesize) _.js += ')'; }, MemberExpression: function generateMemberExpression ($expr, settings) { var $obj = $expr.object, $prop = $expr.property, parenthesize = Precedence.Member < settings.precedence, isNumObj = !$expr.computed && $obj.type === Syntax.Literal && typeof $obj.value === 'number'; if (parenthesize) _.js += '('; if (isNumObj) { //NOTE: When the following conditions are all true: // 1. No floating point // 2. Don't have exponents // 3. The last character is a decimal digit // 4. Not hexadecimal OR octal number literal // then we should add a floating point. var numJs = exprToJs($obj, Preset.e11(settings.allowCall)), withPoint = LAST_DECIMAL_DIGIT_REGEXP.test(numJs) && !FLOATING_OR_OCTAL_REGEXP.test(numJs); _.js += withPoint ? (numJs + '.') : numJs; } else ExprGen[$obj.type]($obj, Preset.e11(settings.allowCall)); if ($expr.computed) { if ($expr.optional) _.js += '?.'; _.js += '['; ExprGen[$prop.type]($prop, Preset.e15(settings.allowCall)); _.js += ']'; } else _.js += ($expr.optional ? '?.' : '.') + $prop.name; if (parenthesize) _.js += ')'; }, UnaryExpression: function generateUnaryExpression ($expr, settings) { var parenthesize = Precedence.Unary < settings.precedence, op = $expr.operator, argJs = exprToJs($expr.argument, Preset.e7); if (parenthesize) _.js += '('; //NOTE: delete, void, typeof // get `typeof []`, not `typeof[]` if (_.optSpace === '' || op.length > 2) _.js += join(op, argJs); else { _.js += op; //NOTE: Prevent inserting spaces between operator and argument if it is unnecessary // like, `!cond` var leftCp = op.charCodeAt(op.length - 1), rightCp = argJs.charCodeAt(0); // 0x2B = '+', 0x2D = '-' if (leftCp === rightCp && (leftCp === 0x2B || leftCp === 0x2D) || isIdentifierCh(leftCp) && isIdentifierCh(rightCp)) { _.js += _.space; } _.js += argJs; } if (parenthesize) _.js += ')'; }, YieldExpression: function generateYieldExpression ($expr, settings) { var $arg = $expr.argument, js = $expr.delegate ? 'yield*' : 'yield', parenthesize = Precedence.Yield < settings.precedence; if (parenthesize) _.js += '('; if ($arg) { var argJs = exprToJs($arg, Preset.e4); js = join(js, argJs); } _.js += js; if (parenthesize) _.js += ')'; }, UpdateExpression: function generateUpdateExpression ($expr, settings) { var $arg = $expr.argument, $op = $expr.operator, prefix = $expr.prefix, precedence = prefix ? Precedence.Unary : Precedence.Postfix, parenthesize = precedence < settings.precedence; if (parenthesize) _.js += '('; if (prefix) { _.js += $op; ExprGen[$arg.type]($arg, Preset.e8); } else { ExprGen[$arg.type]($arg, Preset.e8); _.js += $op; } if (parenthesize) _.js += ')'; }, FunctionExpression: function generateFunctionExpression ($expr) { var isGenerator = !!$expr.generator; if ($expr.async) _.js += 'async '; _.js += isGenerator ? 'function*' : 'function'; if ($expr.id) { _.js += isGenerator ? _.optSpace : _.space; _.js += $expr.id.name; } else _.js += _.optSpace; generateFunctionBody($expr); }, ExportBatchSpecifier: function generateExportBatchSpecifier () { _.js += '*'; }, ArrayPattern: generateArrayPatternOrExpression, ArrayExpression: generateArrayPatternOrExpression, ClassExpression: function generateClassExpression ($expr) { var $id = $expr.id, $super = $expr.superClass, $body = $expr.body, exprJs = 'class'; if ($id) { var idJs = exprToJs($id, Preset.e9); exprJs = join(exprJs, idJs); } if ($super) { var superJs = exprToJs($super, Preset.e4); superJs = join('extends', superJs); exprJs = join(exprJs, superJs); } _.js += exprJs + _.optSpace; StmtGen[$body.type]($body, Preset.s2); }, MetaProperty: function generateMetaProperty ($expr, settings) { var $meta = $expr.meta, $property = $expr.property, parenthesize = Precedence.Member < settings.precedence; if (parenthesize) _.js += '('; _.js += (typeof $meta === "string" ? $meta : $meta.name) + '.' + (typeof $property === "string" ? $property : $property.name); if (parenthesize) _.js += ')'; }, MethodDefinition: function generateMethodDefinition ($expr) { var exprJs = $expr['static'] ? 'static' + _.optSpace : '', keyJs = exprToJs($expr.key, Preset.e5); if ($expr.computed) keyJs = '[' + keyJs + ']'; if ($expr.kind === 'get' || $expr.kind === 'set') { keyJs = join($expr.kind, keyJs); _.js += join(exprJs, keyJs); } else { if ($expr.value.generator) _.js += exprJs + '*' + keyJs; else if ($expr.value.async) _.js += exprJs + 'async ' + keyJs; else _.js += join(exprJs, keyJs); } generateFunctionBody($expr.value); }, Property: function generateProperty ($expr) { var $val = $expr.value, $kind = $expr.kind, keyJs = exprToJs($expr.key, Preset.e4); if ($expr.computed) keyJs = '[' + keyJs + ']'; if ($kind === 'get' || $kind === 'set') { _.js += $kind + _.space + keyJs; generateFunctionBody($val); } else { if ($expr.shorthand) _.js += keyJs; else if ($expr.method) { if ($val.generator) keyJs = '*' + keyJs; else if ($val.async) keyJs = 'async ' + keyJs; _.js += keyJs; generateFunctionBody($val); } else { _.js += keyJs + ':' + _.optSpace; ExprGen[$val.type]($val, Preset.e4); } } }, ObjectExpression: function generateObjectExpression ($expr) { var $props = $expr.properties, propCount = $props.length; if (propCount) { var lastPropIdx = propCount - 1, prevIndent = shiftIndent(); _.js += '{'; for (var i = 0; i < propCount; i++) { var $prop = $props[i], propType = $prop.type || Syntax.Property; _.js += _.newline + _.indent; ExprGen[propType]($prop, Preset.e5); if (i !== lastPropIdx) _.js += ','; } _.indent = prevIndent; _.js += _.newline + _.indent + '}'; } else _.js += '{}'; }, ObjectPattern: function generateObjectPattern ($expr) { var $props = $expr.properties, propCount = $props.length; if (propCount) { var lastPropIdx = propCount - 1, multiline = false; if (propCount === 1) multiline = $props[0].value.type !== Syntax.Identifier; else { for (var i = 0; i < propCount; i++) { if (!$props[i].shorthand) { multiline = true; break; } } } _.js += multiline ? ('{' + _.newline) : '{'; var prevIndent = shiftIndent(), propSuffix = ',' + (multiline ? _.newline : _.optSpace); for (var i = 0; i < propCount; i++) { var $prop = $props[i]; if (multiline) _.js += _.indent; ExprGen[$prop.type]($prop, Preset.e5); if (i !== lastPropIdx) _.js += propSuffix; } _.indent = prevIndent; _.js += multiline ? (_.newline + _.indent + '}') : '}'; } else _.js += '{}'; }, ThisExpression: function generateThisExpression () { _.js += 'this'; }, Identifier: function generateIdentifier ($expr, precedence, flag) { _.js += $expr.name; }, ImportExpression: function generateImportExpression ($expr, settings) { var parenthesize = Precedence.Call < settings.precedence; var $source = $expr.source; if (parenthesize) _.js += '('; _.js += 'import('; ExprGen[$source.type]($source, Preset.e4); _.js += ')'; if (parenthesize) _.js += ')'; }, ImportSpecifier: function generateImportSpecifier ($expr) { _.js += $expr.imported.name; if ($expr.local) _.js += _.space + 'as' + _.space + $expr.local.name; }, ExportSpecifier: function generateImportOrExportSpecifier ($expr) { _.js += $expr.local.name; if ($expr.exported) _.js += _.space + 'as' + _.space + $expr.exported.name; }, ChainExpression: function generateChainExpression ($expr, settings) { var parenthesize = Precedence.OptionalChaining < settings.precedence; var $expression = $expr.expression; settings = settings || {}; var newSettings = { precedence: Precedence.OptionalChaining, allowIn: settings.allowIn , allowCall: settings.allowCall, allowUnparenthesizedNew: settings.allowUnparenthesizedNew }; if (parenthesize) { newSettings.allowCall = true; _.js += '('; } ExprGen[$expression.type]($expression, newSettings); if (parenthesize) _.js += ')'; }, Literal: function generateLiteral ($expr) { if (extra.raw && $expr.raw !== void 0) _.js += $expr.raw; else if ($expr.value === null) _.js += 'null'; else { var valueType = typeof $expr.value; if (valueType === 'string') _.js += escapeString($expr.value); else if (valueType === 'number') _.js += generateNumber($expr.value); else if (valueType === 'boolean') _.js += $expr.value ? 'true' : 'false'; else _.js += generateRegExp($expr.value); } }, GeneratorExpression: generateGeneratorOrComprehensionExpression, ComprehensionExpression: generateGeneratorOrComprehensionExpression, ComprehensionBlock: function generateComprehensionBlock ($expr) { var $left = $expr.left, leftJs = void 0, rightJs = exprToJs($expr.right, Preset.e5); if ($left.type === Syntax.VariableDeclaration) leftJs = $left.kind + _.space + stmtToJs($left.declarations[0], Preset.s6); else leftJs = exprToJs($left, Preset.e10); leftJs = join(leftJs, $expr.of ? 'of' : 'in'); _.js += 'for' + _.optSpace + '(' + join(leftJs, rightJs) + ')'; }, RestElement: function generateRestElement ($node) { _.js += '...' + $node.argument.name; }, SpreadElement: function generateSpreadElement ($expr) { var $arg = $expr.argument; _.js += '...'; ExprGen[$arg.type]($arg, Preset.e4); }, TaggedTemplateExpression: function generateTaggedTemplateExpression ($expr, settings) { var $tag = $expr.tag, $quasi = $expr.quasi, parenthesize = Precedence.TaggedTemplate < settings.precedence; if (parenthesize) _.js += '('; ExprGen[$tag.type]($tag, Preset.e11(settings.allowCall)); ExprGen[$quasi.type]($quasi, Preset.e12); if (parenthesize) _.js += ')'; }, TemplateElement: function generateTemplateElement ($expr) { //NOTE: Don't use "cooked". Since tagged template can use raw template // representation. So if we do so, it breaks the script semantics. _.js += $expr.value.raw; }, TemplateLiteral: function generateTemplateLiteral ($expr) { var $quasis = $expr.quasis, $childExprs = $expr.expressions, quasiCount = $quasis.length, lastQuasiIdx = quasiCount - 1; _.js += '`'; for (var i = 0; i < quasiCount; ++i) { var $quasi = $quasis[i]; ExprGen[$quasi.type]($quasi, Preset.e13); if (i !== lastQuasiIdx) { var $childExpr = $childExprs[i]; _.js += '${' + _.optSpace; ExprGen[$childExpr.type]($childExpr, Preset.e5); _.js += _.optSpace + '}'; } } _.js += '`'; }, Super: function generateSuper () { _.js += 'super'; } }; //-------------------------------------------------===------------------------------------------------------ // Statements //-------------------------------------------------===------------------------------------------------------ //Regular expressions var EXPR_STMT_UNALLOWED_EXPR_REGEXP = /^{|^class(?:\s|{)|^(async )?function(?:\s|\*|\()/; //Common statement generators function generateTryStatementHandlers (stmtJs, $finalizer, handlers) { var handlerCount = handlers.length, lastHandlerIdx = handlerCount - 1; for (var i = 0; i < handlerCount; ++i) { var handlerJs = stmtToJs(handlers[i], Preset.s7); stmtJs = join(stmtJs, handlerJs); if ($finalizer || i !== lastHandlerIdx) stmtJs += adoptionSuffix(handlers[i].body); } return stmtJs; } function generateForStatementIterator ($op, $stmt, settings) { var $body = $stmt.body, $left = $stmt.left, bodySemicolonOptional = !semicolons && settings.semicolonOptional, prevIndent1 = shiftIndent(), awaitStr = $stmt.await ? ' await' : '', stmtJs = 'for' + awaitStr + _.optSpace + '('; if ($left.type === Syntax.VariableDeclaration) { var prevIndent2 = shiftIndent(); stmtJs += $left.kind + _.space + stmtToJs($left.declarations[0], Preset.s6); _.indent = prevIndent2; } else stmtJs += exprToJs($left, Preset.e10); stmtJs = join(stmtJs, $op); var rightJs = exprToJs($stmt.right, Preset.e4); stmtJs = join(stmtJs, rightJs) + ')'; _.indent = prevIndent1; _.js += stmtJs + adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s4(bodySemicolonOptional)); } //Statement generator dictionary var StmtRawGen = { BlockStatement: function generateBlockStatement ($stmt, settings) { var $body = $stmt.body, len = $body.length, lastIdx = len - 1, prevIndent = shiftIndent(); _.js += '{' + _.newline; for (var i = 0; i < len; i++) { var $item = $body[i]; _.js += _.indent; StmtGen[$item.type]($item, Preset.s1(settings.functionBody, i === lastIdx)); _.js += _.newline; } _.indent = prevIndent; _.js += _.indent + '}'; }, BreakStatement: function generateBreakStatement ($stmt, settings) { if ($stmt.label) _.js += 'break ' + $stmt.label.name; else _.js += 'break'; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, ContinueStatement: function generateContinueStatement ($stmt, settings) { if ($stmt.label) _.js += 'continue ' + $stmt.label.name; else _.js += 'continue'; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, ClassBody: function generateClassBody ($stmt) { var $body = $stmt.body, itemCount = $body.length, lastItemIdx = itemCount - 1, prevIndent = shiftIndent(); _.js += '{' + _.newline; for (var i = 0; i < itemCount; i++) { var $item = $body[i], itemType = $item.type || Syntax.Property; _.js += _.indent; ExprGen[itemType]($item, Preset.e5); if (i !== lastItemIdx) _.js += _.newline; } _.indent = prevIndent; _.js += _.newline + _.indent + '}'; }, ClassDeclaration: function generateClassDeclaration ($stmt) { var $body = $stmt.body, $super = $stmt.superClass, js = 'class ' + $stmt.id.name; if ($super) { var superJs = exprToJs($super, Preset.e4); js += _.space + join('extends', superJs); } _.js += js + _.optSpace; StmtGen[$body.type]($body, Preset.s2); }, DirectiveStatement: function generateDirectiveStatement ($stmt, settings) { if (extra.raw && $stmt.raw) _.js += $stmt.raw; else _.js += escapeDirective($stmt.directive); if (semicolons || !settings.semicolonOptional) _.js += ';'; }, DoWhileStatement: function generateDoWhileStatement ($stmt, settings) { var $body = $stmt.body, $test = $stmt.test, bodyJs = adoptionPrefix($body) + stmtToJs($body, Preset.s7) + adoptionSuffix($body); //NOTE: Because `do 42 while (cond)` is Syntax Error. We need semicolon. var stmtJs = join('do', bodyJs); _.js += join(stmtJs, 'while' + _.optSpace + '('); ExprGen[$test.type]($test, Preset.e5); _.js += ')'; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, CatchClause: function generateCatchClause ($stmt) { var $param = $stmt.param, $guard = $stmt.guard, $body = $stmt.body, prevIndent = shiftIndent(); _.js += 'catch' + _.optSpace; if ($param) { _.js += '('; ExprGen[$param.type]($param, Preset.e5); } if ($guard) { _.js += ' if '; ExprGen[$guard.type]($guard, Preset.e5); } _.indent = prevIndent; if ($param) { _.js += ')'; } _.js += adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s7); }, DebuggerStatement: function generateDebuggerStatement ($stmt, settings) { _.js += 'debugger'; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, EmptyStatement: function generateEmptyStatement () { _.js += ';'; }, ExportAllDeclaration: function ($stmt, settings) { StmtRawGen.ExportDeclaration($stmt, settings, true); }, ExportDeclaration: function generateExportDeclaration ($stmt, settings, exportAll) { var $specs = $stmt.specifiers, $decl = $stmt.declaration, withSemicolon = semicolons || !settings.semicolonOptional; // export default AssignmentExpression[In] ; if ($stmt['default']) { var declJs = exprToJs($decl, Preset.e4); _.js += join('export default', declJs); if (withSemicolon) _.js += ';'; } // export * FromClause ; // export ExportClause[NoReference] FromClause ; // export ExportClause ; else if ($specs || exportAll) { var stmtJs = 'export'; if (exportAll) stmtJs += _.optSpace + '*'; else if ($specs.length === 0) stmtJs += _.optSpace + '{' + _.optSpace + '}'; else if ($specs[0].type === Syntax.ExportBatchSpecifier) { var specJs = exprToJs($specs[0], Preset.e5); stmtJs = join(stmtJs, specJs); } else { var prevIndent = shiftIndent(), specCount = $specs.length, lastSpecIdx = specCount - 1; stmtJs += _.optSpace + '{'; for (var i = 0; i < specCount; ++i) { stmtJs += _.newline + _.indent; stmtJs += exprToJs($specs[i], Preset.e5); if (i !== lastSpecIdx) stmtJs += ','; } _.indent = prevIndent; stmtJs += _.newline + _.indent + '}'; } if ($stmt.source) { _.js += join(stmtJs, 'from' + _.optSpace); ExprGen.Literal($stmt.source); } else _.js += stmtJs; if (withSemicolon) _.js += ';'; } // export VariableStatement // export Declaration[Default] else if ($decl) { var declJs = stmtToJs($decl, Preset.s4(!withSemicolon)); _.js += join('export', declJs); } }, ExportNamedDeclaration: function ($stmt, settings) { StmtRawGen.ExportDeclaration($stmt, settings); }, ExpressionStatement: function generateExpressionStatement ($stmt, settings) { var exprJs = exprToJs($stmt.expression, Preset.e5), parenthesize = EXPR_STMT_UNALLOWED_EXPR_REGEXP.test(exprJs) || (directive && settings.directiveContext && $stmt.expression.type === Syntax.Literal && typeof $stmt.expression.value === 'string'); //NOTE: '{', 'function', 'class' are not allowed in expression statement. // Therefore, they should be parenthesized. if (parenthesize) _.js += '(' + exprJs + ')'; else _.js += exprJs; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, ImportDeclaration: function generateImportDeclaration ($stmt, settings) { var $specs = $stmt.specifiers, stmtJs = 'import', specCount = $specs.length; //NOTE: If no ImportClause is present, // this should be `import ModuleSpecifier` so skip `from` // ModuleSpecifier is StringLiteral. if (specCount) { var hasBinding = !!$specs[0]['default'], firstNamedIdx = hasBinding ? 1 : 0, lastSpecIdx = specCount - 1; // ImportedBinding if (hasBinding) stmtJs = join(stmtJs, $specs[0].id.name); // NamedImports if (firstNamedIdx < specCount) { if (hasBinding) stmtJs += ','; stmtJs += _.optSpace + '{'; // import { ... } from "..."; if (firstNamedIdx === lastSpecIdx) stmtJs += _.optSpace + exprToJs($specs[firstNamedIdx], Preset.e5) + _.optSpace; else { var prevIndent = shiftIndent(); // import { // ..., // ..., // } from "..."; for (var i = firstNamedIdx; i < specCount; i++) { stmtJs += _.newline + _.indent + exprToJs($specs[i], Preset.e5); if (i !== lastSpecIdx) stmtJs += ','; } _.indent = prevIndent; stmtJs += _.newline + _.indent; } stmtJs += '}' + _.optSpace; } stmtJs = join(stmtJs, 'from'); } _.js += stmtJs + _.optSpace; ExprGen.Literal($stmt.source); if (semicolons || !settings.semicolonOptional) _.js += ';'; }, VariableDeclarator: function generateVariableDeclarator ($stmt, settings) { var $id = $stmt.id, $init = $stmt.init, genSettings = Preset.e1(settings.allowIn); if ($init) { ExprGen[$id.type]($id, genSettings); _.js += _.optSpace + '=' + _.optSpace; ExprGen[$init.type]($init, genSettings, $stmt); } else { if ($id.type === Syntax.Identifier) _.js += $id.name; else ExprGen[$id.type]($id, genSettings); } }, VariableDeclaration: function generateVariableDeclaration ($stmt, settings) { var $decls = $stmt.declarations, len = $decls.length, prevIndent = len > 1 ? shiftIndent() : _.indent, declGenSettings = Preset.s3(settings.allowIn); _.js += $stmt.kind; for (var i = 0; i < len; i++) { var $decl = $decls[i]; _.js += i === 0 ? _.space : (',' + _.optSpace); StmtGen[$decl.type]($decl, declGenSettings); } if (semicolons || !settings.semicolonOptional) _.js += ';'; _.indent = prevIndent; }, ThrowStatement: function generateThrowStatement ($stmt, settings) { var argJs = exprToJs($stmt.argument, Preset.e5); _.js += join('throw', argJs); if (semicolons || !settings.semicolonOptional) _.js += ';'; }, TryStatement: function generateTryStatement ($stmt) { var $block = $stmt.block, $finalizer = $stmt.finalizer, stmtJs = 'try' + adoptionPrefix($block) + stmtToJs($block, Preset.s7) + adoptionSuffix($block); var $handlers = $stmt.handlers || $stmt.guardedHandlers; if ($handlers) stmtJs = generateTryStatementHandlers(stmtJs, $finalizer, $handlers); if ($stmt.handler) { $handlers = isArray($stmt.handler) ? $stmt.handler : [$stmt.handler]; stmtJs = generateTryStatementHandlers(stmtJs, $finalizer, $handlers); } if ($finalizer) { stmtJs = join(stmtJs, 'finally' + adoptionPrefix($finalizer)); stmtJs += stmtToJs($finalizer, Preset.s7); } _.js += stmtJs; }, SwitchStatement: function generateSwitchStatement ($stmt) { var $cases = $stmt.cases, $discr = $stmt.discriminant, prevIndent = shiftIndent(); _.js += 'switch' + _.optSpace + '('; ExprGen[$discr.type]($discr, Preset.e5); _.js += ')' + _.optSpace + '{' + _.newline; _.indent = prevIndent; if ($cases) { var caseCount = $cases.length, lastCaseIdx = caseCount - 1; for (var i = 0; i < caseCount; i++) { var $case = $cases[i]; _.js += _.indent; StmtGen[$case.type]($case, Preset.s4(i === lastCaseIdx)); _.js += _.newline; } } _.js += _.indent + '}'; }, SwitchCase: function generateSwitchCase ($stmt, settings) { var $conseqs = $stmt.consequent, $firstConseq = $conseqs[0], $test = $stmt.test, i = 0, conseqSemicolonOptional = !semicolons && settings.semicolonOptional, conseqCount = $conseqs.length, lastConseqIdx = conseqCount - 1, prevIndent = shiftIndent(); if ($test) { var testJs = exprToJs($test, Preset.e5); _.js += join('case', testJs) + ':'; } else _.js += 'default:'; if (conseqCount && $firstConseq.type === Syntax.BlockStatement) { i++; _.js += adoptionPrefix($firstConseq); StmtGen[$firstConseq.type]($firstConseq, Preset.s7); } for (; i < conseqCount; i++) { var $conseq = $conseqs[i], semicolonOptional = i === lastConseqIdx && conseqSemicolonOptional; _.js += _.newline + _.indent; StmtGen[$conseq.type]($conseq, Preset.s4(semicolonOptional)); } _.indent = prevIndent; }, IfStatement: function generateIfStatement ($stmt, settings) { var $conseq = $stmt.consequent, $test = $stmt.test, prevIndent = shiftIndent(), semicolonOptional = !semicolons && settings.semicolonOptional; _.js += 'if' + _.optSpace + '('; ExprGen[$test.type]($test, Preset.e5); _.js += ')'; _.indent = prevIndent; _.js += adoptionPrefix($conseq); if ($stmt.alternate) { var conseq = stmtToJs($conseq, Preset.s7) + adoptionSuffix($conseq), alt = stmtToJs($stmt.alternate, Preset.s4(semicolonOptional)); if ($stmt.alternate.type === Syntax.IfStatement) alt = 'else ' + alt; else alt = join('else', adoptionPrefix($stmt.alternate) + alt); _.js += join(conseq, alt); } else StmtGen[$conseq.type]($conseq, Preset.s4(semicolonOptional)); }, ForStatement: function generateForStatement ($stmt, settings) { var $init = $stmt.init, $test = $stmt.test, $body = $stmt.body, $update = $stmt.update, bodySemicolonOptional = !semicolons && settings.semicolonOptional, prevIndent = shiftIndent(); _.js += 'for' + _.optSpace + '('; if ($init) { if ($init.type === Syntax.VariableDeclaration) StmtGen[$init.type]($init, Preset.s6); else { ExprGen[$init.type]($init, Preset.e14); _.js += ';'; } } else _.js += ';'; if ($test) { _.js += _.optSpace; ExprGen[$test.type]($test, Preset.e5); } _.js += ';'; if ($update) { _.js += _.optSpace; ExprGen[$update.type]($update, Preset.e5); } _.js += ')'; _.indent = prevIndent; _.js += adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s4(bodySemicolonOptional)); }, ForInStatement: function generateForInStatement ($stmt, settings) { generateForStatementIterator('in', $stmt, settings); }, ForOfStatement: function generateForOfStatement ($stmt, settings) { generateForStatementIterator('of', $stmt, settings); }, LabeledStatement: function generateLabeledStatement ($stmt, settings) { var $body = $stmt.body, bodySemicolonOptional = !semicolons && settings.semicolonOptional, prevIndent = _.indent; _.js += $stmt.label.name + ':' + adoptionPrefix($body); if ($body.type !== Syntax.BlockStatement) prevIndent = shiftIndent(); StmtGen[$body.type]($body, Preset.s4(bodySemicolonOptional)); _.indent = prevIndent; }, ModuleDeclaration: function generateModuleDeclaration ($stmt, settings) { _.js += 'module' + _.space + $stmt.id.name + _.space + 'from' + _.optSpace; ExprGen.Literal($stmt.source); if (semicolons || !settings.semicolonOptional) _.js += ';'; }, Program: function generateProgram ($stmt) { var $body = $stmt.body, len = $body.length, lastIdx = len - 1; if (safeConcatenation && len > 0) _.js += '\n'; for (var i = 0; i < len; i++) { var $item = $body[i]; _.js += _.indent; StmtGen[$item.type]($item, Preset.s5(!safeConcatenation && i === lastIdx)); if (i !== lastIdx) _.js += _.newline; } }, FunctionDeclaration: function generateFunctionDeclaration ($stmt) { var isGenerator = !!$stmt.generator; if ($stmt.async) _.js += 'async '; _.js += isGenerator ? ('function*' + _.optSpace) : ('function' + _.space ); _.js += $stmt.id.name; generateFunctionBody($stmt); }, ReturnStatement: function generateReturnStatement ($stmt, settings) { var $arg = $stmt.argument; if ($arg) { var argJs = exprToJs($arg, Preset.e5); _.js += join('return', argJs); } else _.js += 'return'; if (semicolons || !settings.semicolonOptional) _.js += ';'; }, WhileStatement: function generateWhileStatement ($stmt, settings) { var $body = $stmt.body, $test = $stmt.test, bodySemicolonOptional = !semicolons && settings.semicolonOptional, prevIndent = shiftIndent(); _.js += 'while' + _.optSpace + '('; ExprGen[$test.type]($test, Preset.e5); _.js += ')'; _.indent = prevIndent; _.js += adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s4(bodySemicolonOptional)); }, WithStatement: function generateWithStatement ($stmt, settings) { var $body = $stmt.body, $obj = $stmt.object, bodySemicolonOptional = !semicolons && settings.semicolonOptional, prevIndent = shiftIndent(); _.js += 'with' + _.optSpace + '('; ExprGen[$obj.type]($obj, Preset.e5); _.js += ')'; _.indent = prevIndent; _.js += adoptionPrefix($body); StmtGen[$body.type]($body, Preset.s4(bodySemicolonOptional)); } }; //CodeGen //----------------------------------------------------------------------------------- function exprToJs ($expr, settings, $parent) { var savedJs = _.js; _.js = ''; ExprGen[$expr.type]($expr, settings, $parent); var src = _.js; _.js = savedJs; return src; } function stmtToJs ($stmt, settings) { var savedJs = _.js; _.js = ''; StmtGen[$stmt.type]($stmt, settings); var src = _.js; _.js = savedJs; return src; } function run ($node) { _.js = ''; if (StmtGen[$node.type]) StmtGen[$node.type]($node, Preset.s7); else ExprGen[$node.type]($node, Preset.e19); return _.js; } function wrapExprGen (gen) { return function ($expr, settings) { if (extra.verbatim && $expr.hasOwnProperty(extra.verbatim)) generateVerbatim($expr, settings); else gen($expr, settings); } } function createExprGenWithExtras () { var gens = {}; for (var key in ExprRawGen) { if (ExprRawGen.hasOwnProperty(key)) gens[key] = wrapExprGen(ExprRawGen[key]); } return gens; } //Strings var _ = { js: '', newline: '\n', optSpace: ' ', space: ' ', indentUnit: ' ', indent: '' }; //Generators var ExprGen = void 0, StmtGen = StmtRawGen; var generate = function ($node, options) { var defaultOptions = getDefaultOptions(); if (options != null) { //NOTE: Obsolete options // // `options.indent` // `options.base` // // Instead of them, we can use `option.format.indent`. if (typeof options.indent === 'string') { defaultOptions.format.indent.style = options.indent; } if (typeof options.base === 'number') { defaultOptions.format.indent.base = options.base; } options = updateDeeply(defaultOptions, options); _.indentUnit = options.format.indent.style; if (typeof options.base === 'string') { _.indent = options.base; } else { _.indent = stringRepeat(_.indentUnit, options.format.indent.base); } } else { options = defaultOptions; _.indentUnit = options.format.indent.style; _.indent = stringRepeat(_.indentUnit, options.format.indent.base); } json$1 = options.format.json; renumber = options.format.renumber; hexadecimal = json$1 ? false : options.format.hexadecimal; quotes = json$1 ? 'double' : options.format.quotes; escapeless = options.format.escapeless; _.newline = options.format.newline; _.optSpace = options.format.space; if (options.format.compact) _.newline = _.optSpace = _.indentUnit = _.indent = ''; _.space = _.optSpace ? _.optSpace : ' '; parentheses = options.format.parentheses; semicolons = options.format.semicolons; safeConcatenation = options.format.safeConcatenation; directive = options.directive; json$1 ? null : options.parse; extra = options; if (extra.verbatim) ExprGen = createExprGenWithExtras(); else ExprGen = ExprRawGen; return run($node); }; // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- var SCRIPT_PROCESSING_INSTRUCTIONS = { getLocation: '__get$Loc', setLocation: '__set$Loc', getProperty: '__get$', setProperty: '__set$', callMethod: '__call$', processScript: '__proc$Script', processHtml: '__proc$Html', getEval: '__get$Eval', getPostMessage: '__get$PostMessage', getProxyUrl: '__get$ProxyUrl', restArray: '__rest$Array', arrayFrom: '__arrayFrom$', restObject: '__rest$Object', swScopeHeaderValue: '__swScopeHeaderValue', getWorkerSettings: '__getWorkerSettings$', }; var TEMP_VARIABLE_PREFIX = '_hh$temp'; var TempVariables = /** @class */ (function () { function TempVariables() { this._list = []; } TempVariables.resetCounter = function () { TempVariables._counter = 0; }; TempVariables.generateName = function (baseName, key, index) { if (!baseName) return TEMP_VARIABLE_PREFIX + TempVariables._counter++; if (key) { if (key.type === Syntax_1.Identifier) return baseName + '$' + key.name; if (key.type === Syntax_1.Literal && key.value) return baseName + '$' + key.value.toString().replace(/[^a-zA-Z0-9]/g, ''); } return baseName + '$i' + index; }; TempVariables.isHHTempVariable = function (name) { return name.indexOf(TEMP_VARIABLE_PREFIX) === 0; }; TempVariables.prototype.append = function (name) { this._list.push(name); }; TempVariables.prototype.get = function () { return this._list; }; TempVariables._counter = 0; return TempVariables; }()); function createIdentifier(name) { return { type: Syntax_1.Identifier, name: name }; } function createExpressionStatement(expression) { return { type: Syntax_1.ExpressionStatement, expression: expression }; } function createAssignmentExpression(left, operator, right) { //@ts-ignore the `right` value can actually be null, but the AssignmentExpression type definition // does not allow to the `right` value be null return { type: Syntax_1.AssignmentExpression, operator: operator, left: left, right: right }; } function createSimpleCallExpression(callee, args) { return { type: Syntax_1.CallExpression, callee: callee, arguments: args, optional: false }; } function createArrayExpression(elements) { return { type: Syntax_1.ArrayExpression, elements: elements }; } function createMemberExpression(object, property, computed) { return { type: Syntax_1.MemberExpression, object: object, property: property, computed: computed, optional: false }; } function createBinaryExpression(left, operator, right) { return { type: Syntax_1.BinaryExpression, left: left, right: right, operator: operator }; } function createSequenceExpression(expressions) { //@ts-ignore SequenceExpression can actually // TODO: To write to https://github.com/estree/estree that SequenceExpression must include Pattern return { type: Syntax_1.SequenceExpression, expressions: expressions }; } function createThisExpression() { return { type: Syntax_1.ThisExpression }; } function createLogicalExpression(left, operator, right) { return { type: Syntax_1.LogicalExpression, left: left, right: right, operator: operator }; } function createReturnStatement(argument) { if (argument === void 0) { argument = null; } return { type: Syntax_1.ReturnStatement, argument: argument }; } function createFunctionExpression(id, params, body, async, generator) { if (async === void 0) { async = false; } if (generator === void 0) { generator = false; } return { type: Syntax_1.FunctionExpression, id: id, params: params, body: body, async: async, generator: generator }; } function createUnaryExpression(operator, argument) { return { type: Syntax_1.UnaryExpression, operator: operator, prefix: true, argument: argument }; } function createUndefined() { return createUnaryExpression('void', createSimpleLiteral(0)); } function createConditionalExpression(test, consequent, alternate) { return { type: Syntax_1.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; } function createSimpleLiteral(value) { return { type: Syntax_1.Literal, value: value }; } function createAssignmentExprStmt(left, right) { return createExpressionStatement(createAssignmentExpression(left, '=', right)); } function createBlockStatement(body) { return { type: Syntax_1.BlockStatement, body: body }; } function createVariableDeclarator(id, init) { if (init === void 0) { init = null; } return { type: Syntax_1.VariableDeclarator, id: id, init: init }; } function createVariableDeclaration(kind, declarations) { return { type: Syntax_1.VariableDeclaration, declarations: declarations, kind: kind }; } function createProcessScriptMethodCall(arg, isApply) { var args = [arg]; var processScriptIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.processScript); if (isApply) args.push(createSimpleLiteral(true)); return createSimpleCallExpression(processScriptIdentifier, args); } function createLocationGetWrapper(location) { var getLocationIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getLocation); return createSimpleCallExpression(getLocationIdentifier, [location]); } function createLocationSetWrapper(locationIdentifier, value, wrapWithSequence) { var tempIdentifier = createIdentifier(TempVariables.generateName()); var setLocationIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.setLocation); var setLocationCall = createSimpleCallExpression(setLocationIdentifier, [locationIdentifier, tempIdentifier]); var locationAssignment = createAssignmentExpression(locationIdentifier, '=', tempIdentifier); var callIdentifier = createIdentifier('call'); var functionWrapper = createFunctionExpression(null, [], createBlockStatement([ createVariableDeclaration('var', [createVariableDeclarator(tempIdentifier, value)]), createReturnStatement(createLogicalExpression(setLocationCall, '||', locationAssignment)), ])); var functionWrapperCallMember = createMemberExpression(functionWrapper, callIdentifier, false); var functionWrapperCall = createSimpleCallExpression(functionWrapperCallMember, [createThisExpression()]); if (wrapWithSequence) return createSequenceExpression([createSimpleLiteral(0), functionWrapperCall]); return functionWrapperCall; } function createPropertySetWrapper(propertyName, obj, value) { var setPropertyIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.setProperty); return createSimpleCallExpression(setPropertyIdentifier, [obj, createSimpleLiteral(propertyName), value]); } function createMethodCallWrapper(owner, method, methodArgs, optional) { if (optional === void 0) { optional = false; } var callMethodIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.callMethod); var methodArgsArray = createArrayExpression(methodArgs); var args = [owner, method, methodArgsArray]; if (optional) args.push(createSimpleLiteral(optional)); return createSimpleCallExpression(callMethodIdentifier, args); } function createPropertyGetWrapper(propertyName, owner, optional) { if (optional === void 0) { optional = false; } var getPropertyIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty); var args = [owner, createSimpleLiteral(propertyName)]; if (optional) args.push(createSimpleLiteral(optional)); return createSimpleCallExpression(getPropertyIdentifier, args); } function createComputedPropertyGetWrapper(property, owner, optional) { if (optional === void 0) { optional = false; } var getPropertyIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty); var args = [owner, property]; if (optional) args.push(createSimpleLiteral(optional)); return createSimpleCallExpression(getPropertyIdentifier, args); } function createComputedPropertySetWrapper(property, owner, value) { var setPropertyIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.setProperty); return createSimpleCallExpression(setPropertyIdentifier, [owner, property, value]); } function createGetEvalMethodCall(node) { var getEvalIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getEval); return createSimpleCallExpression(getEvalIdentifier, [node]); } function getProxyUrlLiteral(source, resolver) { var proxyUrl = resolver(String(source.value), getResourceTypeString({ isScript: true })); return createSimpleLiteral(proxyUrl); } function createGetProxyUrlMethodCall(arg, baseUrl) { var getProxyUrlIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getProxyUrl); var args = [arg]; if (baseUrl) args.push(createSimpleLiteral(baseUrl)); return createSimpleCallExpression(getProxyUrlIdentifier, args); } function createGetPostMessageMethodCall(node) { var getPostMessageIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage); var args = node.type === Syntax_1.MemberExpression ? [node.object] : [createSimpleLiteral(null), node]; return createSimpleCallExpression(getPostMessageIdentifier, args); } function createArrayWrapper(array) { var arrayIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.arrayFrom); return createSimpleCallExpression(arrayIdentifier, [array]); } function createExpandedConcatOperation(left, right) { return createAssignmentExpression(left, '=', createBinaryExpression(left, '+', right)); } function createHtmlProcessorWrapper(node) { var processHtmlIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.processHtml); var parentIdentifier = createIdentifier('parent'); var windowIdentifier = createIdentifier('window'); var processHtmlThroughParent = createMemberExpression(parentIdentifier, processHtmlIdentifier, false); var processHtmlCall = createSimpleCallExpression(processHtmlThroughParent, [windowIdentifier, node.expression]); return createExpressionStatement(processHtmlCall); } function createTempVarsDeclaration(tempVars) { var declarations = []; for (var _i = 0, tempVars_1 = tempVars; _i < tempVars_1.length; _i++) { var variable = tempVars_1[_i]; declarations.push(createVariableDeclarator(createIdentifier(variable))); } return createVariableDeclaration('var', declarations); } // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- // NOTE: constants are exported for the testing purposes var METHODS = [ 'postMessage', 'replace', 'assign', ]; var PROPERTIES = [ 'href', 'location', ]; var INSTRUMENTED_METHOD_RE = new RegExp("^(".concat(METHODS.join('|'), ")$")); var INSTRUMENTED_PROPERTY_RE = new RegExp("^(".concat(PROPERTIES.join('|'), ")$")); // NOTE: Mootools framework contains code that removes the RegExp.prototype.test // method and restores it later. // delete z[A]; // z = RegExp.prototype, A = "test" // __set$(z, A, x.protect()); // x.protect - returns the removed method // The __set$ function calls the test method of the regular expression. (GH-331) var reTest = RegExp.prototype.test; // NOTE: The Function.prototype.call method can also be removed. // But only one of the methods can be removed at a time. var test = function (regexp, str) { return regexp.test ? regexp.test(str) : reTest.call(regexp, str); }; // NOTE: we can't use the map approach here, because // cases like `WRAPPABLE_METHOD['toString']` will fail. // We could use the hasOwnProperty test, but it is // significantly slower than the regular expression test function shouldInstrumentMethod(name) { return test(INSTRUMENTED_METHOD_RE, String(name)); } function shouldInstrumentProperty(name) { return test(INSTRUMENTED_PROPERTY_RE, String(name)); } var instrumentationProcessingUtils = /*#__PURE__*/Object.freeze({ __proto__: null, METHODS: METHODS, PROPERTIES: PROPERTIES, shouldInstrumentMethod: shouldInstrumentMethod, shouldInstrumentProperty: shouldInstrumentProperty }); // ------------------------------------------------------------- // Transform: // obj[prop] --> // __get$(obj, prop) var transformer$l = { name: 'computed-property-get', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.MemberExpression, condition: function (node, parent) { if (!node.computed || !parent) return false; if (node.property.type === Syntax_1.Literal && !shouldInstrumentProperty(node.property.value)) return false; // super[prop] if (node.object.type === Syntax_1.Super) return false; // object[prop] = value if (parent.type === Syntax_1.AssignmentExpression && parent.left === node) return false; // delete object[prop] if (parent.type === Syntax_1.UnaryExpression && parent.operator === 'delete') return false; // object[prop]++ || object[prop]-- || ++object[prop] || --object[prop] if (parent.type === Syntax_1.UpdateExpression && (parent.operator === '++' || parent.operator === '--')) return false; // object[prop]() if (parent.type === Syntax_1.CallExpression && parent.callee === node) return false; // new (object[prop])() || new (object[prop]) if (parent.type === Syntax_1.NewExpression && parent.callee === node) return false; // for(object[prop] in source) if (parent.type === Syntax_1.ForInStatement && parent.left === node) return false; return true; }, run: function (node) { return createComputedPropertyGetWrapper(node.property, node.object, node.optional); }, }; // ------------------------------------------------------------- // Transform: // obj[prop] = value --> // __set$(object, prop, value) var transformer$k = { name: 'computed-property-set', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.AssignmentExpression, condition: function (node) { var left = node.left; // super[prop] = value if (left.type === Syntax_1.MemberExpression && left.object.type === Syntax_1.Super) return false; if (node.operator === '=' && left.type === Syntax_1.MemberExpression && left.computed) return left.property.type === Syntax_1.Literal ? shouldInstrumentProperty(left.property.value) : true; return false; }, run: function (node) { var memberExpression = node.left; return createComputedPropertySetWrapper(memberExpression.property, memberExpression.object, node.right); }, }; // ------------------------------------------------------------- // Transform: // val1 += val2 // --> val1 = val1 + val2 var transformer$j = { name: 'concat-operator', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.AssignmentExpression, condition: function (node) { if (node.operator !== '+=') return false; var left = node.left; // location if (left.type === Syntax_1.Identifier) return shouldInstrumentProperty(left.name); if (left.type === Syntax_1.MemberExpression) { // something['location'] or something[propname] if (left.computed) { return left.property.type === Syntax_1.Literal ? shouldInstrumentProperty(left.property.value) : left.property.type !== Syntax_1.UpdateExpression; } // something.location else if (left.property.type === Syntax_1.Identifier) return shouldInstrumentProperty(left.property.name); } return false; }, run: function (node) { return createExpandedConcatOperation(node.left, node.right); }, }; function replaceNode(node, newNode, parent, key) { var oldNode = parent[key]; if (oldNode instanceof Array) { if (node) oldNode[oldNode.indexOf(node)] = newNode; else oldNode.unshift(newNode); } else { // @ts-ignore parent[key] = newNode; } if (node) { newNode.originStart = newNode.start = node.start; newNode.originEnd = newNode.end = node.end; } else { /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ newNode.start = newNode.end = newNode.originStart = newNode.originEnd = oldNode[1] ? oldNode[1].start : parent.start + 1; } } // ------------------------------------------------------------- // Transform: // eval(script); --> eval(__proc$Script(script)); var transformer$i = { name: 'eval', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.CallExpression, condition: function (node) { if (!node.arguments.length) return false; var callee = node.callee; // eval() if (callee.type === Syntax_1.Identifier && callee.name === 'eval') return true; // obj.eval(), obj['eval'](), return callee.type === Syntax_1.MemberExpression && (callee.property.type === Syntax_1.Identifier && callee.property.name || callee.property.type === Syntax_1.Literal && callee.property.value) === 'eval'; }, run: function (node) { var newArgs = createProcessScriptMethodCall(node.arguments[0]); replaceNode(node.arguments[0], newArgs, node, 'arguments'); return null; }, }; // ------------------------------------------------------------- // Transform: // foo = eval.bind(...); --> // foo = __get$Eval(eval).bind(...); var transformer$h = { name: 'eval-bind', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.CallExpression, condition: function (node) { if (node.callee.type === Syntax_1.MemberExpression && node.callee.property.type === Syntax_1.Identifier && node.callee.property.name === 'bind') { var obj = node.callee.object; // obj.eval.bind(), obj[eval].bind() if (obj.type === Syntax_1.MemberExpression && (obj.property.type === Syntax_1.Identifier && obj.property.name || obj.property.type === Syntax_1.Literal && obj.property.value) === 'eval') return true; // eval.bind() if (obj.type === Syntax_1.Identifier && obj.name === 'eval') return true; } return false; }, run: function (node) { var callee = node.callee; var getEvalNode = createGetEvalMethodCall(callee.object); replaceNode(callee.object, getEvalNode, callee, 'object'); return null; }, }; // ------------------------------------------------------------- var INVOCATION_FUNC_NAME_RE$1 = /^(call|apply)$/; // Transform: // eval.call(ctx, script); // eval.apply(ctx, script); --> // eval.call(ctx, __proc$Script(script)); // eval.apply(ctx, __proc$Script(script, true)); var transformer$g = { name: 'eval-call-apply', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.CallExpression, condition: function (node) { // eval.(ctx, script, ...) if (node.arguments.length < 2) return false; if (node.callee.type === Syntax_1.MemberExpression && node.callee.property.type === Syntax_1.Identifier && INVOCATION_FUNC_NAME_RE$1.test(node.callee.property.name)) { var obj = node.callee.object; // eval.() if (obj.type === Syntax_1.Identifier && obj.name === 'eval') return true; // obj.eval.(), obj[eval].() if (obj.type === Syntax_1.MemberExpression && (obj.property.type === Syntax_1.Identifier && obj.property.name || obj.property.type === Syntax_1.Literal && obj.property.value) === 'eval') return true; } return false; }, run: function (node) { var callee = node.callee; var property = callee.property; var newArg = createProcessScriptMethodCall(node.arguments[1], property.name === 'apply'); replaceNode(node.arguments[1], newArg, node, 'arguments'); return null; }, }; // ------------------------------------------------------------- // Transform: // const foo = eval; foo = eval; { _eval: eval }; return eval; // --> // const foo = _get$Eval(eval); foo = _get$Eval(eval); { _eval: _get$Eval(eval) }; return _get$Eval(eval); var transformer$f = { name: 'eval-get', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.Identifier, condition: function (node, parent) { if (node.name === 'eval' && parent) { // Skip: eval() if (parent.type === Syntax_1.CallExpression && parent.callee === node) return false; // Skip: class X { eval () {} } if (parent.type === Syntax_1.MethodDefinition) return false; // Skip: class eval { x () {} } if (parent.type === Syntax_1.ClassDeclaration) return false; // Skip: window.eval, eval.call if (parent.type === Syntax_1.MemberExpression) return false; // Skip: function eval () { ... } if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration) && parent.id === node) return false; // Skip: function (eval) { ... } || function func(eval) { ... } || eval => { ... } if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration || parent.type === Syntax_1.ArrowFunctionExpression) && parent.params.indexOf(node) !== -1) return false; // Skip: { eval: value } if (parent.type === Syntax_1.Property && parent.key === node) return false; // Skip: { eval } if (parent.type === Syntax_1.Property && parent.value === node && parent.shorthand) return false; // Skip: eval = value || function x (eval = value) { ... } if ((parent.type === Syntax_1.AssignmentExpression || parent.type === Syntax_1.AssignmentPattern) && parent.left === node) return false; // Skip: const eval = value; if (parent.type === Syntax_1.VariableDeclarator && parent.id === node) return false; // Skip: eval++ || eval-- || ++eval || --eval if (parent.type === Syntax_1.UpdateExpression && (parent.operator === '++' || parent.operator === '--')) return false; // Skip already transformed: __get$Eval(eval) if (parent.type === Syntax_1.CallExpression && parent.callee.type === Syntax_1.Identifier && parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.getEval) return false; // Skip: function x (...eval) {} if (parent.type === Syntax_1.RestElement) return false; // Skip: export { eval } from "module"; if (parent.type === Syntax_1.ExportSpecifier) return false; // Skip: import { eval } from "module"; if (parent.type === Syntax_1.ImportSpecifier) return false; return true; } return false; }, run: createGetEvalMethodCall, }; // ------------------------------------------------------------- // Transform: // const foo = window.eval; foo = window.eval; { _eval: window.eval }; return window.eval; // --> // const foo = _get$Eval(window.eval); foo = _get$Eval(window.eval); { _eval: _get$Eval(window.eval) }; return _get$Eval(window.eval); var transformer$e = { name: 'window-eval-get', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.MemberExpression, condition: function (node, parent) { if (!parent) return false; // Skip: window.eval.field if (parent.type === Syntax_1.MemberExpression && (parent.property === node || parent.object === node)) return false; // Skip: window.eval() if (parent.type === Syntax_1.CallExpression && parent.callee === node) return false; // Skip: window.eval = 1, window["eval"] = 1 if (parent.type === Syntax_1.AssignmentExpression && parent.left === node) return false; // Skip already transformed: __get$Eval(window.eval), __get$Eval(window["eval"]) if (parent.type === Syntax_1.CallExpression && parent.callee.type === Syntax_1.Identifier && parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.getEval) return false; // window.eval if (node.property.type === Syntax_1.Identifier && node.property.name === 'eval') return true; // window['eval'] if (node.property.type === Syntax_1.Literal && node.property.value === 'eval') return true; return false; }, run: createGetEvalMethodCall, }; // ------------------------------------------------------------- // Transform: // const foo = postMessage; foo = postMessage; { _postMessage: postMessage }; return postMessage; // --> // const foo = _get$PostMessage(postMessage); foo = _get$PostMessage(postMessage); { _postMessage: _get$PostMessage(postMessage) }; return _get$PostMessage(postMessage); var transformer$d = { name: 'post-message-get', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.Identifier, condition: function (node, parent) { if (node.name !== 'postMessage' || !parent) return false; // Skip: window.postMessage, postMessage.call if (parent.type === Syntax_1.MemberExpression) return false; // Skip: class X { postMessage () {} } if (parent.type === Syntax_1.MethodDefinition) return false; // Skip: class postMessage { x () {} } if (parent.type === Syntax_1.ClassDeclaration) return false; // Skip: function postMessage () { ... } if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration) && parent.id === node) return false; // Skip: function (postMessage) { ... } || function func(postMessage) { ... } || postMessage => { ... } if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration || parent.type === Syntax_1.ArrowFunctionExpression) && parent.params.indexOf(node) !== -1) return false; // Skip: { postMessage: value } if (parent.type === Syntax_1.Property && parent.key === node) return false; // Skip: { postMessage } if (parent.type === Syntax_1.Property && parent.value === node && parent.shorthand) return false; // Skip: postMessage = value || function x (postMessage = value) { ... } if ((parent.type === Syntax_1.AssignmentExpression || parent.type === Syntax_1.AssignmentPattern) && parent.left === node) return false; // Skip: const postMessage = value; if (parent.type === Syntax_1.VariableDeclarator && parent.id === node) return false; // Skip: postMessage++ || postMessage-- || ++postMessage || --postMessage if (parent.type === Syntax_1.UpdateExpression && (parent.operator === '++' || parent.operator === '--')) return false; // Skip already transformed: __get$PostMessage(postMessage) || __call$(obj, postMessage, args...); if (parent.type === Syntax_1.CallExpression && parent.callee.type === Syntax_1.Identifier && (parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage || parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.callMethod && parent.arguments[1] === node)) return false; // Skip: function x (...postMessage) {} if (parent.type === Syntax_1.RestElement) return false; // Skip: export { postMessage } from "module"; if (parent.type === Syntax_1.ExportSpecifier) return false; // Skip: import { postMessage } from "module"; if (parent.type === Syntax_1.ImportSpecifier) return false; return true; }, run: createGetPostMessageMethodCall, }; // ------------------------------------------------------------- // Transform: // const foo = window.postMessage; foo = window.postMessage; { _postMessage: window.postMessage }; return window.postMessage; // --> // const foo = _get$PostMessage(window.postMessage); foo = _get$PostMessage(window.postMessage); { _postMessage: _get$PostMessage(window.postMessage) }; return _get$PostMessage(window.postMessage); var transformer$c = { name: 'window-post-message-get', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.MemberExpression, condition: function (node, parent) { if (!parent) return false; // Skip: window.postMessage.field if (parent.type === Syntax_1.MemberExpression && (parent.property === node || parent.object === node)) return false; // Skip: window.postMessage() if (parent.type === Syntax_1.CallExpression && parent.callee === node) return false; // Skip: window.postMessage = 1, window["postMessage"] = 1 if (parent.type === Syntax_1.AssignmentExpression && parent.left === node) return false; // Skip already transformed: __get$PostMessage(window.postMessage), __get$PostMessage(window["postMessage"]) if (parent.type === Syntax_1.CallExpression && parent.callee.type === Syntax_1.Identifier && parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage) return false; // window.postMessage if (node.property.type === Syntax_1.Identifier && node.property.name === 'postMessage') return true; // window['postMessage'] if (node.property.type === Syntax_1.Literal && node.property.value === 'postMessage') return true; return false; }, run: createGetPostMessageMethodCall, }; // ------------------------------------------------------------- var INVOCATION_FUNC_NAME_RE = /^(call|apply|bind)$/; // Transform: // postMessage.call(ctx, script); // postMessage.apply(ctx, script); // postMessage.bind(...); --> // __get$PostMessage(postMessage).call(ctx, script); // __get$PostMessage(postMessage).apply(ctx, script); // __get$PostMessage(postMessage).bind(...); var transformer$b = { name: 'post-message-call-apply-bind', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.CallExpression, condition: function (node) { if (node.callee.type === Syntax_1.MemberExpression && node.callee.property.type === Syntax_1.Identifier && INVOCATION_FUNC_NAME_RE.test(node.callee.property.name)) { // postMessage.(ctx, script, ...) if (node.arguments.length < 2 && node.callee.property.name !== 'bind') return false; var obj = node.callee.object; // obj.postMessage.(), obj[postMessage].(), if (obj.type === Syntax_1.MemberExpression && (obj.property.type === Syntax_1.Identifier && obj.property.name || obj.property.type === Syntax_1.Literal && obj.property.value) === 'postMessage') return true; // postMessage.() if (obj.type === Syntax_1.Identifier && obj.name === 'postMessage') return true; } return false; }, run: function (node) { var callee = node.callee; var getPostMessageNode = createGetPostMessageMethodCall(callee.object); replaceNode(callee.object, getPostMessageNode, callee, 'object'); return null; }, }; // ------------------------------------------------------------- // Transform: // for(obj[prop] in src), for(obj.prop in src) --> // for(const _hh$temp0 in src) { obj[prop] = _hh$temp0; } var transformer$a = { name: 'for-in', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.ForInStatement, condition: function (node) { return node.left.type === Syntax_1.MemberExpression; }, run: function (node) { var tempVarAst = createIdentifier(TempVariables.generateName()); var varDeclaration = createVariableDeclaration('var', [createVariableDeclarator(tempVarAst)]); var assignmentExprStmt = createAssignmentExprStmt(node.left, tempVarAst); if (node.body.type !== Syntax_1.BlockStatement) replaceNode(node.body, createBlockStatement([assignmentExprStmt, node.body]), node, 'body'); else replaceNode(null, assignmentExprStmt, node.body, 'body'); replaceNode(node.left, varDeclaration, node, 'left'); return null; }, }; function walkDeclarators(node, action) { var declarators = []; var identifiers = []; for (var _i = 0, _a = node.body; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.type === Syntax_1.VariableDeclaration) declarators.push.apply(declarators, statement.declarations); } for (var _b = 0, declarators_1 = declarators; _b < declarators_1.length; _b++) { var declarator = declarators_1[_b]; if (declarator.type === Syntax_1.VariableDeclarator) { if (declarator.id.type === Syntax_1.Identifier) identifiers.push(declarator.id); if (declarator.id.type === Syntax_1.ArrayPattern) identifiers.push.apply(identifiers, declarator.id.elements); if (declarator.id.type === Syntax_1.ObjectPattern) { for (var _c = 0, _d = declarator.id.properties; _c < _d.length; _c++) { var prop = _d[_c]; if ('value' in prop) identifiers.push(prop.value); } } } } for (var _e = 0, identifiers_1 = identifiers; _e < identifiers_1.length; _e++) { var identifier = identifiers_1[_e]; if (identifier && identifier.type === Syntax_1.Identifier) action(identifier); } } function replaceDuplicateDeclarators(forOfNode) { var _a; var forOfLeft = forOfNode.left; var nodesToReplace = []; var isArrayPatternDeclaration = ((_a = forOfLeft.declarations[0]) === null || _a === void 0 ? void 0 : _a.id.type) === Syntax_1.ArrayPattern; var isBlockStatement = forOfNode.body.type === Syntax_1.BlockStatement; if (!isArrayPatternDeclaration || !isBlockStatement) return; var leftDeclaration = forOfLeft.declarations[0].id; var leftIdentifiers = leftDeclaration.elements; walkDeclarators(forOfNode.body, function (node) { for (var _i = 0, leftIdentifiers_1 = leftIdentifiers; _i < leftIdentifiers_1.length; _i++) { var identifier = leftIdentifiers_1[_i]; if (identifier && identifier.name === node.name) nodesToReplace.push(identifier); } }); for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { var nodeToReplace = nodesToReplace_1[_i]; var destIdentifier = createIdentifier(TempVariables.generateName()); replaceNode(nodeToReplace, destIdentifier, leftDeclaration, 'elements'); } } // Transform: // for (let {href, postMessage} of wins) {} --> // for (let _hh$temp0 of wins) { let {href, postMessage} = _hh$temp0; } var forOfTransformer = { name: 'for-of', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.ForOfStatement, condition: function (node) { var left = node.left; if (left.type === Syntax_1.VariableDeclaration) left = left.declarations[0].id; return left.type === Syntax_1.ObjectPattern || left.type === Syntax_1.ArrayPattern; }, run: function (node) { var tempIdentifier = createIdentifier(TempVariables.generateName()); var forOfLeft = node.left; var statementWithTempAssignment; if (forOfLeft.type === Syntax_1.VariableDeclaration) { replaceDuplicateDeclarators(node); statementWithTempAssignment = createVariableDeclaration(forOfLeft.kind, [ createVariableDeclarator(forOfLeft.declarations[0].id, tempIdentifier), ]); statementWithTempAssignment.reTransform = true; replaceNode(forOfLeft.declarations[0].id, tempIdentifier, forOfLeft.declarations[0], 'id'); } else { var varDeclaration = createVariableDeclaration('var', [createVariableDeclarator(tempIdentifier)]); statementWithTempAssignment = createAssignmentExprStmt(forOfLeft, tempIdentifier); replaceNode(forOfLeft, varDeclaration, node, 'left'); } if (node.body.type === Syntax_1.BlockStatement) replaceNode(null, statementWithTempAssignment, node.body, 'body'); else replaceNode(node.body, createBlockStatement([statementWithTempAssignment, node.body]), node, 'body'); return null; }, }; // ------------------------------------------------------------- // Transform: // location --> // __get$Loc(location) var transformer$9 = { name: 'location-get', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.Identifier, condition: function (node, parent) { if (node.name !== 'location' || !parent) return false; // Skip: const location = value; if (parent.type === Syntax_1.VariableDeclarator && parent.id === node) return false; // Skip: location = value || function x (location = value) { ... } if ((parent.type === Syntax_1.AssignmentExpression || parent.type === Syntax_1.AssignmentPattern) && parent.left === node) return false; // Skip: function location() {} if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration) && parent.id === node) return false; // Skip: object.location || location.field if (parent.type === Syntax_1.MemberExpression && parent.property === node) return false; // Skip: { location: value } if (parent.type === Syntax_1.Property && parent.key === node) return false; // Skip: { location } if (parent.type === Syntax_1.Property && parent.value === node && parent.shorthand) return false; // Skip: location++ || location-- || ++location || --location if (parent.type === Syntax_1.UpdateExpression && (parent.operator === '++' || parent.operator === '--')) return false; // Skip: function (location) { ... } || function func(location) { ... } || location => { ... } if ((parent.type === Syntax_1.FunctionExpression || parent.type === Syntax_1.FunctionDeclaration || parent.type === Syntax_1.ArrowFunctionExpression) && parent.params.indexOf(node) !== -1) return false; // Skip already transformed: __get$Loc(location) if (parent.type === Syntax_1.CallExpression && parent.callee.type === Syntax_1.Identifier && parent.callee.name === SCRIPT_PROCESSING_INSTRUCTIONS.getLocation) return false; // Skip: class X { location () {} } if (parent.type === Syntax_1.MethodDefinition) return false; // Skip: class location { x () {} } if (parent.type === Syntax_1.ClassDeclaration) return false; // Skip: function x (...location) {} if (parent.type === Syntax_1.RestElement) return false; // Skip: export { location } from "module"; if (parent.type === Syntax_1.ExportSpecifier) return false; // Skip: import { location } from "module"; if (parent.type === Syntax_1.ImportSpecifier) return false; return true; }, run: createLocationGetWrapper, }; // ------------------------------------------------------------- // Transform: // location = value --> // (function(){ return __set$Loc(location, value) || location = value;}.apply(this)) var transformer$8 = { name: 'location-set', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.AssignmentExpression, condition: function (node) { return node.operator === '=' && node.left.type === Syntax_1.Identifier && node.left.name === 'location'; }, run: function (node, parent, key) { if (!parent) return null; var wrapWithSequence = key !== 'arguments' && key !== 'consequent' && key !== 'alternate' && // @ts-ignore (parent.type !== Syntax_1.SequenceExpression || parent.expressions[0] === node); return createLocationSetWrapper(node.left, node.right, wrapWithSequence); }, }; // ------------------------------------------------------------- // Transform: // obj. --> // __get$(obj, '') var transformer$7 = { name: 'property-get', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.MemberExpression, condition: function (node, parent) { if (node.computed || !parent) return false; if (node.property.type === Syntax_1.Identifier && !shouldInstrumentProperty(node.property.name)) return false; // Skip: super.prop if (node.object.type === Syntax_1.Super) return false; // @ts-ignore var valuableParent = parent.type === Syntax_1.ParenthesizedExpression ? parent.expression : parent; // Skip: object.prop = value if (parent.type === Syntax_1.AssignmentExpression && parent.left === node) return false; // Skip: delete object.prop if (parent.type === Syntax_1.UnaryExpression && parent.operator === 'delete') return false; // Skip: object.prop() if (parent.type === Syntax_1.CallExpression && parent.callee === node) return false; // Skip: object.prop++ || object.prop-- || ++object.prop || --object.prop if (parent.type === Syntax_1.UpdateExpression && (parent.operator === '++' || parent.operator === '--')) return false; // Skip: new (object.prop)() || new (object.prop) if (valuableParent.type === Syntax_1.NewExpression && valuableParent.callee === node) return false; // Skip: for(object.prop in source) if (parent.type === Syntax_1.ForInStatement && parent.left === node) return false; return true; }, // eslint-disable-next-line run: function (node) { return createPropertyGetWrapper(node.property.name, node.object, node.optional); } }; // ------------------------------------------------------------- // Transform: // obj. = value --> // __set$(obj, '', value) var transformer$6 = { name: 'property-set', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.AssignmentExpression, condition: function (node) { // super.prop = value if (node.left.type === Syntax_1.MemberExpression && node.left.object.type === Syntax_1.Super) return false; return node.operator === '=' && node.left.type === Syntax_1.MemberExpression && !node.left.computed && node.left.property.type === Syntax_1.Identifier && shouldInstrumentProperty(node.left.property.name); }, run: function (node) { var memberExpression = node.left; var identifier = memberExpression.property; return createPropertySetWrapper(identifier.name, memberExpression.object, node.right); }, }; // ------------------------------------------------------------- // Transform: // obj.method(args...); obj[method](args...); --> // _call$(obj, 'method', args...); _call$(obj, method, args...); var transformer$5 = { name: 'method-call', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.CallExpression, condition: function (node) { var callee = node.callee; if (callee.type === Syntax_1.MemberExpression) { // Skip: super.meth() if (callee.object.type === Syntax_1.Super) return false; if (callee.computed) return callee.property.type === Syntax_1.Literal ? shouldInstrumentMethod(callee.property.value) : true; return callee.property.type === Syntax_1.Identifier && shouldInstrumentMethod(callee.property.name); } return false; }, run: function (node) { var callee = node.callee; var method = callee.computed ? callee.property : createSimpleLiteral(callee.property.name); // eslint-disable-line no-extra-parens var optional = node.optional; return createMethodCallWrapper(callee.object, method, node.arguments, optional); }, }; // ------------------------------------------------------------- // Transform: // x = 5; "hello" --> x = 5; parent.__proc$Html(window, "hello") // someAction(); generateHtmlPage() --> someAction(); parent.__proc$Html(window, generateHtmlPage()) var transformer$4 = { name: 'js-protocol-last-expression', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.ExpressionStatement, condition: function (node, parent) { return !!transformer$4.wrapLastExpr && !!parent && parent.type === Syntax_1.Program && parent.body[parent.body.length - 1] === node; }, run: function (node) { transformer$4.wrapLastExpr = false; return createHtmlProcessorWrapper(node); }, }; // ------------------------------------------------------------- // Transform: // import something from 'url'; --> import something from 'processed-url'; // export * from 'url'; --> export * from 'processed-url'; // export { x as y } from 'url'; --> export { x as y } from 'processed-url'; var transformer$3 = { name: 'static-import', nodeReplacementRequireTransform: false, nodeTypes: Syntax_1.Literal, condition: function (node, parent) { return !!parent && (parent.type === Syntax_1.ImportDeclaration || parent.type === Syntax_1.ExportAllDeclaration || parent.type === Syntax_1.ExportNamedDeclaration) && parent.source === node; }, run: function (node) { return transformer$3.resolver ? getProxyUrlLiteral(node, transformer$3.resolver) : null; }, }; // ------------------------------------------------------------- // Transform: // import(something).then() // --> // import(__get$ProxyUrl(something)).then() var transformer$2 = { name: 'dynamic-import', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.ImportExpression, condition: function () { return true; }, run: function (node) { var _a; var newSource = createGetProxyUrlMethodCall(node.source, (_a = transformer$2.getBaseUrl) === null || _a === void 0 ? void 0 : _a.call(transformer$2)); replaceNode(node.source, newSource, node, 'source'); return null; }, }; function processObjectProperty(prop, temp, build, baseTempName) { var pattern = prop.value; var computed = prop.computed || prop.key.type === Syntax_1.Literal; var value = createMemberExpression(temp, prop.key, computed); process(pattern, value, build, baseTempName); } function createObjectRest(tempIdentifier, keys) { var restObjectIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.restObject); return createSimpleCallExpression(restObjectIdentifier, [tempIdentifier, createArrayExpression(keys)]); } function createRestArray(array, startIndex) { var restArrayIdentifier = createIdentifier(SCRIPT_PROCESSING_INSTRUCTIONS.restArray); return createSimpleCallExpression(restArrayIdentifier, [array, createSimpleLiteral(startIndex)]); } function createTempIdentifierOrUseExisting(value, build, baseTempName) { if (value.type === Syntax_1.Identifier && TempVariables.isHHTempVariable(value.name)) return value; var tempIdentifier = createIdentifier(baseTempName || TempVariables.generateName(baseTempName)); build(tempIdentifier, value, true); return tempIdentifier; } function processObjectPattern(pattern, value, build, baseTempName) { if (!value) return; var properties = pattern.properties; var hasRest = properties.length && properties[properties.length - 1].type === Syntax_1.RestElement; var tempIdentifier = createTempIdentifierOrUseExisting(value, build, baseTempName); var propNames = []; var baseTempNames = []; if (!baseTempName) baseTempName = tempIdentifier.name; if (hasRest) { for (var i = 0; i < properties.length - 1; i++) { var prop = properties[i]; var key = prop.key; if (key.type === Syntax_1.Identifier) propNames.push(prop.computed ? key : createSimpleLiteral(key.name)); else if (key.type === Syntax_1.Literal) propNames.push(key); else { var tempPropKey = createIdentifier(TempVariables.generateName()); build(tempPropKey, key, true); propNames.push(tempPropKey); prop.key = tempPropKey; } } } for (var i = 0; i < properties.length; i++) { var prop = properties[i]; if (prop.type === Syntax_1.RestElement) build(prop.argument, createObjectRest(tempIdentifier, propNames)); else { var assignmentProp = prop; var newBaseTempName = TempVariables.generateName(baseTempName, assignmentProp.key, i); if (baseTempNames.indexOf(newBaseTempName) > -1) newBaseTempName = TempVariables.generateName(newBaseTempName, void 0, i); baseTempNames.push(newBaseTempName); processObjectProperty(assignmentProp, tempIdentifier, build, newBaseTempName); } } } function processArrayPattern(pattern, value, build, baseTempName) { if (!value) return; // NOTE: support iterable objects (GH-2669) if (value.type !== Syntax_1.ArrayExpression) value = createArrayWrapper(value); var tempIdentifier = createTempIdentifierOrUseExisting(value, build, baseTempName); if (!baseTempName) baseTempName = tempIdentifier.name; for (var i = 0; i < pattern.elements.length; i++) { var elem = pattern.elements[i]; if (!elem) continue; if (elem.type === Syntax_1.RestElement) { value = createRestArray(tempIdentifier, i); elem = elem.argument; } else value = createMemberExpression(tempIdentifier, createSimpleLiteral(i), true); process(elem, value, build, TempVariables.generateName(baseTempName, void 0, i)); } } function processAssignmentPattern(pattern, value, build, baseTempName) { if (!value) return; var left = pattern.left, right = pattern.right; var tempIdentifier = createTempIdentifierOrUseExisting(value, build, baseTempName); var tempCondition = createBinaryExpression(tempIdentifier, '===', createUndefined()); var tempConditional = createConditionalExpression(tempCondition, right, tempIdentifier); if (!baseTempName) baseTempName = tempIdentifier.name; baseTempName += '$assign'; process(left, tempConditional, build, baseTempName); } function process(pattern, value, build, baseTempName) { if (pattern.type === Syntax_1.ObjectPattern) processObjectPattern(pattern, value, build, baseTempName); else if (pattern.type === Syntax_1.ArrayPattern) processArrayPattern(pattern, value, build, baseTempName); else if (pattern.type === Syntax_1.AssignmentPattern) processAssignmentPattern(pattern, value, build, baseTempName); else build(pattern, value); } // ------------------------------------------------------------- // Transform: // var { location: loc } = window, // [{ location }, item] = [window, 6], // --> // var _hh$temp0 = window, // loc = _hh$temp0.location, // _hh$temp1 = [window, 6], // _hh$temp1$0 = _hh$temp1[0], // location = _hh$temp1$0.location, // item = _hh$temp1[1]; // var [a, b] = c; // --> // var _hh$temp0 = __arrayFrom$(c), // a = _hh$temp0[0], // b = _hh$temp0[1]; var transformer$1 = { name: 'declaration-destructuring', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.VariableDeclaration, // @ts-ignore condition: function (node, parent) { // Skip: for (let { x } in some); if ((parent === null || parent === void 0 ? void 0 : parent.type) === Syntax_1.ForInStatement) return false; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var declarator = _a[_i]; if (declarator.id.type === Syntax_1.ObjectPattern || declarator.id.type === Syntax_1.ArrayPattern) return true; } return false; }, run: function (node) { var declarations = []; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { var declarator = _a[_i]; process(declarator.id, declarator.init || null, function (pattern, value) { return declarations.push(createVariableDeclarator(pattern, value)); }); } return createVariableDeclaration(node.kind, declarations); }, }; // ------------------------------------------------------------- // Transform: // ({ location: loc } = window); // [{ location }, item] = [window, 6] // --> // var _hh$temp0, _hh$temp1, _hh$temp1$0; // // (_hh$temp0 = window, loc = _hh$temp0.location, _hh$temp0); // (_hh$temp1 = [window, 6], _hh$temp1$0 = _hh$temp1[0], location = _hh$temp1$0.location, item = _hh$temp1[1], _hh$temp1); var transformer = { name: 'assignment-destructuring', nodeReplacementRequireTransform: true, nodeTypes: Syntax_1.AssignmentExpression, condition: function (node) { return node.operator === '=' && (node.left.type === Syntax_1.ObjectPattern || node.left.type === Syntax_1.ArrayPattern); }, run: function (node, _parent, _key, tempVars) { var assignments = []; var isFirstTemp = true; var firstTemp = null; process(node.left, node.right, function (pattern, value, isTemp) { if (isFirstTemp) { isFirstTemp = false; if (isTemp) firstTemp = pattern; } assignments.push(createAssignmentExpression(pattern, '=', value)); if (isTemp && tempVars) tempVars.append(pattern.name); }); if (firstTemp) assignments.push(firstTemp); return createSequenceExpression(assignments); }, }; // ------------------------------------------------------------- // Transform: // function x ({a, b}, [c, d]) {} // --> // function x (_hh$temp0, _hh$temp1) { // var {a, b} = _hh$temp0, // [c, d] = _hh$temp1; // } function create$2(type) { return { name: 'func-args-destructing', nodeReplacementRequireTransform: false, nodeTypes: type, condition: function (node) { for (var _i = 0, _a = node.params; _i < _a.length; _i++) { var param = _a[_i]; if (param.type === Syntax_1.AssignmentPattern) param = param.left; if (param.type === Syntax_1.ObjectPattern || param.type === Syntax_1.ArrayPattern) return true; } return false; }, run: function (node) { var declarations = []; for (var _i = 0, _a = node.params; _i < _a.length; _i++) { var param = _a[_i]; var tempVarParent = node; var tempVarKey = 'params'; if (param.type === Syntax_1.AssignmentPattern) { // @ts-ignore tempVarParent = param; param = param.left; tempVarKey = 'left'; } if (param.type === Syntax_1.ObjectPattern && param.properties.length || param.type === Syntax_1.ArrayPattern && param.elements.length) { var tempVar = createIdentifier(TempVariables.generateName()); // @ts-ignore replaceNode(param, tempVar, tempVarParent, tempVarKey); declarations.push(createVariableDeclarator(param, tempVar)); } } if (!declarations.length) return null; var declaration = createVariableDeclaration('var', declarations); if (node.body.type !== Syntax_1.BlockStatement) { // @ts-ignore var returnStmt = createReturnStatement(node.body); replaceNode(node.body, createBlockStatement([declaration, returnStmt]), node, 'body'); // @ts-ignore node.expression = false; return node; } replaceNode(null, declaration, node.body, 'body'); declaration.reTransform = true; return null; }, }; } // ------------------------------------------------------------- var TRANSFORMERS = [ create$2(Syntax_1.FunctionDeclaration), create$2(Syntax_1.FunctionExpression), create$2(Syntax_1.ArrowFunctionExpression), transformer, transformer$l, transformer$k, transformer$j, transformer$i, transformer$h, transformer$g, transformer$f, transformer$e, transformer$d, transformer$c, transformer$b, transformer$a, forOfTransformer, transformer$9, transformer$8, transformer$7, transformer$6, transformer$5, transformer$4, transformer$3, transformer$2, transformer$1, ]; function createTransformerMap() { var transformerMap = new Map(); for (var _i = 0, TRANSFORMERS_1 = TRANSFORMERS; _i < TRANSFORMERS_1.length; _i++) { var transformer = TRANSFORMERS_1[_i]; var nodeType = transformer.nodeTypes; var transformers = transformerMap.get(nodeType); if (!transformers) { transformers = []; transformerMap.set(nodeType, transformers); } transformers.push(transformer); } return transformerMap; } var transformers = createTransformerMap(); var STACK_FRAME_REG_EXPS = [ /^\s*at .*\((\S+)\)/, /^\s*at (\S+)/, /^.*@(\S+)/, /(.+)/, // Any string ]; var STACK_FRAME_REGEX = /(?:^|\n)(?:\s*at |.*@)(?:.*\()?(\S+?):\d+:\d+\)?/g; var ROW_COLUMN_NUMBER_REG_EX = /:\d+:\d+$/; function getDestSource(source) { var parsedProxiedUrl = parseProxyUrl$1(source); return parsedProxiedUrl && parsedProxiedUrl.destUrl; } function replaceUrlWithProxied(str, source) { source = source.replace(ROW_COLUMN_NUMBER_REG_EX, ''); var destUrl = getDestSource(source); return destUrl ? str.replace(source, destUrl) : str; } function replaceProxiedUrlsInStack(stack) { if (!stack) return stack; var stackFrames = stack.split('\n'); for (var i = 0; i < stackFrames.length; i++) { var stackFrame = stackFrames[i]; for (var _i = 0, STACK_FRAME_REG_EXPS_1 = STACK_FRAME_REG_EXPS; _i < STACK_FRAME_REG_EXPS_1.length; _i++) { var stackFrameRegExp = STACK_FRAME_REG_EXPS_1[_i]; if (stackFrameRegExp.test(stackFrame)) { stackFrames[i] = stackFrame.replace(stackFrameRegExp, replaceUrlWithProxied); break; } } } return stackFrames.join('\n'); } function getFirstDestUrl(stack) { if (!stack) return null; var searchResult = STACK_FRAME_REGEX.exec(stack); while (searchResult) { var destUrl = getDestSource(searchResult[1]); if (destUrl) { STACK_FRAME_REGEX.lastIndex = 0; return destUrl; } searchResult = STACK_FRAME_REGEX.exec(stack); } return null; } var sharedStackProcessingUtils = /*#__PURE__*/Object.freeze({ __proto__: null, replaceProxiedUrlsInStack: replaceProxiedUrlsInStack, getFirstDestUrl: getFirstDestUrl }); var State = /** @class */ (function () { function State() { this.hasTransformedAncestor = false; } // NOTE: There is an issue with processing `new` expressions. `new a.src.b()` will be transformed // to `new __get$(a, 'src').b()`, which is wrong. The correct result is `new (__get$(a, 'src')).b()`. // To solve this problem, we add a 'state' entity. This entity stores the "new" expression, so that // we can add it to the changes when the transformation is found. State.create = function (currState, node, parent, key, hasTransformedAncestor) { if (hasTransformedAncestor === void 0) { hasTransformedAncestor = false; } var isNewExpression = node.type === Syntax_1.NewExpression; var isNewExpressionAncestor = isNewExpression && !currState.newExpressionAncestor; var newState = new State(); newState.hasTransformedAncestor = currState.hasTransformedAncestor || hasTransformedAncestor; newState.newExpressionAncestor = isNewExpressionAncestor ? node : currState.newExpressionAncestor; newState.newExpressionAncestorParent = isNewExpressionAncestor ? parent : currState.newExpressionAncestorParent; // @ts-ignore newState.newExpressionAncestorKey = isNewExpressionAncestor ? key : currState.newExpressionAncestorKey; return newState; }; return State; }()); // NOTE: We should avoid using native object prototype methods, // since they can be overriden by the client code. (GH-245) var objectToString = Object.prototype.toString; var objectKeys = Object.keys; function getChange(node, parentType) { /*eslint-disable @typescript-eslint/no-non-null-assertion*/ var start = node.originStart; var end = node.originEnd; /*eslint-disable @typescript-eslint/no-non-null-assertion*/ return { start: start, end: end, node: node, parentType: parentType }; } function transformChildNodes(node, changes, state, tempVars) { // @ts-ignore var nodeKeys = objectKeys(node); for (var _i = 0, nodeKeys_1 = nodeKeys; _i < nodeKeys_1.length; _i++) { var key = nodeKeys_1[_i]; var childNode = node[key]; var stringifiedNode = objectToString.call(childNode); if (stringifiedNode === '[object Array]') { // @ts-ignore var childNodes = childNode; for (var _a = 0, childNodes_1 = childNodes; _a < childNodes_1.length; _a++) { var nthNode = childNodes_1[_a]; // NOTE: Some items of ArrayExpression can be null if (nthNode) transform(nthNode, changes, state, node, key, tempVars); } } else if (stringifiedNode === '[object Object]') { // @ts-ignore transform(childNode, changes, state, node, key, tempVars); } } } function isNodeTransformed(node) { return node.originStart !== void 0 && node.originEnd !== void 0; } function addChangeForTransformedNode(state, changes, replacement, parentType) { var hasTransformedAncestor = state.hasTransformedAncestor || state.newExpressionAncestor && isNodeTransformed(state.newExpressionAncestor); if (hasTransformedAncestor) return; if (state.newExpressionAncestor && state.newExpressionAncestorParent) { replaceNode(state.newExpressionAncestor, state.newExpressionAncestor, state.newExpressionAncestorParent, state.newExpressionAncestorKey); changes.push(getChange(state.newExpressionAncestor, state.newExpressionAncestorParent.type)); } else changes.push(getChange(replacement, parentType)); } function addTempVarsDeclaration(node, changes, state, tempVars) { var names = tempVars.get(); if (!names.length) return; var declaration = createTempVarsDeclaration(names); replaceNode(null, declaration, node, 'body'); addChangeForTransformedNode(state, changes, declaration, node.type); } function beforeTransform(wrapLastExprWithProcessHtml, resolver) { if (wrapLastExprWithProcessHtml === void 0) { wrapLastExprWithProcessHtml = false; } transformer$4.wrapLastExpr = wrapLastExprWithProcessHtml; transformer$3.resolver = resolver; var isServerSide = typeof window === 'undefined'; if (isServerSide) { transformer$2.getBaseUrl = function () { if (typeof transformer$2.baseUrl === 'undefined') transformer$2.baseUrl = resolver ? parseProxyUrl$1(resolver('./')).destUrl : ''; return transformer$2.baseUrl; }; } else { transformer$2.getBaseUrl = function () { if (typeof transformer$2.baseUrl === 'undefined') { var currentStack = new Error().stack; // NOTE: IE11 doesn't give the error stack without the 'throw' statement and doesn't support the 'import' statement transformer$2.baseUrl = currentStack && getFirstDestUrl(currentStack) || ''; } return transformer$2.baseUrl; }; } } function afterTransform() { transformer$4.wrapLastExpr = false; transformer$3.resolver = void 0; transformer$2.baseUrl = void 0; } function findTransformer(node, parent) { var nodeTransformers = transformers.get(node.type); if (nodeTransformers) { for (var _i = 0, nodeTransformers_1 = nodeTransformers; _i < nodeTransformers_1.length; _i++) { var transformer = nodeTransformers_1[_i]; if (transformer.condition(node, parent)) return transformer; } } return null; } function transform(node, changes, state, parent, key, tempVars) { var allowTempVarAdd = node.type === Syntax_1.BlockStatement; var nodeTransformed = false; if (allowTempVarAdd) tempVars = new TempVariables(); if (!node.reTransform && isNodeTransformed(node)) { addChangeForTransformedNode(state, changes, node, parent.type); nodeTransformed = true; } else { var storedNode = node; var transformer = findTransformer(node, parent); var replacement = null; while (transformer) { replacement = transformer.run(replacement || node, parent, key, tempVars); if (!replacement) break; nodeTransformed = true; if (!transformer.nodeReplacementRequireTransform) break; transformer = findTransformer(replacement, parent); node = replacement; } if (nodeTransformed && replacement) { replaceNode(storedNode, replacement, parent, key); addChangeForTransformedNode(state, changes, replacement, parent.type); } } state = State.create(state, node, parent, key, nodeTransformed); transformChildNodes(node, changes, state, tempVars); if (allowTempVarAdd) addTempVarsDeclaration(node, changes, state, tempVars); } function transformProgram(node, wrapLastExprWithProcessHtml, resolver) { if (wrapLastExprWithProcessHtml === void 0) { wrapLastExprWithProcessHtml = false; } var changes = []; var state = new State(); var tempVars = new TempVariables(); TempVariables.resetCounter(); beforeTransform(wrapLastExprWithProcessHtml, resolver); transformChildNodes(node, changes, state, tempVars); addTempVarsDeclaration(node, changes, state, tempVars); afterTransform(); return changes; } // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- /* eslint hammerhead/proto-methods: 2 */ // NOTE: taken from https://github.com/benjamingr/RegExp.escape function reEscape (str) { return str.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); } var SERVICE_ROUTES = { hammerhead: '/hammerhead.js', task: '/task.js', iframeTask: '/iframe-task.js', messaging: '/messaging', transportWorker: '/transport-worker.js', workerHammerhead: '/worker-hammerhead.js', }; // ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- // NOTE: We should store the methods of the `JSON` object // since they can be overridden by the client code. var parse$1 = JSON.parse; var stringify = JSON.stringify; function isDOMNode(obj) { if (typeof Node === 'object') return obj instanceof Node; return typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'; } function isJQueryObj(obj) { return !!(obj && obj.jquery); } function isSerializable(value) { if (value) { // NOTE: jquery object, DOM nodes and functions are disallowed obj types because we can't serialize them correctly if (typeof value === 'function' || isJQueryObj(value) || isDOMNode(value)) return false; if (typeof value === 'object') { for (var prop in value) { if (value.hasOwnProperty(prop) && !isSerializable(value[prop])) // eslint-disable-line no-prototype-builtins return false; } } } return true; } var json = /*#__PURE__*/Object.freeze({ __proto__: null, parse: parse$1, stringify: stringify, isSerializable: isSerializable }); // ------------------------------------------------------------- var SCRIPT_PROCESSING_START_COMMENT = '/*hammerhead|script|start*/'; var SCRIPT_PROCESSING_END_COMMENT = '/*hammerhead|script|end*/'; var SCRIPT_PROCESSING_END_HEADER_COMMENT = '/*hammerhead|script|processing-header-end*/'; var STRICT_MODE_PLACEHOLDER = '{strict-placeholder}'; var SW_SCOPE_HEADER_VALUE = '{sw-scope-header-value}'; var WORKER_SETTINGS_PLACEHOLDER = '{worker-settings}'; var IMPORT_WORKER_HAMMERHEAD = "\nif (typeof importScripts !== \"undefined\" && /\\[native code]/g.test(importScripts.toString())) {\n var ".concat(SCRIPT_PROCESSING_INSTRUCTIONS.getWorkerSettings, " = function () {return ").concat(WORKER_SETTINGS_PLACEHOLDER, "};\n importScripts((location.origin || (location.protocol + \"//\" + location.host)) + \"").concat(SERVICE_ROUTES.workerHammerhead, "\");\n}\n"); var PROCESS_DOM_METHOD = "window['".concat(INTERNAL_PROPS.processDomMethodName, "'] && window['").concat(INTERNAL_PROPS.processDomMethodName, "']();"); function trim(val) { return val.replace(/\n(?!$)\s*/g, ''); } var PROXYLESS_HEADER = trim("\n ".concat(SCRIPT_PROCESSING_START_COMMENT, "\n ").concat(STRICT_MODE_PLACEHOLDER, "\n\n if (typeof window !== 'undefined' && window) {\n ").concat(PROCESS_DOM_METHOD, "\n }\n\n ").concat(SCRIPT_PROCESSING_END_HEADER_COMMENT, "\n")); var HEADER = trim("\n ".concat(SCRIPT_PROCESSING_START_COMMENT, "\n ").concat(STRICT_MODE_PLACEHOLDER, "\n ").concat(SW_SCOPE_HEADER_VALUE, "\n\n if (typeof window !== 'undefined' && window){\n ").concat(PROCESS_DOM_METHOD, "\n\n if (window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, " && typeof ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, " === 'undefined')\n var ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getLocation, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getLocation, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setLocation, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setLocation, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setProperty, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setProperty, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.callMethod, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.callMethod, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getEval, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getEval, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processScript, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processScript, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processHtml, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processHtml, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProxyUrl, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProxyUrl, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restArray, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restArray, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restObject, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restObject, ",\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.arrayFrom, " = window.").concat(SCRIPT_PROCESSING_INSTRUCTIONS.arrayFrom, ";\n } else {\n if (typeof ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, " === 'undefined')\n var ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getLocation, " = function(l){return l},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setLocation, " = function(l,v){return l = v},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.setProperty, " = function(o,p,v){return o[p] = v},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProperty, " = function(o,p){return o[p]},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.callMethod, " = function(o,p,a){return o[p].apply(o,a)},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getEval, " = function(e){return e},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processScript, " = function(s){return s},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.processHtml, " = function(h){return h},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getPostMessage, " = function(w,p){return arguments.length===1?w.postMessage:p},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.getProxyUrl, " = function(u,d){return u},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restArray, " = function(a,i){return Array.prototype.slice.call(a, i)},\n ").concat(SCRIPT_PROCESSING_INSTRUCTIONS.restObject, " = function(o,p){var k=Object.keys(o),n={};for(var i=0;i0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by bin/generate-identifier-regex.js // eslint-disable-next-line comma-spacing var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; // eslint-disable-next-line comma-spacing var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 0x10000; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) return code === 36; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes); } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } }); var tokentype = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.types = exports.keywords = exports.TokenType = void 0; // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType = /** @class */ (function () { function TokenType(label, conf) { if (conf === void 0) { conf = {}; } this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; } return TokenType; }()); exports.TokenType = TokenType; function binop(name, prec) { return new TokenType(name, { beforeExpr: true, binop: prec }); } var beforeExpr = { beforeExpr: true }, startsExpr = { startsExpr: true }; // Map keyword names to token types. var keywords = {}; // Succinct definitions of keyword token types exports.keywords = keywords; function kw(name, options) { if (options === void 0) { options = {}; } options.keyword = name; return keywords[name] = new TokenType(name, options); } var types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), privateId: new TokenType("privateId", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), bracketR: new TokenType("]"), braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), braceR: new TokenType("}"), parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), questionDot: new TokenType("?."), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", { beforeExpr: true, isAssign: true }), assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("/<=/>=", 7), bitShift: binop("<>/>>>", 8), plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", { beforeExpr: true }), coalesce: binop("??", 1), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", { isLoop: true, beforeExpr: true }), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", { isLoop: true }), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", { isLoop: true }), _with: kw("with"), _new: kw("new", { beforeExpr: true, startsExpr: true }), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import", startsExpr), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", { beforeExpr: true, binop: 7 }), _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }), _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }), _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }), _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }) }; exports.types = types; }); var whitespace = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.isNewLine = isNewLine; exports.lineBreakG = exports.lineBreak = void 0; exports.nextLineBreak = nextLineBreak; exports.skipWhiteSpace = exports.nonASCIIwhitespace = void 0; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; exports.lineBreak = lineBreak; var lineBreakG = new RegExp(lineBreak.source, "g"); exports.lineBreakG = lineBreakG; function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; } function nextLineBreak(code, from, end) { if (end === void 0) { end = code.length; } for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine(next)) return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1; } return -1; } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; exports.nonASCIIwhitespace = nonASCIIwhitespace; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; exports.skipWhiteSpace = skipWhiteSpace; }); var util = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.loneSurrogate = exports.isArray = exports.hasOwn = void 0; exports.wordsRegexp = wordsRegexp; var _Object$prototype = Object.prototype, hasOwnProperty = _Object$prototype.hasOwnProperty, toString = _Object$prototype.toString; var hasOwn = Object.hasOwn || (function (obj, propName) { return hasOwnProperty.call(obj, propName); }); exports.hasOwn = hasOwn; var isArray = Array.isArray || (function (obj) { return toString.call(obj) === "[object Array]"; }); exports.isArray = isArray; function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"); } var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; exports.loneSurrogate = loneSurrogate; }); var locutil = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.SourceLocation = exports.Position = void 0; exports.getLineInfo = getLineInfo; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = /** @class */ (function () { function Position(line, col) { this.line = line; this.column = col; } Position.prototype.offset = function (n) { return new Position(this.line, this.column + n); }; return Position; }()); exports.Position = Position; var SourceLocation = /** @class */ (function () { function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) this.source = p.sourceFile; } return SourceLocation; }()); // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. exports.SourceLocation = SourceLocation; function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = (0, whitespace.nextLineBreak)(input, cur, offset); if (nextBreak < 0) return new Position(line, offset - cur); ++line; cur = nextBreak; } } }); var options = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.defaultOptions = void 0; exports.getOptions = getOptions; // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the // latest version the library supports). This influences support // for strict mode, the set of reserved words, and support for // new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object exports.defaultOptions = defaultOptions; var warnedAboutEcmaVersion = false; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) options[opt] = opts && (0, util.hasOwn)(opts, opt) ? opts[opt] : defaultOptions[opt]; if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { warnedAboutEcmaVersion = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5; if ((0, util.isArray)(options.onToken)) { var tokens_1 = options.onToken; options.onToken = function (token) { return tokens_1.push(token); }; } if ((0, util.isArray)(options.onComment)) options.onComment = pushComment(options, options.onComment); return options; } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) comment.loc = new locutil.SourceLocation(this, startLoc, endLoc); if (options.ranges) comment.range = [start, end]; array.push(comment); }; } }); var scopeflags = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.SCOPE_VAR = exports.SCOPE_TOP = exports.SCOPE_SUPER = exports.SCOPE_SIMPLE_CATCH = exports.SCOPE_GENERATOR = exports.SCOPE_FUNCTION = exports.SCOPE_DIRECT_SUPER = exports.SCOPE_CLASS_STATIC_BLOCK = exports.SCOPE_ASYNC = exports.SCOPE_ARROW = exports.BIND_VAR = exports.BIND_SIMPLE_CATCH = exports.BIND_OUTSIDE = exports.BIND_NONE = exports.BIND_LEXICAL = exports.BIND_FUNCTION = void 0; exports.functionFlags = functionFlags; // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; exports.SCOPE_VAR = SCOPE_VAR; exports.SCOPE_CLASS_STATIC_BLOCK = SCOPE_CLASS_STATIC_BLOCK; exports.SCOPE_DIRECT_SUPER = SCOPE_DIRECT_SUPER; exports.SCOPE_SUPER = SCOPE_SUPER; exports.SCOPE_SIMPLE_CATCH = SCOPE_SIMPLE_CATCH; exports.SCOPE_ARROW = SCOPE_ARROW; exports.SCOPE_GENERATOR = SCOPE_GENERATOR; exports.SCOPE_ASYNC = SCOPE_ASYNC; exports.SCOPE_FUNCTION = SCOPE_FUNCTION; exports.SCOPE_TOP = SCOPE_TOP; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0); } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE = 0, // Not a binding BIND_VAR = 1, // Var-style binding BIND_LEXICAL = 2, // Let- or const-style binding BIND_FUNCTION = 3, // Function declaration BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE = 5; // Special case for function names as bound inside the function exports.BIND_OUTSIDE = BIND_OUTSIDE; exports.BIND_SIMPLE_CATCH = BIND_SIMPLE_CATCH; exports.BIND_FUNCTION = BIND_FUNCTION; exports.BIND_LEXICAL = BIND_LEXICAL; exports.BIND_VAR = BIND_VAR; exports.BIND_NONE = BIND_NONE; }); var state = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.Parser = void 0; var Parser = /** @class */ (function () { function Parser(options$1, input, startPos) { this.options = options$1 = (0, options.getOptions)(options$1); this.sourceFile = options$1.sourceFile; this.keywords = (0, util.wordsRegexp)(identifier.keywords[options$1.ecmaVersion >= 6 ? 6 : options$1.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options$1.allowReserved !== true) { reserved = identifier.reservedWords[options$1.ecmaVersion >= 6 ? 6 : options$1.ecmaVersion === 5 ? 5 : 3]; if (options$1.sourceType === "module") reserved += " await"; } this.reservedWords = (0, util.wordsRegexp)(reserved); var reservedStrict = (reserved ? reserved + " " : "") + identifier.reservedWords.strict; this.reservedWordsStrict = (0, util.wordsRegexp)(reservedStrict); this.reservedWordsStrictBind = (0, util.wordsRegexp)(reservedStrict + " " + identifier.reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(whitespace.lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = tokentype.types.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options$1.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options$1.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2); // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(scopeflags.SCOPE_TOP); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; } Parser.prototype.parse = function () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node); }; Object.defineProperty(Parser.prototype, "inFunction", { get: function () { return (this.currentVarScope().flags & scopeflags.SCOPE_FUNCTION) > 0; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "inGenerator", { get: function () { return (this.currentVarScope().flags & scopeflags.SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "inAsync", { get: function () { return (this.currentVarScope().flags & scopeflags.SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "canAwait", { get: function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & scopeflags.SCOPE_CLASS_STATIC_BLOCK) return false; if (scope.flags & scopeflags.SCOPE_FUNCTION) return (scope.flags & scopeflags.SCOPE_ASYNC) > 0; } return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "allowSuper", { get: function () { var _this$currentThisScop = this.currentThisScope(), flags = _this$currentThisScop.flags, inClassFieldInit = _this$currentThisScop.inClassFieldInit; return (flags & scopeflags.SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "allowDirectSuper", { get: function () { return (this.currentThisScope().flags & scopeflags.SCOPE_DIRECT_SUPER) > 0; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "treatFunctionsAsVar", { get: function () { return this.treatFunctionsAsVarInScope(this.currentScope()); }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "allowNewDotTarget", { get: function () { var _this$currentThisScop2 = this.currentThisScope(), flags = _this$currentThisScop2.flags, inClassFieldInit = _this$currentThisScop2.inClassFieldInit; return (flags & (scopeflags.SCOPE_FUNCTION | scopeflags.SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit; }, enumerable: false, configurable: true }); Object.defineProperty(Parser.prototype, "inClassStaticBlock", { get: function () { return (this.currentVarScope().flags & scopeflags.SCOPE_CLASS_STATIC_BLOCK) > 0; }, enumerable: false, configurable: true }); Parser.extend = function () { var plugins = []; for (var _i = 0; _i < arguments.length; _i++) { plugins[_i] = arguments[_i]; } var cls = this; for (var i = 0; i < plugins.length; i++) cls = plugins[i](cls); return cls; }; Parser.parse = function (input, options) { return new this(options, input).parse(); }; Parser.parseExpressionAt = function (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression(); }; Parser.tokenizer = function (input, options) { return new this(options, input); }; return Parser; }()); exports.Parser = Parser; }); var DestructuringErrors_1 = DestructuringErrors; var pp$5 = state.Parser.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$5.strictDirective = function (start) { for (;;) { // Try to find string literal. whitespace.skipWhiteSpace.lastIndex = start; start += whitespace.skipWhiteSpace.exec(this.input)[0].length; var match = literal.exec(this.input.slice(start)); if (!match) return false; if ((match[1] || match[2]) === "use strict") return false; start += match[0].length; // Skip semicolon, if any. whitespace.skipWhiteSpace.lastIndex = start; start += whitespace.skipWhiteSpace.exec(this.input)[0].length; if (this.input[start] === ";") start++; } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$5.eat = function (type) { if (this.type === type) { this.next(); return true; } else { return false; } }; // Tests whether parsed token is a contextual keyword. pp$5.isContextual = function (name) { return this.type === tokentype.types.name && this.value === name && !this.containsEsc; }; // Consumes contextual keyword if possible. pp$5.eatContextual = function (name) { if (!this.isContextual(name)) return false; this.next(); return true; }; // Asserts that following token is given contextual keyword. pp$5.expectContextual = function (name) { if (!this.eatContextual(name)) this.unexpected(); }; // Test whether a semicolon can be inserted at the current position. pp$5.canInsertSemicolon = function () { return this.type === tokentype.types.eof || this.type === tokentype.types.braceR || whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); }; pp$5.insertSemicolon = function () { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); return true; } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$5.semicolon = function () { if (!this.eat(tokentype.types.semi) && !this.insertSemicolon()) this.unexpected(); }; pp$5.afterTrailingComma = function (tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); if (!notNext) this.next(); return true; } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$5.expect = function (type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$5.unexpected = function (pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; } pp$5.checkPatternErrors = function (refDestructuringErrors, isAssign) { if (!refDestructuringErrors) return; if (refDestructuringErrors.trailingComma > -1) this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) this.raiseRecoverable(parens, "Parenthesized pattern"); }; pp$5.checkExpressionErrors = function (refDestructuringErrors, andThrow) { if (!refDestructuringErrors) return false; var shorthandAssign = refDestructuringErrors.shorthandAssign, doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0; if (shorthandAssign >= 0) this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); if (doubleProto >= 0) this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }; pp$5.checkYieldAwaitInDefaultParams = function () { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) this.raise(this.yieldPos, "Yield expression cannot be a default value"); if (this.awaitPos) this.raise(this.awaitPos, "Await expression cannot be a default value"); }; pp$5.isSimpleAssignTarget = function (expr) { if (expr.type === "ParenthesizedExpression") return this.isSimpleAssignTarget(expr.expression); return expr.type === "Identifier" || expr.type === "MemberExpression"; }; var parseutil = /*#__PURE__*/Object.defineProperty({ DestructuringErrors: DestructuringErrors_1 }, '__esModule', {value: true}); function _createForOfIteratorHelperLoose$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); } function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var pp$4 = state.Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$4.parseTopLevel = function (node) { var exports = Object.create(null); if (!node.body) node.body = []; while (this.type !== tokentype.types.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) for (var _i = 0, _Object$keys = Object.keys(this.undefinedExports); _i < _Object$keys.length; _i++) { var name_1 = _Object$keys[_i]; this.raiseRecoverable(this.undefinedExports[name_1].start, "Export '".concat(name_1, "' is not defined")); } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program"); }; var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; pp$4.isLet = function (context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) return false; whitespace.skipWhiteSpace.lastIndex = this.pos; var skip = whitespace.skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a // Statement) is allowed here. If context is not empty then only a Statement // is allowed. However, `let [` is an explicit negative lookahead for // ExpressionStatement, so special-case it first. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) return true; // '[', '/', astral if (context) return false; if (nextCh === 123) return true; // '{' if ((0, identifier.isIdentifierStart)(nextCh, true)) { var pos = next + 1; while ((0, identifier.isIdentifierChar)(nextCh = this.input.charCodeAt(pos), true)) ++pos; if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) return true; var ident = this.input.slice(next, pos); if (!identifier.keywordRelationalOperator.test(ident)) return true; } return false; }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$4.isAsyncFunction = function () { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) return false; whitespace.skipWhiteSpace.lastIndex = this.pos; var skip = whitespace.skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, after; return !whitespace.lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !((0, identifier.isIdentifierChar)(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)); }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$4.parseStatement = function (context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = tokentype.types._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case tokentype.types._break: case tokentype.types._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case tokentype.types._debugger: return this.parseDebuggerStatement(node); case tokentype.types._do: return this.parseDoStatement(node); case tokentype.types._for: return this.parseForStatement(node); case tokentype.types._function: // Function as sole body of either an if statement or a labeled statement // works, but not when it is part of a labeled statement that is the sole // body of an if statement. if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) this.unexpected(); return this.parseFunctionStatement(node, false, !context); case tokentype.types._class: if (context) this.unexpected(); return this.parseClass(node, true); case tokentype.types._if: return this.parseIfStatement(node); case tokentype.types._return: return this.parseReturnStatement(node); case tokentype.types._switch: return this.parseSwitchStatement(node); case tokentype.types._throw: return this.parseThrowStatement(node); case tokentype.types._try: return this.parseTryStatement(node); case tokentype.types._const: case tokentype.types._var: kind = kind || this.value; if (context && kind !== "var") this.unexpected(); return this.parseVarStatement(node, kind); case tokentype.types._while: return this.parseWhileStatement(node); case tokentype.types._with: return this.parseWithStatement(node); case tokentype.types.braceL: return this.parseBlock(true, node); case tokentype.types.semi: return this.parseEmptyStatement(node); case tokentype.types._export: case tokentype.types._import: if (this.options.ecmaVersion > 10 && starttype === tokentype.types._import) { whitespace.skipWhiteSpace.lastIndex = this.pos; var skip = whitespace.skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' return this.parseExpressionStatement(node, this.parseExpression()); } if (!this.options.allowImportExportEverywhere) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level"); if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } return starttype === tokentype.types._import ? this.parseImport(node) : this.parseExport(node, exports); // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) this.unexpected(); this.next(); return this.parseFunctionStatement(node, true, !context); } var maybeName = this.value, expr = this.parseExpression(); if (starttype === tokentype.types.name && expr.type === "Identifier" && this.eat(tokentype.types.colon)) return this.parseLabeledStatement(node, maybeName, expr, context); else return this.parseExpressionStatement(node, expr); } }; pp$4.parseBreakContinueStatement = function (node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(tokentype.types.semi) || this.insertSemicolon()) node.label = null; else if (this.type !== tokentype.types.name) this.unexpected(); else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break; } } if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword); return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); }; pp$4.parseDebuggerStatement = function (node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); }; pp$4.parseDoStatement = function (node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(tokentype.types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) this.eat(tokentype.types.semi); else this.semicolon(); return this.finishNode(node, "DoWhileStatement"); }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$4.parseForStatement = function (node) { this.next(); var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(tokentype.types.parenL); if (this.type === tokentype.types.semi) { if (awaitAt > -1) this.unexpected(awaitAt); return this.parseFor(node, null); } var isLet = this.isLet(); if (this.type === tokentype.types._var || this.type === tokentype.types._const || isLet) { var init_1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init_1, true, kind); this.finishNode(init_1, "VariableDeclaration"); if ((this.type === tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init_1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === tokentype.types._in) { if (awaitAt > -1) this.unexpected(awaitAt); } else node.await = awaitAt > -1; } return this.parseForIn(node, init_1); } if (awaitAt > -1) this.unexpected(awaitAt); return this.parseFor(node, init_1); } var startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new parseutil.DestructuringErrors(); var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === tokentype.types._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === tokentype.types._in) { if (awaitAt > -1) this.unexpected(awaitAt); } else node.await = awaitAt > -1; } if (startsWithLet && isForOf) this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init); } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) this.unexpected(awaitAt); return this.parseFor(node, init); }; pp$4.parseFunctionStatement = function (node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync); }; pp$4.parseIfStatement = function (node) { this.next(); node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode node.consequent = this.parseStatement("if"); node.alternate = this.eat(tokentype.types._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement"); }; pp$4.parseReturnStatement = function (node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function"); this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(tokentype.types.semi) || this.insertSemicolon()) node.argument = null; else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement"); }; pp$4.parseSwitchStatement = function (node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(tokentype.types.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== tokentype.types.braceR;) { if (this.type === tokentype.types._case || this.type === tokentype.types._default) { var isCase = this.type === tokentype.types._case; if (cur) this.finishNode(cur, "SwitchCase"); node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); sawDefault = true; cur.test = null; } this.expect(tokentype.types.colon); } else { if (!cur) this.unexpected(); cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) this.finishNode(cur, "SwitchCase"); this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement"); }; pp$4.parseThrowStatement = function (node) { this.next(); if (whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw"); node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); }; // Reused empty array added for node fields that are always empty. var empty$1 = []; pp$4.parseTryStatement = function (node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === tokentype.types._catch) { var clause = this.startNode(); this.next(); if (this.eat(tokentype.types.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? scopeflags.SCOPE_SIMPLE_CATCH : 0); this.checkLValPattern(clause.param, simple ? scopeflags.BIND_SIMPLE_CATCH : scopeflags.BIND_LEXICAL); this.expect(tokentype.types.parenR); } else { if (this.options.ecmaVersion < 10) this.unexpected(); clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(tokentype.types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause"); return this.finishNode(node, "TryStatement"); }; pp$4.parseVarStatement = function (node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration"); }; pp$4.parseWhileStatement = function (node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement"); }; pp$4.parseWithStatement = function (node) { if (this.strict) this.raise(this.start, "'with' in strict mode"); this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement"); }; pp$4.parseEmptyStatement = function (node) { this.next(); return this.finishNode(node, "EmptyStatement"); }; pp$4.parseLabeledStatement = function (node, maybeName, expr, context) { for (var _iterator = _createForOfIteratorHelperLoose$2(this.labels), _step; !(_step = _iterator()).done;) { var label = _step.value; if (label.name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } var kind = this.type.isLoop ? "loop" : this.type === tokentype.types._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label = this.labels[i]; if (label.statementStart === node.start) { // Update information about previous labels on this node label.statementStart = this.start; label.kind = kind; } else break; } this.labels.push({ name: maybeName, kind: kind, statementStart: this.start }); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement"); }; pp$4.parseExpressionStatement = function (node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$4.parseBlock = function (createNewLexicalScope, node, exitStrict) { if (createNewLexicalScope === void 0) { createNewLexicalScope = true; } if (node === void 0) { node = this.startNode(); } node.body = []; this.expect(tokentype.types.braceL); if (createNewLexicalScope) this.enterScope(0); while (this.type !== tokentype.types.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) this.strict = false; this.next(); if (createNewLexicalScope) this.exitScope(); return this.finishNode(node, "BlockStatement"); }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$4.parseFor = function (node, init) { node.init = init; this.expect(tokentype.types.semi); node.test = this.type === tokentype.types.semi ? null : this.parseExpression(); this.expect(tokentype.types.semi); node.update = this.type === tokentype.types.parenR ? null : this.parseExpression(); this.expect(tokentype.types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement"); }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$4.parseForIn = function (node, init) { var isForIn = this.type === tokentype.types._in; this.next(); if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { this.raise(init.start, "".concat(isForIn ? "for-in" : "for-of", " loop variable declaration may not have an initializer")); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(tokentype.types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); }; // Parse a list of variable declarations. pp$4.parseVar = function (node, isFor, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(tokentype.types.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === "const" && !(this.type === tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { this.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === tokentype.types._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(tokentype.types.comma)) break; } return node; }; pp$4.parseVarId = function (decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? scopeflags.BIND_VAR : scopeflags.BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$4.parseFunction = function (node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === tokentype.types.star && statement & FUNC_HANGING_STATEMENT) this.unexpected(); node.generator = this.eat(tokentype.types.star); } if (this.options.ecmaVersion >= 8) node.async = !!isAsync; if (statement & FUNC_STATEMENT) { node.id = statement & FUNC_NULLABLE_ID && this.type !== tokentype.types.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? scopeflags.BIND_VAR : scopeflags.BIND_LEXICAL : scopeflags.BIND_FUNCTION); } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope((0, scopeflags.functionFlags)(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) node.id = this.type === tokentype.types.name ? this.parseIdent() : null; this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression"); }; pp$4.parseFunctionParams = function (node) { this.expect(tokentype.types.parenL); node.params = this.parseBindingList(tokentype.types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$4.parseClass = function (node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(tokentype.types.braceL); while (this.type !== tokentype.types.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) this.raise(element.start, "Duplicate constructor in the same class"); hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { this.raiseRecoverable(element.key.start, "Identifier '#".concat(element.key.name, "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); }; pp$4.parseClassElement = function (constructorAllowsSuper) { if (this.eat(tokentype.types.semi)) return null; var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(tokentype.types.braceL)) { this.parseClassStaticBlock(node); return node; } if (this.isClassElementNameStart() || this.type === tokentype.types.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === tokentype.types.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(tokentype.types.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === tokentype.types.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") this.raise(node.key.start, "Constructor can't have get/set modifier"); node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node; }; pp$4.isClassElementNameStart = function () { return this.type === tokentype.types.name || this.type === tokentype.types.privateId || this.type === tokentype.types.num || this.type === tokentype.types.string || this.type === tokentype.types.bracketL || this.type.keyword; }; pp$4.parseClassElementName = function (element) { if (this.type === tokentype.types.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$4.parseClassMethod = function (method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { if (isGenerator) this.raise(key.start, "Constructor can't be a generator"); if (isAsync) this.raise(key.start, "Constructor can't be an async method"); } else if (method.static && checkKeyName(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) this.raiseRecoverable(value.start, "getter should have no params"); if (method.kind === "set" && value.params.length !== 1) this.raiseRecoverable(value.start, "setter should have exactly one param"); if (method.kind === "set" && value.params[0].type === "RestElement") this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); return this.finishNode(method, "MethodDefinition"); }; pp$4.parseClassField = function (field) { if (checkKeyName(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(tokentype.types.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition"); }; pp$4.parseClassStaticBlock = function (node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(scopeflags.SCOPE_CLASS_STATIC_BLOCK | scopeflags.SCOPE_SUPER); while (this.type !== tokentype.types.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock"); }; pp$4.parseClassId = function (node, isStatement) { if (this.type === tokentype.types.name) { node.id = this.parseIdent(); if (isStatement) this.checkLValSimple(node.id, scopeflags.BIND_LEXICAL, false); } else { if (isStatement === true) this.unexpected(); node.id = null; } }; pp$4.parseClassSuper = function (node) { node.superClass = this.eat(tokentype.types._extends) ? this.parseExprSubscripts(false) : null; }; pp$4.enterClassBody = function () { var element = { declared: Object.create(null), used: [] }; this.privateNameStack.push(element); return element.declared; }; pp$4.exitClassBody = function () { var _this$privateNameStac = this.privateNameStack.pop(), declared = _this$privateNameStac.declared, used = _this$privateNameStac.used; var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!(0, util.hasOwn)(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, "Private field '#".concat(id.name, "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") { privateNameMap[name] = "true"; return false; } else if (!curr) { privateNameMap[name] = next; return false; } else { return true; } } function checkKeyName(node, name) { var computed = node.computed, key = node.key; return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name); } // Parses module export declaration. pp$4.parseExport = function (node, exports) { this.next(); // export * from '...' if (this.eat(tokentype.types.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported.name, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== tokentype.types.string) this.unexpected(); node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration"); } if (this.eat(tokentype.types._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync = void 0; if (this.type === tokentype.types._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) this.next(); node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === tokentype.types._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration"); } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") this.checkVariableExport(exports, node.declaration.declarations); else this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== tokentype.types.string) this.unexpected(); node.source = this.parseExprAtom(); } else { for (var _iterator2 = _createForOfIteratorHelperLoose$2(node.specifiers), _step2; !(_step2 = _iterator2()).done;) { var spec = _step2.value; // check for keywords used as local names this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration"); }; pp$4.checkExport = function (exports, name, pos) { if (!exports) return; if ((0, util.hasOwn)(exports, name)) this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); exports[name] = true; }; pp$4.checkPatternExport = function (exports, pat) { var type = pat.type; if (type === "Identifier") this.checkExport(exports, pat.name, pat.start); else if (type === "ObjectPattern") { for (var _iterator3 = _createForOfIteratorHelperLoose$2(pat.properties), _step3; !(_step3 = _iterator3()).done;) { var prop = _step3.value; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var _iterator4 = _createForOfIteratorHelperLoose$2(pat.elements), _step4; !(_step4 = _iterator4()).done;) { var elt = _step4.value; if (elt) this.checkPatternExport(exports, elt); } } else if (type === "Property") this.checkPatternExport(exports, pat.value); else if (type === "AssignmentPattern") this.checkPatternExport(exports, pat.left); else if (type === "RestElement") this.checkPatternExport(exports, pat.argument); else if (type === "ParenthesizedExpression") this.checkPatternExport(exports, pat.expression); }; pp$4.checkVariableExport = function (exports, decls) { if (!exports) return; for (var _iterator5 = _createForOfIteratorHelperLoose$2(decls), _step5; !(_step5 = _iterator5()).done;) { var decl = _step5.value; this.checkPatternExport(exports, decl.id); } }; pp$4.shouldParseExportStatement = function () { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction(); }; // Parses a comma-separated list of module exports. pp$4.parseExportSpecifiers = function (exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(tokentype.types.braceL); while (!this.eat(tokentype.types.braceR)) { if (!first) { this.expect(tokentype.types.comma); if (this.afterTrailingComma(tokentype.types.braceR)) break; } else first = false; var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport(exports, node.exported[node.exported.type === "Identifier" ? "name" : "value"], node.exported.start); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes; }; // Parses import declaration. pp$4.parseImport = function (node) { this.next(); // import '...' if (this.type === tokentype.types.string) { node.specifiers = empty$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === tokentype.types.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); }; // Parses a comma-separated list of module imports. pp$4.parseImportSpecifiers = function () { var nodes = [], first = true; if (this.type === tokentype.types.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, scopeflags.BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(tokentype.types.comma)) return nodes; } if (this.type === tokentype.types.star) { var node = this.startNode(); this.next(); this.expectContextual("as"); node.local = this.parseIdent(); this.checkLValSimple(node.local, scopeflags.BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportNamespaceSpecifier")); return nodes; } this.expect(tokentype.types.braceL); while (!this.eat(tokentype.types.braceR)) { if (!first) { this.expect(tokentype.types.comma); if (this.afterTrailingComma(tokentype.types.braceR)) break; } else first = false; var node = this.startNode(); node.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node.local = this.parseIdent(); } else { this.checkUnreserved(node.imported); node.local = node.imported; } this.checkLValSimple(node.local, scopeflags.BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportSpecifier")); } return nodes; }; pp$4.parseModuleExportName = function () { if (this.options.ecmaVersion >= 13 && this.type === tokentype.types.string) { var stringLiteral = this.parseLiteral(this.value); if (util.loneSurrogate.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral; } return this.parseIdent(true); }; // Set `ExpressionStatement#directive` property for directive prologues. pp$4.adaptDirectivePrologue = function (statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$4.isDirectiveCandidate = function (statement) { return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && ( // Reject parenthesized strings. this.input[statement.start] === "\"" || this.input[statement.start] === "'"); }; function _createForOfIteratorHelperLoose$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var pp$3 = state.Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$3.toAssignable = function (node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); break; case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break; case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true); for (var _iterator = _createForOfIteratorHelperLoose$1(node.properties), _step; !(_step = _iterator()).done;) { var prop = _step.value; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) { this.raise(prop.argument.start, "Unexpected token"); } } break; case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") this.raise(node.key.start, "Object pattern can't contain getter or setter"); this.toAssignable(node.value, isBinding); break; case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true); this.toAssignableList(node.elements, isBinding); break; case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") this.raise(node.argument.start, "Rest elements cannot have a default value"); break; case "AssignmentExpression": if (node.operator !== "=") this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break; case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break; case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break; case "MemberExpression": if (!isBinding) break; default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true); return node; }; // Convert list of expression atoms to binding list. pp$3.toAssignableList = function (exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) this.toAssignable(elt, isBinding); } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start); } return exprList; }; // Parses spread element. pp$3.parseSpread = function (refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement"); }; pp$3.parseRestBinding = function () { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== tokentype.types.name) this.unexpected(); node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement"); }; // Parses lvalue (assignable) atom. pp$3.parseBindingAtom = function () { if (this.options.ecmaVersion >= 6) { switch (this.type) { case tokentype.types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(tokentype.types.bracketR, true, true); return this.finishNode(node, "ArrayPattern"); case tokentype.types.braceL: return this.parseObj(true); } } return this.parseIdent(); }; pp$3.parseBindingList = function (close, allowEmpty, allowTrailingComma) { var elts = [], first = true; while (!this.eat(close)) { if (first) first = false; else this.expect(tokentype.types.comma); if (allowEmpty && this.type === tokentype.types.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break; } else if (this.type === tokentype.types.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === tokentype.types.comma) this.raise(this.start, "Comma is not permitted after the rest element"); this.expect(close); break; } else { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); elts.push(elem); } } return elts; }; pp$3.parseBindingListItem = function (param) { return param; }; // Parses assignment pattern around given atom if possible. pp$3.parseMaybeDefault = function (startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(tokentype.types.eq)) return left; var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern"); }; // The following three functions all verify that a node is an lvalue — // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += …; // import a from '…'; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = …); // const a = …; // try { … } catch (a) { … } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$3.checkLValSimple = function (expr, bindingType, checkClashes) { if (bindingType === void 0) { bindingType = scopeflags.BIND_NONE; } var isBind = bindingType !== scopeflags.BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); if (isBind) { if (bindingType === scopeflags.BIND_LEXICAL && expr.name === "let") this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); if (checkClashes) { if ((0, util.hasOwn)(checkClashes, expr.name)) this.raiseRecoverable(expr.start, "Argument name clash"); checkClashes[expr.name] = true; } if (bindingType !== scopeflags.BIND_OUTSIDE) this.declareName(expr.name, bindingType, expr.start); } break; case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break; case "MemberExpression": if (isBind) this.raiseRecoverable(expr.start, "Binding member expression"); break; case "ParenthesizedExpression": if (isBind) this.raiseRecoverable(expr.start, "Binding parenthesized expression"); return this.checkLValSimple(expr.expression, bindingType, checkClashes); default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$3.checkLValPattern = function (expr, bindingType, checkClashes) { if (bindingType === void 0) { bindingType = scopeflags.BIND_NONE; } switch (expr.type) { case "ObjectPattern": for (var _iterator2 = _createForOfIteratorHelperLoose$1(expr.properties), _step2; !(_step2 = _iterator2()).done;) { var prop = _step2.value; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break; case "ArrayPattern": for (var _iterator3 = _createForOfIteratorHelperLoose$1(expr.elements), _step3; !(_step3 = _iterator3()).done;) { var elem = _step3.value; if (elem) this.checkLValInnerPattern(elem, bindingType, checkClashes); } break; default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$3.checkLValInnerPattern = function (expr, bindingType, checkClashes) { if (bindingType === void 0) { bindingType = scopeflags.BIND_NONE; } switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break; case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break; case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break; default: this.checkLValPattern(expr, bindingType, checkClashes); } }; var tokencontext = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.types = exports.TokContext = void 0; // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design var TokContext = /** @class */ (function () { function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; } return TokContext; }()); exports.TokContext = TokContext; var types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; exports.types = types; var pp = state.Parser.prototype; pp.initialContext = function () { return [types.b_stat]; }; pp.curContext = function () { return this.context[this.context.length - 1]; }; pp.braceIsBlock = function (prevType) { var parent = this.curContext(); if (parent === types.f_expr || parent === types.f_stat) return true; if (prevType === tokentype.types.colon && (parent === types.b_stat || parent === types.b_expr)) return !parent.isExpr; // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === tokentype.types._return || prevType === tokentype.types.name && this.exprAllowed) return whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); if (prevType === tokentype.types._else || prevType === tokentype.types.semi || prevType === tokentype.types.eof || prevType === tokentype.types.parenR || prevType === tokentype.types.arrow) return true; if (prevType === tokentype.types.braceL) return parent === types.b_stat; if (prevType === tokentype.types._var || prevType === tokentype.types._const || prevType === tokentype.types.name) return false; return !this.exprAllowed; }; pp.inGeneratorContext = function () { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") return context.generator; } return false; }; pp.updateContext = function (prevType) { var update, type = this.type; if (type.keyword && prevType === tokentype.types.dot) this.exprAllowed = false; else if (update = type.updateContext) update.call(this, prevType); else this.exprAllowed = type.beforeExpr; }; // Used to handle egde case when token context could not be inferred correctly in tokenize phase pp.overrideContext = function (tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code tokentype.types.parenR.updateContext = tokentype.types.braceR.updateContext = function () { if (this.context.length === 1) { this.exprAllowed = true; return; } var out = this.context.pop(); if (out === types.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; tokentype.types.braceL.updateContext = function (prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true; }; tokentype.types.dollarBraceL.updateContext = function () { this.context.push(types.b_tmpl); this.exprAllowed = true; }; tokentype.types.parenL.updateContext = function (prevType) { var statementParens = prevType === tokentype.types._if || prevType === tokentype.types._for || prevType === tokentype.types._with || prevType === tokentype.types._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true; }; tokentype.types.incDec.updateContext = function () { }; tokentype.types._function.updateContext = tokentype.types._class.updateContext = function (prevType) { if (prevType.beforeExpr && prevType !== tokentype.types._else && !(prevType === tokentype.types.semi && this.curContext() !== types.p_stat) && !(prevType === tokentype.types._return && whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === tokentype.types.colon || prevType === tokentype.types.braceL) && this.curContext() === types.b_stat)) this.context.push(types.f_expr); else this.context.push(types.f_stat); this.exprAllowed = false; }; tokentype.types.backQuote.updateContext = function () { if (this.curContext() === types.q_tmpl) this.context.pop(); else this.context.push(types.q_tmpl); this.exprAllowed = false; }; tokentype.types.star.updateContext = function (prevType) { if (prevType === tokentype.types._function) { var index = this.context.length - 1; if (this.context[index] === types.f_expr) this.context[index] = types.f_expr_gen; else this.context[index] = types.f_gen; } this.exprAllowed = true; }; tokentype.types.name.updateContext = function (prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== tokentype.types.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) allowed = true; } this.exprAllowed = allowed; }; }); function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var pp$2 = state.Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$2.checkPropClash = function (prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") return; if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return; var key = prop.key, name; switch (key.type) { case "Identifier": name = key.name; break; case "Literal": name = String(key.value); break; default: return; } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return; } name = "$" + name; var other = propHash[name]; if (other) { var redefinition = void 0; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) this.raiseRecoverable(key.start, "Redefinition of property"); } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$2.parseExpression = function (forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === tokentype.types.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); return this.finishNode(node, "SequenceExpression"); } return expr; }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$2.parseMaybeAssign = function (forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) return this.parseYield(forInit); // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else this.exprAllowed = false; } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new parseutil.DestructuringErrors(); ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === tokentype.types.parenL || this.type === tokentype.types.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === tokentype.types.eq) left = this.toAssignable(left, false, refDestructuringErrors); if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly if (this.type === tokentype.types.eq) this.checkLValPattern(left); else this.checkLValSimple(left); node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) refDestructuringErrors.doubleProto = oldDoubleProto; return this.finishNode(node, "AssignmentExpression"); } else { if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true); } if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign; if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma; return left; }; // Parse a ternary conditional (`?:`) operator. pp$2.parseMaybeConditional = function (forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; if (this.eat(tokentype.types.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(tokentype.types.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression"); } return expr; }; // Start the precedence parser. pp$2.parseExprOps = function (forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit); }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$2.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== tokentype.types._in)) { if (prec > minPrec) { var logical = this.type === tokentype.types.logicalOR || this.type === tokentype.types.logicalAND; var coalesce = this.type === tokentype.types.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = tokentype.types.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if (logical && this.type === tokentype.types.coalesce || coalesce && (this.type === tokentype.types.logicalOR || this.type === tokentype.types.logicalAND)) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit); } } return left; }; pp$2.buildBinary = function (startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") this.raise(right.start, "Private identifier can only be left side of binary expression"); var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression"); }; // Parse unary operators, both prefix and postfix. pp$2.parseMaybeUnary = function (refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === tokentype.types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) this.checkLValSimple(node.argument); else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) this.raiseRecoverable(node.start, "Private fields can not be deleted"); else sawUnary = true; expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === tokentype.types.privateId) { if (forInit || this.privateNameStack.length === 0) this.unexpected(); expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== tokentype.types._in) this.unexpected(); } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; while (this.type.postfix && !this.canInsertSemicolon()) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.prefix = false; node.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node, "UpdateExpression"); } } if (!incDec && this.eat(tokentype.types.starstar)) { if (sawUnary) this.unexpected(this.lastTokStart); else return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false); } else { return expr; } }; function isPrivateFieldAccess(node) { return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression); } // Parse call, dot, and `[]`-subscript expressions. pp$2.parseExprSubscripts = function (refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") return expr; var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1; if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1; if (refDestructuringErrors.trailingComma >= result.start) refDestructuringErrors.trailingComma = -1; } return result; }; pp$2.parseSubscripts = function (base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) optionalChained = true; if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element; } base = element; } }; pp$2.parseSubscript = function (base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(tokentype.types.questionDot); if (noCalls && optional) this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); var computed = this.eat(tokentype.types.bracketL); if (computed || optional && this.type !== tokentype.types.parenL && this.type !== tokentype.types.backQuote || this.eat(tokentype.types.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(tokentype.types.bracketR); } else if (this.type === tokentype.types.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(tokentype.types.parenL)) { var refDestructuringErrors = new parseutil.DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(tokentype.types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(tokentype.types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node = this.startNodeAt(startPos, startLoc); node.callee = base; node.arguments = exprList; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "CallExpression"); } else if (this.type === tokentype.types.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node = this.startNodeAt(startPos, startLoc); node.tag = base; node.quasi = this.parseTemplate({ isTagged: true }); base = this.finishNode(node, "TaggedTemplateExpression"); } return base; }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$2.parseExprAtom = function (refDestructuringErrors, forInit) { // If a division operator appears in an expression position, the // tokenizer got confused, and we force it to read a regexp instead. if (this.type === tokentype.types.slash) this.readRegexp(); var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case tokentype.types._super: if (!this.allowSuper) this.raise(this.start, "'super' keyword outside a method"); node = this.startNode(); this.next(); if (this.type === tokentype.types.parenL && !this.allowDirectSuper) this.raise(node.start, "super() call outside constructor of a subclass"); // The `super` keyword can appear at below: // SuperProperty: // super [ Expression ] // super . IdentifierName // SuperCall: // super ( Arguments ) if (this.type !== tokentype.types.dot && this.type !== tokentype.types.bracketL && this.type !== tokentype.types.parenL) this.unexpected(); return this.finishNode(node, "Super"); case tokentype.types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression"); case tokentype.types.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(tokentype.types._function)) { this.overrideContext(tokencontext.types.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit); } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(tokentype.types.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit); if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tokentype.types.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(tokentype.types.arrow)) this.unexpected(); return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit); } } return id; case tokentype.types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = { pattern: value.pattern, flags: value.flags }; return node; case tokentype.types.num: case tokentype.types.string: return this.parseLiteral(this.value); case tokentype.types._null: case tokentype.types._true: case tokentype.types._false: node = this.startNode(); node.value = this.type === tokentype.types._null ? null : this.type === tokentype.types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal"); case tokentype.types.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) refDestructuringErrors.parenthesizedAssign = start; if (refDestructuringErrors.parenthesizedBind < 0) refDestructuringErrors.parenthesizedBind = start; } return expr; case tokentype.types.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(tokentype.types.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression"); case tokentype.types.braceL: this.overrideContext(tokencontext.types.b_expr); return this.parseObj(false, refDestructuringErrors); case tokentype.types._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0); case tokentype.types._class: return this.parseClass(this.startNode(), false); case tokentype.types._new: return this.parseNew(); case tokentype.types.backQuote: return this.parseTemplate(); case tokentype.types._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport(); } else { return this.unexpected(); } default: this.unexpected(); } }; pp$2.parseExprImport = function () { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword import"); var meta = this.parseIdent(true); switch (this.type) { case tokentype.types.parenL: return this.parseDynamicImport(node); case tokentype.types.dot: node.meta = meta; return this.parseImportMeta(node); default: this.unexpected(); } }; pp$2.parseDynamicImport = function (node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(tokentype.types.parenR)) { var errorPos = this.start; if (this.eat(tokentype.types.comma) && this.eat(tokentype.types.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression"); }; pp$2.parseImportMeta = function (node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); if (containsEsc) this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); return this.finishNode(node, "MetaProperty"); }; pp$2.parseLiteral = function (value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); this.next(); return this.finishNode(node, "Literal"); }; pp$2.parseParenExpression = function () { this.expect(tokentype.types.parenL); var val = this.parseExpression(); this.expect(tokentype.types.parenR); return val; }; pp$2.parseParenAndDistinguishExpression = function (canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new parseutil.DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart = void 0; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== tokentype.types.parenR) { first ? first = false : this.expect(tokentype.types.comma); if (allowTrailingComma && this.afterTrailingComma(tokentype.types.parenR, true)) { lastIsComma = true; break; } else if (this.type === tokentype.types.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === tokentype.types.comma) this.raise(this.start, "Comma is not permitted after the rest element"); break; } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(tokentype.types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(tokentype.types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit); } if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart); if (spreadStart) this.unexpected(spreadStart); this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression"); } else { return val; } }; pp$2.parseParenItem = function (item) { return item; }; pp$2.parseParenArrowList = function (startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit); }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty = []; pp$2.parseNew = function () { if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword new"); var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(tokentype.types.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); if (containsEsc) this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); if (!this.allowNewDotTarget) this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); return this.finishNode(node, "MetaProperty"); } var startPos = this.start, startLoc = this.startLoc, isImport = this.type === tokentype.types._import; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); if (isImport && node.callee.type === "ImportExpression") { this.raise(startPos, "Cannot use new with import()"); } if (this.eat(tokentype.types.parenL)) node.arguments = this.parseExprList(tokentype.types.parenR, this.options.ecmaVersion >= 8, false); else node.arguments = empty; return this.finishNode(node, "NewExpression"); }; // Parse template expression. pp$2.parseTemplateElement = function (_a) { var isTagged = _a.isTagged; var elem = this.startNode(); if (this.type === tokentype.types.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value, cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === tokentype.types.backQuote; return this.finishNode(elem, "TemplateElement"); }; pp$2.parseTemplate = function (_a) { var _b = _a === void 0 ? {} : _a, _c = _b.isTagged, isTagged = _c === void 0 ? false : _c; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({ isTagged: isTagged }); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === tokentype.types.eof) this.raise(this.pos, "Unterminated template literal"); this.expect(tokentype.types.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(tokentype.types.braceR); node.quasis.push(curElt = this.parseTemplateElement({ isTagged: isTagged })); } this.next(); return this.finishNode(node, "TemplateLiteral"); }; pp$2.isAsyncProp = function (prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === tokentype.types.name || this.type === tokentype.types.num || this.type === tokentype.types.string || this.type === tokentype.types.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === tokentype.types.star) && !whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); }; // Parse an object literal or binding pattern. pp$2.parseObj = function (isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(tokentype.types.braceR)) { if (!first) { this.expect(tokentype.types.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(tokentype.types.braceR)) break; } else first = false; var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) this.checkPropClash(prop, propHash, refDestructuringErrors); node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); }; pp$2.parseProperty = function (isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(tokentype.types.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === tokentype.types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement"); } // To disallow parenthesized identifier via `this.toAssignable()`. if (this.type === tokentype.types.parenL && refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0) { refDestructuringErrors.parenthesizedAssign = this.start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = this.start; } } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === tokentype.types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } // Finish return this.finishNode(prop, "SpreadElement"); } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) isGenerator = this.eat(tokentype.types.star); } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(tokentype.types.star); this.parsePropertyName(prop, refDestructuringErrors); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property"); }; pp$2.parsePropertyValue = function (prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === tokentype.types.colon) this.unexpected(); if (this.eat(tokentype.types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === tokentype.types.parenL) { if (isPattern) this.unexpected(); prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type !== tokentype.types.comma && this.type !== tokentype.types.braceR && this.type !== tokentype.types.eq) { if (isGenerator || isAsync) this.unexpected(); prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") this.raiseRecoverable(start, "getter should have no params"); else this.raiseRecoverable(start, "setter should have exactly one param"); } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) this.unexpected(); this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) this.awaitIdentPos = startPos; prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === tokentype.types.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) refDestructuringErrors.shorthandAssign = this.start; prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else this.unexpected(); }; pp$2.parsePropertyName = function (prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(tokentype.types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(tokentype.types.bracketR); return prop.key; } else { prop.computed = false; } } return prop.key = this.type === tokentype.types.num || this.type === tokentype.types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); }; // Initialize empty function node. pp$2.initFunction = function (node) { node.id = null; if (this.options.ecmaVersion >= 6) node.generator = node.expression = false; if (this.options.ecmaVersion >= 8) node.async = false; }; // Parse object or class method. pp$2.parseMethod = function (isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) node.generator = isGenerator; if (this.options.ecmaVersion >= 8) node.async = !!isAsync; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope((0, scopeflags.functionFlags)(isAsync, node.generator) | scopeflags.SCOPE_SUPER | (allowDirectSuper ? scopeflags.SCOPE_DIRECT_SUPER : 0)); this.expect(tokentype.types.parenL); node.params = this.parseBindingList(tokentype.types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression"); }; // Parse arrow function expression with given parameters. pp$2.parseArrowExpression = function (node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope((0, scopeflags.functionFlags)(isAsync, false) | scopeflags.SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) node.async = !!isAsync; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression"); }; // Parse function body and check parameters. pp$2.parseFunctionBody = function (node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== tokentype.types.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) this.strict = true; // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) this.checkLValSimple(node.id, scopeflags.BIND_OUTSIDE); node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$2.isSimpleParamList = function (params) { for (var _iterator = _createForOfIteratorHelperLoose(params), _step; !(_step = _iterator()).done;) { var param = _step.value; if (param.type !== "Identifier") return false; } return true; }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$2.checkParams = function (node, allowDuplicates) { var nameHash = Object.create(null); for (var _iterator2 = _createForOfIteratorHelperLoose(node.params), _step2; !(_step2 = _iterator2()).done;) { var param = _step2.value; this.checkLValInnerPattern(param, scopeflags.BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$2.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(tokentype.types.comma); if (allowTrailingComma && this.afterTrailingComma(close)) break; } else first = false; var elt = void 0; if (allowEmpty && this.type === tokentype.types.comma) elt = null; else if (this.type === tokentype.types.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === tokentype.types.comma && refDestructuringErrors.trailingComma < 0) refDestructuringErrors.trailingComma = this.start; } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts; }; pp$2.checkUnreserved = function (_a) { var start = _a.start, end = _a.end, name = _a.name; if (this.inGenerator && name === "yield") this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); if (this.inAsync && name === "await") this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); if (this.currentThisScope().inClassFieldInit && name === "arguments") this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); if (this.inClassStaticBlock && (name === "arguments" || name === "await")) this.raise(start, "Cannot use ".concat(name, " in class static initialization block")); if (this.keywords.test(name)) this.raise(start, "Unexpected keyword '".concat(name, "'")); if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) return; var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); this.raiseRecoverable(start, "The keyword '".concat(name, "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$2.parseIdent = function (liberal, isBinding) { var node = this.startNode(); if (this.type === tokentype.types.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) this.awaitIdentPos = node.start; } return node; }; pp$2.parsePrivateIdent = function () { var node = this.startNode(); if (this.type === tokentype.types.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.privateNameStack.length === 0) { this.raise(node.start, "Private field '#".concat(node.name, "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } return node; }; // Parses yield expression inside generator. pp$2.parseYield = function (forInit) { if (!this.yieldPos) this.yieldPos = this.start; var node = this.startNode(); this.next(); if (this.type === tokentype.types.semi || this.canInsertSemicolon() || this.type !== tokentype.types.star && !this.type.startsExpr) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(tokentype.types.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression"); }; pp$2.parseAwait = function (forInit) { if (!this.awaitPos) this.awaitPos = this.start; var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression"); }; var pp$1 = state.Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$1.raise = function (pos, message) { var loc = (0, locutil.getLineInfo)(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err; }; pp$1.raiseRecoverable = pp$1.raise; pp$1.curPosition = function () { if (this.options.locations) { return new locutil.Position(this.curLine, this.pos - this.lineStart); } }; var pp = state.Parser.prototype; var Scope = /** @class */ (function () { function Scope(flags) { this.flags = flags; // A list of var-declared names in the current lexical scope this.var = []; // A list of lexically-declared names in the current lexical scope this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope this.functions = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; } return Scope; }()); // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp.enterScope = function (flags) { this.scopeStack.push(new Scope(flags)); }; pp.exitScope = function () { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp.treatFunctionsAsVarInScope = function (scope) { return scope.flags & scopeflags.SCOPE_FUNCTION || !this.inModule && scope.flags & scopeflags.SCOPE_TOP; }; pp.declareName = function (name, bindingType, pos) { var redeclared = false; if (bindingType === scopeflags.BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && scope.flags & scopeflags.SCOPE_TOP) delete this.undefinedExports[name]; } else if (bindingType === scopeflags.BIND_SIMPLE_CATCH) { var scope = this.currentScope(); scope.lexical.push(name); } else if (bindingType === scopeflags.BIND_FUNCTION) { var scope = this.currentScope(); if (this.treatFunctionsAsVar) redeclared = scope.lexical.indexOf(name) > -1; else redeclared = scope.lexical.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope = this.scopeStack[i]; if (scope.lexical.indexOf(name) > -1 && !(scope.flags & scopeflags.SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1) { redeclared = true; break; } scope.var.push(name); if (this.inModule && scope.flags & scopeflags.SCOPE_TOP) delete this.undefinedExports[name]; if (scope.flags & scopeflags.SCOPE_VAR) break; } } if (redeclared) this.raiseRecoverable(pos, "Identifier '".concat(name, "' has already been declared")); }; pp.checkLocalExport = function (id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp.currentScope = function () { return this.scopeStack[this.scopeStack.length - 1]; }; pp.currentVarScope = function () { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & scopeflags.SCOPE_VAR) return scope; } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp.currentThisScope = function () { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & scopeflags.SCOPE_VAR && !(scope.flags & scopeflags.SCOPE_ARROW)) return scope; } }; var node = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.Node = void 0; var Node = /** @class */ (function () { function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) this.loc = new locutil.SourceLocation(parser, loc); if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile; if (parser.options.ranges) this.range = [pos, 0]; } return Node; }()); // Start an AST node, attaching a start offset. exports.Node = Node; var pp = state.Parser.prototype; pp.startNode = function () { return new Node(this, this.start, this.startLoc); }; pp.startNodeAt = function (pos, loc) { return new Node(this, pos, loc); }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) node.loc.end = loc; if (this.options.ranges) node.range[1] = pos; return node; } pp.finishNode = function (node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc); }; // Finish node at given position pp.finishNodeAt = function (node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc); }; pp.copyNode = function (node) { var newNode = new Node(this, node.start, this.startLoc); for (var prop in node) newNode[prop] = node[prop]; return newNode; }; }); var unicodePropertyData = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.default = void 0; // This file contains Unicode properties extracted from the ECMAScript // specification. The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; var ecma11BinaryProperties = ecma10BinaryProperties; var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties = ecma12BinaryProperties; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma10BinaryProperties, 11: ecma11BinaryProperties, 12: ecma12BinaryProperties, 13: ecma13BinaryProperties }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma10ScriptValues, 11: ecma11ScriptValues, 12: ecma12ScriptValues, 13: ecma13ScriptValues }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: (0, util.wordsRegexp)(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), nonBinary: { General_Category: (0, util.wordsRegexp)(unicodeGeneralCategoryValues), Script: (0, util.wordsRegexp)(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var _i = 0, _arr = [9, 10, 11, 12, 13]; _i < _arr.length; _i++) { var ecmaVersion = _arr[_i]; buildUnicodeData(ecmaVersion); } var _default = data; exports.default = _default; module.exports = exports["default"]; }); var regexp = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.RegExpValidationState = void 0; var _unicodePropertyData = _interopRequireDefault(unicodePropertyData); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } var pp = state.Parser.prototype; var RegExpValidationState = /** @class */ (function () { function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim".concat(parser.options.ecmaVersion >= 6 ? "uy" : "").concat(parser.options.ecmaVersion >= 9 ? "s" : "").concat(parser.options.ecmaVersion >= 13 ? "d" : ""); this.unicodeProperties = _unicodePropertyData.default[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; } RegExpValidationState.prototype.reset = function (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState.prototype.raise = function (message) { this.parser.raiseRecoverable(this.start, "Invalid regular expression: /".concat(this.source, "/: ").concat(message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function (i, forceU) { if (forceU === void 0) { forceU = false; } var s = this.source; var l = s.length; if (i >= l) { return -1; } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c; } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c; }; RegExpValidationState.prototype.nextIndex = function (i, forceU) { if (forceU === void 0) { forceU = false; } var s = this.source; var l = s.length; if (i >= l) { return l; } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1; } return i + 2; }; RegExpValidationState.prototype.current = function (forceU) { if (forceU === void 0) { forceU = false; } return this.at(this.pos, forceU); }; RegExpValidationState.prototype.lookahead = function (forceU) { if (forceU === void 0) { forceU = false; } return this.at(this.nextIndex(this.pos, forceU), forceU); }; RegExpValidationState.prototype.advance = function (forceU) { if (forceU === void 0) { forceU = false; } this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState.prototype.eat = function (ch, forceU) { if (forceU === void 0) { forceU = false; } if (this.current(forceU) === ch) { this.advance(forceU); return true; } return false; }; return RegExpValidationState; }()); exports.RegExpValidationState = RegExpValidationState; function codePointToString(ch) { if (ch <= 0xFFFF) return String.fromCharCode(ch); ch -= 0x10000; return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00); } /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp.validateRegExpFlags = function (state) { var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp.validateRegExpPattern = function (state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp.regexp_pattern = function (state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */ )) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */ ) || state.eat(0x7D /* } */ )) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var _iterator = _createForOfIteratorHelperLoose(state.backReferenceNames), _step; !(_step = _iterator()).done;) { var name_1 = _step.value; if (state.groupNames.indexOf(name_1) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp.regexp_disjunction = function (state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */ )) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */ )) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp.regexp_alternative = function (state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) ; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp.regexp_eatTerm = function (state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true; } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp.regexp_eatAssertion = function (state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */ ) || state.eat(0x24 /* $ */ )) { return true; } // \b \B if (state.eat(0x5C /* \ */ )) { if (state.eat(0x42 /* B */ ) || state.eat(0x62 /* b */ )) { return true; } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */ ) && state.eat(0x3F /* ? */ )) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */ ); } if (state.eat(0x3D /* = */ ) || state.eat(0x21 /* ! */ )) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */ )) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true; } } state.pos = start; return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp.regexp_eatQuantifier = function (state, noError) { if (noError === void 0) { noError = false; } if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */ ); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp.regexp_eatQuantifierPrefix = function (state, noError) { return state.eat(0x2A /* * */ ) || state.eat(0x2B /* + */ ) || state.eat(0x3F /* ? */ ) || this.regexp_eatBracedQuantifier(state, noError); }; pp.regexp_eatBracedQuantifier = function (state, noError) { var start = state.pos; if (state.eat(0x7B /* { */ )) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */ ) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */ )) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true; } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp.regexp_eatAtom = function (state) { return this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */ ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state); }; pp.regexp_eatReverseSolidusAtomEscape = function (state) { var start = state.pos; if (state.eat(0x5C /* \ */ )) { if (this.regexp_eatAtomEscape(state)) { return true; } state.pos = start; } return false; }; pp.regexp_eatUncapturingGroup = function (state) { var start = state.pos; if (state.eat(0x28 /* ( */ )) { if (state.eat(0x3F /* ? */ ) && state.eat(0x3A /* : */ )) { this.regexp_disjunction(state); if (state.eat(0x29 /* ) */ )) { return true; } state.raise("Unterminated group"); } state.pos = start; } return false; }; pp.regexp_eatCapturingGroup = function (state) { if (state.eat(0x28 /* ( */ )) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */ ) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */ )) { state.numCapturingParens += 1; return true; } state.raise("Unterminated group"); } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp.regexp_eatExtendedAtom = function (state) { return state.eat(0x2E /* . */ ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state); }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp.regexp_eatInvalidBracedQuantifier = function (state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp.regexp_eatSyntaxCharacter = function (state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true; } return false; }; function isSyntaxCharacter(ch) { return ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D; } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp.regexp_eatPatternCharacters = function (state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp.regexp_eatExtendedPatternCharacter = function (state) { var ch = state.current(); if (ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true; } return false; }; // GroupSpecifier :: // [empty] // `?` GroupName pp.regexp_groupSpecifier = function (state) { if (state.eat(0x3F /* ? */ )) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return; } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp.regexp_eatGroupName = function (state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */ )) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */ )) { return true; } state.raise("Invalid capture group name"); } return false; }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp.regexp_eatRegExpIdentifierName = function (state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); } return true; } return false; }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp.regexp_eatRegExpIdentifierStart = function (state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true; } state.pos = start; return false; }; function isRegExpIdentifierStart(ch) { return (0, identifier.isIdentifierStart)(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F; /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // // pp.regexp_eatRegExpIdentifierPart = function (state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true; } state.pos = start; return false; }; function isRegExpIdentifierPart(ch) { return (0, identifier.isIdentifierChar)(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D; /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp.regexp_eatAtomEscape = function (state) { if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) { return true; } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */ ) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false; }; pp.regexp_eatBackReference = function (state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true; } if (n <= state.numCapturingParens) { return true; } state.pos = start; } return false; }; pp.regexp_eatKGroupName = function (state) { if (state.eat(0x6B /* k */ )) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true; } state.raise("Invalid named reference"); } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp.regexp_eatCharacterEscape = function (state) { return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state); }; pp.regexp_eatCControlLetter = function (state) { var start = state.pos; if (state.eat(0x63 /* c */ )) { if (this.regexp_eatControlLetter(state)) { return true; } state.pos = start; } return false; }; pp.regexp_eatZero = function (state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp.regexp_eatControlEscape = function (state) { var ch = state.current(); if (ch === 0x74 /* t */ ) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true; } if (ch === 0x6E /* n */ ) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true; } if (ch === 0x76 /* v */ ) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true; } if (ch === 0x66 /* f */ ) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true; } if (ch === 0x72 /* r */ ) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp.regexp_eatControlLetter = function (state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true; } return false; }; function isControlLetter(ch) { return ch >= 0x41 /* A */ && ch <= 0x5A /* Z */ || ch >= 0x61 /* a */ && ch <= 0x7A; } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp.regexp_eatRegExpUnicodeEscapeSequence = function (state, forceU) { if (forceU === void 0) { forceU = false; } var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */ )) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */ ) && state.eat(0x75 /* u */ ) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true; } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true; } if (switchU && state.eat(0x7B /* { */ ) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */ ) && isValidUnicode(state.lastIntValue)) { return true; } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false; }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF; } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp.regexp_eatIdentityEscape = function (state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true; } if (state.eat(0x2F /* / */ )) { state.lastIntValue = 0x2F; /* / */ return true; } return false; } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */ )) { state.lastIntValue = ch; state.advance(); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp.regexp_eatDecimalEscape = function (state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */ ) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */ ); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ ); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp.regexp_eatCharacterClassEscape = function (state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true; } if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */ )) { state.lastIntValue = -1; state.advance(); if (state.eat(0x7B /* { */ ) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */ )) { return true; } state.raise("Invalid property name"); } return false; }; function isCharacterClassEscape(ch) { return ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57; } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp.regexp_eatUnicodePropertyValueExpression = function (state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */ )) { var name_2 = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name_2, value); return true; } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true; } return false; }; pp.regexp_validateUnicodePropertyNameAndValue = function (state, name, value) { if (!(0, util.hasOwn)(state.unicodeProperties.nonBinary, name)) state.raise("Invalid property name"); if (!state.unicodeProperties.nonBinary[name].test(value)) state.raise("Invalid property value"); }; pp.regexp_validateUnicodePropertyNameOrValue = function (state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) state.raise("Invalid property name"); }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp.regexp_eatUnicodePropertyName = function (state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== ""; }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F; /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp.regexp_eatUnicodePropertyValue = function (state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== ""; }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch); } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp.regexp_eatLoneUnicodePropertyNameOrValue = function (state) { return this.regexp_eatUnicodePropertyValue(state); }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp.regexp_eatCharacterClass = function (state) { if (state.eat(0x5B /* [ */ )) { state.eat(0x5E /* ^ */ ); this.regexp_classRanges(state); if (state.eat(0x5D /* ] */ )) { return true; } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp.regexp_classRanges = function (state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */ ) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp.regexp_eatClassAtom = function (state) { var start = state.pos; if (state.eat(0x5C /* \ */ )) { if (this.regexp_eatClassEscape(state)) { return true; } if (state.switchU) { // Make the same message as V8. var ch_1 = state.current(); if (ch_1 === 0x63 /* c */ || isOctalDigit(ch_1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */ ) { state.lastIntValue = ch; state.advance(); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp.regexp_eatClassEscape = function (state) { var start = state.pos; if (state.eat(0x62 /* b */ )) { state.lastIntValue = 0x08; /* */ return true; } if (state.switchU && state.eat(0x2D /* - */ )) { state.lastIntValue = 0x2D; /* - */ return true; } if (!state.switchU && state.eat(0x63 /* c */ )) { if (this.regexp_eatClassControlLetter(state)) { return true; } state.pos = start; } return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state); }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp.regexp_eatClassControlLetter = function (state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F /* _ */ ) { state.lastIntValue = ch % 0x20; state.advance(); return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp.regexp_eatHexEscapeSequence = function (state) { var start = state.pos; if (state.eat(0x78 /* x */ )) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true; } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp.regexp_eatDecimalDigits = function (state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */ ); state.advance(); } return state.pos !== start; }; function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39; /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp.regexp_eatHexDigits = function (state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start; }; function isHexDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ || ch >= 0x41 /* A */ && ch <= 0x46 /* F */ || ch >= 0x61 /* a */ && ch <= 0x66; } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */ ) { return 10 + (ch - 0x41 /* A */ ); } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */ ) { return 10 + (ch - 0x61 /* a */ ); } return ch - 0x30; /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp.regexp_eatLegacyOctalEscapeSequence = function (state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true; } return false; }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp.regexp_eatOctalDigit = function (state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true; } state.lastIntValue = 0; return false; }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37; /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp.regexp_eatFixedHexDigits = function (state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false; } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true; }; }); var tokenize = createCommonjsModule(function (module, exports) { exports.__esModule = true; exports.Token = void 0; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = /** @class */ (function () { function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) this.loc = new locutil.SourceLocation(p, p.startLoc, p.endLoc); if (p.options.ranges) this.range = [p.start, p.end]; } return Token; }()); // ## Tokenizer exports.Token = Token; var pp = state.Parser.prototype; // Move to the next token pp.next = function (ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); if (this.options.onToken) this.options.onToken(new Token(this)); this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function () { this.next(); return new Token(this); }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () { var _this = this; return { next: function () { var token = _this.getToken(); return { done: token.type === tokentype.types.eof, value: token }; } }; }; // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function () { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) this.skipSpace(); this.start = this.pos; if (this.options.locations) this.startLoc = this.curPosition(); if (this.pos >= this.input.length) return this.finishToken(tokentype.types.eof); if (curContext.override) return curContext.override(this); else this.readToken(this.fullCharCodeAtPos()); }; pp.readToken = function (code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if ((0, identifier.isIdentifierStart)(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */ ) return this.readWord(); return this.getTokenFromCode(code); }; pp.fullCharCodeAtPos = function () { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) return code; var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00; }; pp.skipBlockComment = function () { var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) this.raise(this.pos - 2, "Unterminated comment"); this.pos = end + 2; if (this.options.locations) { for (var nextBreak = void 0, pos = start; (nextBreak = (0, whitespace.nextLineBreak)(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); }; pp.skipLineComment = function (startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !(0, whitespace.isNewLine)(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function () { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32: case 160: // ' ' ++this.pos; break; case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break; case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break; case 47: this.skipLineComment(2); break; default: break loop; } break; default: if (ch > 8 && ch < 14 || ch >= 5760 && whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop; } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function (type, val) { this.end = this.pos; if (this.options.locations) this.endLoc = this.curPosition(); var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function () { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) return this.readNumber(true); var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(tokentype.types.ellipsis); } else { ++this.pos; return this.finishToken(tokentype.types.dot); } }; pp.readToken_slash = function () { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp(); } if (next === 61) return this.finishOp(tokentype.types.assign, 2); return this.finishOp(tokentype.types.slash, 1); }; pp.readToken_mult_modulo_exp = function (code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype$1 = code === 42 ? tokentype.types.star : tokentype.types.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype$1 = tokentype.types.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) return this.finishOp(tokentype.types.assign, size + 1); return this.finishOp(tokentype$1, size); }; pp.readToken_pipe_amp = function (code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) return this.finishOp(tokentype.types.assign, 3); } return this.finishOp(code === 124 ? tokentype.types.logicalOR : tokentype.types.logicalAND, 2); } if (next === 61) return this.finishOp(tokentype.types.assign, 2); return this.finishOp(code === 124 ? tokentype.types.bitwiseOR : tokentype.types.bitwiseAND, 1); }; pp.readToken_caret = function () { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) return this.finishOp(tokentype.types.assign, 2); return this.finishOp(tokentype.types.bitwiseXOR, 1); }; pp.readToken_plus_min = function (code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken(); } return this.finishOp(tokentype.types.incDec, 2); } if (next === 61) return this.finishOp(tokentype.types.assign, 2); return this.finishOp(tokentype.types.plusMin, 1); }; pp.readToken_lt_gt = function (code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tokentype.types.assign, size + 1); return this.finishOp(tokentype.types.bitShift, size); } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `[^\n]*([\n\s]*)?$/; var HTML_COMMENT_PREFIX_REG_EX = /^(\s)*\s*$/; var JAVASCRIPT_PROTOCOL_REG_EX = /^\s*javascript\s*:/i; var EXECUTABLE_SCRIPT_TYPES_REG_EX = /^\s*(application\/(x-)?(ecma|java)script|text\/(javascript(1\.[0-5])?|((x-)?ecma|x-java|js|live)script)|module)\s*$/i; var SVG_XLINK_HREF_TAGS = [ 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'mpath', 'set', 'linearGradient', 'radialGradient', 'stop', 'a', 'altglyph', 'color-profile', 'cursor', 'feimage', 'filter', 'font-face-uri', 'glyphref', 'image', 'mpath', 'pattern', 'script', 'textpath', 'use', 'tref', ]; var INTEGRITY_ATTR_TAGS = ['script', 'link']; var IFRAME_FLAG_TAGS = ['a', 'form', 'area', 'input', 'button']; var PROCESSED_PRELOAD_LINK_CONTENT_TYPE = 'script'; var MODULE_PRELOAD_LINK_REL = 'modulepreload'; var ELEMENT_PROCESSED = 'hammerhead|element-processed'; var AUTOCOMPLETE_ATTRIBUTE_ABSENCE_MARKER = 'hammerhead|autocomplete-attribute-absence-marker'; var DomProcessor = /** @class */ (function () { function DomProcessor(adapter) { this.adapter = adapter; this.HTML_PROCESSING_REQUIRED_EVENT = 'hammerhead|event|html-processing-required'; this.SVG_XLINK_HREF_TAGS = SVG_XLINK_HREF_TAGS; this.AUTOCOMPLETE_ATTRIBUTE_ABSENCE_MARKER = AUTOCOMPLETE_ATTRIBUTE_ABSENCE_MARKER; this.PROCESSED_PRELOAD_LINK_CONTENT_TYPE = PROCESSED_PRELOAD_LINK_CONTENT_TYPE; this.MODULE_PRELOAD_LINK_REL = MODULE_PRELOAD_LINK_REL; this.forceProxySrcForImage = false; this.allowMultipleWindows = false; this.proxyless = false; this.EVENTS = this.adapter.EVENTS; this.elementProcessorPatterns = this._createProcessorPatterns(this.adapter); } DomProcessor.isTagWithTargetAttr = function (tagName) { return !!tagName && TARGET_ATTR_TAGS.target.indexOf(tagName) > -1; }; DomProcessor.isTagWithFormTargetAttr = function (tagName) { return !!tagName && TARGET_ATTR_TAGS.formtarget.indexOf(tagName) > -1; }; DomProcessor.isTagWithIntegrityAttr = function (tagName) { return !!tagName && INTEGRITY_ATTR_TAGS.indexOf(tagName) !== -1; }; DomProcessor.isIframeFlagTag = function (tagName) { return !!tagName && IFRAME_FLAG_TAGS.indexOf(tagName) !== -1; }; DomProcessor.isAddedAutocompleteAttr = function (attrName, storedAttrValue) { return attrName === 'autocomplete' && storedAttrValue === AUTOCOMPLETE_ATTRIBUTE_ABSENCE_MARKER; }; DomProcessor.processJsAttrValue = function (value, _a) { var isJsProtocol = _a.isJsProtocol, isEventAttr = _a.isEventAttr; if (isJsProtocol) value = value.replace(JAVASCRIPT_PROTOCOL_REG_EX, ''); value = processScript(value, false, isJsProtocol && !isEventAttr, void 0); if (isJsProtocol) value = 'javascript:' + value; // eslint-disable-line no-script-url return value; }; DomProcessor.getStoredAttrName = function (attr) { return attr + INTERNAL_ATTRIBUTES.storedAttrPostfix; }; DomProcessor.isJsProtocol = function (value) { return JAVASCRIPT_PROTOCOL_REG_EX.test(value); }; DomProcessor._isHtmlImportLink = function (tagName, relAttr) { return !!tagName && !!relAttr && tagName === 'link' && relAttr === 'import'; }; DomProcessor.isElementProcessed = function (el) { // @ts-ignore return el[ELEMENT_PROCESSED]; }; DomProcessor.setElementProcessed = function (el, processed) { // @ts-ignore el[ELEMENT_PROCESSED] = processed; }; DomProcessor.prototype._getRelAttribute = function (el) { return String(this.adapter.getAttr(el, 'rel')).toLowerCase(); }; DomProcessor.prototype._getAsAttribute = function (el) { return String(this.adapter.getAttr(el, 'as')).toLowerCase(); }; DomProcessor.prototype._createProcessorPatterns = function (adapter) { var _this = this; var selectors = { HAS_HREF_ATTR: function (el) { return _this.isUrlAttr(el, 'href'); }, HAS_SRC_ATTR: function (el) { return _this.isUrlAttr(el, 'src'); }, HAS_SRCSET_ATTR: function (el) { return _this.isUrlAttr(el, 'srcset'); }, HAS_ACTION_ATTR: function (el) { return _this.isUrlAttr(el, 'action'); }, HAS_FORMACTION_ATTR: function (el) { return _this.isUrlAttr(el, 'formaction'); }, HAS_FORMTARGET_ATTR: function (el) { return DomProcessor.isTagWithFormTargetAttr(adapter.getTagName(el)) && adapter.hasAttr(el, 'formtarget'); }, HAS_MANIFEST_ATTR: function (el) { return _this.isUrlAttr(el, 'manifest'); }, HAS_DATA_ATTR: function (el) { return _this.isUrlAttr(el, 'data'); }, HAS_SRCDOC_ATTR: function (el) { var tagName = _this.adapter.getTagName(el); return (tagName === 'iframe' || tagName === 'frame') && adapter.hasAttr(el, 'srcdoc'); }, HTTP_EQUIV_META: function (el) { var tagName = adapter.getTagName(el); return tagName === 'meta' && adapter.hasAttr(el, 'http-equiv'); }, ALL: function () { return true; }, IS_SCRIPT: function (el) { return adapter.getTagName(el) === 'script'; }, IS_LINK: function (el) { return adapter.getTagName(el) === 'link'; }, IS_INPUT: function (el) { return adapter.getTagName(el) === 'input'; }, IS_FILE_INPUT: function (el) { return adapter.getTagName(el) === 'input' && adapter.hasAttr(el, 'type') && adapter.getAttr(el, 'type').toLowerCase() === 'file'; }, IS_STYLE: function (el) { return adapter.getTagName(el) === 'style'; }, HAS_EVENT_HANDLER: function (el) { return adapter.hasEventHandler(el); }, IS_SANDBOXED_IFRAME: function (el) { var tagName = adapter.getTagName(el); return (tagName === 'iframe' || tagName === 'frame') && adapter.hasAttr(el, 'sandbox'); }, IS_SVG_ELEMENT_WITH_XLINK_HREF_ATTR: function (el) { return adapter.isSVGElement(el) && adapter.hasAttr(el, 'xlink:href') && SVG_XLINK_HREF_TAGS.indexOf(adapter.getTagName(el)) !== -1; }, IS_SVG_ELEMENT_WITH_XML_BASE_ATTR: function (el) { return adapter.isSVGElement(el) && adapter.hasAttr(el, 'xml:base'); }, }; return [ { selector: selectors.HAS_FORMTARGET_ATTR, targetAttr: 'formtarget', elementProcessors: [this._processTargetBlank], }, { selector: selectors.HAS_HREF_ATTR, urlAttr: 'href', targetAttr: 'target', elementProcessors: [this._processTargetBlank, this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_SRC_ATTR, urlAttr: 'src', targetAttr: 'target', elementProcessors: [this._processTargetBlank, this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_SRCSET_ATTR, urlAttr: 'srcset', targetAttr: 'target', elementProcessors: [this._processTargetBlank, this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_ACTION_ATTR, urlAttr: 'action', targetAttr: 'target', elementProcessors: [this._processTargetBlank, this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_FORMACTION_ATTR, urlAttr: 'formaction', targetAttr: 'formtarget', elementProcessors: [this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_MANIFEST_ATTR, urlAttr: 'manifest', elementProcessors: [this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_DATA_ATTR, urlAttr: 'data', elementProcessors: [this._processUrlAttrs, this._processUrlJsAttr], }, { selector: selectors.HAS_SRCDOC_ATTR, elementProcessors: [this._processSrcdocAttr], }, { selector: selectors.HTTP_EQUIV_META, urlAttr: 'content', elementProcessors: [this._processMetaElement], }, { selector: selectors.IS_SCRIPT, elementProcessors: [this._processScriptElement, this._processIntegrityAttr], }, { selector: selectors.ALL, elementProcessors: [this._processStyleAttr] }, { selector: selectors.IS_LINK, relAttr: 'rel', elementProcessors: [this._processIntegrityAttr, this._processRelPrefetch], }, { selector: selectors.IS_STYLE, elementProcessors: [this._processStylesheetElement] }, { selector: selectors.IS_INPUT, elementProcessors: [this._processAutoComplete] }, { selector: selectors.IS_FILE_INPUT, elementProcessors: [this._processRequired] }, { selector: selectors.HAS_EVENT_HANDLER, elementProcessors: [this._processEvtAttr] }, { selector: selectors.IS_SANDBOXED_IFRAME, elementProcessors: [this._processSandboxedIframe] }, { selector: selectors.IS_SVG_ELEMENT_WITH_XLINK_HREF_ATTR, urlAttr: 'xlink:href', elementProcessors: [this._processSVGXLinkHrefAttr, this._processUrlAttrs], }, { selector: selectors.IS_SVG_ELEMENT_WITH_XML_BASE_ATTR, urlAttr: 'xml:base', elementProcessors: [this._processUrlAttrs], }, ]; }; // API DomProcessor.prototype.processElement = function (el, urlReplacer) { if (DomProcessor.isElementProcessed(el)) return; for (var _i = 0, _a = this.elementProcessorPatterns; _i < _a.length; _i++) { var pattern = _a[_i]; if (pattern.selector(el) && !this._isShadowElement(el)) { for (var _b = 0, _c = pattern.elementProcessors; _b < _c.length; _b++) { var processor = _c[_b]; processor.call(this, el, urlReplacer, pattern); } DomProcessor.setElementProcessed(el, true); } } }; // Utils DomProcessor.prototype.getElementResourceType = function (el) { var tagName = this.adapter.getTagName(el); if (tagName === 'link' && (this._getAsAttribute(el) === PROCESSED_PRELOAD_LINK_CONTENT_TYPE || this._getRelAttribute(el) === MODULE_PRELOAD_LINK_REL)) return getResourceTypeString({ isScript: true }); return getResourceTypeString({ isIframe: tagName === 'iframe' || tagName === 'frame' || this._isOpenLinkInIframe(el), isForm: tagName === 'form' || tagName === 'input' || tagName === 'button', isScript: tagName === 'script', isHtmlImport: tagName === 'link' && this._getRelAttribute(el) === 'import', isObject: tagName === 'object', }); }; DomProcessor.prototype.isUrlAttr = function (el, attr, ns) { var tagName = this.adapter.getTagName(el); attr = attr ? attr.toLowerCase() : attr; // @ts-ignore if (URL_ATTR_TAGS[attr] && URL_ATTR_TAGS[attr].indexOf(tagName) !== -1) return true; return this.adapter.isSVGElement(el) && (attr === 'xml:base' || attr === 'base' && ns === XML_NAMESPACE); }; DomProcessor.prototype.getUrlAttr = function (el) { var tagName = this.adapter.getTagName(el); for (var _i = 0, URL_ATTRS_1 = URL_ATTRS; _i < URL_ATTRS_1.length; _i++) { var urlAttr = URL_ATTRS_1[_i]; // @ts-ignore if (URL_ATTR_TAGS[urlAttr].indexOf(tagName) !== -1) return urlAttr; } return null; }; DomProcessor.prototype.getTargetAttr = function (el) { var tagName = this.adapter.getTagName(el); for (var _i = 0, TARGET_ATTRS_1 = TARGET_ATTRS; _i < TARGET_ATTRS_1.length; _i++) { var targetAttr = TARGET_ATTRS_1[_i]; // @ts-ignore if (TARGET_ATTR_TAGS[targetAttr].indexOf(tagName) > -1) return targetAttr; } return null; }; DomProcessor.prototype._isOpenLinkInIframe = function (el) { var tagName = this.adapter.getTagName(el); var targetAttr = this.getTargetAttr(el); var target = targetAttr ? this.adapter.getAttr(el, targetAttr) : null; var rel = this._getRelAttribute(el); if (target !== '_top') { var isImageInput = tagName === 'input' && this.adapter.getAttr(el, 'type') === 'image'; var mustProcessTag = !isImageInput && DomProcessor.isIframeFlagTag(tagName) || DomProcessor._isHtmlImportLink(tagName, rel); var isNameTarget = target ? target[0] !== '_' : false; if (target === '_parent') return mustProcessTag && !this.adapter.isTopParentIframe(el); if (mustProcessTag && (this.adapter.hasIframeParent(el) || isNameTarget && this.adapter.isExistingTarget(target, el))) return true; } return false; }; DomProcessor.prototype._isShadowElement = function (el) { var className = this.adapter.getClassName(el); return typeof className === 'string' && className.indexOf(SHADOW_UI_CLASS_NAME.postfix) > -1; }; // Element processors DomProcessor.prototype._processAutoComplete = function (el) { var storedUrlAttr = DomProcessor.getStoredAttrName('autocomplete'); var processed = this.adapter.hasAttr(el, storedUrlAttr); var attrValue = this.adapter.getAttr(el, processed ? storedUrlAttr : 'autocomplete'); if (!processed) { this.adapter.setAttr(el, storedUrlAttr, attrValue || attrValue === '' ? attrValue : AUTOCOMPLETE_ATTRIBUTE_ABSENCE_MARKER); } this.adapter.setAttr(el, 'autocomplete', 'off'); }; DomProcessor.prototype._processRequired = function (el) { var storedRequired = DomProcessor.getStoredAttrName('required'); var processed = this.adapter.hasAttr(el, storedRequired); if (!processed && this.adapter.hasAttr(el, 'required')) { var attrValue = this.adapter.getAttr(el, 'required'); this.adapter.setAttr(el, storedRequired, attrValue); this.adapter.removeAttr(el, 'required'); } }; // NOTE: We simply remove the 'integrity' attribute because its value will not be relevant after the script // content changes (http://www.w3.org/TR/SRI/). If this causes problems in the future, we will need to generate // the correct SHA for the changed script. // In addition, we create stored 'integrity' attribute with the current 'integrity' attribute value. (GH-235) DomProcessor.prototype._processIntegrityAttr = function (el) { var storedIntegrityAttr = DomProcessor.getStoredAttrName('integrity'); var processed = this.adapter.hasAttr(el, storedIntegrityAttr) && !this.adapter.hasAttr(el, 'integrity'); var attrValue = this.adapter.getAttr(el, processed ? storedIntegrityAttr : 'integrity'); if (attrValue) this.adapter.setAttr(el, storedIntegrityAttr, attrValue); if (!processed) this.adapter.removeAttr(el, 'integrity'); }; // NOTE: We simply remove the 'rel' attribute if rel='prefetch' and use stored 'rel' attribute, because the prefetch // resource type is unknown. https://github.com/DevExpress/testcafe/issues/2528 DomProcessor.prototype._processRelPrefetch = function (el, _urlReplacer, pattern) { if (!pattern.relAttr) return; var storedRelAttr = DomProcessor.getStoredAttrName(pattern.relAttr); var processed = this.adapter.hasAttr(el, storedRelAttr) && !this.adapter.hasAttr(el, pattern.relAttr); var attrValue = this.adapter.getAttr(el, processed ? storedRelAttr : pattern.relAttr); if (attrValue) { var formatedValue = trim$1(attrValue.toLowerCase()); if (formatedValue === 'prefetch') { this.adapter.setAttr(el, storedRelAttr, attrValue); if (!processed) this.adapter.removeAttr(el, pattern.relAttr); } } }; DomProcessor.prototype._processJsAttr = function (el, attrName, _a) { var isJsProtocol = _a.isJsProtocol, isEventAttr = _a.isEventAttr; var storedUrlAttr = DomProcessor.getStoredAttrName(attrName); var processed = this.adapter.hasAttr(el, storedUrlAttr); var attrValue = this.adapter.getAttr(el, processed ? storedUrlAttr : attrName) || ''; var processedValue = DomProcessor.processJsAttrValue(attrValue, { isJsProtocol: isJsProtocol, isEventAttr: isEventAttr }); if (attrValue !== processedValue) { this.adapter.setAttr(el, storedUrlAttr, attrValue); this.adapter.setAttr(el, attrName, processedValue); } }; DomProcessor.prototype._processEvtAttr = function (el) { var events = this.adapter.EVENTS; for (var i = 0; i < events.length; i++) { var attrValue = this.adapter.getAttr(el, events[i]); if (attrValue) { this._processJsAttr(el, events[i], { isJsProtocol: DomProcessor.isJsProtocol(attrValue), isEventAttr: true, }); } } }; DomProcessor.prototype._processMetaElement = function (el, urlReplacer, pattern) { var httpEquivAttrValue = (this.adapter.getAttr(el, 'http-equiv') || '').toLowerCase(); if (httpEquivAttrValue === BUILTIN_HEADERS.refresh && pattern.urlAttr) { var attr = this.adapter.getAttr(el, pattern.urlAttr) || ''; attr = processMetaRefreshContent(attr, urlReplacer); this.adapter.setAttr(el, pattern.urlAttr, attr); } // TODO: remove after https://github.com/DevExpress/testcafe-hammerhead/issues/244 implementation else if (httpEquivAttrValue === BUILTIN_HEADERS.contentSecurityPolicy) { this.adapter.removeAttr(el, 'http-equiv'); this.adapter.removeAttr(el, 'content'); } }; DomProcessor.prototype._processSandboxedIframe = function (el) { var attrValue = this.adapter.getAttr(el, 'sandbox') || ''; var allowSameOrigin = attrValue.indexOf('allow-same-origin') !== -1; var allowScripts = attrValue.indexOf('allow-scripts') !== -1; var storedAttr = DomProcessor.getStoredAttrName('sandbox'); this.adapter.setAttr(el, storedAttr, attrValue); if (!allowSameOrigin || !allowScripts) { attrValue += !allowSameOrigin ? ' allow-same-origin' : ''; attrValue += !allowScripts ? ' allow-scripts' : ''; } this.adapter.setAttr(el, 'sandbox', attrValue); }; DomProcessor.prototype._processScriptElement = function (script, urlReplacer) { var scriptContent = this.adapter.getScriptContent(script); if (!scriptContent || !this.adapter.needToProcessContent(script)) return; var scriptProcessedOnServer = isScriptProcessed(scriptContent); if (scriptProcessedOnServer) return; // NOTE: We do not process scripts that are not executed during page load. We process scripts of types like // text/javascript, application/javascript etc. (a complete list of MIME types is specified in the w3c.org // html5 specification). If the type is not set, it is considered 'text/javascript' by default. var scriptType = this.adapter.getAttr(script, 'type'); var isExecutableScript = !scriptType || EXECUTABLE_SCRIPT_TYPES_REG_EX.test(scriptType); if (isExecutableScript) { var result = scriptContent; var commentPrefix = ''; var commentPrefixMatch = result.match(HTML_COMMENT_PREFIX_REG_EX); var commentPostfix = ''; var commentPostfixMatch = null; var hasCDATA = CDATA_REG_EX.test(result); if (commentPrefixMatch) { commentPrefix = commentPrefixMatch[0]; commentPostfixMatch = result.match(HTML_COMMENT_POSTFIX_REG_EX); if (commentPostfixMatch) commentPostfix = commentPostfixMatch[0]; else if (!HTML_COMMENT_SIMPLE_POSTFIX_REG_EX.test(commentPrefix)) commentPostfix = '//-->'; result = result.replace(commentPrefix, '').replace(commentPostfix, ''); } if (hasCDATA) result = result.replace(CDATA_REG_EX, '$2'); result = commentPrefix + processScript(result, true, false, urlReplacer) + commentPostfix; if (hasCDATA) result = '\n//'; this.adapter.setScriptContent(script, result); } }; DomProcessor.prototype._processStyleAttr = function (el, urlReplacer) { var style = this.adapter.getAttr(el, 'style'); if (style) this.adapter.setAttr(el, 'style', styleProcessor.process(style, urlReplacer, false)); }; DomProcessor.prototype._processStylesheetElement = function (el, urlReplacer) { var content = this.adapter.getStyleContent(el); if (content && urlReplacer && this.adapter.needToProcessContent(el)) { content = styleProcessor.process(content, urlReplacer, true); this.adapter.setStyleContent(el, content); } }; DomProcessor.prototype._processTargetBlank = function (el, _urlReplacer, pattern) { if (this.allowMultipleWindows || !pattern.targetAttr) return; var storedTargetAttr = DomProcessor.getStoredAttrName(pattern.targetAttr); var processed = this.adapter.hasAttr(el, storedTargetAttr); if (processed) return; var attrValue = this.adapter.getAttr(el, pattern.targetAttr); // NOTE: Value may have whitespace. attrValue = attrValue && attrValue.replace(/\s/g, ''); if (attrValue === '_blank') { this.adapter.setAttr(el, pattern.targetAttr, '_top'); this.adapter.setAttr(el, storedTargetAttr, attrValue); } }; DomProcessor.prototype._processUrlAttrs = function (el, urlReplacer, pattern) { if (!pattern.urlAttr || this.proxyless) return; var storedUrlAttr = DomProcessor.getStoredAttrName(pattern.urlAttr); var resourceUrl = this.adapter.getAttr(el, pattern.urlAttr); var isSpecialPageUrl = !!resourceUrl && isSpecialPage$1(resourceUrl); var processedOnServer = this.adapter.hasAttr(el, storedUrlAttr); if ((!resourceUrl && resourceUrl !== '' || processedOnServer) || //eslint-disable-line @typescript-eslint/no-extra-parens !isSupportedProtocol$1(resourceUrl) && !isSpecialPageUrl) return; var elTagName = this.adapter.getTagName(el); var isIframe = elTagName === 'iframe' || elTagName === 'frame'; var isScript = elTagName === 'script'; var isAnchor = elTagName === 'a'; var isUrlsSet = pattern.urlAttr === 'srcset'; var target = pattern.targetAttr ? this.adapter.getAttr(el, pattern.targetAttr) : null; // NOTE: Elements with target=_parent shouldn’t be processed on the server,because we don't // know what is the parent of the processed page (an iframe or the top window). if (!this.adapter.needToProcessUrl(elTagName, target || '')) return; var resourceType = this.getElementResourceType(el) || ''; var parsedResourceUrl = parseUrl$1(resourceUrl); var isRelativePath = parsedResourceUrl.protocol !== 'file:' && !parsedResourceUrl.host; var charsetAttrValue = isScript && this.adapter.getAttr(el, 'charset') || ''; var isImgWithoutSrc = elTagName === 'img' && resourceUrl === ''; var isIframeWithEmptySrc = isIframe && resourceUrl === ''; var parsedProxyUrl = parseProxyUrl$1(urlReplacer('/')); var isCrossDomainSrc = false; var proxyUrl = resourceUrl; // NOTE: Only a non-relative iframe src can be cross-domain. if (isIframe && !isSpecialPageUrl && !isRelativePath && parsedProxyUrl) isCrossDomainSrc = !this.adapter.sameOriginCheck(parsedProxyUrl.destUrl, resourceUrl); if ((!isSpecialPageUrl || isAnchor) && !isImgWithoutSrc && !isIframeWithEmptySrc) { proxyUrl = elTagName === 'img' && !this.forceProxySrcForImage && !isUrlsSet ? resolveUrlAsDest$1(resourceUrl, urlReplacer) : urlReplacer(resourceUrl, resourceType, charsetAttrValue, isCrossDomainSrc, isUrlsSet); } this.adapter.setAttr(el, storedUrlAttr, resourceUrl); this.adapter.setAttr(el, pattern.urlAttr, proxyUrl); }; DomProcessor.prototype._processSrcdocAttr = function (el) { var storedAttr = DomProcessor.getStoredAttrName('srcdoc'); var html = this.adapter.getAttr(el, 'srcdoc') || ''; var processedHtml = this.adapter.processSrcdocAttr(html); this.adapter.setAttr(el, storedAttr, html); this.adapter.setAttr(el, 'srcdoc', processedHtml); }; DomProcessor.prototype._processUrlJsAttr = function (el, _urlReplacer, pattern) { if (pattern.urlAttr && DomProcessor.isJsProtocol(this.adapter.getAttr(el, pattern.urlAttr) || '')) this._processJsAttr(el, pattern.urlAttr, { isJsProtocol: true, isEventAttr: false }); }; DomProcessor.prototype._processSVGXLinkHrefAttr = function (el, _urlReplacer, pattern) { if (!pattern.urlAttr) return; var attrValue = this.adapter.getAttr(el, pattern.urlAttr) || ''; if (HASH_RE$1.test(attrValue)) { var storedUrlAttr = DomProcessor.getStoredAttrName(pattern.urlAttr); this.adapter.setAttr(el, storedUrlAttr, attrValue); } }; return DomProcessor; }()); var lengthWeakMap = new WeakMap(); function updateOrigin(ancestorOrigins, wrapper, index, origin) { var descriptor = createOverriddenDescriptor(ancestorOrigins, index, { value: origin }); nativeMethods.objectDefineProperty(wrapper, index, descriptor); } var DOMStringListInheritor = /** @class */ (function () { function DOMStringListInheritor() { } return DOMStringListInheritor; }()); DOMStringListInheritor.prototype = DOMStringList.prototype; var DOMStringListWrapper = /** @class */ (function (_super) { __extends(DOMStringListWrapper, _super); function DOMStringListWrapper(window, getCrossDomainOrigin) { var _this = _super.call(this) || this; var nativeOrigins = window.location.ancestorOrigins; var length = nativeOrigins.length; var parentWindow = window.parent; lengthWeakMap.set(_this, length); var _loop_1 = function (i) { var parentLocationWrapper = LocationAccessorsInstrumentation.getLocationWrapper(parentWindow); var isCrossDomainParent = parentLocationWrapper === parentWindow.location; // eslint-disable-next-line no-restricted-properties updateOrigin(nativeOrigins, this_1, i.toString(), isCrossDomainParent ? '' : parentLocationWrapper.origin); if (isCrossDomainParent && getCrossDomainOrigin) //@ts-ignore getCrossDomainOrigin(parentWindow, function (origin) { return updateOrigin(nativeOrigins, _this, i, origin); }); parentWindow = parentWindow.parent; }; var this_1 = this; for (var i = 0; i < length; i++) { _loop_1(i); } return _this; } DOMStringListWrapper.prototype.item = function (index) { return this[index]; }; DOMStringListWrapper.prototype.contains = function (origin) { if (typeof origin !== 'string') origin = String(origin); var length = lengthWeakMap.get(this) || 0; for (var i = 0; i < length; i++) { if (this[i] === origin) return true; } return false; }; Object.defineProperty(DOMStringListWrapper.prototype, "length", { get: function () { return lengthWeakMap.get(this); }, enumerable: false, configurable: true }); return DOMStringListWrapper; }(DOMStringListInheritor)); var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; var IntegerIdGenerator = /** @class */ (function () { function IntegerIdGenerator() { this._id = MIN_SAFE_INTEGER; } IntegerIdGenerator.prototype.increment = function () { this._id = this._id === MAX_SAFE_INTEGER ? MIN_SAFE_INTEGER : this._id + 1; return this._id; }; Object.defineProperty(IntegerIdGenerator.prototype, "value", { get: function () { return this._id; }, enumerable: false, configurable: true }); return IntegerIdGenerator; }()); var GET_ORIGIN_CMD = 'hammerhead|command|get-origin'; var ORIGIN_RECEIVED_CMD = 'hammerhead|command|origin-received'; function getLocationUrl(window) { try { return window.location.toString(); } catch (e) { return void 0; } } var LocationInheritor = /** @class */ (function () { function LocationInheritor() { } return LocationInheritor; }()); LocationInheritor.prototype = Location.prototype; var LocationWrapper = /** @class */ (function (_super) { __extends(LocationWrapper, _super); function LocationWrapper(window, messageSandbox, onChanged) { var _this = _super.call(this) || this; var parsedLocation = parseProxyUrl(getLocationUrl(window)); var locationResourceType = parsedLocation ? parsedLocation.resourceType : ''; var parsedResourceType = parseResourceType(locationResourceType); // @ts-ignore var isLocationPropsInProto = nativeMethods.objectHasOwnProperty.call(window.Location.prototype, 'href'); // @ts-ignore var locationPropsOwner = isLocationPropsInProto ? window.Location.prototype : window.location; var locationProps = {}; parsedResourceType.isIframe = parsedResourceType.isIframe || isIframeWindow(window); var resourceType = getResourceTypeString({ isIframe: parsedResourceType.isIframe, isForm: parsedResourceType.isForm, }); var getHref = function () { // eslint-disable-next-line no-restricted-properties if (isIframeWindow(window) && window.location.href === SPECIAL_BLANK_PAGE) return SPECIAL_BLANK_PAGE; var locationUrl = get$2(); var resolveElement = urlResolver.getResolverElement(window.document); nativeMethods.anchorHrefSetter.call(resolveElement, locationUrl); var href = nativeMethods.anchorHrefGetter.call(resolveElement); return ensureTrailingSlash(href, locationUrl); }; var getProxiedHref = function (href) { if (typeof href !== 'string') href = String(href); href = prepareUrl(href); if (DomProcessor.isJsProtocol(href)) return DomProcessor.processJsAttrValue(href, { isJsProtocol: true, isEventAttr: false }); var locationUrl = getLocationUrl(window); var proxyPort = null; if (window !== window.parent) { var parentLocationUrl = getLocationUrl(window.parent); var parsedParentLocationUrl = parseProxyUrl(parentLocationUrl); if (parsedParentLocationUrl && parsedParentLocationUrl.proxy) { // eslint-disable-next-line no-restricted-properties var parentProxyPort = parsedParentLocationUrl.proxy.port; proxyPort = sameOriginCheck(parentLocationUrl, href) ? parentProxyPort : getCrossDomainProxyPort(parentProxyPort); } } var changedOnlyHash = locationUrl && isChangedOnlyHash(locationUrl, href); var currentResourceType = changedOnlyHash ? locationResourceType : resourceType; return getProxyUrl(href, { resourceType: currentResourceType, proxyPort: proxyPort }); }; // eslint-disable-next-line no-restricted-properties locationProps.href = createOverriddenDescriptor(locationPropsOwner, 'href', { getter: getHref, setter: function (href) { var proxiedHref = getProxiedHref(href); // eslint-disable-next-line no-restricted-properties window.location.href = proxiedHref; onChanged(proxiedHref); return href; }, }); // eslint-disable-next-line no-restricted-properties locationProps.search = createOverriddenDescriptor(locationPropsOwner, 'search', { // eslint-disable-next-line no-restricted-properties getter: function () { return window.location.search; }, setter: function (search) { var newLocation = changeDestUrlPart(window.location.toString(), nativeMethods.anchorSearchSetter, search, resourceType); // @ts-ignore window.location = newLocation; onChanged(newLocation); return search; }, }); // eslint-disable-next-line no-restricted-properties locationProps.origin = createOverriddenDescriptor(locationPropsOwner, 'origin', { getter: function () { return getDomain(getParsed()); }, setter: function (origin) { return origin; }, }); locationProps.hash = createOverriddenDescriptor(locationPropsOwner, 'hash', { getter: function () { return window.location.hash; }, setter: function (hash) { window.location.hash = hash; return hash; }, }); if (window.location.ancestorOrigins) { var callbacks_1 = nativeMethods.objectCreate(null); var idGenerator_1 = new IntegerIdGenerator(); var getCrossDomainOrigin = function (win, callback) { var id = idGenerator_1.increment(); callbacks_1[id] = callback; messageSandbox.sendServiceMsg({ id: id, cmd: GET_ORIGIN_CMD }, win); }; if (messageSandbox) { messageSandbox.on(messageSandbox.SERVICE_MSG_RECEIVED_EVENT, function (_a) { var message = _a.message, source = _a.source; if (message.cmd === GET_ORIGIN_CMD) { // @ts-ignore messageSandbox.sendServiceMsg({ id: message.id, cmd: ORIGIN_RECEIVED_CMD, origin: _this.origin }, source); // eslint-disable-line no-restricted-properties } else if (message.cmd === ORIGIN_RECEIVED_CMD) { var callback = callbacks_1[message.id]; if (callback) callback(message.origin); // eslint-disable-line no-restricted-properties } }); } var ancestorOrigins_1 = new DOMStringListWrapper(window, messageSandbox ? getCrossDomainOrigin : void 0); locationProps.ancestorOrigins = createOverriddenDescriptor(locationPropsOwner, 'ancestorOrigins', { getter: function () { return ancestorOrigins_1; }, }); } var createLocationPropertyDesc = function (property, nativePropSetter) { locationProps[property] = createOverriddenDescriptor(locationPropsOwner, property, { getter: function () { var frameElement = getFrameElement(window); var inIframeWithoutSrc = frameElement && isIframeWithoutSrc(frameElement); var parsedDestLocation = inIframeWithoutSrc ? window.location : getParsed(); return parsedDestLocation[property]; }, setter: function (value) { var newLocation = changeDestUrlPart(window.location.toString(), nativePropSetter, value, resourceType); // @ts-ignore window.location = newLocation; onChanged(newLocation); return value; }, }); }; createLocationPropertyDesc('port', nativeMethods.anchorPortSetter); createLocationPropertyDesc('host', nativeMethods.anchorHostSetter); createLocationPropertyDesc('hostname', nativeMethods.anchorHostnameSetter); createLocationPropertyDesc('pathname', nativeMethods.anchorPathnameSetter); createLocationPropertyDesc('protocol', nativeMethods.anchorProtocolSetter); locationProps.assign = createOverriddenDescriptor(locationPropsOwner, 'assign', { value: function (url) { var proxiedHref = getProxiedHref(url); var result = window.location.assign(proxiedHref); onChanged(proxiedHref); return result; }, }); locationProps.replace = createOverriddenDescriptor(locationPropsOwner, 'replace', { value: function (url) { var proxiedHref = getProxiedHref(url); var result = window.location.replace(proxiedHref); onChanged(proxiedHref); return result; }, }); locationProps.reload = createOverriddenDescriptor(locationPropsOwner, 'reload', { value: function () { var result = window.location.reload(); onChanged(window.location.toString()); return result; }, }); locationProps.toString = createOverriddenDescriptor(locationPropsOwner, 'toString', { value: getHref }); if (!isLocationPropsInProto && nativeMethods.objectHasOwnProperty.call(window.location, 'valueOf')) locationProps.valueOf = createOverriddenDescriptor(locationPropsOwner, 'valueOf', { value: function () { return _this; } }); nativeMethods.objectDefineProperties(_this, locationProps); // NOTE: We shouldn't break the client script if the browser add the new API. For example: // > From Chrome 80 to Chrome 85, the fragmentDirective property was defined on Location.prototype. if (isIE11) return _this; var protoKeys = nativeMethods.objectKeys(Location.prototype); var locWrapper = _this; var rewriteDescriptorFn = function (descriptor, key) { if (!isFunction(descriptor[key])) return; var nativeMethod = descriptor[key]; descriptor[key] = function () { var ctx = this === locWrapper ? window.location : this; return nativeMethod.apply(ctx, arguments); }; }; for (var _i = 0, protoKeys_1 = protoKeys; _i < protoKeys_1.length; _i++) { var protoKey = protoKeys_1[_i]; if (protoKey in locationProps) continue; var protoKeyDescriptor = nativeMethods.objectGetOwnPropertyDescriptor(Location.prototype, protoKey); rewriteDescriptorFn(protoKeyDescriptor, 'get'); rewriteDescriptorFn(protoKeyDescriptor, 'set'); rewriteDescriptorFn(protoKeyDescriptor, 'value'); nativeMethods.objectDefineProperty(locWrapper, protoKey, protoKeyDescriptor); // NOTE: We hide errors with a new browser API and we should know about it. nativeMethods.consoleMeths.log("testcafe-hammerhead: unwrapped Location.prototype.".concat(protoKey, " descriptor!")); } return _this; } return LocationWrapper; }(LocationInheritor)); // NOTE: window.Location in IE11 is object if (!isFunction(Location)) LocationWrapper.toString = function () { return Location.toString(); }; else overrideStringRepresentation(LocationWrapper, Location); var LOCATION_WRAPPER = 'hammerhead|location-wrapper'; var LocationAccessorsInstrumentation = /** @class */ (function (_super) { __extends(LocationAccessorsInstrumentation, _super); function LocationAccessorsInstrumentation(_messageSandbox) { var _this = _super.call(this) || this; _this._messageSandbox = _messageSandbox; _this.LOCATION_CHANGED_EVENT = 'hammerhead|event|location-changed'; _this._locationChangedEventCallback = function (e) { return _this.emit(_this.LOCATION_CHANGED_EVENT, e); }; return _this; } LocationAccessorsInstrumentation.isLocationWrapper = function (obj) { return obj instanceof LocationWrapper; }; LocationAccessorsInstrumentation.getLocationWrapper = function (owner) { // NOTE: IE11 case. We can get cross-domain location wrapper without any exceptions. // We return owner.location in this case, as in other browsers. if (isIE && isCrossDomainWindows(window, owner)) return owner.location; // NOTE: When the owner is cross-domain, we cannot get its location wrapper, so we return the original // location, which cannot be accessed but behaves like a real one. Cross-domain location retains the 'replace' // and 'assign' methods, so we intercept calls to them through MethodCallInstrumentation. try { return owner[LOCATION_WRAPPER]; } catch (e) { return owner.location; } }; LocationAccessorsInstrumentation.prototype.attach = function (window) { _super.prototype.attach.call(this, window); var document = window.document; var locationWrapper = new LocationWrapper(window, this._messageSandbox, this._locationChangedEventCallback); // NOTE: In Google Chrome, iframes whose src contains html code raise the 'load' event twice. // So, we need to define code instrumentation functions as 'configurable' so that they can be redefined. nativeMethods.objectDefineProperty(window, LOCATION_WRAPPER, { value: locationWrapper, configurable: true }); nativeMethods.objectDefineProperty(document, LOCATION_WRAPPER, { value: locationWrapper, configurable: true }); nativeMethods.objectDefineProperty(window, SCRIPT_PROCESSING_INSTRUCTIONS.getLocation, { value: function (location) { return isLocation(location) ? locationWrapper : location; }, configurable: true, }); nativeMethods.objectDefineProperty(window, SCRIPT_PROCESSING_INSTRUCTIONS.setLocation, { value: function (location, value) { if (isLocation(location) && typeof value === 'string') { // @ts-ignore locationWrapper.href = value; // eslint-disable-line no-restricted-properties return value; } return null; }, configurable: true, }); }; return LocationAccessorsInstrumentation; }(SandboxBase)); var IFRAME_WINDOW_INITED = 'hammerhead|iframe-window-inited'; var IframeSandbox = /** @class */ (function (_super) { __extends(IframeSandbox, _super); function IframeSandbox(_nodeMutation, _cookieSandbox) { var _this = _super.call(this) || this; _this._nodeMutation = _nodeMutation; _this._cookieSandbox = _cookieSandbox; _this.RUN_TASK_SCRIPT_EVENT = 'hammerhead|event|run-task-script'; _this.EVAL_HAMMERHEAD_SCRIPT_EVENT = 'hammerhead|event|eval-hammerhead-script'; _this.EVAL_EXTERNAL_SCRIPT_EVENT = 'hammerhead|event|eval-external-script'; _this.IFRAME_DOCUMENT_CREATED_EVENT = 'hammerhead|event|iframe-document-created'; _this.on(_this.RUN_TASK_SCRIPT_EVENT, _this.iframeReadyToInitHandler); _this._nodeMutation.on(_this._nodeMutation.IFRAME_ADDED_TO_DOM_EVENT, function (iframe) { return _this.processIframe(iframe); }); _this.iframeNativeMethodsBackup = null; return _this; } IframeSandbox.prototype._shouldSaveIframeNativeMethods = function (iframe) { if (!isWebKit) return false; var iframeSrc = this.nativeMethods.getAttribute.call(iframe, 'src'); return DomProcessor.isJsProtocol(iframeSrc); }; IframeSandbox.prototype._ensureIframeNativeMethodsForChrome = function (iframe) { var contentWindow = nativeMethods.contentWindowGetter.call(iframe); var contentDocument = nativeMethods.contentDocumentGetter.call(iframe); if (this.iframeNativeMethodsBackup) { this.iframeNativeMethodsBackup.restoreDocumentMeths(contentWindow, contentDocument); this.iframeNativeMethodsBackup = null; } else if (this._shouldSaveIframeNativeMethods(iframe)) // @ts-ignore this.iframeNativeMethodsBackup = new this.nativeMethods.constructor(contentDocument, contentWindow); }; IframeSandbox.prototype._ensureIframeNativeMethodsForIE = function (iframe) { var contentWindow = nativeMethods.contentWindowGetter.call(iframe); var contentDocument = nativeMethods.contentDocumentGetter.call(iframe); var iframeNativeMethods = contentWindow[INTERNAL_PROPS.iframeNativeMethods]; if (iframeNativeMethods) { iframeNativeMethods.restoreDocumentMeths(contentWindow, contentDocument); delete contentWindow[INTERNAL_PROPS.iframeNativeMethods]; } }; IframeSandbox.prototype._ensureIframeNativeMethods = function (iframe) { // NOTE: In Chrome, iframe with javascript protocol src raises the load event twice. // As a result, when the second load event is raised, we write the overridden methods to the native methods. // So, we need to save the native methods when the first load event is raised. // https://code.google.com/p/chromium/issues/detail?id=578812 this._ensureIframeNativeMethodsForChrome(iframe); // NOTE: Restore native document methods for the iframe's document if it overrided earlier (IE9, IE10 only) // https://github.com/DevExpress/testcafe-hammerhead/issues/279 this._ensureIframeNativeMethodsForIE(iframe); }; IframeSandbox.prototype._emitEvents = function (iframe) { // NOTE: Raise this internal event to eval the Hammerhead code script. this.emit(this.EVAL_HAMMERHEAD_SCRIPT_EVENT, { iframe: iframe }); // NOTE: Raise this event to eval external code script. this.emit(this.EVAL_EXTERNAL_SCRIPT_EVENT, { iframe: iframe }); // NOTE: Raise this event to eval the "task" script and to call the Hammerhead initialization method // and external script initialization code. this.emit(this.RUN_TASK_SCRIPT_EVENT, iframe); }; IframeSandbox.prototype._raiseReadyToInitEvent = function (iframe) { if (!isIframeWithoutSrc(iframe)) return; var contentWindow = nativeMethods.contentWindowGetter.call(iframe); var contentDocument = nativeMethods.contentDocumentGetter.call(iframe); if (!IframeSandbox.isIframeInitialized(iframe)) { // NOTE: Even if iframe is not loaded (iframe.contentDocument.documentElement does not exist), we // still need to override the document.write method without initializing Hammerhead. This method can // be called before iframe is fully loaded, we should override it now. if (isNativeFunction(contentDocument.write)) this.emit(this.IFRAME_DOCUMENT_CREATED_EVENT, { iframe: iframe }); } else if (!contentWindow[IFRAME_WINDOW_INITED] && !contentWindow[INTERNAL_PROPS.hammerhead]) { this._ensureIframeNativeMethods(iframe); // NOTE: Ok, the iframe is fully loaded now, but Hammerhead is not injected. nativeMethods.objectDefineProperty(contentWindow, IFRAME_WINDOW_INITED, { value: true }); this._emitEvents(iframe); contentWindow[INTERNAL_PROPS.processDomMethodName](); } }; IframeSandbox.isIframeInitialized = function (iframe) { var contentWindow = nativeMethods.contentWindowGetter.call(iframe); var contentDocument = nativeMethods.contentDocumentGetter.call(iframe); if (isFirefox) return contentDocument.readyState !== 'uninitialized'; if (isIE) return !!contentDocument.documentElement || contentWindow[INTERNAL_PROPS.documentWasCleaned]; if (!contentWindow[INTERNAL_PROPS.documentWasCleaned] && isIframeWithSrcdoc(iframe)) // eslint-disable-next-line no-restricted-properties return contentWindow.location.href === 'about:srcdoc'; return true; }; IframeSandbox.isWindowInited = function (window) { return window[IFRAME_WINDOW_INITED]; }; IframeSandbox.prototype.iframeReadyToInitHandler = function (iframe) { // NOTE: We are using String.replace in order to avoid adding Mustache scripts on the client side. // If it is needed elsewhere in a certain place, we should consider using Mustache. var taskScriptTemplate = settings.get().iframeTaskScriptTemplate; var escapeStringPatterns = function (str) { return str.replace(/\$/g, '$$$$'); }; var cookie = stringify(this._cookieSandbox.getCookie()); var referer = settings.get().referer || this.window.location.toString(); var iframeTaskScriptTemplate = stringify(taskScriptTemplate); var taskScript = taskScriptTemplate .replace('{{{cookie}}}', escapeStringPatterns(cookie)) .replace('{{{referer}}}', escapeStringPatterns(stringify(referer))) .replace('{{{iframeTaskScriptTemplate}}}', escapeStringPatterns(iframeTaskScriptTemplate)); var contentWindow = nativeMethods.contentWindowGetter.call(iframe); contentWindow.eval.call(contentWindow, taskScript); }; IframeSandbox.prototype.onIframeBeganToRun = function (iframe) { this._raiseReadyToInitEvent(iframe); }; IframeSandbox.prototype.processIframe = function (el) { var _this = this; if (isShadowUIElement(el)) return; if (isIframeElement(el) && nativeMethods.contentWindowGetter.call(el) || isFrameElement(el) && nativeMethods.frameContentWindowGetter.call(el)) this._raiseReadyToInitEvent(el); // NOTE: This handler exists for iframes without the src attribute. In some the browsers (e.g. Chrome) // the load event is triggering immediately after an iframe added to DOM. In other browsers, // the _raiseReadyToInitEvent function is calling in our function wrapper after an iframe added to DOM. this.nativeMethods.addEventListener.call(el, 'load', function () { return _this._raiseReadyToInitEvent(el); }); }; return IframeSandbox; }(SandboxBase)); var BaseDomAdapter = /** @class */ (function () { function BaseDomAdapter() { this.EVENTS = ['onblur', 'onchange', 'onclick', 'oncontextmenu', 'oncopy', 'oncut', 'ondblclick', 'onerror', 'onfocus', 'onfocusin', 'onfocusout', 'onhashchange', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onpaste', 'onreset', 'onresize', 'onscroll', 'onselect', 'onsubmit', 'ontextinput', 'onunload', 'onwheel', 'onpointerdown', 'onpointerup', 'onpointercancel', 'onpointermove', 'onpointerover', 'onpointerout', 'onpointerenter', 'onpointerleave', 'ongotpointercapture', 'onlostpointercapture', 'onmspointerdown', 'onmspointerup', 'onmspointercancel', 'onmspointermove', 'onmspointerover', 'onmspointerout', 'onmspointerenter', 'onmspointerleave', 'onmsgotpointercapture', 'onmslostpointercapture', ]; } return BaseDomAdapter; }()); // ------------------------------------------------------------- var CLEANUP_FORMATTING_REGEXP = /\n\s*|\/\*[\S\s]*?\*\//g; function create$1(script) { return "\n \n ").replace(CLEANUP_FORMATTING_REGEXP, ''); } var sharedSelfRemovingScripts = { iframeInit: create$1("\n var parentHammerhead = null;\n\n if (!window[\"".concat(INTERNAL_PROPS.hammerhead, "\"])\n Object.defineProperty(window, \"").concat(INTERNAL_PROPS.documentWasCleaned, "\", { value: true, configurable: true });\n\n try {\n parentHammerhead = window.parent[\"").concat(INTERNAL_PROPS.hammerhead, "\"];\n } catch(e) {}\n\n if (parentHammerhead)\n parentHammerhead.sandbox.onIframeDocumentRecreated(window.frameElement);\n ")), onWindowRecreation: create$1("\n var hammerhead = window[\"".concat(INTERNAL_PROPS.hammerhead, "\"];\n var sandbox = hammerhead && hammerhead.sandbox;\n\n if (!sandbox) {\n try {\n sandbox = window.parent[\"").concat(INTERNAL_PROPS.hammerhead, "\"].sandboxUtils.backup.get(window);\n } catch(e) {}\n }\n\n if (sandbox) {\n Object.defineProperty(window, \"").concat(INTERNAL_PROPS.documentWasCleaned, "\", { value: true, configurable: true });\n\n sandbox.node.mutation.onDocumentCleaned(window, document);\n\n /* NOTE: B234357 */\n sandbox.node.processNodes(null, document);\n }\n ")), onBodyCreated: create$1("\n if (window[\"".concat(INTERNAL_PROPS.hammerhead, "\"])\n window[\"").concat(INTERNAL_PROPS.hammerhead, "\"].sandbox.node.raiseBodyCreatedEvent();\n ")), onOriginFirstTitleLoaded: create$1("\n window[\"".concat(INTERNAL_PROPS.hammerhead, "\"].sandbox.node.onOriginFirstTitleElementInHeadLoaded();\n ")), restoreStorages: create$1("\n window.localStorage.setItem(\"%s\", %s);\n window.sessionStorage.setItem(\"%s\", %s);\n "), }; var InsertPosition; (function (InsertPosition) { InsertPosition["beforeBegin"] = "beforebegin"; InsertPosition["afterBegin"] = "afterbegin"; InsertPosition["beforeEnd"] = "beforeend"; InsertPosition["afterEnd"] = "afterend"; })(InsertPosition || (InsertPosition = {})); var InsertPosition$1 = InsertPosition; function removeElement (element) { var parent = nativeMethods.nodeParentNodeGetter.call(element); if (parent) nativeMethods.removeChild.call(parent, element); return element; } var FAKE_TAG_NAME_PREFIX = 'hh_fake_tag_name_'; var FAKE_DOCTYPE_TAG_NAME = 'hh_fake_doctype'; var FAKE_HEAD_TAG_NAME = "".concat(FAKE_TAG_NAME_PREFIX, "head"); var FAKE_BODY_TAG_NAME = "".concat(FAKE_TAG_NAME_PREFIX, "body"); var FAKE_ATTR_WITH_TAG_NAME = 'hh_fake_attr'; var FAKE_TAG_NAME_RE = new RegExp('(<\\/?)' + FAKE_TAG_NAME_PREFIX, 'ig'); var WRAP_TAGS_RE = /(<\/?)(html|head|body|table|tbody|tfoot|thead|tr|td|th|caption|colgroup)((?:\s[^>]*)?>)/ig; var WRAP_TAGS_TEMPLATE = "$1".concat(FAKE_TAG_NAME_PREFIX, "$2$3"); var WRAP_COL_NOSCRIPT_TAGS_RE = /<(\/?(?:col|noscript))(\s[^>]*?)?(\s?\/)?>/ig; var WRAP_COL_NOSCRIPT_TAGS_TEMPLATE = "
"); var UNWRAP_COL_NOSCRIPT_TAGS_RE = new RegExp("]*?) ".concat(FAKE_ATTR_WITH_TAG_NAME, "=\"([^|]+)\\|([^\"]*)\"([^>]*)"), 'ig'); var WRAP_DOCTYPE_RE = /]*)>/ig; var WRAP_DOCTYPE_TEMPLATE = "<".concat(FAKE_DOCTYPE_TAG_NAME, ">$1"); var UNWRAP_DOCTYPE_RE = new RegExp("<".concat(FAKE_DOCTYPE_TAG_NAME, ">([\\S\\s]*?)"), 'ig'); var FIND_SVG_RE = /]*>/ig; var FIND_NS_ATTRS_RE = /\s(?:NS[0-9]+:[^"']+('|")[\S\s]*?\1|[^:]+:NS[0-9]+=(?:""|''))/g; var STORED_ATTRS_SELECTOR = (function () { var storedAttrs = []; for (var _i = 0, URL_ATTRS_1 = URL_ATTRS; _i < URL_ATTRS_1.length; _i++) { var attr = URL_ATTRS_1[_i]; storedAttrs.push(DomProcessor.getStoredAttrName(attr)); } for (var _a = 0, ATTRS_WITH_SPECIAL_PROXYING_LOGIC_1 = ATTRS_WITH_SPECIAL_PROXYING_LOGIC; _a < ATTRS_WITH_SPECIAL_PROXYING_LOGIC_1.length; _a++) { var attr = ATTRS_WITH_SPECIAL_PROXYING_LOGIC_1[_a]; storedAttrs.push(DomProcessor.getStoredAttrName(attr)); } return '[' + storedAttrs.join('],[') + ']'; })(); var SHADOW_UI_ELEMENTS_SELECTOR = "[class*=\"".concat(SHADOW_UI_CLASS_NAME.postfix, "\"]"); var HOVER_AND_FOCUS_PSEUDO_CLASS_ELEMENTS_SELECTOR = "[".concat(INTERNAL_ATTRIBUTES.hoverPseudoClass, "],[").concat(INTERNAL_ATTRIBUTES.focusPseudoClass, "]"); var FAKE_ELEMENTS_SELECTOR = "".concat(FAKE_HEAD_TAG_NAME, ", ").concat(FAKE_BODY_TAG_NAME); var HTML_PARSER_ELEMENT_FLAG = 'hammerhead|html-parser-element-flag'; var SCRIPT_AND_STYLE_SELECTOR = 'script,link[rel="stylesheet"]'; var htmlDocument = nativeMethods.createHTMLDocument.call(document.implementation, 'title'); var htmlParser = nativeMethods.createDocumentFragment.call(htmlDocument); htmlParser[HTML_PARSER_ELEMENT_FLAG] = true; function getHtmlDocument() { try { // NOTE: IE bug: access denied. if (htmlDocument.location) htmlDocument.location.toString(); } catch (e) { htmlDocument = nativeMethods.createHTMLDocument.call(document.implementation, 'title'); htmlParser = nativeMethods.createDocumentFragment.call(htmlDocument); htmlParser[HTML_PARSER_ELEMENT_FLAG] = true; } return htmlDocument; } function wrapHtmlText(html) { return html .replace(WRAP_DOCTYPE_RE, WRAP_DOCTYPE_TEMPLATE) .replace(WRAP_COL_NOSCRIPT_TAGS_RE, WRAP_COL_NOSCRIPT_TAGS_TEMPLATE) .replace(WRAP_TAGS_RE, WRAP_TAGS_TEMPLATE); } function unwrapHtmlText(html) { return html .replace(UNWRAP_DOCTYPE_RE, '') .replace(UNWRAP_COL_NOSCRIPT_TAGS_RE, '<$2$1$4$3') .replace(FAKE_TAG_NAME_RE, '$1'); } function isPageHtml(html) { return /^\s*(<\s*(!doctype|html|head|body)[^>]*>)/i.test(html); } function processHtmlInternal(html, process) { var container = nativeMethods.createElement.call(getHtmlDocument(), 'div'); html = wrapHtmlText(html); nativeMethods.appendChild.call(htmlParser, container); nativeMethods.elementInnerHTMLSetter.call(container, html); var processedHtml = process(container) ? nativeMethods.elementInnerHTMLGetter.call(container) : html; removeElement(container); processedHtml = unwrapHtmlText(processedHtml); // NOTE: hack for IE (GH-1083) if (isIE && !isMSEdge && html !== processedHtml) processedHtml = removeExtraSvgNamespaces(html, processedHtml); return processedHtml; } function cleanUpUrlAttr(el) { var urlAttr = domProcessor.getUrlAttr(el); if (!urlAttr || !nativeMethods.hasAttribute.call(el, urlAttr)) return; var storedAttr = DomProcessor.getStoredAttrName(urlAttr); if (nativeMethods.hasAttribute.call(el, storedAttr)) { nativeMethods.setAttribute.call(el, urlAttr, nativeMethods.getAttribute.call(el, storedAttr)); nativeMethods.removeAttribute.call(el, storedAttr); } } function cleanUpAutocompleteAttr(el) { if (!nativeMethods.hasAttribute.call(el, 'autocomplete')) return; var storedAttr = DomProcessor.getStoredAttrName('autocomplete'); if (nativeMethods.hasAttribute.call(el, storedAttr)) { var storedAttrValue = nativeMethods.getAttribute.call(el, storedAttr); if (DomProcessor.isAddedAutocompleteAttr('autocomplete', storedAttrValue)) nativeMethods.removeAttribute.call(el, 'autocomplete'); else nativeMethods.setAttribute.call(el, 'autocomplete', storedAttrValue); nativeMethods.removeAttribute.call(el, storedAttr); } } function cleanUpTargetAttr(el) { var targetAttr = domProcessor.getTargetAttr(el); if (!targetAttr || !nativeMethods.hasAttribute.call(el, targetAttr)) return; var storedAttr = DomProcessor.getStoredAttrName(targetAttr); if (nativeMethods.hasAttribute.call(el, storedAttr)) { nativeMethods.setAttribute.call(el, targetAttr, nativeMethods.getAttribute.call(el, storedAttr)); nativeMethods.removeAttribute.call(el, storedAttr); } } function cleanUpSandboxAttr(el) { if (domProcessor.adapter.getTagName(el) !== 'iframe' || !nativeMethods.hasAttribute.call(el, 'sandbox')) return; var storedAttr = DomProcessor.getStoredAttrName('sandbox'); if (nativeMethods.hasAttribute.call(el, storedAttr)) { nativeMethods.setAttribute.call(el, 'sandbox', nativeMethods.getAttribute.call(el, storedAttr)); nativeMethods.removeAttribute.call(el, storedAttr); } } function cleanUpStyleAttr(el) { if (!nativeMethods.hasAttribute.call(el, 'style')) return; var storedAttr = DomProcessor.getStoredAttrName('style'); if (nativeMethods.hasAttribute.call(el, storedAttr)) { nativeMethods.setAttribute.call(el, 'style', nativeMethods.getAttribute.call(el, storedAttr)); nativeMethods.removeAttribute.call(el, storedAttr); } } function cleanUpHtml(html) { return processHtmlInternal(html, function (container) { var changed = false; find(container, STORED_ATTRS_SELECTOR, function (el) { cleanUpUrlAttr(el); cleanUpAutocompleteAttr(el); cleanUpTargetAttr(el); cleanUpSandboxAttr(el); cleanUpStyleAttr(el); changed = true; }); find(container, SHADOW_UI_ELEMENTS_SELECTOR, function (el) { var parent = nativeMethods.nodeParentNodeGetter.call(el); if (parent) { nativeMethods.removeChild.call(parent, el); changed = true; } }); find(container, 'script', function (el) { var textContent = nativeMethods.nodeTextContentGetter.call(el); var cleanedTextContent = remove$1(textContent); if (textContent !== cleanedTextContent) { nativeMethods.nodeTextContentSetter.call(el, cleanedTextContent); changed = true; } }); find(container, 'style', function (el) { var textContent = nativeMethods.nodeTextContentGetter.call(el); var cleanedTextContent = styleProcessor.cleanUp(textContent, parseProxyUrl); if (textContent !== cleanedTextContent) { nativeMethods.nodeTextContentSetter.call(el, cleanedTextContent); changed = true; } }); find(container, HOVER_AND_FOCUS_PSEUDO_CLASS_ELEMENTS_SELECTOR, function (el) { nativeMethods.removeAttribute.call(el, INTERNAL_ATTRIBUTES.hoverPseudoClass); nativeMethods.removeAttribute.call(el, INTERNAL_ATTRIBUTES.focusPseudoClass); changed = true; }); find(container, FAKE_ELEMENTS_SELECTOR, function (el) { var innerHtml = nativeMethods.elementInnerHTMLGetter.call(el); if (innerHtml.indexOf(sharedSelfRemovingScripts.iframeInit) !== -1) { nativeMethods.elementInnerHTMLSetter.call(el, innerHtml.replace(sharedSelfRemovingScripts.iframeInit, '')); changed = true; } }); return changed; }); } function processHtml(html, options) { if (options === void 0) { options = {}; } var parentTag = options.parentTag, prepareDom = options.prepareDom, processedContext = options.processedContext, isPage = options.isPage; return processHtmlInternal(html, function (container) { var doctypeElement = null; var htmlElements = []; var children = []; var length = 0; var storedBaseUrl = urlResolver.getBaseUrl(document); if (prepareDom) prepareDom(container); if (nativeMethods.htmlCollectionLengthGetter.call(nativeMethods.elementChildrenGetter.call(container))) { children = nativeMethods.elementQuerySelectorAll.call(container, '*'); length = nativeMethods.nodeListLengthGetter.call(children); } var base = nativeMethods.elementQuerySelector.call(container, 'base'); if (base) urlResolver.updateBase(nativeMethods.getAttribute.call(base, 'href'), document); for (var i = 0; i < length; i++) { var child = children[i]; if (isScriptElement(child)) { var scriptContent = nativeMethods.nodeTextContentGetter.call(child); nativeMethods.nodeTextContentSetter.call(child, unwrapHtmlText(scriptContent)); } child[INTERNAL_PROPS.processedContext] = processedContext; domProcessor.processElement(child, convertToProxyUrl); var elTagName = getTagName(child); if (elTagName === FAKE_HEAD_TAG_NAME || elTagName === FAKE_BODY_TAG_NAME) htmlElements.push(child); else if (elTagName === FAKE_DOCTYPE_TAG_NAME) doctypeElement = child; } if (!parentTag) { if (htmlElements.length) { for (var _i = 0, htmlElements_1 = htmlElements; _i < htmlElements_1.length; _i++) { var htmlElement = htmlElements_1[_i]; var firstScriptOrStyle = nativeMethods.elementQuerySelector.call(htmlElement, SCRIPT_AND_STYLE_SELECTOR); if (firstScriptOrStyle) nativeMethods.insertAdjacentHTML.call(firstScriptOrStyle, InsertPosition$1.beforeBegin, sharedSelfRemovingScripts.iframeInit); else nativeMethods.insertAdjacentHTML.call(htmlElement, InsertPosition$1.beforeEnd, sharedSelfRemovingScripts.iframeInit); } } else if (doctypeElement && isIE) nativeMethods.insertAdjacentHTML.call(doctypeElement, InsertPosition$1.afterEnd, sharedSelfRemovingScripts.iframeInit); else if (isPage) nativeMethods.insertAdjacentHTML.call(container, InsertPosition$1.afterBegin, sharedSelfRemovingScripts.iframeInit); } urlResolver.updateBase(storedBaseUrl, document); return true; }); } function dispose$1() { htmlParser = null; htmlDocument = null; } function isInternalHtmlParserElement(el) { while (nativeMethods.nodeParentNodeGetter.call(el)) el = nativeMethods.nodeParentNodeGetter.call(el); return !!el[HTML_PARSER_ELEMENT_FLAG]; } function removeExtraSvgNamespaces(html, processedHtml) { var initialSvgStrs = html.match(FIND_SVG_RE); var index = 0; if (!initialSvgStrs) return processedHtml; return processedHtml.replace(FIND_SVG_RE, function (svgStr) { var initialSvgStr = initialSvgStrs[index]; var initialNSAttrs = initialSvgStr ? initialSvgStr.match(FIND_NS_ATTRS_RE) : null; if (initialSvgStr) index++; return initialSvgStr ? svgStr.replace(FIND_NS_ATTRS_RE, function () { var replacement = initialNSAttrs ? initialNSAttrs.join('') : ''; if (initialNSAttrs) initialNSAttrs = null; return replacement; }) : svgStr; }); } var htmlUtils = /*#__PURE__*/Object.freeze({ __proto__: null, isPageHtml: isPageHtml, cleanUpHtml: cleanUpHtml, processHtml: processHtml, dispose: dispose$1, isInternalHtmlParserElement: isInternalHtmlParserElement }); var BEGIN_MARKER_TAG_NAME = 'hammerhead_write_marker_begin'; var END_MARKER_TAG_NAME = 'hammerhead_write_marker_end'; var BEGIN_MARKER_MARKUP = "<".concat(BEGIN_MARKER_TAG_NAME, ">"); var END_MARKER_MARKUP = "<".concat(END_MARKER_TAG_NAME, ">"); var BEGIN_REMOVE_RE = new RegExp("^[\\S\\s]*".concat(BEGIN_MARKER_MARKUP), 'g'); var END_REMOVE_RE = new RegExp("".concat(END_MARKER_MARKUP, "[\\S\\s]*$"), 'g'); var REMOVE_OPENING_TAG_RE = /^<[^>]+>/g; var REMOVE_CLOSING_TAG_RE = /<\/[^<>]+>$/g; var PENDING_RE = /<\/?(?:[A-Za-z][^>]*)?$/g; var UNCLOSED_ELEMENT_FLAG = 'hammerhead|unclosed-element-flag'; var DocumentWriter = /** @class */ (function () { function DocumentWriter(window, document) { this.window = window; this.document = document; this.pending = ''; this.parentTagChain = []; this.isBeginMarkerInDOM = false; this.isEndMarkerInDOM = false; this.isClosingContentEl = false; this.isNonClosedComment = false; this.isAddContentToEl = false; this.contentForProcessing = ''; this.nonClosedEl = null; this.cachedStartsWithClosingTagRegExps = {}; } DocumentWriter.prototype._cutPending = function (htmlChunk) { var match = htmlChunk.match(PENDING_RE); this.pending = match ? match[0] : ''; return this.pending ? htmlChunk.substring(0, htmlChunk.length - this.pending.length) : htmlChunk; }; DocumentWriter.prototype._wrapHtmlChunk = function (htmlChunk) { var parentTagChainMarkup = this.parentTagChain.length ? '<' + this.parentTagChain.join('><') + '>' : ''; if (this.isNonClosedComment) parentTagChainMarkup += '