UNPKG

tldjs

Version:

JavaScript API to work against complex domain names, subdomains and URIs.

1,684 lines (1,400 loc) 384 kB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.tldjs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ 'use strict'; var deprecate = require('util').deprecate; // Load rules var Trie = require('./lib/suffix-trie.js'); var allRules = Trie.fromJson(require('./rules.json')); // Internals var extractHostname = require('./lib/clean-host.js'); var getDomain = require('./lib/domain.js'); var getPublicSuffix = require('./lib/public-suffix.js'); var getSubdomain = require('./lib/subdomain.js'); var isValidHostname = require('./lib/is-valid.js'); var isIp = require('./lib/is-ip.js'); var tldExists = require('./lib/tld-exists.js'); // Flags representing steps in the `parse` function. They are used to implement // a early stop mechanism (simulating some form of laziness) to avoid doing more // work than necessary to perform a given action (e.g.: we don't need to extract // the domain and subdomain if we are only interested in public suffix). var TLD_EXISTS = 1; var PUBLIC_SUFFIX = 2; var DOMAIN = 3; var SUB_DOMAIN = 4; var ALL = 5; /** * @typedef {object} FactoryOptions * @property {import('./lib/suffix-trie.js')} [rules] * @property {string[]} [validHosts] * @property {(string) => string|null} [extractHostname] */ /** * @typedef {Object} tldjs * @property {(url: string) => string} extractHostname * @property {(url: string) => boolean} isValidHostname * @property {(url: string) => boolean} isValid * @property {(url: string) => ParseResult} parse * @property {(url: string) => boolean} tldExists * @property {(url: string) => string} getPublicSuffix * @property {(url: string) => string|null} getDomain * @property {(url: string) => string} getSubdomain * @property {(FactoryOptions) => tldjs} fromUserSettings */ /** * @typedef {object} ParseResult * @property {string|null} hostname * @property {boolean} isValid * @property {boolean} isIp * @property {boolean} tldExists * @property {string|null} publicSuffix * @property {string|null} domain * @property {string|null} subdomain */ /** * Creates a new instance of tldjs * @param {FactoryOptions} options [description] * @return {tldjs} [description] */ function factory(options) { var rules = options.rules || allRules || {}; var validHosts = options.validHosts || []; var _extractHostname = options.extractHostname || extractHostname; /** * Process a given url and extract all information. This is a higher level API * around private functions of `tld.js`. It allows to remove duplication (only * extract hostname from url once for all operations) and implement some early * termination mechanism to not pay the price of what we don't need (this * simulates laziness at a lower cost). * * @param {string} url * @param {number} [_step] - where should we stop processing * @return {ParseResult} */ function parse(url, _step) { var step = _step || ALL; /** * @type {ParseResult} */ var result = { hostname: _extractHostname(url), isValid: null, isIp: null, tldExists: false, publicSuffix: null, domain: null, subdomain: null, }; if (result.hostname === null) { result.isIp = false; result.isValid = false; return result; } // Check if `hostname` is a valid ip address result.isIp = isIp(result.hostname); if (result.isIp) { result.isValid = true; return result; } // Check if `hostname` is valid result.isValid = isValidHostname(result.hostname); if (result.isValid === false) { return result; } // Check if tld exists if (step === ALL || step === TLD_EXISTS) { result.tldExists = tldExists(rules, result.hostname); } if (step === TLD_EXISTS) { return result; } // Extract public suffix result.publicSuffix = getPublicSuffix(rules, result.hostname); if (step === PUBLIC_SUFFIX) { return result; } // Extract domain result.domain = getDomain(validHosts, result.publicSuffix, result.hostname); if (step === DOMAIN) { return result; } // Extract subdomain result.subdomain = getSubdomain(result.hostname, result.domain); return result; } return { extractHostname: _extractHostname, isValidHostname: isValidHostname, isValid: deprecate(function isValid (hostname) { return isValidHostname(hostname); }, '"isValid" is deprecated, please use "isValidHostname" instead.'), parse: parse, tldExists: function (url) { return parse(url, TLD_EXISTS).tldExists; }, getPublicSuffix: function (url) { return parse(url, PUBLIC_SUFFIX).publicSuffix; }, getDomain: function (url) { return parse(url, DOMAIN).domain; }, getSubdomain: function (url) { return parse(url, SUB_DOMAIN).subdomain; }, fromUserSettings: factory }; } module.exports = factory({}); },{"./lib/clean-host.js":2,"./lib/domain.js":3,"./lib/is-ip.js":5,"./lib/is-valid.js":6,"./lib/public-suffix.js":7,"./lib/subdomain.js":8,"./lib/suffix-trie.js":9,"./lib/tld-exists.js":10,"./rules.json":80,"util":78}],2:[function(require,module,exports){ var URL = require('url'); var isValid = require('./is-valid.js'); /** * Utility to cleanup the base host value. Also removes url fragments. * * Works for: * - hostname * - //hostname * - scheme://hostname * - scheme+scheme://hostname * * @param {string} value * @return {String} */ // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var hasPrefixRE = /^(([a-z][a-z0-9+.-]*)?:)?\/\//; /** * @see https://github.com/thom4parisot/tld.js/issues/95 * * @param {string} value */ function trimTrailingDots(value) { if (value[value.length - 1] === '.') { return value.substr(0, value.length - 1); } return value; } /** * Fast check to avoid calling `trim` when not needed. * * @param {string} value */ function checkTrimmingNeeded(value) { return ( value.length > 0 && ( value.charCodeAt(0) <= 32 || value.charCodeAt(value.length - 1) <= 32 ) ); } /** * Fast check to avoid calling `toLowerCase` when not needed. * * @param {string} value */ function checkLowerCaseNeeded(value) { for (var i = 0; i < value.length; i += 1) { var code = value.charCodeAt(i); if (code >= 65 && code <= 90) { // [A-Z] return true; } } return false; } module.exports = function extractHostname(value) { // First check if `value` is already a valid hostname. if (isValid(value)) { return trimTrailingDots(value); } var url = value; if (typeof url !== 'string') { url = '' + url; } var needsTrimming = checkTrimmingNeeded(url); if (needsTrimming) { url = url.trim(); } var needsLowerCase = checkLowerCaseNeeded(url); if (needsLowerCase) { url = url.toLowerCase(); } // Try again after `url` has been transformed to lowercase and trimmed. if ((needsLowerCase || needsTrimming) && isValid(url)) { return trimTrailingDots(url); } // Proceed with heavier url parsing to extract the hostname. if (!hasPrefixRE.test(url)) { url = '//' + url; } var parts = URL.parse(url, null, true); if (parts.hostname) { return trimTrailingDots(parts.hostname); } return null; }; },{"./is-valid.js":6,"url":75}],3:[function(require,module,exports){ 'use strict'; /** * Polyfill for `endsWith` * * @param {string} str * @param {string} pattern * @return {boolean} */ function endsWith(str, pattern) { return ( str.lastIndexOf(pattern) === (str.length - pattern.length) ); } /** * Check if `vhost` is a valid suffix of `hostname` (top-domain) * * It means that `vhost` needs to be a suffix of `hostname` and we then need to * make sure that: either they are equal, or the character preceding `vhost` in * `hostname` is a '.' (it should not be a partial label). * * * hostname = 'not.evil.com' and vhost = 'vil.com' => not ok * * hostname = 'not.evil.com' and vhost = 'evil.com' => ok * * hostname = 'not.evil.com' and vhost = 'not.evil.com' => ok * * @param {string} hostname * @param {string} vhost * @return {boolean} */ function shareSameDomainSuffix(hostname, vhost) { if (endsWith(hostname, vhost)) { return ( hostname.length === vhost.length || hostname[hostname.length - vhost.length - 1] === '.' ); } return false; } /** * Given a hostname and its public suffix, extract the general domain. * * @param {string} hostname * @param {string} publicSuffix * @return {string} */ function extractDomainWithSuffix(hostname, publicSuffix) { // Locate the index of the last '.' in the part of the `hostname` preceding // the public suffix. // // examples: // 1. not.evil.co.uk => evil.co.uk // ^ ^ // | | start of public suffix // | index of the last dot // // 2. example.co.uk => example.co.uk // ^ ^ // | | start of public suffix // | // | (-1) no dot found before the public suffix var publicSuffixIndex = hostname.length - publicSuffix.length - 2; var lastDotBeforeSuffixIndex = hostname.lastIndexOf('.', publicSuffixIndex); // No '.' found, then `hostname` is the general domain (no sub-domain) if (lastDotBeforeSuffixIndex === -1) { return hostname; } // Extract the part between the last '.' return hostname.substr(lastDotBeforeSuffixIndex + 1); } /** * Detects the domain based on rules and upon and a host string * * @api * @param {string} host * @return {String} */ module.exports = function getDomain(validHosts, suffix, hostname) { // Check if `hostname` ends with a member of `validHosts`. for (var i = 0; i < validHosts.length; i += 1) { var vhost = validHosts[i]; if (shareSameDomainSuffix(hostname, vhost)) { return vhost; } } // If there is no suffix, there is no hostname if (suffix === null) { return null; } // If `hostname` is a valid public suffix, then there is no domain to return. // Since we already know that `getPublicSuffix` returns a suffix of `hostname` // there is no need to perform a string comparison and we only compare the // size. if (suffix.length === hostname.length) { return null; } // To extract the general domain, we start by identifying the public suffix // (if any), then consider the domain to be the public suffix with one added // level of depth. (e.g.: if hostname is `not.evil.co.uk` and public suffix: // `co.uk`, then we take one more level: `evil`, giving the final result: // `evil.co.uk`). return extractDomainWithSuffix(hostname, suffix); }; },{}],4:[function(require,module,exports){ 'use strict'; /** * Utility to extract the TLD from a hostname string * * @param {string} host * @return {String} */ module.exports = function extractTldFromHost(hostname) { var lastDotIndex = hostname.lastIndexOf('.'); if (lastDotIndex === -1) { return null; } return hostname.substr(lastDotIndex + 1); }; },{}],5:[function(require,module,exports){ 'use strict'; /** * Check if a hostname is an IP. You should be aware that this only works * because `hostname` is already garanteed to be a valid hostname! * * @param {string} hostname * @return {boolean} */ function isProbablyIpv4(hostname) { var numberOfDots = 0; for (var i = 0; i < hostname.length; i += 1) { var code = hostname.charCodeAt(i); if (code === 46) { // '.' numberOfDots += 1; } else if (code < 48 || code > 57) { // 48 => '0' // 57 => '9' return false; } } return ( numberOfDots === 3 && hostname[0] !== '.' && hostname[hostname.length - 1] !== '.' ); } /** * Similar to isProbablyIpv4. * * @param {string} hostname * @return {boolean} */ function isProbablyIpv6(hostname) { var hasColon = false; for (var i = 0; i < hostname.length; i += 1) { var code = hostname.charCodeAt(i); if (code === 58) { // ':' hasColon = true; } else if (!( (code >= 48 && code <= 57) || // 0-9 (code >= 97 && code <= 102) // a-f )) { return false; } } return hasColon; } /** * Check if `hostname` is *probably* a valid ip addr (either ipv6 or ipv4). * This *will not* work on any string. We need `hostname` to be a valid * hostname. * * @param {string} hostname * @return {boolean} */ module.exports = function isIp(hostname) { if (typeof hostname !== 'string') { return false; } if (hostname.length === 0) { return false; } return (isProbablyIpv6(hostname) || isProbablyIpv4(hostname)); }; },{}],6:[function(require,module,exports){ 'use strict'; /** * Check if the code point is a digit [0-9] * * @param {number} code * @return boolean */ function isDigit(code) { // 48 == '0' // 57 == '9' return code >= 48 && code <= 57; } /** * Check if the code point is a letter [a-zA-Z] * * @param {number} code * @return boolean */ function isAlpha(code) { // 97 === 'a' // 122 == 'z' return code >= 97 && code <= 122; } /** * Check if a hostname string is valid (according to RFC). It's usually a * preliminary check before trying to use getDomain or anything else. * * Beware: it does not check if the TLD exists. * * @api * @param {string} hostname * @return {boolean} */ module.exports = function isValid(hostname) { if (typeof hostname !== 'string') { return false; } if (hostname.length > 255) { return false; } if (hostname.length === 0) { return false; } // Check first character: [a-zA-Z0-9] var firstCharCode = hostname.charCodeAt(0); if (!(isAlpha(firstCharCode) || isDigit(firstCharCode))) { return false; } // Validate hostname according to RFC var lastDotIndex = -1; var lastCharCode; var code; var len = hostname.length; for (var i = 0; i < len; i += 1) { code = hostname.charCodeAt(i); if (code === 46) { // '.' if ( // Check that previous label is < 63 bytes long (64 = 63 + '.') (i - lastDotIndex) > 64 || // Check that previous character was not already a '.' lastCharCode === 46 || // Check that the previous label does not end with a '-' lastCharCode === 45 ) { return false; } lastDotIndex = i; } else if (!(isAlpha(code) || isDigit(code) || code === 45)) { // Check if there is a forbidden character in the label: [^a-zA-Z0-9-] return false; } lastCharCode = code; } return ( // Check that last label is shorter than 63 chars (len - lastDotIndex - 1) <= 63 && // Check that the last character is an allowed trailing label character. // Since we already checked that the char is a valid hostname character, // we only need to check that it's different from '-'. lastCharCode !== 45 ); }; },{}],7:[function(require,module,exports){ 'use strict'; var extractTldFromHost = require('./from-host.js'); /** * Returns the public suffix (including exact matches) * * @api * @since 1.5 * @param {string} hostname * @return {string} */ module.exports = function getPublicSuffix(rules, hostname) { // First check if `hostname` is already a valid top-level Domain. if (rules.hasTld(hostname)) { return hostname; } var candidate = rules.suffixLookup(hostname); if (candidate === null) { // Prevailing rule is '*' so we consider the top-level domain to be the // public suffix of `hostname` (e.g.: 'example.org' => 'org'). return extractTldFromHost(hostname); } return candidate; }; },{"./from-host.js":4}],8:[function(require,module,exports){ 'use strict'; /** * Returns the subdomain of a hostname string * * @api * @param {string} hostname * @param {string} domain - the root domain of the hostname * @return {string|null} a subdomain string if any, blank string if subdomain * is empty, otherwise null. */ module.exports = function getSubdomain(hostname, domain) { // No domain found? Just abort, abort! if (domain === null) { return null; } return hostname.substr(0, hostname.length - domain.length - 1); }; },{}],9:[function(require,module,exports){ 'use strict'; var VALID_HOSTNAME_VALUE = 0; /** * @typedef {string} PlainRules */ /** * Return min(a, b), handling possible `null` values. * * @param {number|null} a * @param {number|null} b * @return {number|null} */ function minIndex(a, b) { if (a === null) { return b; } else if (b === null) { return a; } return a < b ? a : b; } /** * Insert a public suffix rule in the `trie`. * * @param {object} rule * @param {object} trie * @return {object} trie (updated) */ function insertInTrie(rule, trie) { var parts = rule.parts; var node = trie; for (var i = 0; i < parts.length; i += 1) { var part = parts[i]; var nextNode = node[part]; if (nextNode === undefined) { nextNode = Object.create(null); node[part] = nextNode; } node = nextNode; } node.$ = VALID_HOSTNAME_VALUE; return trie; } /** * Recursive lookup of `parts` (starting at `index`) in the tree. * * @param {array} parts * @param {object} trie * @param {number} index - when to start in `parts` (initially: length - 1) * @return {number} size of the suffix found (in number of parts matched) */ function lookupInTrie(parts, trie, index) { var part; var nextNode; var publicSuffixIndex = null; // We have a match! if (trie.$ !== undefined) { publicSuffixIndex = index + 1; } // No more `parts` to look for if (index === -1) { return publicSuffixIndex; } part = parts[index]; // Check branch corresponding to next part of hostname nextNode = trie[part]; if (nextNode !== undefined) { publicSuffixIndex = minIndex( publicSuffixIndex, lookupInTrie(parts, nextNode, index - 1) ); } // Check wildcard branch nextNode = trie['*']; if (nextNode !== undefined) { publicSuffixIndex = minIndex( publicSuffixIndex, lookupInTrie(parts, nextNode, index - 1) ); } return publicSuffixIndex; } /** * Contains the public suffix ruleset as a Trie for efficient look-up. * * @constructor * @param {PlainRules} [rules] */ function SuffixTrie(rules) { this.exceptions = Object.create(null); this.rules = Object.create(null); if (rules) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; if (rule.exception) { insertInTrie(rule, this.exceptions); } else { insertInTrie(rule, this.rules); } } } } /** * Load the trie from JSON (as serialized by JSON.stringify). */ SuffixTrie.fromJson = function (json) { var trie = new SuffixTrie(); trie.exceptions = json.exceptions; trie.rules = json.rules; return trie; }; /** * Check if `value` is a valid TLD. */ SuffixTrie.prototype.hasTld = function (value) { // All TLDs are at the root of the Trie. return this.rules[value] !== undefined; }; /** * Check if `hostname` has a valid public suffix in `trie`. * * @param {string} hostname * @return {string|null} public suffix */ SuffixTrie.prototype.suffixLookup = function (hostname) { var parts = hostname.split('.'); // Look for a match in rules var publicSuffixIndex = lookupInTrie( parts, this.rules, parts.length - 1 ); if (publicSuffixIndex === null) { return null; } // Look for exceptions var exceptionIndex = lookupInTrie( parts, this.exceptions, parts.length - 1 ); if (exceptionIndex !== null) { return parts.slice(exceptionIndex + 1).join('.'); } return parts.slice(publicSuffixIndex).join('.'); }; module.exports = SuffixTrie; },{}],10:[function(require,module,exports){ 'use strict'; var extractTldFromHost = require('./from-host.js'); /** * Checks if the TLD exists for a given hostname * * @api * @param {string} rules * @param {string} hostname * @return {boolean} */ module.exports = function tldExists(rules, hostname) { // Easy case, it's a TLD if (rules.hasTld(hostname)) { return true; } // Popping only the TLD of the hostname var hostTld = extractTldFromHost(hostname); if (hostTld === null) { return false; } return rules.hasTld(hostTld); }; },{"./from-host.js":4}],11:[function(require,module,exports){ (function (global){(function (){ 'use strict'; var possibleNames = require('possible-typed-array-names'); var g = typeof globalThis === 'undefined' ? global : globalThis; /** @type {import('.')} */ module.exports = function availableTypedArrays() { var /** @type {ReturnType<typeof availableTypedArrays>} */ out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g[possibleNames[i]] === 'function') { // @ts-expect-error out[out.length] = possibleNames[i]; } } return out; }; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"possible-typed-array-names":61}],12:[function(require,module,exports){ },{}],13:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var $apply = require('./functionApply'); var $call = require('./functionCall'); var $reflectApply = require('./reflectApply'); /** @type {import('./actualApply')} */ module.exports = $reflectApply || bind.call($call, $apply); },{"./functionApply":15,"./functionCall":16,"./reflectApply":18,"function-bind":34}],14:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var $apply = require('./functionApply'); var actualApply = require('./actualApply'); /** @type {import('./applyBind')} */ module.exports = function applyBind() { return actualApply(bind, $apply, arguments); }; },{"./actualApply":13,"./functionApply":15,"function-bind":34}],15:[function(require,module,exports){ 'use strict'; /** @type {import('./functionApply')} */ module.exports = Function.prototype.apply; },{}],16:[function(require,module,exports){ 'use strict'; /** @type {import('./functionCall')} */ module.exports = Function.prototype.call; },{}],17:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var $TypeError = require('es-errors/type'); var $call = require('./functionCall'); var $actualApply = require('./actualApply'); /** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ module.exports = function callBindBasic(args) { if (args.length < 1 || typeof args[0] !== 'function') { throw new $TypeError('a function is required'); } return $actualApply(bind, $call, args); }; },{"./actualApply":13,"./functionCall":16,"es-errors/type":29,"function-bind":34}],18:[function(require,module,exports){ 'use strict'; /** @type {import('./reflectApply')} */ module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; },{}],19:[function(require,module,exports){ 'use strict'; var setFunctionLength = require('set-function-length'); var $defineProperty = require('es-define-property'); var callBindBasic = require('call-bind-apply-helpers'); var applyBind = require('call-bind-apply-helpers/applyBind'); module.exports = function callBind(originalFunction) { var func = callBindBasic(arguments); var adjustedLength = originalFunction.length - (arguments.length - 1); return setFunctionLength( func, 1 + (adjustedLength > 0 ? adjustedLength : 0), true ); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } },{"call-bind-apply-helpers":17,"call-bind-apply-helpers/applyBind":14,"es-define-property":23,"set-function-length":69}],20:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); var callBindBasic = require('call-bind-apply-helpers'); /** @type {(thisArg: string, searchString: string, position?: number) => number} */ var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); /** @type {import('.')} */ module.exports = function callBoundIntrinsic(name, allowMissing) { /* eslint no-extra-parens: 0 */ var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBindBasic(/** @type {const} */ ([intrinsic])); } return intrinsic; }; },{"call-bind-apply-helpers":17,"get-intrinsic":35}],21:[function(require,module,exports){ 'use strict'; var $defineProperty = require('es-define-property'); var $SyntaxError = require('es-errors/syntax'); var $TypeError = require('es-errors/type'); var gopd = require('gopd'); /** @type {import('.')} */ module.exports = function defineDataProperty( obj, property, value ) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new $TypeError('`obj` must be an object or a function`'); } if (typeof property !== 'string' && typeof property !== 'symbol') { throw new $TypeError('`property` must be a string or a symbol`'); } if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); } if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); } if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); } if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { throw new $TypeError('`loose`, if provided, must be a boolean'); } var nonEnumerable = arguments.length > 3 ? arguments[3] : null; var nonWritable = arguments.length > 4 ? arguments[4] : null; var nonConfigurable = arguments.length > 5 ? arguments[5] : null; var loose = arguments.length > 6 ? arguments[6] : false; /* @type {false | TypedPropertyDescriptor<unknown>} */ var desc = !!gopd && gopd(obj, property); if ($defineProperty) { $defineProperty(obj, property, { configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, value: value, writable: nonWritable === null && desc ? desc.writable : !nonWritable }); } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable obj[property] = value; // eslint-disable-line no-param-reassign } else { throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); } }; },{"es-define-property":23,"es-errors/syntax":28,"es-errors/type":29,"gopd":40}],22:[function(require,module,exports){ 'use strict'; var callBind = require('call-bind-apply-helpers'); var gOPD = require('gopd'); var hasProtoAccessor; try { // eslint-disable-next-line no-extra-parens, no-proto hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; } catch (e) { if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { throw e; } } // eslint-disable-next-line no-extra-parens var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); var $Object = Object; var $getPrototypeOf = $Object.getPrototypeOf; /** @type {import('./get')} */ module.exports = desc && typeof desc.get === 'function' ? callBind([desc.get]) : typeof $getPrototypeOf === 'function' ? /** @type {import('./get')} */ function getDunder(value) { // eslint-disable-next-line eqeqeq return $getPrototypeOf(value == null ? value : $Object(value)); } : false; },{"call-bind-apply-helpers":17,"gopd":40}],23:[function(require,module,exports){ 'use strict'; /** @type {import('.')} */ var $defineProperty = Object.defineProperty || false; if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = false; } } module.exports = $defineProperty; },{}],24:[function(require,module,exports){ 'use strict'; /** @type {import('./eval')} */ module.exports = EvalError; },{}],25:[function(require,module,exports){ 'use strict'; /** @type {import('.')} */ module.exports = Error; },{}],26:[function(require,module,exports){ 'use strict'; /** @type {import('./range')} */ module.exports = RangeError; },{}],27:[function(require,module,exports){ 'use strict'; /** @type {import('./ref')} */ module.exports = ReferenceError; },{}],28:[function(require,module,exports){ 'use strict'; /** @type {import('./syntax')} */ module.exports = SyntaxError; },{}],29:[function(require,module,exports){ 'use strict'; /** @type {import('./type')} */ module.exports = TypeError; },{}],30:[function(require,module,exports){ 'use strict'; /** @type {import('./uri')} */ module.exports = URIError; },{}],31:[function(require,module,exports){ 'use strict'; /** @type {import('.')} */ module.exports = Object; },{}],32:[function(require,module,exports){ 'use strict'; var isCallable = require('is-callable'); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; /** @type {<This, A extends readonly unknown[]>(arr: A, iterator: (this: This | void, value: A[number], index: number, arr: A) => void, receiver: This | undefined) => void} */ var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; /** @type {<This, S extends string>(string: S, iterator: (this: This | void, value: S[number], index: number, string: S) => void, receiver: This | undefined) => void} */ var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; /** @type {<This, O>(obj: O, iterator: (this: This | void, value: O[keyof O], index: keyof O, obj: O) => void, receiver: This | undefined) => void} */ var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; /** @type {(x: unknown) => x is readonly unknown[]} */ function isArray(x) { return toStr.call(x) === '[object Array]'; } /** @type {import('.')._internal} */ module.exports = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (isArray(list)) { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; },{"is-callable":48}],33:[function(require,module,exports){ 'use strict'; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var toStr = Object.prototype.toString; var max = Math.max; var funcType = '[object Function]'; var concatty = function concatty(a, b) { var arr = []; for (var i = 0; i < a.length; i += 1) { arr[i] = a[i]; } for (var j = 0; j < b.length; j += 1) { arr[j + a.length] = b[j]; } return arr; }; var slicy = function slicy(arrLike, offset) { var arr = []; for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { arr[j] = arrLike[i]; } return arr; }; var joiny = function (arr, joiner) { var str = ''; for (var i = 0; i < arr.length; i += 1) { str += arr[i]; if (i + 1 < arr.length) { str += joiner; } } return str; }; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; } return target.apply( that, concatty(args, arguments) ); }; var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs[i] = '$' + i; } bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; },{}],34:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); module.exports = Function.prototype.bind || implementation; },{"./implementation":33}],35:[function(require,module,exports){ 'use strict'; var undefined; var $Object = require('es-object-atoms'); var $Error = require('es-errors'); var $EvalError = require('es-errors/eval'); var $RangeError = require('es-errors/range'); var $ReferenceError = require('es-errors/ref'); var $SyntaxError = require('es-errors/syntax'); var $TypeError = require('es-errors/type'); var $URIError = require('es-errors/uri'); var abs = require('math-intrinsics/abs'); var floor = require('math-intrinsics/floor'); var max = require('math-intrinsics/max'); var min = require('math-intrinsics/min'); var pow = require('math-intrinsics/pow'); var round = require('math-intrinsics/round'); var sign = require('math-intrinsics/sign'); var $Function = Function; // eslint-disable-next-line consistent-return var getEvalledConstructor = function (expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = require('gopd'); var $defineProperty = require('es-define-property'); var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = require('has-symbols')(); var getProto = require('get-proto'); var $ObjectGPO = require('get-proto/Object.getPrototypeOf'); var $ReflectGPO = require('get-proto/Reflect.getPrototypeOf'); var $apply = require('call-bind-apply-helpers/functionApply'); var $call = require('call-bind-apply-helpers/functionCall'); var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); var INTRINSICS = { __proto__: null, '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': $Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': $EvalError, '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': $Object, '%Object.getOwnPropertyDescriptor%': $gOPD, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': $RangeError, '%ReferenceError%': $ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': $URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '%Function.prototype.call%': $call, '%Function.prototype.apply%': $apply, '%Object.defineProperty%': $defineProperty, '%Object.getPrototypeOf%': $ObjectGPO, '%Math.abs%': abs, '%Math.floor%': floor, '%Math.max%': max, '%Math.min%': min, '%Math.pow%': pow, '%Math.round%': round, '%Math.sign%': sign, '%Reflect.getPrototypeOf%': $ReflectGPO }; if (getProto) { try { null.error; // eslint-disable-line no-unused-expressions } catch (e) { // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 var errorProto = getProto(getProto(e)); INTRINSICS['%Error.prototype%'] = errorProto; } } var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen && getProto) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { __proto__: null, '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = require('function-bind'); var hasOwn = require('hasown'); var $concat = bind.call($call, Array.prototype.concat); var $spliceApply = bind.call($apply, Array.prototype.splice); var $replace = bind.call($call, String.prototype.replace); var $strSlice = bind.call($call, String.prototype.slice); var $exec = bind.call($call, RegExp.prototype.exec); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/, name) === null) { throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ( ( (first === '"' || first === "'" || first === '`') || (last === '"' || last === "'" || last === '`') ) && first !== last ) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; },{"call-bind-apply-helpers/functionApply":15,"call-bind-apply-helpers/functionCall":16,"es-define-property":23,"es-errors":25,"es-errors/eval":24,"es-errors/range":26,"es-errors/ref":27,"es-errors/syntax":28,"es-errors/type":29,"es-errors/uri":30,"es-object-atoms":31,"function-bind":34,"get-proto":38,"get-proto/Object.getPrototypeOf":36,"get-proto/Reflect.getPrototypeOf":37,"gopd":40,"has-symbols":42,"hasown":45,"math-intrinsics/abs":52,"math-intrinsics/floor":53,"math-intrinsics/max":55,"math-intrinsics/min":56,"math-intrinsics/pow":57,"math-intrinsics/round":58,"math-intrinsics/sign":59}],36:[function(require,module,exports){ 'use strict'; var $Object = require('es-object-atoms'); /** @type {import('